The Summed Start-up Costs in a Unit Commitment Problem
Ren\'e Brandenberg\thanks{brandenb@ma.tum.de
Department of Mathematics
We consider the sum of the incurred start-up costs of a single unit in a Unit Commitment problem. Our major result is a correspondence between the facets of its epigraph and some binary trees for concave start-up cost functions~$\StartupCostFunction(,)$, which is bijective if $\StartupCostFunction(,)$ is strictly concave. We derive an exponential \hrepresentation of this epigraph, and provide an exact linear separation algorithm. These results significantly reduce the integrality gap of the Mixed Integer formulation of a Unit Commitment Problem compared to current literature.
Header.tex
%
\RequirePackage[english]{babel}
\RequirePackage[utf8]{inputenc}
\RequirePackage{ellipsis, fixltx2e, ragged2e}
\RequirePackage{xifthen}
\RequirePackage{calc}
\overfullrule=5pt

%
\RequirePackage{fix-cm}
\RequirePackage{mathptmx}
\RequirePackage[T1]{fontenc}
\RequirePackage[final]{microtype}
\RequirePackage{eurosym}

%
\RequirePackage{amssymb,amsmath}
\RequirePackage{bm}
\RequirePackage{array}
\RequirePackage{mathtools}
\RequirePackage{xfrac}
\RequirePackage[ruled, vlined, linesnumbered]{algorithm2e}
\RequirePackage{multirow}

%
\RequirePackage{tumcolors}
\RequirePackage{pgf,tikz,pgfplots}
\pgfplotsset{compat=1.11}
\usepgfplotslibrary{fillbetween,statistics}
\pgfdeclarelayer{background}
\pgfdeclarelayer{foreground}
\pgfsetlayers{background,main,foreground}
\RequirePackage{graphicx}
\RequirePackage{float}

%
\RequirePackage{longtable}
\RequirePackage{tabulary}
\binoppenalty = 10000			  %
\relpenalty = 10000				  %
\clubpenalty = 10000              %
\widowpenalty = 10000             %
\displaywidowpenalty = 10000      %
\makeatletter
\renewcommand{\fps@figure}{htb}   %
\renewcommand{\fps@table}{htb}    %
\makeatother
\RequirePackage{mdwlist}		  %
\RequirePackage{fancybox}
\RequirePackage{booktabs}
\RequirePackage{enumerate}
\RequirePackage[autostyle=true]{csquotes}
\RequirePackage{tabulary}
\RequirePackage{verbatim}
\RequirePackage{xspace}
\RequirePackage{subcaption}

\usepackage{natbib}
\setcitestyle{authoryear, aysep={}, open={}, close={}}

\RequirePackage[hyperref, amsmath, thmmarks]{ntheorem}
\newcommand{\manualqed}{\PotEndMark{\hbox{}\nobreak\hfill\nobreak}}
\newcommand{\eqqed}[1]{}
	
\theorembodyfont{\itshape}%
\theoremheaderfont{\bfseries}%
\theoremseparator{}%
\newtheorem{theorem}{Theorem}%
\newtheorem{proposition}[theorem]{Proposition}
\newtheorem{lemma}[theorem]{Lemma}%
\newtheorem{corollary}[theorem]{Corollary}
	
\theorembodyfont{\upshape}%
\newtheorem{definition}[theorem]{Definition}%
\newtheorem{problem}[theorem]{Problem}%
	
\theoremstyle{break}
\newtheorem{example}[theorem]{Example}%
	
\theoremstyle{nonumberplain}%
\theoremheaderfont{\bfseries}%
\theorembodyfont{\normalfont}%
\theoremseparator{.}
\theoremsymbol{\ensuremath{\Box}}%
\newtheorem{proof}{Proof}%

\usepackage{enumitem}
\setlength{\parindent}{1.4em}
\setlist[1]{noitemsep,leftmargin=1.4em,topsep=0.25em plus 0.25em minus 0.5em}
\frenchspacing
	
\usepackage[format=plain,labelfont=bf]{caption}
\usepackage{subcaption}
\addto\captionsenglish{\renewcommand{\figurename}{Fig.}}

\usepackage[plainpages=false,pdfpagelabels]{hyperref}

\usepackage[english,capitalise]{cleveref}
\crefname{theorem}{Theorem}{Theorems}
\Crefname{theorem}{Theorem}{Theorems}
\crefname{proposition}{Proposition}{Propositions}
\Crefname{proposition}{Proposition}{Propositions}
\crefname{lemma}{Lemma}{Lemmata}
\Crefname{lemma}{Lemma}{Lemmata}
\crefname{corollary}{Corollary}{Corollaries}
\Crefname{corollary}{Corollary}{Corollaries}
\crefname{definition}{Definition}{Definitions}
\Crefname{definition}{Definition}{Definitions}
\crefname{problem}{Problem}{Problems}
\Crefname{problem}{Problem}{Problems}
\crefname{example}{Example}{Examples}
\Crefname{example}{Example}{Examples}
\crefname{proof}{Proof}{Proofs}
\Crefname{proof}{Proof}{Proofs}
\crefname{algocf}{Algorithm}{Algorithms}
\Crefname{algocf}{Algorithm}{Algorithms}

%
%
\let\originalleft\left
\let\originalright\right
\renewcommand{\left}{\mathopen{}\mathclose\bgroup\originalleft}
\renewcommand{\right}{\aftergroup\egroup\originalright}

%
%
\renewcommand{\textvisiblespace}[1][.3em]{%
  \mbox{\kern.06em\vrule height.3ex}%
  \vbox{\hrule width#1}%
  \hbox{\vrule height.3ex}%
}

%
\providecommand{\ie}{i.\,e.\xspace}%
\providecommand{\eg}{e.\,g.\xspace}%
\providecommand{\cf}{cf.\xspace}%

%
\setlength{\unitlength}{1mm}


%
%
%

%
%
%
%
%

%
%
%
\newcommand{\naturals}{{\mathbb{N}_0}}
\newcommand{\positiveNaturals}{{\mathbb{N}_{1}}}
\newcommand{\pnaturals}{\positiveNaturals}
%
\newcommand{\integers}{\mathbb{Z}}
%
\newcommand{\rationals}{\mathbb{Q}}
%
\newcommand{\reals}{\mathbb{R}}
\newcommand{\positiveReals}{\mathbb{R}_{> 0}}
\newcommand{\nonnegativeReals}{\mathbb{R}_{\geq 0}}
\newcommand{\negativeReals}{\mathbb{R}_{< 0}}
\newcommand{\nonpositiveReals}{\mathbb{R}_{\leq 0}}
\newcommand{\preals}{\positiveReals}
\newcommand{\nnreals}{\nonnegativeReals}
\newcommand{\nreals}{\negativeReals}
\newcommand{\npreals}{\nonpositiveReals}
%
\newcommand{\irrationals}{\mathbb{I}}
%
\newcommand{\complex}{\mathbb{C}}


%
%
%
\renewcommand{\implies}{{\ \Rightarrow\ }}
\renewcommand{\impliedby}{{\ \Leftarrow\ }}
\newcommand{\equals}{{\ \Longleftrightarrow\ }}

%
%
%
\DeclareMathOperator*{\argmin}{arg\,min}
\DeclareMathOperator*{\argmax}{arg\,max}
\let\mathprod\prod

%
%
%
\DeclareMathOperator*{\graph}{graph}
\DeclareMathOperator*{\epi}{epi}
\DeclareMathOperator*{\convexHull}{conv}
\DeclareMathOperator*{\affineHull}{aff}
\DeclareMathOperator*{\positiveHull}{pos}
\DeclareMathOperator*{\linearHull}{span}
\newcommand{\conv}{\convexHull}
\newcommand{\aff}{\convexHull}
\newcommand{\pos}{\positiveHull}
\newcommand{\lin}{\linearHull}

\DeclareMathOperator*{\concave}{concave}
\DeclareMathOperator*{\closure}{closure}

\renewcommand{\exp}[1]{\text{e}^{#1}}

%
%
%
\newcommand{\NP}{\ensuremath{\mathbb{N\,P}}}
\renewcommand{\P}{\ensuremath{\mathbb{P}}}
\newcommand{\EXPTIME}{\textit{EXPTIME}}
\newcommand{\PSPACE}{\textit{PSPACE}}
\newcommand{\FPT}{\textit{FPT}}
\newcommand{\FPTAS}{\textit{FPTAS}}
\newcommand{\W}[1]{\textit{W[#1]}}

%
%
%
%
\providecommand\given{}
\newcommand\SetSymbol[1][]{\nonscript\:#1\vert\nonscript\:\allowbreak}
\newcommand\AltSetSymbol{\nonscript\::\nonscript\:\allowbreak}
\makeatletter
\DeclarePairedDelimiterX\set[1]\{\}{%
	\renewcommand\given{\@ifstar\AltSetSymbol{\SetSymbol[\delimsize]}}%
	#1%
}
\makeatother
\newcommand{\subjectTo}{:}
\newcommand{\djcup}{\mathbin{\dot{\cup}}}%
\newcommand{\djbigcup}{\mathop{\dot{\bigcup}}} %
\let\subseteq\subset
\let\supseteq\supset
\let\subset\subsetneq
\let\supset\supsetneq

%
%
%
\newcommand{\hyperplane}[2]{H_{#1, #2}}
\newcommand{\halfspace}[2]{H^{\leq}_{#1, #2}}
\newcommand{\strictHalfspace}[2]{H^{<}_{#1, #2}}
\newcommand{\nonnegativeHalfspace}[2]{H^{\geq}_{#1, #2}}
\newcommand{\positiveHalfspace}[2]{H^{> 0}_{#1, #2}}
\newcommand{\unitVec}[1]{u_{#1}}
\newcommand{\eye}{\ensuremath{I}}

%
\newcommand{\abs}[1]{{\left| #1 \right|}}
%
\newcommand{\norm}[1]{{\left|\left|#1\right|\right|}}
%
\newcommand{\ceil}[1]{{\left\lceil #1 \right\rceil}}
%
\newcommand{\floor}[1]{{\left\lfloor #1 \right\lfloor}}

\let\orgwidehat\widehat
\renewcommand{\widehat}[2][\empty]{%
	\ifthenelse{\isempty{#1}}{%
		\orgwidehat{#2}%
	}{%
		\settowidth{\dimen0}{$#2$}%
		\hbox to \dimen0{%
			\hfuzz=10000pt\relax%
			\hbox to 0pt{$#2$}%
			\hfil$\orgwidehat{\hbox to #1{}}$\hfil%
		}%
	}%
}
\let\orgwidetilde\widetilde
\renewcommand{\widetilde}[2][\empty]{%
	\ifthenelse{\isempty{#1}}{%
		\orgwidetilde{#2}%
	}{{%
		\settowidth{\dimen0}{$#2$}%
		\hbox to \dimen0{%
			\hfuzz=10000pt\relax%
			\hbox to 0pt{$#2$}%
			\hfil$\orgwidetilde{\hbox to #1{}}$\hfil%
		}%
	}}%
}

%
%
%
%
%

%
\newcommand{\bigO}{\mathcal{O}}
%
\newcommand{\setneg}[1]{\overline{#1}}
%
\newcommand{\setto}{\leftarrow}
%
\newcommand{\ds}{\displaystyle}
\def\range#1#2{[#1,#2]}
%
\makeatletter
\def\discrange{\@ifnextchar*\discrangeStar{\discrangeInternal{n}}}
\makeatother
\def\discrangeStar*{\discrangeInternal{y}}
\def\discrangeInternal#1#2#3{{%
	\toks255={#2}%
	\ifthenelse{\equal{\the\toks255}{1}}{%
		%
		\lbrack#3\rbrack%
	}{%
		%
		\lbrack%
		\ifthenelse{\equal{#1}{y}}{%
			\text{%
				\thinmuskip=0.25\thinmuskip%
				\medmuskip=0.25\medmuskip%
				\thickmuskip=0.25\thickmuskip%
				%
				$#2\ ..\ #3$%
			}%
		}{%
			%
			#2..#3
		}%
		\rbrack%
	}
}}%
%
%
\newcommand{\squeeze}[2][0.25]{
	{\text{%
		\thinmuskip=#1\thinmuskip%
		\medmuskip=#1\medmuskip%
		\thickmuskip=#1\thickmuskip%
		%
		$#2$%
	}}%
}
\newcommand{\diff}{\operatorname{d}\!}
%
\newcommand{\with}[2]{\stackrel{\scriptstyle #1}{#2}}
\newcommand{\withtextl}[2]{%
	%
	\stackrel{\hbox to 0pt{\hss\scriptsize #1\hss}}{#2}%
	%
	%
		\unskip\makebox[(\widthof{\scriptsize #1} - \widthof{$#2$}) / 2]{}%
	%
}
%
\newcommand{\withtext}[2]{\with{\text{#1}}{#2}}
\newcommand{\withl}[2]{\withtextl{$#1$}{#2}}
%
%
\newcommand{\tightsum}[2]{ %
  %
  \newbox\bigbox
  \newbox\smallbox
  \newbox\argbox
  \newdimen\smallwidth
  \newdimen\offsetwidth
  \newdimen\argwidth
  %
  %
  \sbox\bigbox{\ensuremath{\displaystyle \sum_{#1}}}
  %
  \sbox\smallbox{\ensuremath{\smashoperator{\sum_{#1}}}}
  %
  \sbox\argbox{\ensuremath{\displaystyle \,#2}}
  %
  \argwidth=\wd\argbox
  %
  %
  %
  \offsetwidth=\wd\bigbox
  \smallwidth=\wd\smallbox
  \multiply\smallwidth by -1
  \advance\offsetwidth by \smallwidth
  \divide\offsetwidth by 2
  %
  %
  %
  \usebox\bigbox\hspace{-\offsetwidth}\usebox\argbox
  %
  %
  %
  \ifnum\offsetwidth>\argwidth \hspace{\offsetwidth}\hspace{-\argwidth} \fi
  %
}

%
\newcommand{\biggskip}{\bigskip\bigskip}

%
\def\hyph{-\penalty0\hskip0pt\relax}
\hyphenation{last-Period-Length last-Unit-Length pa-ram-e-tri-za-tion pa-ram-e-ter-i-za-tion}

%
%
%
%
\makeatletter
\newcommand{\renewvar}[3]{%
	%
	\expandafter\def\csname #1\endcsname{\@ifnextchar({\csname #1Parentheses\endcsname}{\csname #1Braces\endcsname}}%
	%
	\ifcase #2
		%
		\expandafter\def\csname #1\endcsname{#3\@ifnextchar({\PackageError{newvar}{The variable #1 should have no parameters!}{}}\relax}%
		\expandafter\def\csname #1Braces\endcsname{#3}%
	\or	\expandafter\def\csname #1Parentheses\endcsname(##1){#3}%
		\expandafter\def\csname #1Braces\endcsname##1{#3}%
	\or	\expandafter\def\csname #1Parentheses\endcsname(##1,##2){#3}%
		\expandafter\def\csname #1Braces\endcsname##1##2{#3}%
	\or	\expandafter\def\csname #1Parentheses\endcsname(##1,##2,##3){#3}%
		\expandafter\def\csname #1Braces\endcsname##1##2##3{#3}%
	\or	\expandafter\def\csname #1Parentheses\endcsname(##1,##2,##3,##4){#3}%
		\expandafter\def\csname #1Braces\endcsname##1##2##3##4{#3}%
	\or	\expandafter\def\csname #1Parentheses\endcsname(##1,##2,##3,##4,##5){#3}%
		\expandafter\def\csname #1Braces\endcsname##1##2##3##4##5{#3}%
	\or	\expandafter\def\csname #1Parentheses\endcsname(##1,##2,##3,##4,##5,##6){#3}%
		\expandafter\def\csname #1Braces\endcsname##1##2##3##4##5##6{#3}%
	\or	\expandafter\def\csname #1Parentheses\endcsname(##1,##2,##3,##4,##5,##6,##7){#3}%
		\expandafter\def\csname #1Braces\endcsname##1##2##3##4##5##6##7{#3}%
	\or	\expandafter\def\csname #1Parentheses\endcsname(##1,##2,##3,##4,##5,##6,##7,##8){#3}%
		\expandafter\def\csname #1Braces\endcsname##1##2##3##4##5##6##7##8{#3}%
	\or	\expandafter\def\csname #1Parentheses\endcsname(##1,##2,##3,##4,##5,##6,##7,##8,##9){#3}%
		\expandafter\def\csname #1Braces\endcsname##1##2##3##4##5##6##7##8##9{#3}%
	\fi
}
\newcommand{\newvar}[3]{
	%
	\@ifundefined{#1}{}{\PackageError{newvar}{The variable #1 is already exists!}{Use renewvar to redefine existing variables.}}
	\renewvar{#1}{#2}{#3}
}
\makeatother

%
%
%
%
%
\newcommand{\convexcycle}[2]{
  [   
  create hullcoords/.code={
  	%
    \global\edef\namelist{#1}
    \foreach [count=\counter] \nodename in \namelist {
      \global\edef\numberofnodes{\counter}
      \coordinate (hullcoord\counter) at (\nodename);
    }
    %
    \coordinate (hullcoord0) at (hullcoord\numberofnodes);
    %
    \pgfmathtruncatemacro\lastnumber{\numberofnodes+1}
    \coordinate (hullcoord\lastnumber) at (hullcoord1);
  },
  create hullcoords
  ]
  %
  ($(hullcoord1)!#2!-90:(hullcoord0)$)
  \foreach [
  evaluate=\currentnode as \previousnode using \currentnode-1,
  evaluate=\currentnode as \nextnode using \currentnode+1
  ] \currentnode in {1,...,\numberofnodes} {
    let \p1 = ($(hullcoord\currentnode) - (hullcoord\previousnode)$),
    \n1 = {atan2(\y1,\x1)+90}, %
    \p2 = ($(hullcoord\nextnode) - (hullcoord\currentnode)$),
    \n2 = {atan2(\y2,\x2)+90}, %
    \n{delta} = {Mod(\n2-\n1,360) - 360}
    in 
    {arc [start angle=\n1, delta angle=\n{delta}, radius=#2]}
    -- ($(hullcoord\nextnode)!#2!-90:(hullcoord\currentnode)$)
  }
}
%
\makeatletter
\newcommand{\convexpath}[2]{
  [   
  create hullcoords/.code={
    \global\edef\namelist{#1}
    \foreach [count=\counter] \nodename in \namelist {
      \global\edef\numberofnodes{\counter}
      \coordinate (hullcoord\counter) at (\nodename);
    }
    \pgfmathtruncatemacro\lastnumber{\numberofnodes+1}
    \pgfmathtruncatemacro\lalalanumber{\numberofnodes-1}
    \coordinate (hullcoord\lastnumber) at (hullcoord1);
    \coordinate (hullstart) at ($(hullcoord2)!#2!-90:(hullcoord1)$);
    \path[name path=startline] (hullstart) -- ($(hullcoord1)!#2!90:(hullcoord2)$);
    \path[name path=endline] ($(hullcoord\numberofnodes)!#2!90:(hullcoord1)$) -- ($(hullcoord1)!#2!-90:(hullcoord\numberofnodes)$);
    \path[name intersections={of=startline and endline,total=\t}]
    	coordinate (hullcorner) at (intersection-1);
  },
  create hullcoords
  ]
  (hullcorner) -- (hullstart)
  \foreach [
  evaluate=\currentnode as \previousnode using \currentnode-1,
  evaluate=\currentnode as \nextnode using \currentnode+1
  ] \currentnode in {2,...,\lalalanumber} {
    let \p1 = ($(hullcoord\currentnode) - (hullcoord\previousnode)$),
    \n1 = {atan2(\y1,\x1) + 90},
    \p2 = ($(hullcoord\nextnode) - (hullcoord\currentnode)$),
    \n2 = {atan2(\y2,\x2) + 90},
    \n{delta} = {Mod(\n2-\n1,360) - 360}
    in 
    {arc [start angle=\n1, delta angle=\n{delta}, radius=#2]}
    -- ($(hullcoord\nextnode)!#2!-90:(hullcoord\currentnode)$) 
  }
  let \p1 = ($(hullcoord\numberofnodes) - (hullcoord\lalalanumber)$),
    \n1 = {atan2(\y1,\x1) + 90},
    \p2 = ($(hullcoord1) - (hullcoord\numberofnodes)$),
    \n2 = {atan2(\y2,\x2) + 90},
    \n{delta} = {Mod(\n2-\n1,360) - 360}
    in 
    {arc [start angle=\n1, delta angle=\n{delta}, radius=#2]}
    -- cycle
}
\makeatother

%

\definecolor{TUMblue}{RGB}{0,101,189} %
\definecolor{TUMivory}{RGB}{218,215,203}
\definecolor{TUMorange}{RGB}{227,114,34}

%
\definecolor{TUMred}{RGB}{189,0,6}
\definecolor{TUMyellow}{RGB}{189,183,0}

%
\definecolor{TUMgreen}{RGB}{101,189,0}
\definecolor{TUMmagenta}{RGB}{189,0,101}

\colorlet{quantileColor}{TUMblue}
\colorlet{medianColor}{TUMred}
\colorlet{quantileBack}{TUMivory!50!white}

%
\colorlet{Temp}{TUMblue!80!black}
\colorlet{Tcuts}{TUMblue!80!white}
\colorlet{3Bin}{TUMred}
\colorlet{1Bin}{TUMgreen}
\colorlet{1BinS}{TUMorange}


%
\input{pics/Common}

Notation.tex
%
%
%
%
%


%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%

\newcommand{\idx}{j}
\newcommand{\idxx}{k}
\renewcommand{\time}{\overline{t}}
\newcommand{\pivotalL}{\overline{\textup{ol}}}
\def\tau{{t'}}

%
\let\defaultCompany\empty
%
\DeclareRobustCommand{\nonDefaultCompany}[1]{%
\ifthenelse{\equal{#1}{\defaultCompany}}{}{%
		#1%
	}%
}
\DeclareRobustCommand{\nonDefaultCompanyKern}[2]{%
\ifthenelse{\equal{#1}{\defaultCompany}}{}{%
		#2\relax#1%
	}%
}
\newcommand{\nonEmptyKern}[2]{%
\ifthenelse{\isempty{#1}}{}{%
		#2\relax#1%
	}%
}

%
%
%
%
%

\newcommand{\Units}{\mkern-2mu\mathcal{I}\mkern-2mu}
\newcommand{\Periods}{[T]}
%
\newcommand{\maxTime}{T}
\newvar{periodLength}{1}{\textup{L}^{#1}}
\newvar{minProd}{1}{\underline{\textup{P}}_{\nonDefaultCompany{#1}}}
\newvar{maxProd}{1}{\overline{\textup{P}}_{\nonDefaultCompany{#1}}}
\newvar{heatingProd}{1}{\overline{\textup{HP}}_{\nonDefaultCompany{#1}}}
\newvar{heatingSpeed}{1}{\overline{\textup{H}}_{\nonDefaultCompany{#1}}}
\newvar{maxHeating}{2}{\overline{\textup{h}}_{\nonDefaultCompany{#1}}^{#2}}
\newvar{minUptime}{1}{\textup{UT}_{\nonDefaultCompany{#1}}}
\newvar{minDowntime}{1}{\textup{DT}_{\nonDefaultCompany{#1}}}
\newvar{initialOffline}{1}{\textup{IDT}_{\nonDefaultCompany{#1}}}
\newvar{initialOnline}{1}{\textup{IUT}_{\nonDefaultCompany{#1}}}
\newvar{rampup}{1}{\textup{RU}_{\nonDefaultCompany{#1}}}
\newvar{rampdown}{1}{\textup{RD}_{\nonDefaultCompany{#1}}}
\newvar{startupRamp}{1}{\textup{SU}_{\nonDefaultCompany{#1}}}
\newvar{shutdownRamp}{1}{\textup{SD}_{\nonDefaultCompany{#1}}}
\newvar{preOffline}{1}{\textup{PDT}_{\nonDefaultCompany{#1}}}

\newvar{StartupCostFunction}{2}{%
\textup{CU}_{\nonDefaultCompany{#1}}%
\ifthenelse{\isempty{#2}}{}{({#2})}%
}
\newvar{StartupCostFunctionTilde}{2}{%
\tilde{\textup{CU}}_{\nonDefaultCompany{#1}}%
\ifthenelse{\isempty{#2}}{}{\left({#2}\right)}%
}
\newvar{StartupCost}{3}{\textup{CU}_{\nonDefaultCompany{#1}}^{#2}\ifthenelse{\isempty{#3}}{}{({#3})}}
\newvar{StartupCostTilde}{3}{\tilde{\textup{CU}}_{\nonDefaultCompany{#1}}^{#2}\ifthenelse{\isempty{#3}}{}{({#3})}}
\newvar{ShutdownCost}{1}{\textup{CD}_{\nonDefaultCompany{#1}}}
\newvar{heatloss}{1}{\lambda_{#1}}
\newvar{heatingCost}{1}{V_{#1}}
\newvar{fixedStartupCost}{1}{F_{#1}}

\newvar{fuelType}{1}{\textup{F}_{\nonDefaultCompany{#1}}}
\newvar{fuelCost}{2}{\textup{FC}_{\nonDefaultCompany{#1}}^{#2}}
\newvar{varFuel}{1}{\textup{FA}_{#1}}
\newvar{fixedFuel}{1}{\textup{FB}_{#1}}
\newvar{varCost}{1}{\textup{PA}_{#1}}
\newvar{fixedCost}{1}{\textup{PB}_{#1}}
\newcommand{\StartupTol}{\textup{CU}_{\textup{tol}}}



%
%
%
%
%

\newvar{onOff}{2}{v^{\nonEmptyKern{#2}{\mkern2mu}}_{\nonDefaultCompanyKern{#1}{\mkern-2mu}}}
\newvar{tildeOnOff}{2}{\tilde{v}^{\nonEmptyKern{#2}{\mkern2mu}}_{\nonDefaultCompanyKern{#1}{\mkern-2mu}}}
\renewvar{prod}{2}{p_{\nonDefaultCompany{#1}}^{#2}}
\newvar{startupCost}{2}{\textup{cu}_{\nonDefaultCompany{#1}}^{#2}}
\newvar{tildeStartupCost}{2}{\tilde{\textup{cu}}_{\nonDefaultCompany{#1}}^{#2}}
\newvar{startupIndicator}{2}{\textup{sui}_{\nonDefaultCompany{#1}}^{#2}}
\newvar{tildeStartupIndicator}{2}{\tilde{\textup{sui}}_{\nonDefaultCompany{#1}}^{#2}}
\newvar{shutdownIndicator}{2}{\textup{sdi}_{\nonDefaultCompany{#1}}^{#2}}
\newvar{shutdownCost}{2}{\textup{cd}_{\nonDefaultCompany{#1}}^{#2}}
\newvar{startupType}{3}{\delta_{#1}^{#2}(#3)}
\newvar{temp}{2}{\textup{temp}_{#1}^{#2}}
\newvar{heating}{2}{h_{#1}^{#2}}\newvar{prodCost}{2}{\textup{cp}_{\nonDefaultCompany{#1}}^{#2}}

%
%
%
\newvar{startupIndicatorFunc}{1}{\textup{sui}_{\onOff(i,)}^{#1}}
\newvar{tildeStartupIndicatorFunc}{1}{\tilde{\textup{sui}}_{\tildeOnOff(i,)}^{#1}}
\newvar{shutdownIndicatorFunc}{1}{\textup{sdi}_{\onOff(i,)}^{#1}}
\newvar{tildeShutdownIndicatorFunc}{1}{\tilde{\textup{sdi}}_{\tildeOnOff(i,)}^{#1}}
\newvar{startupCostFunc}{1}{\textup{cu}_{\onOff(i,)}^{#1}}
\newvar{tildeStartupCostFunc}{1}{\tilde{\textup{cu}}_{\tildeOnOff(i,)}^{#1}}

%
%
%
\newvar{offlineNumber}{2}{\textup{ol}^{#1}\ifthenelse{\isempty{#2}}{}{(#2)}}
\newvar{offlineNumberRight}{2}{\textup{or}^{\mkern2mu #1}(#2)}
\newvar{offlineFromTo}{2}{\textup{OL}(#1\textvisiblespace[1.5ex]#2)}
\newvar{offlineLength}{2}{\textup{OL}^{#1}\ifthenelse{\isempty{#2}}{}{(#2)}}
\newvar{offlineLengthTree}{1}{\textup{OL}(#1)}
\renewvar{offlineFromTo}{2}{\textup{L}_{#1,#2}}



%
%
%
%
%

%
\newvar{DiscreteStartupCost}{2}{\textup{DCU}_{\nonDefaultCompany{#1}}^{#2}}
\newcommand{\StartupCostIndividual}{\textup{LCU}_{\nonDefaultCompany{i}}^t}
\newcommand{\sciEpigraph}{\epi(\StartupCostIndividual)}
\newcommand{\sciPolyhedron}{{P^t}}
\newcommand{\sciVertices}{{V^t}}
\newcommand{\sciProj}{\pi^t}

%
\newcommand{\DiscreteStartupCostSum}{\textup{DCU}_{\nonDefaultCompany{i}}^\Sigma}
\newcommand{\StartupCostSum}{\textup{LCU}_{\nonDefaultCompany{i}}^\Sigma}
\newcommand{\startupCostSum}{\startupCost(i,\Sigma)}
\newcommand{\tildeStartupCostSum}{\tilde{\startupCost}(i,\Sigma)}
\newcommand{\scsEpigraph}{\epi(\StartupCostSum)}
\newcommand{\scsVertices}{{V^{\Sigma}}}
\newcommand{\scsBinaryTrees}{{\mathcal{B}}}
\newcommand{\scsSumDiff}[1]{\delta^{#1}}
\newvar{bticoeff}{1}{\alpha_{\mkern2mu #1}}

%
%
%
%
%

\newcommand{\newTreeFunction}[2]{
	\newvar{#1T}{2}{{#2}^{##1}\ifthenelse{\isempty{##2}}{}{(##2)}}
	\newvar{#1}{1}{{#2}\ifthenelse{\isempty{##1}}{}{(##1)}}
}

%
\newTreeFunction{depth}{d}
\newTreeFunction{rank}{\textup{rank}}
\newvar{rankInv}{1}{\textup{rank}^{-1}\ifthenelse{\isempty{#1}}{}{(#1)}}

%
\newTreeFunction{subtree}{S}
\newTreeFunction{size}{s}
\newTreeFunction{leftSubtree}{L}
\newTreeFunction{leftSize}{l}
\newTreeFunction{rightSubtree}{R}
\newTreeFunction{rightSize}{r}
\newcommand{\oneSubtree}[2][B]{#1({#2})}

%
\let\root\relax
\newvar{root}{1}{\textup{root}\ifthenelse{\isempty{#1}}{}{(#1)}}
\newTreeFunction{parent}{p}
\newTreeFunction{leftChild}{\textup{llink}}
\newTreeFunction{rightChild}{\textup{rlink}}

%
\newvar{topleftT}{2}{\mu^{#1}_{#2}}
\newvar{topleft}{1}{\topleftT{}{#1}}
\newcommand{\topleftN}{\depth(1)+1}
\newvar{toprightT}{2}{\eta^{#1}_{#2}}
\newvar{topright}{1}{\toprightT{}{#1}}
\newcommand{\toprightN}{{\depth(T)+1}}


%
%
%
%
%

\colorlet{onOffColor}{green}
\colorlet{onOffText}{green!50!black}
\colorlet{onOffBack}{green!20}

\colorlet{prodColor}{blue}
\colorlet{prodText}{blue!80!black}

\colorlet{tempColor}{red}
\colorlet{tempText}{red!80!black}

\colorlet{fuelNeedColor}{red}
\colorlet{efficiencyColor}{blue}

\colorlet{cooling}{blue!70!green}
\colorlet{coolingBack}{cooling!8!white}
\colorlet{coolingText}{cooling!80!black}
\colorlet{heating}{red}
\colorlet{heatingBack}{red!8!white}
\colorlet{heatingText}{red!70!black}



%
%
%
%
%

\newcommand{\forallPeriods}{\forall\, t \in \Periods}
\newcommand{\forallUnitsPeriods}{\forall\, i \in \Units, t \in \Periods}
\newcommand{\forallUnits}{\forall\, i \in \Units}

\makeatletter
\newcommand{\@rr}{ep\-re\-sen\-ta\-tion}
\newcommand{\@mc}[1]{\texorpdfstring{$\mathcal{#1}$}{#1}}
\newcommand{\hrepresentation}{\@mc{H}-r\@rr\xspace}
\newcommand{\Hrepresentation}{\@mc{H}-R\@rr\xspace}
\newcommand{\hrepresentations}{\@mc{H}-r\@rr s\xspace}
\newcommand{\Hrepresentations}{\@mc{H}-R\@rr s\xspace}
\newcommand{\vrepresentation}{\@mc{V}-r\@rr\xspace}
\newcommand{\Vrepresentation}{\@mc{V}-R\@rr\xspace}
\newcommand{\vrepresentations}{\@mc{V}-r\@rr s\xspace}
\newcommand{\Vrepresentations}{\@mc{V}-R\@rr s\xspace}
\makeatother


Paper.tex
\documentclass[headings=small]{scrartcl}
\pdfoutput=1

\newcommand{\textwidthScaling}{0.98}
\newcommand{\textwidthScalingInv}{1.041666667}

\input{Header}
\input{Notation}

\usepackage{multicol}

\usepackage[a4paper,text={36.526315789em,230mm},heightrounded]{geometry}

\begin{document}

\author{Ren\'e Brandenberg\thanks{brandenb@ma.tum.de, Department of Mathematics} \and Matthias Huber\thanks{matthias.huber@tum.de, Department of Electrical and Computer Engineering} \and Matthias Silbernagl\thanks{silbernagl@tum.de, Department of Mathematics \newline The authors are with the Technische Universit\"at M\"unchen, 80333 M\"unchen, Germany.}}

\title{The Summed Start-up Costs in a Unit Commitment Problem}

\date{Preprint, 4.3.2015}

\maketitle

\input{sections/Abstract}
\input{sections/IntroductionGeneral}
\input{sections/IntroductionSpecific}
\input{sections/Lifting}
\input{sections/BinaryTrees}
\input{sections/BTI}
\input{sections/Sufficiency}
\input{sections/Separation}
\input{sections/Experiments}
\input{sections/Conclusion}

\bibliographystyle{apalike}
\bibliography{refs}

\end{document}

pgfcorearrows.code.tex
% Copyright 2006, 2013 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/basiclayer/pgfcorearrows.code.tex,v 1.40 2013/11/07 15:45:46 tantau Exp $



% Define a new (meta) arrow or a shorthand
%
% #1 = key--value pairs
%
% Description:
%
% This command is used to define a new arrow tip kind. For more
% details on the description of the keys, please see the pgfmanual.
% 
% name         = Name of the arrow. If the name contains a dash
%                (hyphen), the text before the hyphen is the start name
%                and the text behind it the end name.
%
% means        = If set, none of the below options may be
%                given. The effect is that whenever the arrow is
%                used, it gets replaced by this "text", which is
%                parsed by the parser.
%
% setup code   = Code that does "precomputations". These will be
%                executed only once for each combination of the
%                dependencies. At the end of this code, you can use
%                \savethe and \save to "save" computed values, which
%                will then be available inside the "code". Values needed
%                only for the "... end" keys and the convex hull do not
%                need to be saved since these are also executed only
%                once. 
% drawing code = Code for drawing the arrow. When the cache key is set to
%                true, which is the default, the code will be protocolled
%                and the resulting code is inserted using \pgflowlevelobj.
% cache        = Boolean that decides whether the arrow can be cached. The
%                default is true, so you have to say cache=false to switch
%                caching off. In this case, each time the arrow is drawn,
%                its code is simply executed. This allows you to put things
%                like text or shadings in arrow tips.
% bending mode = Can be set to "orthogonal", "polar", or
%                "none". Defaults to "orthogonal".
% defaults     = A list of "default" options for the arrow tip. These
%                are executed as if they were given to the arrow tip in
%                brackets. This is useful for setting up default values.
% parameters   = A list of comma-separated macro names on whose values
%                the appearance of the arrow tip depends. When an arrow
%                tip is used, these macros are expanded. If an
%                arrow tip was already installed with the same macro
%                names (and caching is true), the cached code is
%                used. Note that when you use dimensions here, add \the.
%               
% Inside the setup code, the following macros are available:               
%
% \pgfarrowsettipend
%              The code should draw an arrow pointing "right along the x
%              axis". The "tip" key specifies how far the arrow goes
%              along the x axis, that is, it should be the x coordinate
%              of the very tip of the arrow. In previous versions this
%              was called the "right extend". The value passed to this
%              key should be some code that sets the dimension
%              "\pgfarrowresult", which is \let to be equal to
%              \pgf@x. A \relax will be added after the code provided
%              here, so you can write things like "\pgfarrowresult=1pt".
% \pgfarrowsetbackend
%              The leftmost x-coordinate that is still part of the
%              arrow tip (the "back end" of the arrow"). This coordinate
%              will be used when multiple arrow tips are
%              composed. Defaults to 0pt.
% \pgfarrowsetlineend
%              The x-coordinate where a line should stop inside the arrow
%              tip so that it gets "obscured" by the arrow. Defaults to 0pt.
% \pgfarrowsetvisualtipend
%              When the arrow tip is drawn in flex mode, it is rotated
%              such that the x-coordinates of "visual tip end" and "visual
%              back end" lie on the path. Defaults to \pgfarrowsettipend.
% \pgfarrowsetvisualbackend
%              See above. Defaults to \pgfarrowsetbackend

\def\pgfdeclarearrow#1{%
  \let\pgf@decl@arrow@defaults\pgfutil@empty%
  \let\pgf@decl@arrow@means\relax%
  \let\pgf@decl@arrow@code\relax%
  \pgfkeys{/pgf/@arrows decl/.cd,
    name=,
    setup code=,
    cache=true,
    bending mode=orthogonal,
    parameters=,%
    #1%
  }%
  \ifx\pgf@decl@arrow@name@end\pgfutil@empty%
    \pgferror{Declaring unnamed arrow}%
  \else%
    \pgf@arrow@letter{name@end}%
    \pgf@arrow@letter{name@start}%
    \expandafter\let\csname pgf@ar@start@\pgf@decl@arrow@name@start\endcsname\pgf@decl@arrow@name@end%
    \expandafter\let\expandafter\pgf@old@code\csname pgf@ar@code@\pgf@decl@arrow@name@end\endcsname%
    \expandafter\let\expandafter\pgf@old@means\csname pgf@ar@means@\pgf@decl@arrow@name@end\endcsname%
    \ifx\pgf@decl@arrow@code\relax%
      \ifx\pgf@decl@arrow@means\relax%
        \pgferror{You must set either the 'means' or the drawing code' keys for arrow tip '\pgf@decl@arrow@name@end'}%
      \else%
        \ifx\pgf@old@code\relax%
          \let\pgf@arrow@tip@sequence\pgfutil@empty%
          \let\pgf@arrow@translate\relax%
          \expandafter\let\expandafter\pgf@arrows@direct\csname pgf@arrows@direct@name@end@\pgf@decl@arrow@means\endcsname%
          \ifx\pgf@arrows@direct\relax%
            \let\pgf@arrows@options\pgfutil@empty%
            \expandafter\pgfarrows@initial@parser\pgf@decl@arrow@means[]\pgf@stop%
          \else%
            \let\pgf@arrow@tip@sequence\pgf@arrows@direct%
          \fi%
          \pgf@arrow@letter@\pgf@arrow@tip@sequence{means}%
          \expandafter\let\csname pgf@ar@code@\pgf@decl@arrow@name@end\endcsname\relax%
        \else%
          \pgferror{Arrow tip '\pgf@decl@arrow@name@end' was already
            defined with key 'drawing code' previously and you cannot change this}%
        \fi%
      \fi%
    \else%
      \ifx\pgf@decl@arrow@means\relax%
        \ifx\pgf@old@means\relax%
          \pgf@arrow@letter{code}%
          \pgf@arrow@letter{defaults}%
          \pgf@arrow@letter{setup}%
          \pgf@arrow@letter{bending@mode}%
          \pgf@arrow@letter{par}%
          \expandafter\let\csname pgf@ar@do@cache@\pgf@decl@arrow@name@end\endcsname\pgf@decl@arrow@cache%
        \else%
          \pgferror{Arrow tip '\pgf@decl@arrow@name@end' was already
            defined with key 'means' previously and you cannot change this}%          
        \fi%
      \else%
        \pgferror{You cannot set both the 'means' and also the 'drawing code' 
          keys for arrow tip '\pgf@decl@arrow@name@end'}%
      \fi%
    \fi%
  \fi%
}

\def\pgf@arrow@letter#1{%
  \expandafter\pgf@arrow@letter@\expandafter{\csname pgf@decl@arrow@#1\endcsname}{#1}%
}
\def\pgf@arrow@letter@#1#2{%
  \expandafter\let\csname pgf@ar@#2@\pgf@decl@arrow@name@end\endcsname#1%
}

\pgfkeys{
  /pgf/@arrows decl/.cd,
  name/.code={%
    \pgfutil@in@-{#1}%
    \ifpgfutil@in@%
      \pgf@arrows@name@decomp#1\pgf@stop%
    \else%
      \def\pgf@decl@arrow@name@end{#1}\let\pgf@decl@arrow@name@start\pgf@decl@arrow@name@end%
    \fi},
  means/.store in=\pgf@decl@arrow@means,
  setup code/.store in=\pgf@decl@arrow@setup,
  drawing code/.store in=\pgf@decl@arrow@code,
  cache/.store in=\pgf@decl@arrow@cache,
  bending mode/.is choice,
  bending mode/none/.code=\let\pgf@decl@arrow@bending@mode\pgfutil@empty,
  bending mode/orthogonal/.code=\def\pgf@decl@arrow@bending@mode{\pgfpointcurvilinearbezierorthogonal},
  bending mode/polar/.code=\def\pgf@decl@arrow@bending@mode{\pgfpointcurvilinearbezierpolar},
  parameters/.store in=\pgf@decl@arrow@par,
  defaults/.code={%
    \let\pgf@arrows@options\pgfutil@empty%
    \pgfkeys{/pgf/arrow keys/.cd,#1}%
    \let\pgf@decl@arrow@defaults\pgf@arrows@options%
  }
}

\def\pgf@arrows@name@decomp#1-#2\pgf@stop{%
  \def\pgf@decl@arrow@name@start{#1}%
  \def\pgf@decl@arrow@name@end{#2}%
}


% Handler for defining arrow tips:
% 
% Description:
% 
% When you write "my name/.tip = arrow spec", this has the same
% effect as writeing \pgfdeclarearrow{name = my name, means = arrow spec}.

\pgfkeys{/handlers/.tip/.code=%
  \expandafter\expandafter\expandafter\pgf@arrows@unravel\pgfkeyscurrentpath/\pgf@stop%
  \expandafter\pgf@arrows@key@call\expandafter{\pgf@arrows@unravelled}{#1}}
\def\pgf@arrows@unravel#1/{\pgfutil@ifnextchar\pgf@stop{\def\pgf@arrows@unravelled{#1}\pgfutil@gobble}{\pgf@arrows@unravel}}
\def\pgf@arrows@key@call#1#2{\pgfdeclarearrow{name={#1},means={#2}}}




% Draw an arrow
% 
% #1 = arrow specification
% 
% Description:
% 
% Draws the arrow in the given specification (and "end"
% specification). The arrow will be drawn such that it touches the
% origin "from the left", that is, the arrow will lie completely in
% the half plane with negative $x$ values and the tip will end exactly
% at the origin.

\def\pgfarrowdraw#1{%
  {%
    \pgfsetarrowsend{#1}%
    \pgf@arrow@compute@shortening\pgf@end@tip@sequence%
    \pgf@arrow@draw@arrow\pgf@end@tip@sequence\pgf@xb%
  }%
}



% Compute the length of an arrow
% 
% #1 = arrow specification
% 
% Description:
% 
% In \pgf@x, this will return the total length of the arrow given as
% #1, in \pgf@xa it will return the distance from the tip to the line
% end. 

\def\pgfarrowtotallength#1{%
  {%
    \pgfsetarrowsend{#1}%
    \pgf@arrow@compute@shortening\pgf@end@tip@sequence%
    \expandafter\expandafter\expandafter%
  }%
  \expandafter\expandafter\expandafter\pgf@x\expandafter\the\expandafter\pgf@xb\expandafter\pgf@xa\the\pgf@xa%
}





% Sets the end arrow tip
%
% #1 = An arrow specification
%
% Description:
% 
% An "arrow specification" is a sequence of names of meta arrow tips
% together with options in brackets. In detail:
% 
% In #1, consider the text from the start up to the first bracket. If
% this text is the name of a (meta) arrow tip, we use this arrow tip
% with the provided options. If it is the name of a arrow tip
% shorthand, this shorthand is expanded and the options are applied to
% each arrow tip inside the shorthand. If the text is neither or the
% above, the first letter of text is treated as a shorthand without
% options.
% 
% The special arrow tip "." is used to indicate the end of the line. 
%
% \pgfsetarrowsend{stealth[reversed]}
% \pgfsetarrowsend{stealth[length=1pt] . stealth[length=2pt]}
% \pgfsetarrowsend{>>>}
% \pgfsetarrowsend{>.>}

\def\pgfsetarrowsend#1{%
  \let\pgf@arrow@tip@sequence\pgfutil@empty%
  \pgf@arrows@translatefalse%
  \expandafter\let\expandafter\pgf@arrows@direct\csname pgf@arrows@direct@name@end@#1\endcsname%
  \ifx\pgf@arrows@direct\relax%
    \edef\pgf@marshal{\noexpand\pgfarrows@initial@parser#1[]\noexpand\pgf@stop}%
    \pgf@marshal%
  \else%
    \let\pgf@arrow@tip@sequence\pgf@arrows@direct%
  \fi%
  \let\pgf@end@tip@sequence\pgf@arrow@tip@sequence%
}

\newif\ifpgf@arrows@translate

\def\pgfarrows@initial@parser{%
  \pgfutil@ifnextchar[\pgfarrows@initial@parser@{\pgfarrows@initial@parser@[]}}%}

\def\pgfarrows@initial@parser@[#1]{%
  \let\pgf@arrows@options\pgfutil@empty%
  \pgfkeys{/pgf/arrow keys/.cd,#1}%
  \let\pgf@arrows@options@initial\pgf@arrows@options%
  \pgfarrows@parser%
}

\def\pgfarrows@parser#1[{%
  \pgfkeys@spdef\pgf@temp{#1}%
  \ifx\pgf@temp\pgfutil@empty%
    \let\pgf@next\pgf@arrows@empty%
  \else%
    \ifx\pgf@temp\pgf@dot@text%
      \let\pgf@next\pgf@arrows@dot@parsed%
    \else%
      \let\pgf@untranslated\pgf@temp%
      \ifpgf@arrows@translate%
        \pgf@arrow@swapper%
      \fi%
      % Now, let's see what we do with this...
      \expandafter\ifx\csname pgf@ar@code@\pgf@temp\endcsname\relax
        \expandafter\ifx\csname pgf@ar@means@\pgf@temp\endcsname\relax
          % #1 should start with a single-char shorthands
          \let\pgf@next\pgf@arrows@single@char@parser%
          \let\pgf@temp\pgf@untranslated%
        \else%
          % #1 is a shorthand!
          \let\pgf@next\pgf@arrows@shorthand@parsed%
        \fi%
      \else%
        % #1 is a meta arrow!
        \let\pgf@next\pgf@arrows@meta@parsed%
      \fi%
    \fi%
  \fi%
  \expandafter\pgf@next\pgf@temp[%  
}

\def\pgf@arrows@empty[#1]{%
  \pgfutil@ifnextchar\pgf@stop\pgf@arrows@parser@done\pgfarrows@parser%  
}

\def\pgf@arrows@single@char@parser#1{%
  \def\pgf@temp{#1}%
  \ifx\pgf@temp\pgf@dot@text%
    \let\pgf@next\pgf@arrows@dot@parsed%
  \else%
    \let\pgf@untranslated\pgf@temp%
    \ifpgf@arrows@translate%
      \pgf@arrow@swapper%
    \fi%
    \expandafter\ifx\csname pgf@ar@code@\pgf@temp\endcsname\relax
      \expandafter\ifx\csname pgf@ar@means@\pgf@temp\endcsname\relax
        \let\pgf@temp\pgf@untranslated%
        \let\pgf@next\pgf@arrows@unknown%
      \else%
        \let\pgf@next\pgf@arrows@shorthand@parsed%  
      \fi%
    \else%
      \let\pgf@next\pgf@arrows@meta@parsed%  
    \fi
  \fi
  \expandafter\pgf@next\pgf@temp[]%  
}
\def\pgf@arrows@unknown#1[]#2[#3]{%
  \pgferror{Unknown arrow tip kind '#1#2'}%
}

\def\pgf@arrows@meta@parsed#1[#2]{%
  % Ok, run the keys #2. This will add commands to \pgf@arrows@options:
  % 
  \let\pgf@arrows@options\pgf@arrows@options@initial%
  \pgfkeys{/pgf/arrow keys/.cd,#2}%
  % Append the arrow and its options to the arrow tip sequence:
  \expandafter\pgf@arrows@meta@set\expandafter{\pgf@arrows@options}{#1}{\pgf@arrow@handle}%
  \pgfutil@ifnextchar\pgf@stop\pgf@arrows@parser@done\pgfarrows@parser%  
}

\def\pgf@arrows@parser@done#1{%
}

\def\pgf@arrows@dot@parsed#1[#2]{%
  \pgf@arrows@append@to@tips{\pgf@arrow@handle@dot}%
  \pgfutil@ifnextchar\pgf@stop\pgf@arrows@parser@done\pgfarrows@parser%  
}

\def\pgf@arrows@meta@set#1#2#3{%
  \pgf@arrows@append@to@tips{#3{#2}{#1}}%
}
\def\pgf@arrows@append@to@tips#1{%
  \let\pgf@tempa\pgf@arrow@tip@sequence%
  \def\pgf@tempb{#1}%
  \ifpgf@arrows@translate%
    \let\pgf@tempa\pgf@tempb%
    \let\pgf@tempb\pgf@arrow@tip@sequence%
  \fi%
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\pgf@arrow@tip@sequence%
  \expandafter\expandafter\expandafter{\expandafter\pgf@tempa\pgf@tempb}%  
}

\def\pgf@arrows@shorthand@parsed#1[#2]{%
  \let\pgf@arrows@options\pgf@arrows@options@initial%
  \pgfkeys{/pgf/arrow keys/.cd,#2}%
  \ifx\pgf@arrows@options\pgfutil@empty%
    \expandafter\pgf@arrows@append@to@tips\expandafter{%
      \expandafter\pgf@arrow@handle@shorthand@empty\expandafter{\csname pgf@ar@means@#1\endcsname}}%
  \else%
    \expandafter\expandafter\expandafter\pgf@arrows@meta@set\expandafter\expandafter\expandafter{%
      \expandafter\pgf@arrows@options\expandafter}\expandafter{\csname pgf@ar@means@#1\endcsname}{\pgf@arrow@handle@shorthand}%
  \fi%
  \pgfutil@ifnextchar\pgf@stop\pgf@arrows@parser@done\pgfarrows@parser%  
}


% General handler:

\def\pgf@arrow@handle@shorthand@empty#1{#1}

\def\pgf@arrow@handle@shorthand#1#2{%
  \def\pgf@temp@opt{#2}%
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\pgf@arrows@nested@options@temp%
  \expandafter\expandafter\expandafter{\expandafter\pgf@temp@opt\pgf@arrows@nested@options}%
  \expandafter\let\expandafter\pgf@arrows@nested@options\expandafter\pgf@arrows@nested@options@temp%
  \expandafter#1% all these expandafters to avoid creating groups, but having the options nest
  \expandafter\def\expandafter\pgf@arrows@nested@options\expandafter{\pgf@arrows@nested@options}%
}

\let\pgf@arrows@nested@options\pgfutil@empty




% Sets the start arrow tip
%
% #1 = An arrow specification
%
% Description:
% 
% This works like \pgfsetarrowsend, only the order of the tips in the
% arrow specification is reversed and the "reversed names" are used.
%
% \pgfsetarrowsend{<<}
% \pgfsetarrowsend{>.>}

\def\pgfsetarrowsstart#1{%
  \let\pgf@arrow@tip@sequence\pgfutil@empty%
  \pgf@arrows@translatetrue%
  \expandafter\let\expandafter\pgf@arrows@direct\csname pgf@arrows@direct@name@start@#1\endcsname%
  \ifx\pgf@arrows@direct\relax%
    \edef\pgf@marshal{\noexpand\pgfarrows@initial@parser#1[]\noexpand\pgf@stop}%
    \pgf@marshal%
  \else%
    \let\pgf@arrow@tip@sequence\pgf@arrows@direct%
  \fi%
  \let\pgf@start@tip@sequence\pgf@arrow@tip@sequence%
}

\def\pgf@arrow@swapper{%
  \expandafter\let\expandafter\pgf@temp\csname pgf@ar@start@\pgf@temp\endcsname%
  \ifx\pgf@temp\relax%
    \def\pgf@temp{undefined}%
  \fi%
}

\let\pgf@start@tip@sequence\pgfutil@empty
\let\pgf@end@tip@sequence\pgfutil@empty


\expandafter\def\csname pgf@arrows@direct@name@start@\endcsname{}
\expandafter\def\csname pgf@arrows@direct@name@end@\endcsname{}


% Predefined lengths and ifs

\newdimen\pgfarrowsep

\newif\ifpgfarrowswap
\newif\ifpgfarrowreversed
\newif\ifpgfarrowharpoon
\newif\ifpgfarrowopen

\let\pgf@arrows@stroke@color\pgfutil@empty
\let\pgf@arrows@fill@color\pgfutil@empty

\def\pgfarrows@length@scale{1}
\def\pgfarrows@width@scale{1}
\def\pgfarrows@slant{0}

\let\pgfarrows@scale@list\pgfutil@empty
\def\pgfarrowsaddtolengthscalelist#1{\expandafter\def\expandafter\pgfarrows@scale@list\expandafter{\pgfarrows@scale@list#1\pgfarrows@length@scale#1}}
\def\pgfarrowsaddtowidthscalelist#1{\expandafter\def\expandafter\pgfarrows@scale@list\expandafter{\pgfarrows@scale@list#1\pgfarrows@width@scale#1}}

\pgfkeys{
  /pgf/arrow keys/.cd,
  scale/.code={%
    \pgfmathparse{#1}%
    \expandafter\pgfarrowsaddtooptions\expandafter{\expandafter\def\expandafter\pgfarrows@length@scale\expandafter{\pgfmathresult}}%
    \expandafter\pgfarrowsaddtooptions\expandafter{\expandafter\def\expandafter\pgfarrows@width@scale\expandafter{\pgfmathresult}}%
  },
  scale length/.code={\pgfmathparse{#1}\expandafter\pgfarrowsaddtooptions\expandafter{\expandafter\def\expandafter\pgfarrows@length@scale\expandafter{\pgfmathresult}}},
  scale width/.code={\pgfmathparse{#1}\expandafter\pgfarrowsaddtooptions\expandafter{\expandafter\def\expandafter\pgfarrows@width@scale\expandafter{\pgfmathresult}}},
  slant/.code={\pgfmathparse{#1}\expandafter\pgfarrowsaddtooptions\expandafter{\expandafter\def\expandafter\pgfarrows@slant\expandafter{\pgfmathresult}}},
  sep/.code={
    \pgfarrowsthreeparameters{#1}%
    \expandafter\pgfarrowsaddtooptions\expandafter{\expandafter\pgfarrowslinewidthdependent\pgfarrowstheparameters\pgfarrowsep\pgf@x}%
  },
  sep/.default=0.88pt .3 1,
  %
  swap/.code=\pgfarrowsaddtooptions{\ifpgfarrowswap\pgfarrowswapfalse\else\pgfarrowswaptrue\fi},
  reversed/.code=\pgfarrowsaddtooptions{\ifpgfarrowreversed\pgfarrowreversedfalse\else\pgfarrowreversedtrue\fi},
  harpoon/.is choice,
  harpoon/.default=true,
  harpoon/true/.code=\pgfarrowsaddtooptions{\pgfarrowharpoontrue},
  harpoon/false/.code=\pgfarrowsaddtooptions{\pgfarrowharpoonfalse},
  left/.style={harpoon},
  right/.style={harpoon,swap},
  %
  color/.code=\pgfarrowsaddtooptions{\def\pgf@arrows@stroke@color{#1}},
  fill/.code={%
    \def\pgf@temp{#1}%
    \ifx\pgf@temp\pgf@nonetext%
      \pgfarrowsaddtooptions{\pgfarrowopentrue}
    \else
      \pgfarrowsaddtooptions{\pgfarrowopenfalse\def\pgf@arrows@fill@color{#1}}
    \fi
  },
  fill/.value required,
  open/.style={fill=none},
  .unknown/.code={ 
    \expandafter\pgfutil@in@\expandafter!\expandafter{\pgfkeyscurrentname}%
    \ifpgfutil@in@%
      % this is a color!
      \expandafter\pgfarrowsaddtooptions\expandafter{\expandafter\def\expandafter\pgf@arrows@stroke@color\expandafter{\pgfkeyscurrentname}}%
    \else%
      \pgfutil@doifcolorelse{\pgfkeyscurrentname}
      {%     
        \expandafter\pgfarrowsaddtooptions\expandafter{\expandafter\def\expandafter\pgf@arrows@stroke@color\expandafter{\pgfkeyscurrentname}}%
      }
      {%
        \edef\pgf@temp{\pgfkeyscurrentname}%
        \pgfkeys{/errors/unknown key/.expand once=\expandafter{\pgf@temp}{#1}}%
      }
      \fi
    }
}
\def\pgf@nonetext{none}

\def\pgfarrowsaddtooptions#1{\expandafter\def\expandafter\pgf@arrows@options\expandafter{\pgf@arrows@options#1}}
\def\pgfarrowsaddtolateoptions#1{\expandafter\def\expandafter\pgf@arrows@options\expandafter{\pgf@arrows@options\pgf@arrows@add@to@late@options{#1}}}
\def\pgf@arrows@add@to@late@options#1{\expandafter\def\expandafter\pgf@arrows@late@options\expandafter{\pgf@arrows@late@options#1}}



\def\pgfarrowsthreeparameters#1{%
  \pgfarrowsthreeparameters@#1 +0 +0 +0 \pgf@stop%
}
\def\pgfarrowsthreeparameters@#1 #2 #3 #4\pgf@stop{%
  \pgfmathsetlength\pgf@x{#1}%
  \pgfmathsetmacro\pgf@temp@a{#2}%
  \pgfmathsetmacro\pgf@temp@b{#3}%
  \edef\pgfarrowstheparameters{{\the\pgf@x}{\pgf@temp@a}{\pgf@temp@b}}%
}

\def\pgfarrowsfourparameters#1{%
  \pgfarrowsfourparameters@#1 +0 +0 +0 \pgf@stop%
}
\def\pgfarrowsfourparameters@#1:#2 #3 #4 #5\pgf@stop{%
  \pgfmathsetmacro\pgf@temp@z{#1}%
  \pgfmathsetlength\pgf@x{#2}%
  \pgfmathsetmacro\pgf@temp@a{#3}%
  \pgfmathsetmacro\pgf@temp@b{#4}%
  \edef\pgfarrowstheparameters{{\pgf@temp@z}{\the\pgf@x}{\pgf@temp@a}{\pgf@temp@b}}%
}

\def\pgfarrows@angle@setup#1#2#3#4{%
  \pgfarrowslinewidthdependent{#2}{#3}{#4}
  \pgf@xc\pgf@x
  \pgf@yc#1 pt%
  \pgf@yc.5\pgf@yc%
  \pgfpointpolar{\pgf@yc}{\pgf@xc}
  \pgfarrowlength\pgf@x%
  \pgf@y2\pgf@y%
  \expandafter\pgf@arrows@add@to@late@options\expandafter{\expandafter\pgfarrowwidth\the\pgf@y}%
}

\def\pgfarrows@angle@setup@prime#1{%
  \pgf@yc#1 pt%
  \pgfmathtan@{.5\pgf@yc}%
  \pgfarrowwidth\pgfmathresult\pgfarrowlength%
  \pgfarrowwidth2\pgfarrowwidth%
}

\def\pgfarrowslinewidthdependent#1#2#3{%
  \pgf@x#1%
  \ifdim\pgfinnerlinewidth>0pt%
    \pgf@arrows@inner@line@width@dep{#2}{#3}%
  \else%  
    \advance\pgf@x by#2\pgflinewidth%
  \fi%
}
\def\pgf@arrows@inner@line@width@dep#1#2{%
  % #1*((1-#2/2)*full line width - (#2/2) * inner line width)
  % Compute "real" line width
  \pgf@xa\pgflinewidth%
  \pgf@xb-.5\pgflinewidth%
  \pgf@xb#2\pgf@xb%
  \advance\pgf@xa by\pgf@xb%
  \pgf@xb\pgfinnerlinewidth%
  \pgf@xb-.5\pgf@xb
  \advance\pgf@xa by#2\pgf@xb%
  \advance\pgf@x by#1\pgf@xa%
}


\def\pgfarrowslengthdependent#1#2#3#4{%
  #4#1%
  \advance#4by#2\pgfarrowlength%
  \advance#4by#3\pgflinewidth%
}



% Build the full name:

\def\pgf@arrow@fullname#1{pgf@@ar@#1@\the\pgflinewidth @\pgfinnerlinewidth @\ifpgfarrowreversed r\fi @\pgf@arrows@stroke@color @\pgf@arrows@fill@color @\csname pgf@ar@par@#1\endcsname}
\def\pgf@arrow@id@count{0}%

% Compute the arrow id of an arrow
% 
% #1 = arrow name
% #2 = options
% 
% Description:
% 
% Returns the an id in \pgf@arrow@id that identifies the instantiation
% of the given arrow. If the arrow was not instantiated, this happens now.

\def\pgfarrows@getid#1#2{%
  % Execute options:
  \let\pgf@arrows@late@options\pgfutil@empty%
  % 1. Defaults:
  \csname pgf@ar@defaults@#1\endcsname%
  % 2. Scope:
  \pgf@arrows@options@scope
  % 3. Local:
  #2\relax%
  % 4. Nested:
  \pgf@arrows@nested@options% 
  % 5. Last options:
  \pgf@arrows@late@options%
  % 6. Scaling:
  \pgfarrows@scale@list%
  % Now, test:
  \expandafter\global\expandafter\let\expandafter\pgf@arrow@id\csname\pgf@arrow@fullname{#1}\endcsname\relax%
  \ifx\pgf@arrow@id\relax%
    \pgf@arrows@instantiate{#1}
  \fi%
}

\def\pgf@arrows@instantiate#1{%
  % Not defined. Rats!
  % Allocate new id:
  \pgfutil@tempcnta\pgf@arrow@id@count\relax%
  \advance\pgfutil@tempcnta by1\relax%
  \xdef\pgf@arrow@id@count{\the\pgfutil@tempcnta}%
  \expandafter\global\expandafter\let\csname\pgf@arrow@fullname{#1}\endcsname\pgf@arrow@id@count%
  \global\let\pgf@arrow@id\pgf@arrow@id@count%
  {%
    \csname pgf@ar@setup@#1\endcsname%
    % Handle reversal
    \ifpgfarrowreversed%
      % Compute transformation:
      \pgf@arrows@handle@reverse%
    \fi%
    % Save computed values
    \expandafter\global\expandafter\let\csname pgf@ar@saves@\pgf@arrow@id\endcsname\pgf@arrows@saves%
    \expandafter\global\expandafter\let\csname pgf@ar@hull@\pgf@arrow@id\endcsname\pgf@arrows@convexhull%
    \expandafter\xdef\csname pgf@ar@ends@\pgf@arrow@id\endcsname{{\pgf@arrows@the@tipend}{\pgf@arrows@the@backend}{\pgf@arrows@the@lineend}}%
    \expandafter\xdef\csname pgf@ar@visual@\pgf@arrow@id\endcsname{{\pgf@arrows@the@visualtipend}{\pgf@arrows@the@visualbackend}{}}%
    % Save code (needed for bending)
    \edef\pgf@arrow@code{%
      \ifpgfarrowreversed\noexpand\pgftransformxscale{-1}\fi%
      \expandafter\noexpand\csname pgf@ar@code@#1\endcsname%
    }%
    \expandafter\global\expandafter\let\csname pgf@ar@inst@code@\pgf@arrow@id\endcsname\pgf@arrow@code%
    % Should we cache?
    \expandafter\ifx\csname pgf@ar@do@cache@#1\endcsname\pgf@truetext%
      \pgfsysprotocol@getcurrentprotocol\pgf@arrow@temp%
      {%
        \pgfinterruptpath%
          \let\pgfusepath=\pgf@nousepath@here%
          \pgf@relevantforpicturesizefalse%
          \pgftransformreset%
          \pgfsysprotocol@setcurrentprotocol\pgfutil@empty%
          \pgfsysprotocol@bufferedtrue%
          \pgfscope%
          \pgf@arrow@code%
          \endpgfscope%
          \pgfsysprotocol@getcurrentprotocol\pgf@@arrow@temp%
          \expandafter\gdef\expandafter\pgf@arrow@code\expandafter{\expandafter\pgfsysprotocol@literal\expandafter{\pgf@@arrow@temp}}%
        \endpgfinterruptpath%
      }%
      \pgfsysprotocol@setcurrentprotocol\pgf@arrow@temp%
    \fi%
    \expandafter\global\expandafter\let\csname pgf@ar@cache@\pgf@arrow@id\endcsname\pgf@arrow@code%
  }%
}
\def\pgf@truetext{true}

% Ok, now run setup:
\def\pgf@arrows@copy@tipend{\pgf@arrows@the@tipend}
\def\pgf@arrows@copy@backend{\pgf@arrows@the@backend}
\def\pgf@arrows@copy@lineend{\pgf@arrows@the@lineend}
\def\pgf@arrows@zeropt{0pt}%

\let\pgf@arrows@saves\pgfutil@empty%
\let\pgf@arrows@convexhull\pgfutil@empty%
\let\pgf@arrows@the@tipend\pgf@arrows@zeropt%
\let\pgf@arrows@the@backend\pgf@arrows@zeropt%
\let\pgf@arrows@the@lineend\pgf@arrows@zeropt%
\let\pgf@arrows@the@visualtipend\pgf@arrows@copy@tipend%
\let\pgf@arrows@the@visualbackend\pgf@arrows@copy@backend%


\def\pgf@arrows@handle@reverse{%
  \pgf@x\pgf@arrows@the@visualtipend\pgf@x-\pgf@x%
  \pgf@y\pgf@arrows@the@visualbackend\pgf@y-\pgf@y
  \edef\pgf@arrows@the@visualtipend{\the\pgf@y}%
  \edef\pgf@arrows@the@visualbackend{\the\pgf@x}%
  \pgf@x\pgf@arrows@the@tipend\pgf@x-\pgf@x%
  \pgf@y\pgf@arrows@the@backend\pgf@y-\pgf@y
  \edef\pgf@arrows@the@tipend{\the\pgf@y}%
  \edef\pgf@arrows@the@backend{\the\pgf@x}%
  \pgf@x\pgf@arrows@the@lineend\pgf@x-\pgf@x\edef\pgf@arrows@the@lineend{\the\pgf@x}%
  \let\pgf@temp\pgf@arrows@convexhull%
  \let\pgf@arrows@convexhull\pgfutil@empty%
  \let\pgf@arrow@hull@point\pgf@arrow@hull@point@reverse%
  \pgf@temp%
}
\def\pgf@arrow@hull@point@reverse#1#2{%
  \pgf@x#1%
  \pgfarrowshullpoint{-\pgf@x}{#2}%
}

\def\pgf@nousepath@here#1{\pgferror{The definition of an arrow may not use \string\pgfusepath}}

\def\pgfarrowssavethe#1{%
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\pgf@arrows@saves%
  \expandafter\expandafter\expandafter{\expandafter\pgf@arrows@saves\expandafter#1\the#1\relax}
}

\def\pgfarrowssave#1{%
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\pgf@arrows@saves%
  \expandafter\expandafter\expandafter{\expandafter\pgf@arrows@saves\expandafter\def\expandafter#1\expandafter{#1}}
}

\def\pgfarrowshullpoint#1#2{%
  \pgf@x#1\relax%
  \pgf@y#2\relax%
  \edef\pgf@arrows@temp{\noexpand\pgf@arrows@convexhull\noexpand\pgf@arrow@hull@point{\the\pgf@x}{\the\pgf@y}}%
  \expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter\pgf@arrows@convexhull\expandafter\expandafter\expandafter{\pgf@arrows@temp}%
}

\def\pgfarrowsupperhullpoint#1#2{%
  \pgf@x#1\relax%
  \pgf@y#2\relax%
  \ifdim\pgf@y>0pt
    \edef\pgf@arrows@temp{\noexpand\pgf@arrows@convexhull\noexpand\pgf@arrow@hull@point{\the\pgf@x}{\the\pgf@y}\ifpgfarrowharpoon\else\noexpand\pgf@arrow@hull@point{\the\pgf@x}{-\the\pgf@y}\fi}%
  \else
    \edef\pgf@arrows@temp{\noexpand\pgf@arrows@convexhull\noexpand\pgf@arrow@hull@point{\the\pgf@x}{\the\pgf@y}}%
  \fi
  \expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter\pgf@arrows@convexhull\expandafter\expandafter\expandafter{\pgf@arrows@temp}%
}

\def\pgfarrowssettipend#1{\pgf@x#1\edef\pgf@arrows@the@tipend{\the\pgf@x}}
\def\pgfarrowssetbackend#1{\pgf@x#1\edef\pgf@arrows@the@backend{\the\pgf@x}}
\def\pgfarrowssetlineend#1{\pgf@x#1\edef\pgf@arrows@the@lineend{\the\pgf@x}}
\def\pgfarrowssetvisualtipend#1{\pgf@x#1\edef\pgf@arrows@the@visualtipend{\the\pgf@x}}
\def\pgfarrowssetvisualbackend#1{\pgf@x#1\edef\pgf@arrows@the@visualbackend{\the\pgf@x}}


% Internal computatin of the line end (shortening) for an arrow 
% 
% #1 = arrow tip list
% 
% Description:
% 
% \pgf@xa will contain the necessary path shortening for the given
% arrow tip list, \pgf@xb will contain the total length of the arrow
% tip list (sum of the differences between tip end and back end plus
% the seps).

\def\pgf@arrow@compute@shortening#1{%
  \let\pgf@arrow@handle\pgf@arrow@compute@shortening@
  \let\pgf@arrow@handle@dot\pgf@arrow@after@line@endtrue%
  \pgf@arrow@after@line@endfalse%
  \pgf@xa0pt%
  \pgf@xb0pt%
  #1%
}
\newif\ifpgf@arrow@after@line@end

\def\pgf@arrow@compute@shortening@#1#2{%
  {\pgfarrows@getid{#1}{#2}\ifnum\pgf@arrow@flex@mode>0\relax\global\pgf@precise@shorteningtrue\fi\expandafter}\expandafter\pgf@x\the\pgfarrowsep%
  \expandafter\expandafter\expandafter\pgf@arrow@cont@short\csname pgf@ar@ends@\pgf@arrow@id\endcsname%
}
\def\pgf@dot@text{.}

\def\pgf@arrow@cont@short#1#2#3{% tip end, back end, line end, sep
  \advance\pgf@xb by#1%
  \pgf@xc#2%
  \advance\pgf@xb by-\pgf@xc%
  \advance\pgf@xb by\pgf@x%
  \ifpgf@arrow@after@line@end%
    \advance\pgf@xa by#1%
    \advance\pgf@xa by\pgf@x%
    \pgf@xc#2%
    \advance\pgf@xa by-\pgf@xc%
  \else%
    \pgf@xa#1%
    \advance\pgf@xa by\pgf@x%
    \pgf@xc#3%
    \advance\pgf@xa by-\pgf@xc%
  \fi%
}




% Draw an arrow
% 
% #1 = arrow tip list
% #2 = total length of the arrow (the value of \pgf@xb computed by
% \pgf@arrow@compute@shortening)
% 
% Description:
% 
% Draws an arrow tip list. The coordinate system must have been
% transformed so that the to-be-drawn arrow points right and should
% "end" at the origin.

\def\pgf@arrow@draw@arrow#1#2{%
  {%
    \pgf@xb=#2%
    \pgftransformxshift{-\pgf@xb}%
    \let\pgf@arrow@handle\pgf@arrow@drawer
    \let\pgf@arrow@handle@dot\relax%
    #1%
  }%
}


\def\pgf@arrow@drawer#1#2{%
  % Prepare:
  {%
    \pgfarrows@getid{#1}{#2}%
    % Do shift:
    \expandafter\expandafter\expandafter\pgf@arrow@drawer@shift\csname pgf@ar@ends@\pgf@arrow@id\endcsname%
    % Do slant:  
    \ifdim\pgfarrows@slant pt=0pt%
    \else%
      \pgftransformxslant{\pgfarrows@slant}%
    \fi%
    % do swap:
    \ifpgfarrowswap%
      \pgftransformyscale{-1}%
    \fi%
    {%
      \csname pgf@ar@saves@\pgf@arrow@id\endcsname%
      \pgfscope%
        \pgf@arrows@color@setup%
        \pgflowlevelsynccm\csname pgf@ar@cache@\pgf@arrow@id\endcsname%
      \endpgfscope%
      \pgf@arrows@rigid@hull%
    }%  
  \expandafter}%
  % Transform to next tip:
  \expandafter\pgftransformxshift\expandafter{\the\pgf@xc}%
}

\def\pgf@arrows@color@setup{%
  \ifx\pgf@arrows@stroke@color\pgfutil@empty\else\pgfsetstrokecolor{\pgf@arrows@stroke@color}\fi%
  \ifx\pgf@arrows@fill@color\pgfutil@empty%
    \expandafter\expandafter\expandafter\ifx%
    \expandafter\csname\expandafter\string\expandafter\color@pgfstrokecolor\expandafter\endcsname\csname\string\color@pgffillcolor\endcsname%
    \else
      \pgfsetfillcolor{pgfstrokecolor}%
    \fi%
  \else%  
    \pgfsetfillcolor{\pgf@arrows@fill@color}%
  \fi%
}

\def\pgf@arrow@drawer@shift#1#2#3{% tip end, back end, line end, sep
  \pgf@xb#2\pgftransformxshift{-\pgf@xb}%
  \pgf@xc#1%
  \advance\pgf@xc by\pgfarrowsep%
  \advance\pgf@xc by-\pgf@xb%
}

\def\pgf@arrows@rigid@hull{%
  \ifpgf@relevantforpicturesize%
    % Do bb update:
    \expandafter\let\expandafter\pgf@temp\csname pgf@ar@hull@\pgf@arrow@id\endcsname%
    \ifx\pgf@temp\pgfutil@empty\else%
      \let\pgf@arrow@hull@point\pgf@arrow@hull@point@first%
      \pgf@temp%
      \pgf@arrow@update@bb%
    \fi%
  \fi
}


% Convex hull stuff:

\def\pgf@arrow@hull@point@first#1#2{%
% {\pgfsys@beginscope\pgfpathcircle{\pgfqpoint{#1}{#2}}{0.5pt}\pgfusepathqfill\pgfsys@endscope}%
  \pgf@x#1\pgf@y#2%
  \pgf@xa\pgf@pt@aa\pgf@x%
  \advance\pgf@xa by\pgf@pt@ba\pgf@y%
  \pgf@ya\pgf@pt@ab\pgf@x%
  \advance\pgf@ya by\pgf@pt@bb\pgf@y%
  \pgf@xb\pgf@xa\pgf@yb\pgf@ya%
  \let\pgf@arrow@hull@point\pgf@arrow@hull@point@other%
}
\def\pgf@arrow@hull@point@other#1#2{%
%  {\pgfsys@beginscope\pgfpathcircle{\pgfqpoint{#1}{#2}}{0.5pt}\pgfusepathqfill\pgfsys@endscope}%
  \pgfutil@tempdima#1\pgfutil@tempdimb#2%
  \pgf@x\pgf@pt@aa\pgfutil@tempdima%
  \advance\pgf@x by\pgf@pt@ba\pgfutil@tempdimb%
  \pgf@y\pgf@pt@ab\pgfutil@tempdima%
  \advance\pgf@y by\pgf@pt@bb\pgfutil@tempdimb%
  \ifdim\pgf@x<\pgf@xa\pgf@xa\pgf@x\else\ifdim\pgf@x>\pgf@xb\pgf@xb\pgf@x\fi\fi%
  \ifdim\pgf@y<\pgf@ya\pgf@ya\pgf@y\else\ifdim\pgf@y>\pgf@yb\pgf@yb\pgf@y\fi\fi%
}

\def\pgf@arrow@update@bb{%
  \advance\pgf@xa by\pgf@pt@x%
  \advance\pgf@ya by\pgf@pt@y%
  \advance\pgf@xb by\pgf@pt@x%
  \advance\pgf@yb by\pgf@pt@y%
  \ifdim\pgf@picmaxx=-16000pt\relax%
    \global\pgf@picminx\pgf@xa%
    \global\pgf@picmaxx\pgf@xb%
    \global\pgf@picminy\pgf@ya%
    \global\pgf@picmaxy\pgf@yb%
  \else%
    \ifdim\pgf@xa<\pgf@picminx\global\pgf@picminx\pgf@xa\fi%
    \ifdim\pgf@ya<\pgf@picminy\global\pgf@picminy\pgf@ya\fi%
    \ifdim\pgf@xb>\pgf@picmaxx\global\pgf@picmaxx\pgf@xb\fi%
    \ifdim\pgf@yb>\pgf@picmaxy\global\pgf@picmaxy\pgf@yb\fi%
  \fi%
}


% Sets arrows
%
% #1 = An arrow specification of the form
%      <start spec>-<end spec>. This will call \pgfsetstartarrow{start
%        spec} and \pgfsetendarrow{end spec}.
%      
%      Alternatively, it may be of the form [options]. In this case,
%      the arrow options are set for the local scope and all arrows in
%      the current scope will have these options set.
%
% Example:
%
% \pgfsetarrows{-to}

\def\pgfsetarrows#1{\pgf@arrows#1\pgf@stop}
\def\pgf@arrows{\pgfutil@ifnextchar[\pgf@arrows@test@opt\pgf@arrows@}%}
\def\pgf@arrows@#1-#2\pgf@stop{%
  \pgfsetarrowsstart{#1}%
  \pgfsetarrowsend{#2}%
}
\def\pgf@arrows@test@opt[{%
  \pgfutil@ifnextchar-{\pgf@arrows@[}%} go back to normal reading for compat. reasons.
  \pgf@arrows@test@opt@%
}
\def\pgf@arrows@test@opt@#1]{%
  \pgfutil@ifnextchar\pgf@stop{%
    \let\pgf@arrows@options\pgf@arrows@options@scope%
    \pgfkeys{/pgf/arrow keys/.cd,#1}%
    \let\pgf@arrows@options@scope\pgf@arrows@options%    
    % Ok, setup the options
    \pgfutil@gobble%
  }{%
    \pgf@arrows@[#1]% Oops: go back to normal mode
  }%
}

\let\pgf@arrows@options@scope\pgfutil@empty





%
% Predefined arrows:
% 


% A dot is used to indicate the end of the line:

\pgfdeclarearrow{
  name = .,
  drawing code =
}


% An underscore adds a space as in >_> or >_ >. However, it will be
% faster to say ">[sep] >" or ">[sep=2pt] >".

\pgfdeclarearrow{
  name = _,
  defaults = {sep},
  drawing code =
}



% Default shorthands:

\pgfdeclarearrow{ name = To,  means = } % forward declaration
\pgfdeclarearrow{ name = Bar, means = } % forward declaration
\pgfkeys{
  <-> /.tip           = {To},
  >-< /.tip           = {>[reversed]},
  | /.tip             = {Bar}
}



% Compatibility with old arrow system: 

\pgfkeys {}

\def\pgf@arrows@direct@def#1#2{\expandafter\pgf@arrows@direct@def@\expandafter{\csname pgf@ar@means@#2\endcsname}{#1}}
\def\pgf@arrows@direct@def@#1#2{\expandafter\def\csname pgf@arrows@direct@name@#2\endcsname{\pgf@arrow@handle@shorthand@empty{#1}}}
\pgf@arrows@direct@def{start@[}{]}
\pgf@arrows@direct@def{start@]}{[}
\pgf@arrows@direct@def{start@spaced [}{spaced ]}
\pgf@arrows@direct@def{start@spaced ]}{spaced [}
\pgf@arrows@direct@def{end@[}{[}
\pgf@arrows@direct@def{end@]}{]}
\pgf@arrows@direct@def{end@spaced [}{spaced [}
\pgf@arrows@direct@def{end@spaced ]}{spaced ]}

\def\pgfsetarrowoptions#1#2{\expandafter\def\csname pgf@arrow@compat@opt@#1\endcsname{#2}}
\def\pgfgetarrowoptions#1{\csname pgf@arrow@compat@opt@#1\endcsname}
\def\pgfarrowsdeclare#1#2#3#4{%
  \pgfdeclarearrow{ name  ={#1}-{#2}, setup code ={#3}, drawing code={#4}, parameters/.expand once={\csname pgf@arrow@compat@opt@#2\endcsname}}  
  \expandafter\def\csname pgf@arrow@compat@opt@#2\endcsname{0}}
\def\pgfarrowsleftextend#1{\pgfmathsetlength\pgf@xa{#1}\pgfarrowssetbackend{\pgf@xa}}
\def\pgfarrowsrightextend#1{\pgfmathsetlength\pgf@xb{#1}\pgfarrowssettipend{\pgf@xb}}
\def\pgfarrowsdeclarealias#1#2#3#4{\pgfdeclarearrow{ name  ={#1}-{#2}, means ={#4} } }
\def\pgfarrowsdeclarereversed#1#2#3#4{\pgfdeclarearrow{ name ={#1}-{#2}, means={{#4}[reversed]}}}
\def\pgfarrowsdeclarecombine{\pgfutil@ifnextchar*{\pgfarrowsdeclarecombine@star}{\pgf@@arrowsdeclarecombine}}
\def\pgf@@arrowsdeclarecombine{\pgfutil@ifnextchar[{\pgf@arrowsdeclarecombine}{\pgf@arrowsdeclarecombine[0pt]}}
\def\pgf@arrowsdeclarecombine[#1]#2#3#4#5#6#7{\def\pgf@@temp{#1}\ifx\pgf@@temp\pgf@linewidthtext\def\pgf@@temp{+0pt 1}\fi%
  \pgfdeclarearrow{name ={#2}-{#3}, means={#5[sep/.expand once=\pgf@@temp]#6}}}
\def\pgf@linewidth@text{\pgflinewidth}
\def\pgfarrowsdeclarecombine@star*{\pgfutil@ifnextchar[{\pgf@arrowsdeclarecombine@star}{\pgf@arrowsdeclarecombine@star[0pt]}}
\def\pgf@arrowsdeclarecombine@star[#1]#2#3#4#5#6#7{\def\pgf@@temp{#1}\ifx\pgf@@temp\pgf@linewidthtext\def\pgf@@temp{+0pt 1}\fi%
  \pgfdeclarearrow{name ={#2}-{#3}, means={#5[sep/.expand once=\pgf@@temp].#6}}}
\def\pgfarrowsdeclaredouble{\pgfutil@ifnextchar[{\pgf@arrowsdeclaredouble}{\pgf@arrowsdeclaredouble[0pt]}}
\def\pgf@arrowsdeclaredouble[#1]#2#3#4#5{\pgfarrowsdeclarecombine[#1]{#2}{#3}{#4}{#5}{#4}{#5}}
\def\pgfarrowsdeclaretriple{\pgfutil@ifnextchar[{\pgf@arrowsdeclaretriple}{\pgf@arrowsdeclaretriple[0pt]}}
\def\pgf@arrowsdeclaretriple[#1]#2#3#4#5{ \pgfarrowsdeclarecombine[#1]{pgf@trip@#2}{pgf@trip@#3}{#4}{#5}{#4}{#5}%
  \pgfarrowsdeclarecombine[#1]{#2}{#3}{pgf@trip@#2}{pgf@trip@#3}{#4}{#5}}
\def\pgf@linewidthtext{\pgflinewidth}

\pgfarrowsdeclare{stealth}{stealth}
{
  \pgfutil@tempdima=0.28pt%
  \pgfutil@tempdimb=\pgflinewidth%
  \ifdim\pgfinnerlinewidth>0pt%
    \pgfmathsetlength\pgfutil@tempdimb{.6\pgflinewidth-.4*\pgfinnerlinewidth}%
  \fi%
  \advance\pgfutil@tempdima by.3\pgfutil@tempdimb%
  \pgfarrowsleftextend{+-3\pgfutil@tempdima}
  \pgfarrowsrightextend{+5\pgfutil@tempdima}
}
{
  \pgfutil@tempdima=0.28pt%
  \pgfutil@tempdimb=\pgflinewidth%
  \ifdim\pgfinnerlinewidth>0pt%
    \pgfmathsetlength\pgfutil@tempdimb{.6\pgflinewidth-.4*\pgfinnerlinewidth}%
  \fi%
  \advance\pgfutil@tempdima by.3\pgfutil@tempdimb%
  \pgfpathmoveto{\pgfqpoint{5\pgfutil@tempdima}{0pt}}
  \pgfpathlineto{\pgfqpoint{-3\pgfutil@tempdima}{4\pgfutil@tempdima}}
  \pgfpathlineto{\pgfpointorigin}
  \pgfpathlineto{\pgfqpoint{-3\pgfutil@tempdima}{-4\pgfutil@tempdima}}
  \pgfusepathqfill
}
\pgfarrowsdeclarereversed{stealth reversed}{stealth reversed}{stealth}{stealth}
\pgfarrowsdeclare{to}{to}
{
  \pgfutil@tempdima=-0.84pt%
  \advance\pgfutil@tempdima by-1.3\pgflinewidth%
  \pgfutil@tempdimb=0.21pt%
  \advance\pgfutil@tempdimb by.625\pgflinewidth%
  \pgfarrowsleftextend{+\pgfutil@tempdima}
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.28pt%
  \advance\pgfutil@tempdima by.3\pgflinewidth%
  \pgfsetlinewidth{0.8\pgflinewidth}
  \pgfsetdash{}{+0pt}
  \pgfsetroundcap
  \pgfsetroundjoin
  \pgfpathmoveto{\pgfqpoint{-3\pgfutil@tempdima}{4\pgfutil@tempdima}}
  \pgfpathcurveto
  {\pgfqpoint{-2.75\pgfutil@tempdima}{2.5\pgfutil@tempdima}}
  {\pgfqpoint{0pt}{0.25\pgfutil@tempdima}}
  {\pgfqpoint{0.75\pgfutil@tempdima}{0pt}}
  \pgfpathcurveto
  {\pgfqpoint{0pt}{-0.25\pgfutil@tempdima}}
  {\pgfqpoint{-2.75\pgfutil@tempdima}{-2.5\pgfutil@tempdima}}
  {\pgfqpoint{-3\pgfutil@tempdima}{-4\pgfutil@tempdima}}
  \pgfusepathqstroke
}
\pgfkeys{To /.tip = to}
\pgfarrowsdeclare{to reversed}{to reversed}
{
  \pgfutil@tempdima=-0.21pt%
  \advance\pgfutil@tempdima by-0.475\pgflinewidth%
  \pgfutil@tempdimb=0.98pt%
  \advance\pgfutil@tempdimb by1.45\pgflinewidth%
  \pgfarrowsleftextend{+\pgfutil@tempdima}
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.28pt%
  \advance\pgfutil@tempdima by.3\pgflinewidth%
  \pgfsetlinewidth{+0.8\pgflinewidth}
  \pgfsetdash{}{+0pt}
  \pgfsetroundcap
  \pgfsetroundjoin
  \pgfpathmoveto{\pgfqpoint{3.5\pgfutil@tempdima}{4\pgfutil@tempdima}}
  \pgfpathcurveto
  {\pgfqpoint{3.25\pgfutil@tempdima}{2.5\pgfutil@tempdima}}
  {\pgfqpoint{0.5\pgfutil@tempdima}{0.25\pgfutil@tempdima}}
  {\pgfqpoint{-0.25\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathcurveto
  {\pgfqpoint{0.5\pgfutil@tempdima}{-0.25\pgfutil@tempdima}}
  {\pgfqpoint{3.25\pgfutil@tempdima}{-2.5\pgfutil@tempdima}}
  {\pgfqpoint{3.5\pgfutil@tempdima}{-4\pgfutil@tempdima}}
  \pgfusepathqstroke
}
\pgfarrowsdeclare{latex}{latex}
{
  \pgfutil@tempdima=0.28pt%
  \pgfutil@tempdimb=\pgflinewidth%
  \ifdim\pgfinnerlinewidth>0pt%
    \pgfmathsetlength\pgfutil@tempdimb{.6\pgflinewidth-.4*\pgfinnerlinewidth}%
  \fi%
  \advance\pgfutil@tempdima by.3\pgfutil@tempdimb%
  \pgfarrowsleftextend{+-1\pgfutil@tempdima}
  \pgfarrowsrightextend{+9\pgfutil@tempdima}
}
{
  \pgfutil@tempdima=0.28pt%
  \pgfutil@tempdimb=\pgflinewidth%
  \ifdim\pgfinnerlinewidth>0pt%
    \pgfmathsetlength\pgfutil@tempdimb{.6\pgflinewidth-.4*\pgfinnerlinewidth}%
  \fi%
  \advance\pgfutil@tempdima by.3\pgfutil@tempdimb%
  \pgfpathmoveto{\pgfqpoint{9\pgfutil@tempdima}{0pt}}
  \pgfpathcurveto
  {\pgfqpoint{6.3333\pgfutil@tempdima}{.5\pgfutil@tempdima}}
  {\pgfqpoint{2\pgfutil@tempdima}{2\pgfutil@tempdima}}
  {\pgfqpoint{-1\pgfutil@tempdima}{3.75\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{-1\pgfutil@tempdima}{-3.75\pgfutil@tempdima}}
  \pgfpathcurveto
  {\pgfqpoint{2\pgfutil@tempdima}{-2\pgfutil@tempdima}}
  {\pgfqpoint{6.3333\pgfutil@tempdima}{-.5\pgfutil@tempdima}}
  {\pgfqpoint{9\pgfutil@tempdima}{0pt}}
  \pgfusepathqfill
}
\pgfarrowsdeclarereversed{latex reversed}{latex reversed}{latex}{latex}
\pgfarrowsdeclare{@bar}{@bar}
{
  \pgfarrowsleftextend{+-0.25\pgflinewidth}
  \pgfarrowsrightextend{+.75\pgflinewidth}
}
{
  \pgfutil@tempdima=2pt%
  \advance\pgfutil@tempdima by1.5\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetrectcap
  \pgfpathmoveto{\pgfqpoint{0.25\pgflinewidth}{-\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{0.25\pgflinewidth}{\pgfutil@tempdima}}
  \pgfusepathqstroke
}
\pgfkeys{Bar /.tip = @bar}
\pgfarrowsdeclare{space}{space}
{
  \pgfutil@tempdima=0.88pt%
  \advance\pgfutil@tempdima by.3\pgflinewidth%
  \pgfarrowsleftextend{0pt}
  \pgfarrowsrightextend{\pgfutil@tempdima}
}
{}



\endinput



pgfcore.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesPackageRCS[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/basiclayer/pgfcore.code.tex,v 1.7 2010/04/11 07:09:19 ludewich Exp $

\newif\ifpgf@draftmode

\input pgfmath.code.tex

\input pgfcorepoints.code.tex
\input pgfcorepathconstruct.code.tex
\input pgfcorepathusage.code.tex
\input pgfcorescopes.code.tex
\input pgfcoregraphicstate.code.tex
\input pgfcoretransformations.code.tex
\input pgfcorequick.code.tex
\input pgfcoreobjects.code.tex
\input pgfcorepathprocessing.code.tex
\input pgfcorearrows.code.tex
\input pgfcoreshade.code.tex
\input pgfcoreimage.code.tex
\input pgfcorelayers.code.tex
\input pgfcoretransparency.code.tex
\input pgfcorepatterns.code.tex

\pgfutil@ifundefined{pgf@texdist@protect}{%
	\def\pgf@texdist@protect{}%
}{}
\endinput

pgfcoreexternal.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/basiclayer/pgfcoreexternal.code.tex,v 1.20 2013/07/15 12:05:31 tantau Exp $



\newif\ifpgfexternal@aux@in@dpth
\newif\ifpgfexternal@info

\pgfkeys{
    /pgf/images/include external/.code={\pgfimage{#1}},
    /pgf/images/aux in dpth/.is if=pgfexternal@aux@in@dpth,
    /pgf/images/aux in dpth/.default=true,
    /pgf/images/trim external/.code n args={4}{%
        \def\pgf@external@kern@left{#1}%
        \def\pgf@external@kern@bottom{#2}%
        \def\pgf@external@kern@right{#3}%
        \def\pgf@external@kern@top{#4}%
        \ifx\pgf@external@kern@left\pgfutil@empty\def\pgf@external@kern@left{0sp}\fi%
        \ifx\pgf@external@kern@bottom\pgfutil@empty\def\pgf@external@kern@bottom{0sp}\fi%
        \ifx\pgf@external@kern@right\pgfutil@empty\def\pgf@external@kern@right{0sp}\fi%
        \ifx\pgf@external@kern@top\pgfutil@empty\def\pgf@external@kern@top{0sp}\fi%
    },
    /pgf/images/trim external={1truein}{1truein}{1truein}{1truein},
    /pgf/images/external info/.is if=pgfexternal@info,
    /pgf/images/external info/.default=true,
}

% The external read/write mechanism is used as follows:
%
% In your document, you put a number or all of your pgfpicture (or
% tikzpicture) environments inside a pair of \beginpgfexternal and
% \endpgfexternal. The \beginpgfexternal gets one parameter called the
% graphics name.
%
% Once this is done, the next step is to declare the names of your
% graphics in the document at the beginning using the
% \pgfdeclaregraphicname command.
%
% Now, when you typeset your document, each time a \beginpgfexternal
% command is encountered, it will be checked whether the corresponding
% graphics file exists. If this is the case, it will be included and
% the code between \beginpgfexternal and \endpgfexternal is
% ignored. Otherwise, the code is executed normally.
%
% Things change when you run tex on your file with the \jobname set to
% the name of a decalred graphics name. In this case, only your
% graphic will be typeset, the rest of the document will be "thrown away". 
% To be more precise, everything is gobbled up to the beginning
% of the first \beginpgfexternal with the given graphics name. Then,
% the content of the "environment" is put in a box (this "environment"
% need not contain a graphics, it may contain anything that can be put
% in a box). Then a single page is output whose size is exactly the
% size of the picture.
%
% So, once you have run tex repeatedly, each time with the jobname set
% to each of the graphics, you can then run tex on the whole document
% and this will cause all graphics to be included rather than begin
% typeset.
%
% Finally, once all the graphics have been created, you can also say
% \input pgfexternal.tex instead of including pgf/TikZ.


\newif\ifpgfexternalreadmainaux
\pgfexternalreadmainauxtrue

% Tells pgf which jobname is the name of the real file
%
% #1 = name
%
% Description:
%
% This command is used to tell pgf that the file named #1 should be
% typeset normally. If \jobname is not equal to #1, only
% the graphic called \jobname will be typeset. 
%
% Example:
%
% \pgfrealjobname{survey}
%
% Note that afterwards, \jobname will be set to the argument. In our
% example, \jobname will be 'survey'. This is to accomplish
% compatibility with aux-file generation.

\def\pgfrealjobname#1{%
  \global\let\pgfactualjobname=\jobname
  \edef\pgf@tempa{\expandafter\string\csname #1\endcsname}%
  \edef\pgf@tempb{\expandafter\string\csname\jobname\endcsname}%
  \ifx\pgf@tempa\pgf@tempb%
  \else%
    \pgf@external@grabshipouttrue%
    \pgfexternal@nofiles% see also \pgf@external@init@aux@in@dpth
    \ifpgfexternalreadmainaux
        % and reset the jobname. This should allow to handle any
        % \label/\ref constructions which are stored in \jobname.aux (and
        % which won't be found otherwise)
        \gdef\jobname{#1}%
    \fi
    \ifpgfexternal@aux@in@dpth
        \csname newwrite\endcsname\w@pgfexternal@auxout
    \fi
    \pgfexternal@geometry@compatibility
  \fi%
  \gdef\pgfrealjobname##1{}% avoid multiple calls.
}

\def\pgfexternal@geometry@compatibility{%
    % check if \usepackage{geometry} is loaded:
    \pgfutil@ifundefined{geometry}{%
    }{%
        % The geometry package hooks into \begin{document}, evaluates
        % its driver -- and generates \special instructions to set the
        % paper size.
        %
        % Unfortunately, this confuses dvips utterly - and perhaps
        % other drivers as well.
        %
        % Thus, if we currently about to generate some external
        % graphics, we WANT to disable geometry (it has no purpose in
        % this context anyway).
        %
        % This here works well:
        \immediate\write16{Package TikZ externalization: calling \string\geometry{driver=none} during externalization.^^J}%
        \geometry{driver=none}%
    }%
}%

\def\pgfexternal@nofiles{%
    % replace \relax. The \nofiles macros does
    % \let\makeglossary=\relax
    % but the glossary.sty calls \renewcommand\makeglossary (which
    % will fail if \makeglossary=\relax). Stupid, but it works.
    \let\pgfexternal@nofiles@=\relax
    \def\relax{\relax}%
    %
    % suppress generation of LaTeX .aux, .toc etc files. 
    % generation of these files is not thread-safe.
    % the \csname \endcsname yields \relax if \nofiles doesn't exist.
    \csname nofiles\endcsname
    %
    \let\relax=\pgfexternal@nofiles@
}%

\newif\ifpgf@external@grabshipout
\newbox\pgfexternal@startupbox

\pgfutil@ifundefined{AtBeginDocument}{}{%
    \AtBeginDocument{%
      \ifpgf@external@grabshipout%
        \global\let\pgfexternal@originalshipout=\shipout%
        \global\def\shipout{\setbox\pgfpic=}%
        \maxdeadcycles=10000%
        % Ok, gather everything we have seen up to now in a box. This box
        % will contain any specials that have been used.
        {%
          \output{\global\setbox\pgfexternal@startupbox=\vbox{\csname @begindvi\endcsname\unvbox255}}%
          \hbox{}\eject%
        }%
      \fi%
    }
}%

\pgfutil@ifundefined{AtEndDocument}{}{%
    \AtEndDocument{%
      \ifpgf@external@grabshipout
        \pgfutil@ifundefined{pgfexternal@did@a@shipout}{%
          \pgfexternal@error@no@shipout
        }{}%
      \fi
    }%
}

% This will be overwritten by the tikz external lib if it is loaded.
\def\pgfexternal@error@no@shipout{%
    \pgferror{Sorry, image externalization failed: the resulting image was EMPTY. I tried to externalize '\pgfactualjobname'. Perhaps there was a typo somewhere? Please check that your document contains '\string\beginpgfgraphicnamed{\pgfactualjobname} ... \string\endpgfgraphicnamed'}%
}%


% "Environment" for an external graphic.
%
% #1 = graphic name
%
% Example:
%
% \beginpgfgraphicnamed{main-graphic2}
%   \begin{tikzpicture}
%     ...
%   \end{tikzpicture}
% \endpgfgraphicnamed

\def\pgf@externalbegin#1{%
  % First, check whether we wish to grab this graphic:
  \let\pgf@next=\pgf@external@normal%
  \ifpgf@external@grabshipout%
    \edef\pgf@tempa{\expandafter\string\csname #1\endcsname}%
    \edef\pgf@tempb{\expandafter\string\csname\pgfactualjobname\endcsname}%
    \ifx\pgf@tempa\pgf@tempb%
      \let\pgf@next=\pgf@external@grab%
    \fi%
  \fi%
  \pgf@next{#1}%
}


\AtBeginDocument{
  \let\beginpgfgraphicnamed=\pgf@externalbegin% overwrite definition of pgfexternal.tex if necessary   
  \let\endpgfgraphicnamed=\unskip
}


% Normal operation: Include an external graphic instead of the
% picture, if such an external picture exists.
\def\pgf@external@normal#1{%
  \let\pgf@filename=\pgfutil@empty%
  \expandafter\pgf@findfile\pgfsys@imagesuffixlist:+{#1}%
  \ifx\pgf@filename\pgfutil@empty%
    % Ok, no such image... Just typeset the picture normally.
    \let\pgf@next=\relax%
  \else%
    \let\pgf@next=\pgf@replacepicturebygraphic%
  \fi%
  \pgf@next%  
}

\long\def\pgf@replacepicturebygraphic#1\endpgfgraphicnamed{%
    \expandafter\pgfincludeexternalgraphics\expandafter{\pgf@filename}\unskip
}

% This is almost the same as \includegraphics{#1}, but it checks
% whether '#1.dpth' exists. In such case, it restores the boxes depth
% stored in #1.dpth.
%
% Furthermore, the .dpth file may contain .aux related information
% collected for the external graphics (references). They start after
% the first line (if any).
\def\pgfincludeexternalgraphics#1{%
    \begingroup
    \pgfexternalreaddpth{#1}%
    \pgfkeysifdefined{/pgf/images/include external/#1/.@cmd}{%
        \pgfkeysgetvalue{/pgf/images/include external/#1/.@cmd}\pgf@tempa
        \pgfkeyslet{/pgf/images/include external/.@cmd}\pgf@tempa
    }{}%
    \setbox1=\hbox{\pgfkeysvalueof{/pgf/images/include external/.@cmd}{#1}\pgfeov}%
    \ifdim\pgfexternaltrimleft=0sp \else \kern\pgfexternaltrimleft\relax \fi
    \ifdim\pgfexternaldepth=0pt
        \box1
    \else
        \dimen0=\pgfexternaldepth\relax
        \hbox{\lower\dimen0 \box1 }%
    \fi
    \ifdim\pgfexternaltrimright=0sp \else \kern\pgfexternaltrimright\relax \fi
    \endgroup
}

% Reads the .dpth file which contains meta data of the external
% picture.
% 
% This command handles the following stuff:
% - it defines \pgfexternaldepth . The macro contains the contents of
%   a line which does not start with a control sequence (for example a
%   line containing '50pt')
% - it defines \pgfexternaltrimleft and \pgfexternaltrimright 
% - it checks if the .dpth file contains content stored by means of
%   \pgfexternalstorecommand. If so, the argument of
%   \pgfexternalstorecommand will be restored.
% - anything else will be appended to the main .aux file, assuming that
%   it contains \label or \ref information (only if the LaTeX switch
%      \if@filesw is \iftrue).
%
%
% #1: the image file name (such that #1.dpth exists)
\def\pgfexternalreaddpth#1{%
    % no \begingroup. Handle that manually:
    \edef\pgfexternalreaddpth@restore{%
        \noexpand\endlinechar=\the\endlinechar\space
        \noexpand\catcode`\noexpand\@=\the\catcode`\@\space
    }%
    %
    \def\pgfexternaldepth{0sp}%
    \def\pgfexternaltrimleft{0sp}%
    \def\pgfexternaltrimright{0sp}%
    \endlinechar=-1 % suppress white space at end
    \catcode`\@=11
    \openin\r@pgf@reada=#1.dpth
    \pgfincludeexternalgraphics@read@dpth
    %
    \pgfexternalreaddpth@restore
}%
%
% The .dpth consists of 0-N lines, where each is either a single
% dimension (the box' depth) or something which belongs to the .aux
% file (such lines will always start with a macro).
\def\pgfincludeexternalgraphics@read@dpth{%
    \ifeof\r@pgf@reada
        \closein\r@pgf@reada
    \else
        \read\r@pgf@reada to\pgfincludeexternalgraphics@auxline
        \ifx\pgfincludeexternalgraphics@auxline\pgfutil@empty
        \else
            \expandafter\pgfincludeexternalgraphics@read@dpth@line\pgfincludeexternalgraphics@auxline\pgfincludeexternalgraphics@read@dpth@line@EOI
        \fi
        \expandafter\pgfincludeexternalgraphics@read@dpth
    \fi
}%

\def\pgfexternal@restore#1{#1}%

\long\def\pgfincludeexternalgraphics@read@dpth@line@getfirst#1#2\pgfincludeexternalgraphics@read@dpth@line@EOI{%
    \def\pgf@first{#1}%
}%
\long\def\pgfincludeexternalgraphics@read@dpth@line#1\pgfincludeexternalgraphics@read@dpth@line@EOI{%
    \pgfincludeexternalgraphics@read@dpth@line@getfirst#1\pgfincludeexternalgraphics@read@dpth@line@EOI
    \expandafter\ifcat\expandafter\noexpand\pgf@first\relax
        % Ah -- the first token is a control sequence. It belongs to
        % the .aux file.
        %
        \expandafter\ifx\pgf@first\pgfexternal@restore
            % if the first line in the .dpth file starts with the
            % magic string \pgfexternal@restore, the complete line
            % will be executed as-is. Example:
            % \pgfexternal@restore{\def\somevalue{1}}
            #1%
        \else
            % do NOT execute #1! many LaTeX commands don't support it (\label for example)
            \pgfutil@ifundefined{if@filesw}{%
                % sorry, .aux file support only for latex
            }{%
                % append to main .aux file (for forward references)
                \if@filesw
                    {%
                    \toks0={#1}%
                    % believe it or not, but the
                    % \def\dpthimport{...}\dpthimport *makes* a
                    % difference! In ensures any occuring `##' characters are properly expanded to `#'.
                    \immediate\write\@auxout{%
                        \noexpand\def\noexpand\dpthimport{\the\toks0}\noexpand\dpthimport}%
                    }%
                \fi             
            }%
        \fi
    \else% it is the depth (which is simply a number for backwards compatibility)
        \def\pgfexternaldepth{#1}%
    \fi
}%

% Stores '#1' (expanded!) into the .dpth file of the currently
% exported image. 
%
% This command has only an effect if an image is being exported.
%
% The stored contents will be read in the context where
% /pgf/images/include external is active (i.e. by
% \pgfexternalreaddpth).
%
\def\pgfexternalstorecommand#1{%
}%
\def\pgfexternalstorecommand@isexporting#1{%
    \immediate\write\w@pgfexternal@auxout{\noexpand\pgfexternal@restore{#1}}%
}%



% Grab operation: If jobname matches the graphic name, typeset this
% picture normall.
% REMARK:
%   this method is also invoked from within the tikz external library.
\def\pgf@external@grab#1{%
  \def\pgf@filename{#1}%
  \ifpgfexternal@aux@in@dpth    
    \begingroup
    \pgf@external@init@aux@in@dpth
    \let\G@refundefinedtrue=\pgf@external@grab@refundefinedtrue
  \fi
  \gdef\pgf@trimleft@final{0sp}%
  \gdef\pgf@trimright@final{0sp}%
  \setbox\pgfpic=\hbox\bgroup\bgroup%
    \let\endpgfgraphicnamed=\pgf@externalend%
}

{\catcode`\^=12 \gdef\pgfexternal@hat{^}}

\expandafter\let\expandafter\pgf@external@grab@refundefinedtrue@orig\csname G@refundefinedtrue\endcsname

\def\pgf@external@grab@refundefinedtrue{%
    \pgf@external@grab@refundefinedtrue@orig
    \begingroup
    \def\n{\pgfexternal@hat\pgfexternal@hat J}%
    \pgfexternalstorecommand{%
      \noexpand\immediate\noexpand\write16{\pgf@external@grab@refundefinedtrue@warning}%
      \noexpand\G@refundefinedtrue
    }%
    \endgroup
}%
\def\pgf@external@grab@refundefinedtrue@warning{%
    LaTeX Warning: External picture `\pgfactualjobname' contains undefined references\noexpand\on@line.\n
}%

\let\pgf@external@@protected@write@orig=\protected@write
\long\def\pgf@external@@protected@write@immediate#1#2#3{%
  \begingroup
    \let\pgf@write@=\write
    \def\write{\noexpand\immediate\pgf@write@}%
    \pgf@external@@protected@write@orig{#1}{#2}{#3}%
  \endgroup
}%

\def\pgf@external@init@aux@in@dpth{%
  \let\pgfexternalstorecommand=\pgfexternalstorecommand@isexporting
  %
  % tell LaTeX to write aux files...
  \csname @fileswtrue\endcsname
  % ... but redirect output to the .dpth file!
  \immediate\openout\w@pgfexternal@auxout=\pgf@filename.dpth
  \let\@auxout=\w@pgfexternal@auxout
  % ... and disable the correct page numbers. I can't get that
  % (because the correct page number is only available in the
  % shipout routine). Use immediate output:
  \let\protected@write=\pgf@external@@protected@write@immediate
}%

\def\pgf@externalend@storeshifts#1{%
  \immediate\write#1{\the\dp\pgfpic}% store the depth simply as number for backw. compat.
  \ifx\pgf@trimleft@final\pgfutil@empty\else
    \immediate\write#1{\noexpand\pgfexternal@restore{\noexpand\def\noexpand\pgfexternaltrimleft{\pgf@trimleft@final}}}%
  \fi
  \ifx\pgf@trimright@final\pgfutil@empty\else
    \immediate\write#1{\noexpand\pgfexternal@restore{\noexpand\def\noexpand\pgfexternaltrimright{\pgf@trimright@final}}}%
  \fi
  \ifpgfexternal@info
    \immediate\write#1{\noexpand\pgfexternal@restore{\noexpand\def\noexpand\pgfexternalwidth{\the\wd\pgfpic}}}%
    \immediate\write#1{\noexpand\pgfexternal@restore{\noexpand\def\noexpand\pgfexternalheight{\the\dimen0}}}%
  \fi
}
% REMARK:
%   this method is also invoked from within the tikz external library.
\def\pgf@externalend{%
  \unskip\egroup\egroup%
  {%
    \def\pgf@external@trim{0}%
    \def\pgf@external@store@dpth{0}%
    %
    \ifpgf@trim@lowlevel
      \gdef\pgf@trimleft@final{}%
      \gdef\pgf@trimright@final{}%
    \else
      \ifdim\pgf@trimleft@final=0sp  \gdef\pgf@trimleft@final{}  \else\def\pgf@external@trim{1}\fi
      \ifdim\pgf@trimright@final=0sp \gdef\pgf@trimright@final{} \else\def\pgf@external@trim{1}\fi
      \if1\pgf@external@trim
          % UNDO the trimming! export to pdf doesn't supported trimmed
          % bounding boxes (has to do with the mediabox/trimbox etc).
          % I'll keep the bounding box intact and store the trim information 
          % into the .dpth file.
          \setbox\pgfpic=\hbox{%
              \ifx\pgf@trimleft@final\pgfutil@empty\else\kern-\pgf@trimleft@final\fi
              \box\pgfpic
              \ifx\pgf@trimright@final\pgfutil@empty\else\kern-\pgf@trimright@final\fi
          }%
          \def\pgf@external@store@dpth{1}%
      \fi
    \fi
    %
    \parindent0pt % leave the space
%    \leftmargin0pt%
%    \rightmargin0pt%
    \hoffset=0pt % reset to default
    \voffset=0pt
    \dimen0\ht\pgfpic%
    \advance\dimen0\dp\pgfpic%
    \ifdim\dp\pgfpic=0pt\relax
    \else% store the picture's depth. Otherwise, it would be lost.
      \def\pgf@external@store@dpth{1}%
    \fi
    \ifpgfexternal@info
      \def\pgf@external@store@dpth{1}%
    \fi
    %
    \if1\pgf@external@store@dpth
      \ifpgfexternal@aux@in@dpth
        \pgf@externalend@storeshifts\@auxout
        \immediate\closeout\@auxout
      \else
        \immediate\openout\pgf@plotwrite=\pgf@filename.dpth
        \pgf@externalend@storeshifts\pgf@plotwrite
        \immediate\closeout\pgf@plotwrite
      \fi
    \fi
    \pgfsys@papersize{\the\wd\pgfpic}{\the\dimen0}%
    %
    \setbox0=\vbox{%
      % I admit that I don't know why there is this kerning:
      \kern -\pgf@external@kern@top\relax%
      \hbox{%
        \kern -\pgf@external@kern@left\relax%
        \hbox to0pt{%
          \wd\pgfexternal@startupbox=0pt %
          \ht\pgfexternal@startupbox=0pt %
          \dp\pgfexternal@startupbox=0pt %
          \box\pgfexternal@startupbox%
          \pgfsys@atbegindocument\hss}%
        \box\pgfpic%
        \kern\pgf@external@kern@right\relax%
      }%
      \kern\pgf@external@kern@bottom\relax%
    }%
    %
    % compatibility with eso-pic package: \nointerlineskip is not
    % allowed here, but the eso-pic package uses \nointerlineskip in
    % its shipout routine.
    \let\pgfexternal@nointerlineskip@orig=\nointerlineskip
    \let\nointerlineskip=\pgfexternal@nointerlineskip
    %
    \pgfexternal@originalshipout\box0 %
    \gdef\pgfexternal@did@a@shipout{1}%
  }%
  \ifpgfexternal@aux@in@dpth
    \endgroup
  \fi
}

\def\pgfexternal@nointerlineskip{%
    \ifvmode
      \pgfexternal@nointerlineskip@orig
    \else
      \relax% \nointerlineskip in horizontal mode not allowed. Silently ignore the error message.
    \fi
}%

\endinput
% vi: tabstop=4 shiftwidth=2 expandtab

pgfcoregraphicstate.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/basiclayer/pgfcoregraphicstate.code.tex,v 1.11 2013/09/19 22:34:34 tantau Exp $

% Globals

\newdimen\pgflinewidth


% Set the line width to #1.
% 
% #1 = new line width.
% 
% Example:
%
% \pgfsetlinewidth{3pt}

\def\pgfsetlinewidth#1{%
  \pgfmathsetlength\pgflinewidth{#1}%
  \global\pgflinewidth=\pgflinewidth%
  \pgfsys@setlinewidth{\the\pgflinewidth}%
  \ignorespaces}


% Set the inner line width to #1.
% 
% #1 = new inner line width.
% 
% Description:
%
% The inner line width is the width of a second line that is drawn on
% top of the main stroked line. If the inner line width is 0pt, no
% inner line is drawn. The main use of inner lines is for creating
% "double" lines.
%
% Inner lines are not drawn when a path is used for clipping.
%
% The inner line width is local to the current TeX group, it is not
% part of the graphic state.
%
% Example:
%
% \pgfsetinnerlinewidth{1pt}

\def\pgfsetinnerlinewidth#1{%
  \pgfmathsetlength\pgf@x{#1}%
  \edef\pgfinnerlinewidth{\the\pgf@x}%
}
\def\pgfinnerlinewidth{0pt}


% Set the inner line color to #1.
%
% #1 = color for the inner line
%
% Example:
%
% \pgfsetinnerlinecolor{green} % yikes!

\def\pgfsetinnerstrokecolor#1{\def\pgfinnerstrokecolor{#1}}
\def\pgfinnerstrokecolor{white}


% Set the miter limit to #1.
% 
% #1 = new miter limit factor.
% 
% Example:
%
% \pgfsetmiterlimit{3}

\def\pgfsetmiterlimit#1{%
  \pgfsys@setmiterlimit{#1}%
  \ignorespaces}


% Set the dash pattern to #1 with phase #2/
% 
% #1 = a row of numbers of length of ``on'' and ``off'' points.
% #2 = a phase
% 
% Example:
%
% \pgfsetdash{}          {0pt} % solid line
% \pgfsetdash{{.1cm}}    {0pt} % long dashes
% \pgfsetdash{{1pt}{1ex}}{0pt} % dotted

\def\pgfsetdash#1#2{%
  \def\pgf@temp{}%
  \def\pgf@next{\pgf@strip}%
  \pgf@strip#1{pgf@stop}%
  \pgfmathsetlength\pgf@x{#2}%
  \pgfsys@setdash{\pgf@temp}{\the\pgf@x}%
  \ignorespaces}

\def\pgf@strip#1{%
  \def\pgf@@temp{#1}%
  \ifx\pgf@@temp\pgf@stop%
    \let\pgf@next=\relax%
  \else%
    \pgfmathsetlength\pgf@x{#1}%
    \ifx\pgf@temp\pgfutil@empty%
      \edef\pgf@temp{\the\pgf@x}%
    \else%
      \edef\pgf@temp{\pgf@temp,\the\pgf@x}%
    \fi%
  \fi\pgf@next}

\def\pgf@stop{pgf@stop}


% Set color of strokes. This will overrule the normal color.
% 
% Example:
%
% \pgfsetstrokecolor{red}

\def\pgfsetstrokecolor#1{%
  \pgfutil@colorlet{pgfstrokecolor}{#1}%
  \pgfutil@ifundefined{applycolormixins}{}{\applycolormixins{pgfstrokecolor}}%
  \expandafter\expandafter\expandafter\global%
  \expandafter\expandafter\expandafter\let\expandafter\csname\expandafter\string\expandafter\color@pgfstrokecolor\expandafter\endcsname\csname\string\color@pgfstrokecolor\endcsname%
  \expandafter\expandafter\expandafter\pgf@setstrokecolor\csname\string\color@pgfstrokecolor\endcsname%
}
\def\pgf@setstrokecolor#1#2#3#4#5{%
  \expandafter\ifx\csname pgfsys@color@#4@stroke\endcsname\relax%
    \pgferror{Unsupported color model `#4'. Sorry}%
  \else%
    \edef\pgf@colmarshal{\expandafter\noexpand\csname pgfsys@color@#4@stroke\endcsname}%
    \pgf@uncomma#5,,%
    \pgf@colmarshal%
  \fi}

\def\pgf@uncomma#1,{%
  \def\pgf@coltest{#1}%
  \ifx\pgf@coltest\pgfutil@empty%
    \let\pgf@colnext=\relax%
  \else%
    \expandafter\def\expandafter\pgf@colmarshal\expandafter{\pgf@colmarshal{#1}}%
    \let\pgf@colnext=\pgf@uncomma%
  \fi%
  \pgf@colnext%  
}


% Set color of fills. This will overrule the normal color.
% 
% Example:
%
% \pgfsetfillcolor{gray}

\def\pgfsetfillcolor#1{%
  \pgfutil@colorlet{pgffillcolor}{#1}%
  \pgfutil@ifundefined{applycolormixins}{}{\applycolormixins{pgffillcolor}}%
  \expandafter\expandafter\expandafter\global%
  \expandafter\expandafter\expandafter\let\expandafter\csname\expandafter\string\expandafter\color@pgffillcolor\expandafter\endcsname\csname\string\color@pgffillcolor\endcsname%
  \expandafter\expandafter\expandafter\pgf@setfillcolor\csname\string\color@pgffillcolor\endcsname%
}
\def\pgf@setfillcolor#1#2#3#4#5{%
  \expandafter\ifx\csname pgfsys@color@#4@fill\endcsname\relax%
    \pgferror{Unsupported color model `#4'. Sorry}%
  \else%
    \edef\pgf@colmarshal{\expandafter\noexpand\csname pgfsys@color@#4@fill\endcsname}%
    \pgf@uncomma#5,,%
    \pgf@colmarshal%
  \fi}



% Sets both the stroke and fill color.
% 
% Example:
%
% \pgfsetcolor{blue}

\def\pgfsetcolor#1{%
  \pgfutil@colorlet{pgfstrokecolor}{#1}%
  \pgfutil@ifundefined{applycolormixins}{}{\applycolormixins{pgfstrokecolor}}%
  \expandafter\expandafter\expandafter\global%
  \expandafter\expandafter\expandafter\let\expandafter\csname\expandafter\string\expandafter\color@pgfstrokecolor\expandafter\endcsname\csname\string\color@pgfstrokecolor\endcsname%
  \expandafter\expandafter\expandafter\global%
  \expandafter\expandafter\expandafter\let\expandafter\csname\expandafter\string\expandafter\color@pgffillcolor\expandafter\endcsname\csname\string\color@pgfstrokecolor\endcsname%
  \expandafter\expandafter\expandafter\pgf@setcolor\csname\string\color@pgfstrokecolor\endcsname%
}
\def\pgf@setcolor#1#2#3#4#5{%
  \expandafter\ifx\csname pgfsys@color@#4\endcsname\relax%
    \pgferror{Unsupported color model `#4'. Sorry}%
  \else%
    \edef\pgf@colmarshal{\expandafter\noexpand\csname pgfsys@color@#4\endcsname}%
    \pgf@uncomma#5,,%
    \pgf@colmarshal%
  \fi}

% Code for ensuring the stroke/fill colors are correctly reset.
\def\XC@bcolor{\pgfsys@color@reset}

% Set a butt line cap.
% 
% Example:
%
% \pgfsetbuttcap

\def\pgfsetbuttcap{\pgfsys@buttcap\ignorespaces}


% Set a round line cap.
% 
% Example:
%
% \pgfsetroundcap

\def\pgfsetroundcap{\pgfsys@roundcap\ignorespaces}


% Set a rectangular line cap.
% 
% Example:
%
% \pgfsetrectcap

\def\pgfsetrectcap{\pgfsys@rectcap\ignorespaces}


% Set a miter line join.
% 
% Example:
%
% \pgfsetmiterjoin

\def\pgfsetmiterjoin{\pgfsys@miterjoin\ignorespaces}


% Set a bevel line join.
% 
% Example:
%
% \pgfsetbeveljoin

\def\pgfsetbeveljoin{\pgfsys@beveljoin\ignorespaces}


% Set a round line join.
% 
% Example:
%
% \pgfsetroundjoin

\def\pgfsetroundjoin{\pgfsys@roundjoin\ignorespaces}


% Sets the even-odd rule for filling and clipping.
% 
% Example:
%
% \pgfseteorule

\def\pgfseteorule{\pgfsys@eoruletrue\ignorespaces}


% Sets the non-zero winding number rule for filling and clipping.
% 
% Example:
%
% \pgfsetnonzerorule

\def\pgfsetnonzerorule{\pgfsys@eorulefalse\ignorespaces}



\endinput

pgfcoreimage.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/basiclayer/pgfcoreimage.code.tex,v 1.18 2013/07/15 15:41:24 tantau Exp $



% Declare an image
%
% #1 = optional argument: width, height, page specification
% #2 = name of the image for later use
% #4 = filename without extension, automatic extensions are .pdf,
%      .jpg, and .png for PDF and .ps, .eps, .epsi for postscript.
%
% Description:
%
% This command declares an image file for later use. Even if the image
% is used several times in the document, in PDF it will only be stored
% once. 
%
% Example:
%
% \pgfdeclareimage[width=2cm,page=2]{myimage}{imagefilename}

\def\pgfdeclareimage{\pgfutil@ifnextchar[{\pgf@declareimage}{\pgf@declareimage[]}}
\def\pgf@declareimage[#1]#2#3{%
  \pgfqkeys{/pgf/images}{height=,width=,page=,interpolate=false,mask=,#1}%
  % Try to find the file
  \gdef\pgf@filename{}%
  % If page= parameter is not empty, try that file first:
  \ifx\pgf@imagepage\pgfutil@empty%
  \else%
  \expandafter\pgf@findfile\pgfsys@imagesuffixlist:+{#3.page\pgf@imagepage}%
  \fi%
  \ifx\pgf@filename\pgfutil@empty%
    \expandafter\pgf@findfile\pgfsys@imagesuffixlist:+{#3}%
  \else%
    \pgfkeys{/pgf/images/page=}% make page empty     
  \fi%
  \ifx\pgf@filename\pgfutil@empty%
    \pgfwarning%
    {File "#3" not found when defining image "#2".
      Tried all extensions in "\pgfsys@imagesuffixlist"}%
    \pgf@declaredraftimage{#2}{#3}%
  \else%
    \ifpgf@draftmode%
      \pgf@declaredraftimage{#2}{#3}%
    \else%
      \pgfsys@defineimage%
    \fi%
  \fi%
  \expandafter\global\expandafter\let\csname pgf@image@#2!\endcsname=\pgf@image%
}


\pgfkeys{
	/pgf/images/draft/.is if=pgf@draftmode,
	/pgf/images/draft/.default=true}
\pgfkeys{/pgf/images/width/.estore in=\pgf@imagewidth}
\pgfkeys{/pgf/images/height/.estore in=\pgf@imageheight}
\pgfkeys{/pgf/images/page/.estore in=\pgf@imagepage}
\pgfkeys{/pgf/images/interpolate/.cd,.code=\edef\pgf@imageinterpolate{#1},.default=true}
\let\pgf@imageinterpolate\pgfutil@empty
\pgfkeys{/pgf/images/mask/.code=%
  {%
    \edef\pgf@imagemask{#1}%
    \ifx\pgf@imagemask\pgfutil@empty%
    \else%
      \pgfutil@ifundefined{pgf@mask@#1}%
      {\pgferror{Undefined mask "#1".}%
        \edef\pgf@imagemask{}}%
      {\edef\pgf@imagemask{\csname pgf@mask@#1\endcsname}%
      }%
    \fi%
  }}


\def\pgf@findfile#1:#2+#3{%
  \pgfutil@IfFileExists{#3#1}%
  {\xdef\pgf@filename{#3#1}}%
  {\def\pgf@mightbeempty{#2}%
    \ifx\pgf@mightbeempty\pgfutil@empty\else%
    \pgf@findfile#2+{#3}%
    \fi}}

% #1: image name
% #2: file name
\def\pgf@declaredraftimage#1#2{%
  \ifx\pgf@imagewidth\pgfutil@empty%
    \pgfwarning{Missing width for image "#1" ("#2") in draft mode. Using 1cm instead}%
    \edef\pgf@imagewidth{1cm}%
  \fi%
  \ifx\pgf@imageheight\pgfutil@empty%
    \pgfwarning{Missing height for image "#1" ("#2") in draft mode. Using 1cm instead}%
    \edef\pgf@imageheight{1cm}%
  \fi%  
  \ifx\pgf@imagepage\pgfutil@empty\else\edef\pgf@imagepagetext{ page \pgf@imagepage}\fi%
  \edef\pgf@image{%
    \hbox to \pgf@imagewidth{%
      \vrule\kern-0.4pt%
      \vbox to \pgf@imageheight{%
        \hrule\vfil%
        \hbox to \pgf@imagewidth{\hskip-10cm\hfil\noexpand\pgfutil@font@tiny#2\pgf@imagepage\hfil\hskip-10cm}%
        \vfil\hrule}%
      \kern-0.4pt\vrule}%
  }%
}



% Declare a soft mask
%
% #1 = optional argument: matte specification. default matte is
%      white. 
% #2 = name of the mask for later use
% #3 = filename without extension, automatic extensions are .pdf,
%      .jpg, and .png for PDF. Postscript is not supported.
%
% Description:
%
% This command declares a soft mask for later masking an image. The
% declared mask should be used together with an image of exactly the
% same height/width if matte is defined. Matte should be the
% preblended background color (see pdf spec for details).
%
% Example:
%
% \pgfdeclaremask[matte=white]{maskname}{maskfilename}
% \pgfdeclareimage[mask=maskname]{image}{imagefilename}

\def\pgfdeclaremask{\pgfutil@ifnextchar[\pgf@declaremask{\pgf@declaremask[]}}
\def\pgf@declaremask[#1]#2#3{%
  \pgfqkeys{/pgf/images/mask}{matte={1 1 1},#1}% defaults
  \def\pgf@mask{}%
  % Try to find the file
  \gdef\pgf@filename{}%
  \expandafter\pgf@findfile\pgfsys@imagesuffixlist:+{#3}%
  \ifx\pgf@filename\pgfutil@empty%
    \pgfwarning%
    {File "#3" not found when defining mask "#2".
      Tried all extensions in "\pgfsys@imagesuffixlist"}%
  \else%
    \pgfsys@definemask{#2}%
  \fi%
  \expandafter\global\expandafter\let\csname pgf@mask@#2\endcsname=\pgf@mask%
}

\pgfkeys{/pgf/images/mask/matte/.cd,.estore in=\pgf@maskmatte,.value required}



% Create an alias name for an image
%
% #1 = name of the alias
% #2 = name of the original
%
% Example:
%
% \pgfdeclareimage{image}{1cm}{1cm}{filename
% \pgfaliasimage{alias}{image}
% \pgfuseimage{alias}

\def\pgfaliasimage#1#2{%
  \expandafter\global\expandafter\let\expandafter\pgf@temp\expandafter=\csname pgf@image@#2!\endcsname%
  \expandafter\global\expandafter\let\csname pgf@image@#1!\endcsname=\pgf@temp%
  }

  
% Use an image
%
% #1 = name of a previously declared image
%
% Example:
%
% \pgfputat{\pgforigin}{\pgfbox[left,base]{\pgfuseimage{myimage}}}

\def\pgfuseimage#1{%
  \def\pgf@imagename{pgf@image@#1}%
  \pgf@tryextensions{\pgf@imagename}{\pgfalternateextension}%
  \expandafter\pgfutil@ifundefined\expandafter{\pgf@imagename}%
  {\pgferror{Undefined image "#1"}}%
  {{\leavevmode\csname\pgf@imagename\endcsname}}}

\def\pgf@tryextensions#1#2{%
  \edef\pgf@args{[#2!]}\expandafter\pgf@@tryextensions\pgf@args{#1}}
\def\pgf@@tryextensions[#1!#2]#3{%
  \expandafter\pgfutil@ifundefined\expandafter{#3#1!#2}%
  {\def\pgf@temp{#2}%
    \ifx\pgf@temp\pgfutil@empty%
    \edef#3{#3!}%
    \else%
    \pgf@@tryextensions[#2]{#3}%
    \fi}%
  {\edef#3{#3#1!#2}}}


% Alternate image
%
% Description:
%
% When an image is used, pgf first attempts to use the image with the
% alternate extension added. If this fails, the original image is
% used. If the alternate extension contains ``!'', then the text up to
% the ! is successively removed and the remainder is tried as an
% alternate extension.
%
% Example:
%
% \def\pgfalternateextension{20!white}

\def\pgfalternateextension{}



% Directly insert an image
%
% #1 = optional argument: width, height, page specification
% #2 = file name
%
% Description:
%
% Directly inserts an image without declaration. You can, however,
% still access this image using the name pgflastimage. By using
% pgfaliasimage, you can also save this image for later.
%
% Example:
%
% \pgfimage[height=2cm]{filename}

\def\pgfimage{\pgfutil@ifnextchar[\pgf@imagecom{\pgf@imagecom[]}}
\def\pgf@imagecom[#1]#2{%
  \pgfdeclareimage[#1]{pgflastimage}{#2}%
  \pgfuseimage{pgflastimage}}


\input pgfcoreexternal.code.tex

\endinput

pgfcorelayers.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/basiclayer/pgfcorelayers.code.tex,v 1.7 2013/07/18 17:07:38 tantau Exp $


% Creates a new pgf layer
%
% #1 = layer name
%
% Declares a new layer for pgf.
%
% Example:
%
% \pgfdeclarelayer{background}

\def\pgfdeclarelayer#1{%
  \pgfutil@ifundefined{pgf@layerbox@#1}{%
    \expandafter\expandafter\csname pgf@newbox\endcsname\csname pgf@layerbox@#1\endcsname%
    \expandafter\expandafter\csname pgf@newbox\endcsname\csname pgf@layerboxsaved@#1\endcsname%
  }{}%
}
\let\pgf@newbox=\newbox % avoid plain TeX outer problem

% Sets the layers that compose the picture
%
% #1 = List of layers
%
% Description:
%
% Sets the list of layers that make up the picture. The layers will be
% put on top of each other in the order given. 
%
% This command can also be given inside of a picture in which case it
% applies only to that very picture.
%
% Example:
%
% \pgfsetlayers{background,main}

\def\pgfsetlayers#1{\edef\pgf@layerlist{#1}}
\pgfsetlayers{main}

% Adds code to a layer
%
% #1 = layer name
%
% Note:
%
% You cannot add anything to the ``main'' layer using this command.
%
% Example:
%
% \begin{pgfonlayer}{background}
%   \fill[red] (0,0) -- (1,1);
% \end{pgfonlayer}

\def\pgfonlayer@name{main}

\def\pgfonlayer#1{%
  \pgfutil@ifundefined{pgf@layerbox@#1}{%
     \pgferror{Sorry, the requested layer '#1' could not be found. Maybe you misspelled it?}%
   \bgroup
     \begingroup
  }{%
      \begingroup
        \edef\pgf@temp{#1}%
        \ifx\pgf@temp\pgfonlayer@name
          % we are already on this layer.
          \def\pgf@temp{%
            \bgroup
            \begingroup
          }%
      \else
        \let\pgfonlayer@name=\pgf@temp
        \pgfonlayer@assert@is@active
        \def\pgf@temp{%
          \expandafter\global\expandafter%
          \setbox\csname pgf@layerbox@#1\endcsname=\hbox to 0pt%
            \bgroup%
              \expandafter\box\csname pgf@layerbox@#1\endcsname%
              \begingroup%
        }%
      \fi
   \pgfsetlinewidth{0.4pt}% always reset the line width
   \pgf@temp
  }%
}
\def\endpgfonlayer{%
      \endgroup%
      \hss
    \egroup%
  \endgroup
}

\let\startpgfonlayer=\pgfonlayer
\let\stoppgfonlayer=\endpgfonlayer

\def\pgfdiscardlayername{discard}

\def\pgfonlayer@assert@is@active{%
  \ifx\pgfonlayer@name\pgfdiscardlayername
     % this special layer name can be used as /dev/null without
   % warning.
  \else
    \begingroup
    \def\pgfonlayer@isactive{0}%
    \expandafter\pgf@assert@layer@is@active@loop\pgf@layerlist,,\relax%
    \if0\pgfonlayer@isactive
       \pgfonlayer@assert@fail
    \fi
    \endgroup
  \fi
}%
\def\pgfonlayer@assert@fail{%
  \pgferror{Sorry, the requested layer '\pgfonlayer@name' is not 
   part of the layer list. Please verify that you provided 
   \string\pgfsetlayers\space and that '\pgfonlayer@name' is part of this list}%
}%
\def\pgf@assert@layer@is@active@loop#1,#2,\relax{%
  \edef\pgf@test{#1}%
  \ifx\pgf@test\pgfonlayer@name
     \def\pgfonlayer@isactive{1}%
  \else
    \def\pgf@test{#2}%
    \ifx\pgf@test\pgfutil@empty%
    \else%
    \pgf@assert@layer@is@active@loop#2,\relax%
    \fi%
  \fi
}

% Hooks into the scoping:

\def\pgf@insertlayers{%
  \expandafter\pgf@dolayer\pgf@layerlist,,\relax%
}
\def\pgf@maintext{main}%
\def\pgf@dolayer#1,#2,\relax{%
  \def\pgf@test{#1}%
  \ifx\pgf@test\pgf@maintext%
    \box\pgf@layerbox@main%
  \else%
    \pgfsys@beginscope%
      \expandafter\box\csname pgf@layerbox@#1\endcsname%
    \pgfsys@endscope%
  \fi%
  \def\pgf@test{#2}%
  \ifx\pgf@test\pgfutil@empty%
  \else%
    \pgf@dolayer#2,\relax%
  \fi%
}

\def\pgf@savelayers{%
  \expandafter\pgf@dosavelayer\pgf@layerlist,,\relax%
}
\def\pgf@dosavelayer#1,#2,\relax{%
  \def\pgf@test{#1}%
  \ifx\pgf@test\pgf@maintext%
  \else%
    \setbox\csname pgf@layerboxsaved@#1\endcsname=\box\csname pgf@layerbox@#1\endcsname%
  \fi%
  \def\pgf@test{#2}%
  \ifx\pgf@test\pgfutil@empty%
  \else%
    \pgf@dosavelayer#2,\relax%
  \fi%
}

\def\pgf@restorelayers{%
  \expandafter\pgf@dorestorelayer\pgf@layerlist,,\relax%
}
\def\pgf@dorestorelayer#1,#2,\relax{%
  \def\pgf@test{#1}%
  \ifx\pgf@test\pgf@maintext%
  \else%
    \global\setbox\csname pgf@layerbox@#1\endcsname=\box\csname pgf@layerboxsaved@#1\endcsname%
  \fi%
  \def\pgf@test{#2}%
  \ifx\pgf@test\pgfutil@empty%
  \else%
    \pgf@dorestorelayer#2,\relax%
  \fi%
}

\endinput

pgfcoreobjects.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/basiclayer/pgfcoreobjects.code.tex,v 1.2 2006/10/11 15:22:25 tantau Exp $


% Object reuse


% Define a pgf object for reuse. Such objects will be stored
% efficiently internally.
%
% #1 = name for later reuse
% #2 = lower left corner point of bounding box
% #3 = upper right left corner point of bounding box
% #4 = pure pgf code (nothing too fancy!)
%
% Description:
% 
% Used to define reusable objects. The object must be composed of
% basic pgf graphic primitives. Nothing fancy can be used. The
% created object will be stored as an xform object in pdf or as a
% postscript procedure in postscript.
%  
% Example:
%
% \pgfdefobject{myrect}{\pgfpoint{-1pt}{-1pt}}{\pgfpoint{11pt}{11pt}}
% {\pgfpathqmoveto{0pt}{0pt}
%  \pgfpathqmoveto{10pt}{0pt}
%  \pgfpathqmoveto{10pt}{10pt}
%  \pgfpathqmoveto{0pt}{10pt}
%  \pgfpathclose
%  \pgfusepath{stroke}}
%
% \begin{pgfpicture}{0cm}{0cm}{1cm}{1cm}
%   \pgfuseobject{myrect}
% \end{pgfpicture}

\def\pgfdefobject#1#2#3#4{%
  \pgfinterruptpath%
    \pgf@relevantforpicturesizefalse%
    \pgfsys@defobject{#1}{#2}{#3}{#4}%
  \endpgfinterruptpath%
  \ignorespaces%
}


% Use an object that was previously defined using pgfdefobject
%
% #1 = name of previously defined object
%  
% Example:
%
% \pgfdefobject{myrect}{\pgfpoint{-1pt}{-1pt}}{\pgfpoint{11pt}{11pt}}
% {\pgfqmoveto{0}{0}
%  \pgfqmoveto{10}{0}
%  \pgfqmoveto{10}{10}
%  \pgfqmoveto{0}{10}
%  \pgfclosestroke}
%
% \begin{pgfpicture}{0cm}{0cm}{1cm}{1cm}
%   \pgfuseobject{myrect}
% \end{pgfpicture}

\def\pgfuseobject#1{\pgfsys@beginscope\pgfsys@useobject{#1}{}\pgfsys@endscope}


% Use an object that was previously defined using pgfdefobject, but
% magnify the object by the current x and y register values
%
% #1 = name of previously defined object
%  
% Example:
%
% \pgfdefobject{myrect}{\pgfpoint{-1pt}{-1pt}}{\pgfpoint{11pt}{11pt}}
% {\pgfqmoveto{0}{0}
%  \pgfqmoveto{10}{0}
%  \pgfqmoveto{10}{10}
%  \pgfqmoveto{0}{10}
%  \pgfclosestroke}
%
% \begin{pgfpicture}{0cm}{0cm}{1cm}{1cm}
%   \pgf@x=2pt% Scale by factor two in x-direction
%   \pgf@y=2pt% Scale by factor two in y-direction
%   \pgfuseobjectmagnify{myrect}
% \end{pgfpicture}

\def\pgfuseobjectmagnify#1{%
  \pgfsys@beginscope%
  \pgfsys@useobject{#1}{\pgfsys@transformxyscale{\pgf@sys@tonumber{\pgf@x}}{\pgf@sys@tonumber{\pgf@y}}}%
  \pgfsys@endscope%
}


\endinput

pgfcorepathconstruct.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/basiclayer/pgfcorepathconstruct.code.tex,v 1.29 2013/10/07 15:51:46 tantau Exp $


\newdimen\pgf@path@lastx
\newdimen\pgf@path@lasty

\let\pgfgetpath=\pgfsyssoftpath@getcurrentpath
\let\pgfsetpath=\pgfsyssoftpath@setcurrentpath



% Replace corners by arcs.
%
% #1 = in-size of arc
% #2 = out-size of arc
% 
% Description:
% 
% This command influences path construction command like
% \pgfpathlineto or \pgfpatharc. It will cause the corners at the end
% of these commands to be replaced by little arcs. If the
% corner is a 90 degrees corner and if #1=#2, a quarter-circle of
% radius #1 is put in place of the corner. If #1 and #2 are different,
% the quarter circle will instead by a quarter ellipse. If the angle
% is different from 90 degrees, a deformed quarter circle will
% result, which may or may not be desirable. For a ``perfect'' arc you
% must use the \pgfpatharc command. 
% 
% 
% Example: One rounded corner.
%
% \pgfpathmoveto{\pgfpointxy{0}{0}}
% \pgfsetcornersarced{4pt}{4pt}
% \pgfpathlineto{\pgfpointxy{0}{1}}
% \pgfpathlineto{\pgfpointxy{1}{1}}
% \pgfstroke
%
% Example: A rounded rectangle
%
% \pgfsetcornersarced{4pt}{4pt}
% \pgfpathrectangle{\pgfpointorigin}{\pgfpoint{1cm}{1cm}}
% \pgfstroke
%
% Example: A rounded triangles
%
% \pgfsetcornersarced{4pt}{4pt}
% \pgfpathmoveto{\pgfpointorigin}
% \pgfpathlineto{\pgfpoint{1cm}{0cm}}
% \pgfpathlineto{\pgfpoint{1cm}{1cm}}
% \pgfpathclose
% \pgfstroke

\newif\ifpgf@arccorners

\def\pgfsetcornersarced#1{%
  \pgf@process{#1}%
  \edef\pgf@corner@arc{{\the\pgf@x}{\the\pgf@y}}%
  \pgf@arccornerstrue%
  \ifdim\pgf@x=0pt%
    \ifdim\pgf@y=0pt\relax%
      \pgf@arccornersfalse%
    \fi%
  \fi%
}

\def\pgf@roundcornerifneeded{%
  \ifpgf@arccorners\expandafter\pgfsyssoftpath@specialround\pgf@corner@arc\fi%
}



% The following protocol the passed sizes and all the corresponding
% softpath commands. The nonlinear transformation (nlt) module
% overwrites these commands. 

\def\pgf@lt@moveto#1#2{%
  \pgf@protocolsizes{#1}{#2}%
  \pgfsyssoftpath@moveto{\the#1}{\the#2}%
}
\def\pgf@lt@lineto#1#2{%
  \pgf@protocolsizes{#1}{#2}%
  \pgfsyssoftpath@lineto{\the#1}{\the#2}%
}
\def\pgf@lt@curveto#1#2#3#4#5#6{%
  \pgf@protocolsizes{#1}{#2}%
  \pgf@protocolsizes{#3}{#4}%
  \pgf@protocolsizes{#5}{#6}%
  \pgfsyssoftpath@curveto{\the#1}{\the#2}{\the#3}{\the#4}{\the#5}{\the#6}%
}

\let\pgf@lt@closepath\pgfsyssoftpath@closepath

\let\pgf@nlt@moveto\pgf@lt@moveto
\let\pgf@nlt@lineto\pgf@lt@lineto
\let\pgf@nlt@curveto\pgf@lt@curveto
\let\pgf@nlt@closepath\pgf@lt@closepath

\let\pgf@nlt@list\pgfutil@empty % If non-empty, the nlt module is active


% Move current point to #1.
%
% #1 = new current point
% 
% Example:
%
% \pgfpathmoveto{\pgfxy(0,0)}
% \pgfpathlineto{\pgfxy(0,1)}
% \pgfstroke

\def\pgfpathmoveto#1{%
  \pgfpointtransformed{#1}%
  \pgf@nlt@moveto{\pgf@x}{\pgf@y}%
  \global\pgf@path@lastx=\pgf@x%
  \global\pgf@path@lasty=\pgf@y%
}

\def\pgf@protocolsizes#1#2{%
  \ifpgf@relevantforpicturesize%
    \ifdim#1<\pgf@picminx\global\pgf@picminx#1\fi%
    \ifdim#1>\pgf@picmaxx\global\pgf@picmaxx#1\fi%
    \ifdim#2<\pgf@picminy\global\pgf@picminy#2\fi%
    \ifdim#2>\pgf@picmaxy\global\pgf@picmaxy#2\fi%
    \ifpgf@size@hooked%
      \let\pgf@size@hook@x#1\let\pgf@size@hook@y#2\pgf@path@size@hook%
    \fi%
  \fi%
  \ifdim#1<\pgf@pathminx\global\pgf@pathminx#1\fi%
  \ifdim#1>\pgf@pathmaxx\global\pgf@pathmaxx#1\fi%
  \ifdim#2<\pgf@pathminy\global\pgf@pathminy#2\fi%
  \ifdim#2>\pgf@pathmaxy\global\pgf@pathmaxy#2\fi%
}
\newif\ifpgf@size@hooked
\let\pgf@path@size@hook=\pgfutil@empty%

\def\pgf@resetpathsizes{%
  \global\pgf@pathmaxx=-16000pt\relax%
  \global\pgf@pathminx=16000pt\relax%
  \global\pgf@pathmaxy=-16000pt\relax%
  \global\pgf@pathminy=16000pt\relax%
}

\def\pgf@getpathsizes#1{%
  \edef#1{{\the\pgf@pathmaxx}{\the\pgf@pathminx}{\the\pgf@pathmaxy}{\the\pgf@pathminy}}%
}
\def\pgf@setpathsizes#1{%
  \expandafter\pgf@@setpathsizes#1%
}
\def\pgf@@setpathsizes#1#2#3#4{%
  \global\pgf@pathmaxx=#1\relax%
  \global\pgf@pathminx=#2\relax%
  \global\pgf@pathmaxy=#3\relax%
  \global\pgf@pathminy=#4\relax%
}





% Append a line from the current point to #1 to the current path.
%
% #1 = end of line
% 
% Example:
%
% \pgfpathmoveto{\pgfxy(0,0)}
% \pgfpathlineto{\pgfxy(0,1)}
% \pgfstroke

\def\pgfpathlineto#1{%
  \pgfpointtransformed{#1}%
  \pgf@roundcornerifneeded%
  \pgf@nlt@lineto{\pgf@x}{\pgf@y}%
  \global\pgf@path@lastx=\pgf@x%
  \global\pgf@path@lasty=\pgf@y%
}



% Close the current path.
%
% Example:
%
% % Draws two triangles
% \pgfpathmoveto{\pgfxy(0,0)}
% \pgfpathlineto{\pgfxy(0,1)}
% \pgfpathlineto{\pgfxy(1,0)}
% \pgfclosepath
% \pgfpathmoveto{\pgfxy(2,0)}
% \pgfpathlineto{\pgfxy(2,1)}
% \pgfpathlineto{\pgfxy(3,0)}
% \pgfpathclose
% \pgfstroke

\def\pgfpathclose{%
  \pgf@roundcornerifneeded%
  \pgf@nlt@closepath%
}


% Append a cubic bezier spline from the current point to #3 with control
% points #1 and #2 to the current path.
%
% #1 = first control point
% #2 = second control point
% #3 = end point
% 
% Example:
%
% \pgfpathmoveto{\pgfpointxy{0}{0}}
% \pgfpathcurveto{\pgfpointxy{0}{1}}{\pgfpointxy{1}{1}}{\pgfpointxy{1}{2}}
% \pgfstroke

\def\pgfpathcurveto#1#2#3{%
  \pgfpointtransformed{#3}%
  \pgf@xb=\pgf@x%
  \pgf@yb=\pgf@y%
  \pgfpointtransformed{#2}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \pgfpointtransformed{#1}%
  \pgf@roundcornerifneeded%
  \pgf@nlt@curveto{\pgf@x}{\pgf@y}{\pgf@xa}{\pgf@ya}{\pgf@xb}{\pgf@yb}%
  \global\pgf@path@lastx=\pgf@xb%
  \global\pgf@path@lasty=\pgf@yb%
}



% Append a quadratic bezier spline from the current point to #2 with
% control point #1 to the current path.
%
% #1 = control point
% #2 = end point
% 
% Example:
%
% \pgfpathmoveto{\pgfpointxy{0}{0}}
% \pgfpathquadraticcurveto{\pgfpointxy{1}{1}}{\pgfpointxy{2}{0}}
% \pgfstroke

\def\pgfpathquadraticcurveto#1#2{%
  \pgfpointtransformed{#2}%
  \pgf@xb=\pgf@x%
  \pgf@yb=\pgf@y%
  \pgfpointtransformed{#1}%
  \pgf@xc=.6666666\pgf@x%
  \pgf@yc=.6666666\pgf@y%
  % compute second control point:
  \pgf@xa=.33333333\pgf@xb%
  \pgf@ya=.33333333\pgf@yb%
  \advance\pgf@xa by\pgf@xc%
  \advance\pgf@ya by\pgf@yc%
  % compute first control point
  \advance\pgf@xc by.3333333\pgf@path@lastx%
  \advance\pgf@yc by.3333333\pgf@path@lasty%
  \pgf@roundcornerifneeded%
  \pgf@nlt@curveto{\pgf@xc}{\pgf@yc}{\pgf@xa}{\pgf@ya}{\pgf@xb}{\pgf@yb}%
  \global\pgf@path@lastx=\pgf@xb%
  \global\pgf@path@lasty=\pgf@yb%
}




% Append an arc to the current point, where the current point is at
% angle #1 and the end is at angle #2. If #2 > #1, the arc is drawn
% counter-clockwise, otherwise it is clockwise.
%
% #1 = angle of first point
% #2 = angle of second point
% #3 = radius or x-radius/y-radius
% 
% Example:
%
% \pgfpathmoveto{\pgfxy(0,0)}
% \pgfpatharc{0}{90}{2cm}
% \pgfstroke

\def\pgfpatharc#1#2#3{%
  {%
    \pgfmathparse{#1}\let\pgf@temp@a=\pgfmathresult%
    \pgfmathparse{#2}\let\pgf@temp@b=\pgfmathresult%
    \pgfutil@in@{and }{#3}%
    \ifpgfutil@in@%
      \pgf@arc@get@radii#3\pgf@arc@stop%
    \else
      \pgf@arc@get@radii#3and #3\pgf@arc@stop%
    \fi%
    \pgf@arc@local@angle@a=\pgf@temp@a pt%
    \pgf@arc@local@angle@b=\pgf@temp@b pt%
    \loop%
      \pgfutil@tempdima=\pgf@arc@local@angle@a%
      \advance\pgfutil@tempdima by-\pgf@arc@local@angle@b\relax%
      \ifdim\pgfutil@tempdima<0pt\relax%
        \pgfutil@tempdima=-\pgfutil@tempdima\relax%
      \fi%
    \ifdim\pgfutil@tempdima>90pt\relax%
      \ifdim\pgfutil@tempdima>115pt\relax%
        \pgf@arc@temp=90pt% big skip
      \else%
        \pgf@arc@temp=60pt% smaller skip to ensure wide segments
                          % (important shortened end segments because
                          % of arrow tips)
      \fi%
      \ifdim\pgf@arc@local@angle@b>\pgf@arc@local@angle@a\relax%
        {%
          \pgf@arc@local@angle@b=\pgf@arc@local@angle@a\relax%
          \advance\pgf@arc@local@angle@b by\pgf@arc@temp\relax%
          \pgf@arc%
        }
        \advance\pgf@arc@local@angle@a by\pgf@arc@temp\relax%
      \else
        {%
          \pgf@arc@local@angle@b=\pgf@arc@local@angle@a\relax%
          \advance\pgf@arc@local@angle@b by-\pgf@arc@temp\relax%
          \pgf@arc%
        }%
        \advance\pgf@arc@local@angle@a by-\pgf@arc@temp\relax%
      \fi%
    \repeat%
    \pgf@roundcornerifneeded%
    \pgf@arc%
  }%
}
\dimendef\pgf@arc@local@angle@a=0
\dimendef\pgf@arc@local@angle@b=1
\dimendef\pgf@arc@temp=2

\def\pgf@arc@get@radii#1and #2\pgf@arc@stop{%
  \pgfmathparse{#1}\let\pgf@arc@radius@a=\pgfmathresult%
  \pgfmathparse{#2}\let\pgf@arc@radius@b=\pgfmathresult%
}


\def\pgf@arc{%
  {%
  \pgfutil@tempdima=\pgf@arc@radius@a pt%
  \pgfutil@tempdimb=\pgf@arc@radius@b pt%
  %
  \pgf@xa=\pgf@arc@local@angle@a\relax% 
  \pgf@xb=\pgf@arc@local@angle@b\relax%
  \advance\pgf@xb by-\pgf@xa\relax%
  \ifdim\pgf@xb<0pt\relax%
    \pgf@xb=-\pgf@xb\relax%
  \fi%
  \ifdim\pgf@xb=90.0pt%
    \def\pgfmathresult{0.55228475}%
  \else%
    \pgfmathparse{1.333333333*tan(.25*\pgf@sys@tonumber{\pgf@xb})}% many thanks to Ken Starks
  \fi%
  \pgfutil@tempdima=\pgfmathresult\pgfutil@tempdima%
  \pgfutil@tempdimb=\pgfmathresult\pgfutil@tempdimb%
  %.. controls +(\pgf@xa+90:\pgfutil@tempdima) and +(\pgf@xb-90:\pgfutil@tempdima) .. +(-(#1:#3)+(#2:#3))%
  % store first support vector in xa/ya:
  \pgf@xa=\pgf@arc@local@angle@a\relax%
  \ifdim\pgf@arc@local@angle@b>\pgf@arc@local@angle@a\relax%
    \advance\pgf@xa by 90pt\relax%
  \else%
    \advance\pgf@xa by -90pt\relax%
  \fi%
  \edef\pgf@arc@angle{\pgf@sys@tonumber{\pgf@xa}}%  
  \pgfpointtransformed{\pgfpointpolar{\pgf@arc@angle}{\pgfutil@tempdima and \pgfutil@tempdimb}}%
  \advance\pgf@x by-\pgf@pt@x%
  \advance\pgf@y by-\pgf@pt@y%
  \pgf@xa=\pgf@path@lastx%
  \pgf@ya=\pgf@path@lasty%
  \advance\pgf@xa by \pgf@x%
  \advance\pgf@ya by \pgf@y%
  % store target in xb/yb:
  \pgfpointtransformed{\pgfpointpolar{\pgf@sys@tonumber{\pgf@arc@local@angle@a}}{\pgf@arc@radius@a pt and \pgf@arc@radius@b pt}}%
  \pgf@xb=\pgf@path@lastx%
  \pgf@yb=\pgf@path@lasty%
  \advance\pgf@xb by -\pgf@x%
  \advance\pgf@yb by -\pgf@y%
  \pgfpointtransformed{\pgfpointpolar{\pgf@sys@tonumber{\pgf@arc@local@angle@b}}{\pgf@arc@radius@a pt and \pgf@arc@radius@b pt}}%
  \advance\pgf@xb by \pgf@x%
  \advance\pgf@yb by \pgf@y%
  % store second support xc/yc:
  \ifdim\pgf@arc@local@angle@b>\pgf@arc@local@angle@a\relax%
    \advance\pgf@arc@local@angle@b by -90pt\relax%
  \else%
    \advance\pgf@arc@local@angle@b by 90pt\relax%
  \fi%
  \pgfpointtransformed{\pgfpointpolar{\pgf@sys@tonumber{\pgf@arc@local@angle@b}}{\pgfutil@tempdima and \pgfutil@tempdimb}}%
  \advance\pgf@x by-\pgf@pt@x%
  \advance\pgf@y by-\pgf@pt@y%
  \pgf@xc=\pgf@xb\relax%
  \pgf@yc=\pgf@yb\relax%
  \advance \pgf@xc by \pgf@x\relax%
  \advance \pgf@yc by \pgf@y\relax%
  \pgf@nlt@curveto{\pgf@xa}{\pgf@ya}{\pgf@xc}{\pgf@yc}{\pgf@xb}{\pgf@yb}%
  \global\pgf@path@lastx=\pgf@xb%
  \global\pgf@path@lasty=\pgf@yb%
  }%
}


% Append an arc to the current point, where the arc is on an ellipse
% given by two axis vectors.
%
% #1 = angle of first point
% #2 = angle of second point
% #3 = first axis
% #4 = second axis
% 
% Example:
%
% \pgfpathmoveto{\pgfxy(0,0)}
% \pgfpatharcaxes{0}{90}{\pgfpointxy{2}{0}}{\pgfpointxy{0}{2}}
% \pgfstroke

\def\pgfpatharcaxes#1#2#3#4{%
  {%
    \pgftransformtriangle{\pgfpointorigin}{#3}{#4}%
    \pgfpatharc{#1}{#2}{1pt}%
  }%
}



% Append an arc to the current point that ends at a given position. 
%
% #1 = x-radius
% #2 = y-radius
% #3 = x-axis-rotation (in degrees)
% #4 = large-arc-sweep-flag (0 or 1)
% #5 = sweep-flag (0 or 1)
% #6 = target point
%
% Description:
%
% This command implements an arc drawing where a given target
% coordinate (#6) is given and the task is to draw an arc of an
% ellipse with the given radii. The center point of the ellipse is not
% give, but computed automatically. 
%
% This kind of "endpoint parameterization" of an arc is exactly the
% same as the one specified by the SVG-specification for the "A" and
% "a" path commands. Please see the SVG-specification for details.
% 
% Note that the problem is internally converted to drawing an arc
% using \pgfpatharc. This means that there may be a heavy loss of
% accuracy.
% 
% Example:
% 
% \pgfpathmoveto{\pgfpoint{1cm}{1cm}}
% \pgfpatharcto{1cm}{1cm}{0}{0}{0}{\pgfpoint{0cm}{2cm}}

\def\pgfpatharcto#1#2#3#4#5#6{%
  {%
    % The following code is based on the transformation described in svg
    % 1.1 specification Section F.6.5
    % 
    % Step 1: store the simple parameters (xa=x1 since TeX does not
    % allow numbers in names)
    % 
    \pgfmathsetmacro\pgf@arcto@rx{abs(#1)}%
    \pgfmathsetmacro\pgf@arcto@ry{abs(#2)}%
    \ifdim\pgf@arcto@rx pt=0pt% special rule: zero radius=straight line
      \gdef\pgf@marshal{\pgfpathlineto{#6}}%
    \else
    \ifdim\pgf@arcto@ry pt=0pt% special rule: zero radius=straight line
      \gdef\pgf@marshal{\pgfpathlineto{#6}}%
    \else
    \pgfmathsetmacro\pgf@arcto@phi{#3}%
    \pgfmathsetmacro\pgf@arcto@fA{#4}%
    \ifdim\pgf@arcto@fA pt=0pt
    \else
      \pgfmathsetmacro\pgf@arcto@fA{1.0} % Special rule: every non-zero value is 1.
    \fi
    \pgfmathsetmacro\pgf@arcto@fS{#5}%
    \ifdim\pgf@arcto@fS pt=0pt
    \else
      \pgfmathsetmacro\pgf@arcto@fS{1.0} % Special rule: every non-zero value is 1.
    \fi
    \pgf@process{#6}
    \edef\pgf@arcto@xb{\the\pgf@x}%
    \edef\pgf@arcto@yb{\the\pgf@y}%
    % 
    % Step 2: x1,y1 is more complicated to compute: It is given by lastx
    % and lasty, but these are transformed coordinates, we need the
    % untransformed ones. So, we inverse the transformation (arghh...)
    % 
    \pgftransforminvert%
    \pgf@process{\pgfpointtransformed{\pgfqpoint{\pgf@path@lastx}{\pgf@path@lasty}}}
    \edef\pgf@arcto@xa{\the\pgf@x}
    \edef\pgf@arcto@ya{\the\pgf@y}
    \edef\pgf@temp@a{\pgf@arcto@xa,\pgf@arcto@ya}
    \edef\pgf@temp@b{\pgf@arcto@xb,\pgf@arcto@yb}
    \ifx\pgf@temp@a\pgf@temp@b% special rule: skip!
      \global\let\pgf@marshal\pgfutil@empty
    \else
    %
    % Ok, now we got all the parameters setup. Now comes the
    % computation...
    % 
    % 
    % Step 3: Start with a new coordinate system and rotate everything
    % by the negated phi.
    % 
    \pgftransformreset
    \pgftransformrotate{-\pgf@arcto@phi}
    % Ok, using \pgfpointtransformed we now get transformed points...
    % 
    % Step 4: Compute x1' and y1' (xaprime and yaprime)
    %
    \pgf@process{
      \pgfpointtransformed{\pgfpointscale{.5}{\pgfpointdiff
          {\pgfqpoint{\pgf@arcto@xb}{\pgf@arcto@yb}}
          {\pgfqpoint{\pgf@arcto@xa}{\pgf@arcto@ya}}
        }
      }
    }
    \edef\pgf@arcto@xaprime{\pgf@sys@tonumber\pgf@x}
    \edef\pgf@arcto@yaprime{\pgf@sys@tonumber\pgf@y}
    % 
    % Compute Lambda 
    %
    \pgfmathsetmacro\pgf@arcto@frac@x{\pgf@arcto@xaprime/\pgf@arcto@rx}
    \pgfmathsetmacro\pgf@arcto@frac@y{\pgf@arcto@yaprime/\pgf@arcto@ry}
    \pgfmathsetmacro\pgf@arcto@lambda{
      \pgf@arcto@frac@x*\pgf@arcto@frac@x+\pgf@arcto@frac@y*\pgf@arcto@frac@y
    }
    \ifdim\pgf@arcto@lambda pt>1pt%
      \pgfmathsetmacro\pgf@arcto@sqrt@lambda{sqrt(\pgf@arcto@lambda)}
      \pgfmathsetmacro\pgf@arcto@rx{\pgf@arcto@sqrt@lambda*\pgf@arcto@rx}
      \pgfmathsetmacro\pgf@arcto@ry{\pgf@arcto@sqrt@lambda*\pgf@arcto@ry}
    \fi
    % 
    % Do some scaling 
    % 
    \pgfmathsetmacro\pgf@arcto@xaprime@abs{abs(\pgf@arcto@xaprime)}
    \pgfmathsetmacro\pgf@arcto@yaprime@abs{abs(\pgf@arcto@yaprime)}
    \pgfmathmax@{\pgf@arcto@rx,\pgf@arcto@ry,\pgf@arcto@xaprime@abs,\pgf@arcto@yaprime@abs}
    \pgfmathsetmacro\pgf@arcto@scaling{20/\pgfmathresult}
    \pgfmathsetmacro\pgf@arcto@rx@scaled{\pgf@arcto@scaling*\pgf@arcto@rx}
    \pgfmathsetmacro\pgf@arcto@ry@scaled{\pgf@arcto@scaling*\pgf@arcto@ry}
    \pgfmathsetmacro\pgf@arcto@xaprime@scaled{\pgf@arcto@scaling*\pgf@arcto@xaprime}
    \pgfmathsetmacro\pgf@arcto@yaprime@scaled{\pgf@arcto@scaling*\pgf@arcto@yaprime}
    % 
    % Step 5: Now comes the messy computation of c1' and c2'. 
    % 
    \ifdim\pgf@arcto@rx pt>\pgf@arcto@ry pt%
      \pgfmathsetmacro\pgf@arcto@rx@over@ry{\pgf@arcto@rx/\pgf@arcto@ry}
      \pgfmathsetmacro\pgf@arcto@ry@over@rx{\pgf@arcto@ry/\pgf@arcto@rx}
      \pgfmathsetmacro\pgf@arcto@temp{\pgf@arcto@ry@over@rx*\pgf@arcto@xaprime@scaled}
      \pgfmathsetmacro\pgf@arcto@numerator{
        \pgf@arcto@ry@scaled*\pgf@arcto@ry@scaled-
        \pgf@arcto@yaprime@scaled*\pgf@arcto@yaprime@scaled-
        \pgf@arcto@temp*\pgf@arcto@temp
      }
      \pgfmathsetmacro\pgf@arcto@denominator{
        \pgf@arcto@yaprime@scaled*\pgf@arcto@yaprime@scaled+
        \pgf@arcto@temp*\pgf@arcto@temp
      }
    \else
      \pgfmathsetmacro\pgf@arcto@rx@over@ry{\pgf@arcto@rx/\pgf@arcto@ry}
      \pgfmathsetmacro\pgf@arcto@ry@over@rx{\pgf@arcto@ry/\pgf@arcto@rx}
      \pgfmathsetmacro\pgf@arcto@temp{\pgf@arcto@rx@over@ry*\pgf@arcto@yaprime@scaled}
      \pgfmathsetmacro\pgf@arcto@numerator{
        \pgf@arcto@rx@scaled*\pgf@arcto@rx@scaled-
        \pgf@arcto@xaprime@scaled*\pgf@arcto@xaprime@scaled-
        \pgf@arcto@temp*\pgf@arcto@temp
      }
      \pgfmathsetmacro\pgf@arcto@denominator{
        \pgf@arcto@xaprime@scaled*\pgf@arcto@xaprime@scaled+
        \pgf@arcto@temp*\pgf@arcto@temp
      }
    \fi
    \pgfmathsetmacro\pgf@arcto@frac{
      \pgf@arcto@numerator/\pgf@arcto@denominator
    }
    \ifdim\pgf@arcto@frac pt<0pt
      \pgfmathsetmacro\pgf@arcto@factor{0}
    \else
      \pgfmathsetmacro\pgf@arcto@factor{sqrt(\pgf@arcto@frac)}
    \fi
    \ifx\pgf@arcto@fA\pgf@arcto@fS
      \pgfmathsetmacro\pgf@arcto@factor{-\pgf@arcto@factor}
    \fi
    \pgfmathsetmacro\pgf@arcto@cxprime{
      \pgf@arcto@factor*\pgf@arcto@rx@over@ry*\pgf@arcto@yaprime
    }
    \pgfmathsetmacro\pgf@arcto@cyprime{
      -\pgf@arcto@factor*\pgf@arcto@ry@over@rx*\pgf@arcto@xaprime
    }
    % 
    % Step 6: Ok, now compute cx,cy 
    % 
    \pgftransformreset
    \pgftransformrotate{\pgf@arcto@phi}
    \pgf@process{
      \pgfpointtransformed{\pgfqpoint{\pgf@arcto@cxprime pt}{\pgf@arcto@cyprime pt}}
    }
    \edef\pgf@arcto@temp{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}
    \pgf@process{\pgfpointadd{\pgf@arcto@temp}{
        \pgfpointscale{.5}{
          \pgfpointadd
          {\pgfqpoint{\pgf@arcto@xa}{\pgf@arcto@ya}}
          {\pgfqpoint{\pgf@arcto@xb}{\pgf@arcto@yb}}        }
      }
    }
    \edef\pgf@arcto@cx{\the\pgf@x}
    \edef\pgf@arcto@cy{\the\pgf@y}
    % 
    % Step 7: Compute start angle: 
    % 
    \pgfmathsetmacro\pgf@arcto@vec@x{(\pgf@arcto@xaprime-\pgf@arcto@cxprime)/\pgf@arcto@rx}
    \pgfmathsetmacro\pgf@arcto@vec@y{(\pgf@arcto@yaprime-\pgf@arcto@cyprime)/\pgf@arcto@ry}
    \pgfmathsetmacro\pgf@arcto@denominator{veclen(\pgf@arcto@vec@x,\pgf@arcto@vec@y)}
    \pgfmathsetmacro\pgf@arcto@frac{\pgf@arcto@vec@x/\pgf@arcto@denominator}
    \pgfmathsetmacro\pgf@arcto@theta@start{acos(\pgf@arcto@frac)}
    \ifdim\pgf@arcto@vec@y pt<0pt
      \pgfmathsetmacro\pgf@arcto@theta@start{-\pgf@arcto@theta@start}
    \fi
    % 
    % Step 8: Compute end angle: 
    % 
    \pgfmathsetmacro\pgf@arcto@vec@x{(-\pgf@arcto@xaprime-\pgf@arcto@cxprime)/\pgf@arcto@rx}
    \pgfmathsetmacro\pgf@arcto@vec@y{(-\pgf@arcto@yaprime-\pgf@arcto@cyprime)/\pgf@arcto@ry}
    \pgfmathsetmacro\pgf@arcto@denominator{veclen(\pgf@arcto@vec@x,\pgf@arcto@vec@y)}
    \pgfmathsetmacro\pgf@arcto@frac{\pgf@arcto@vec@x/\pgf@arcto@denominator}
    \pgfmathsetmacro\pgf@arcto@theta@end{acos(\pgf@arcto@frac)}
    \ifdim\pgf@arcto@vec@y pt<0pt
      \pgfmathsetmacro\pgf@arcto@theta@end{-\pgf@arcto@theta@end}
    \fi
    \pgfmathsetmacro\pgf@arcto@delta@theta{abs(\pgf@arcto@theta@start-\pgf@arcto@theta@end)}
    \ifdim\pgf@arcto@fA pt=0pt%
      \ifdim\pgf@arcto@delta@theta pt>180pt%
        % Ok, we need to adjust the angle!
        \ifdim\pgf@arcto@theta@end pt>\pgf@arcto@theta@start pt
          \pgfmathsetmacro\pgf@arcto@theta@end{\pgf@arcto@theta@end-360}
        \else
          \pgfmathsetmacro\pgf@arcto@theta@end{\pgf@arcto@theta@end+360}
        \fi
      \fi
    \else
      \ifdim\pgf@arcto@delta@theta pt<180pt%
        % Ok, we need to adjust the angle!
        \ifdim\pgf@arcto@theta@end pt>\pgf@arcto@theta@start pt
          \pgfmathsetmacro\pgf@arcto@theta@end{\pgf@arcto@theta@end-360}
        \else
          \pgfmathsetmacro\pgf@arcto@theta@end{\pgf@arcto@theta@end+360}
        \fi
      \fi
    \fi
    \xdef\pgf@marshal{\noexpand
      \pgfpatharcaxes{\pgf@arcto@theta@start}{\pgf@arcto@theta@end}
      {\noexpand\pgfpointpolar{\pgf@arcto@phi}{\pgf@arcto@rx}}
      {\noexpand\pgfpointpolar{\pgf@arcto@phi+90}{\pgf@arcto@ry}}
    }
    \fi\fi\fi
  }
  \pgf@marshal
}



% the quality of arc approximation by means of Bezier splines is
% controlled by a mesh width.
%
% The mesh width is provided in (full!) degrees. The smaller the mesh
% width, the more precise the arc approximation.
%
% Use an empty value to disable spline approximation (uses a single
% cubic polynomial for the complete arc).
%
% The value must be an integer!
\def\pgfpatharctomaxstepsize{45}

% A specialized arc operation for an arc on an (axis--parallel) ellipse.
%
% In contrast to \pgfpatharc, it explicitly interpolates start- and end points.
%
% In contrast to \pgfpatharcto, this routine is numerically stable and
% quite fast since it relies on a lot of precomputed information.
%
% #1 center of ellipse
% #2 angle of last path position inside of the ellipse
% #3 end angle
% #4 end point (a \pgfpoint)
% #5 xradius
% #6 yradius
% #7 the ratio xradius/yradius of the ellipse
% #8 the ratio yradius/xradius of the ellipse
% Example:
%	\def\cx{1cm}% center x
%	\def\cy{1cm}% center y
%	\def\startangle{0}%
%	\def\endangle{45}%
%	\def\a{5cm}% xradius
%	\def\b{10cm}% yradius
%	\pgfmathparse{\a/\b}\let\abratio=\pgfmathresult
%	\pgfmathparse{\b/\a}\let\baratio=\pgfmathresult
%
% \pgfpathmoveto{\pgfpoint{\cx+\a*cos(\startangle)}{\cy+\b*sin(\startangle)}}%
% \pgfpatharctoprecomputed
% 	{\pgfpoint{\cx}{\cy}}
% 	{\startangle}
% 	{\endangle}
% 	{\pgfpoint{\cx+\a*cos(\endangle)}{\cy+\b*sin(\endangle)}}%
% 	{\a}
% 	{\b}
% 	{\abratio}
% 	{\baratio}
%
\def\pgfpatharctoprecomputed#1#2#3#4#5#6#7#8{%
	\begingroup
	% Implementation idea:
	% 
	% let 
	%   m = center (#1)
	%   \gamma_0 = start angle
	%   \gamma_1 = end angle
	%   a = x radius
	%   b = y radius
	%
	% an axis parallel ellipse is parameterized by
	% C(\gamma) = m + ( a cos(\gamma), b sin(\gamma) ), \gamma in [0,360].
	%
	% Now, consider the segment \gamma(t), 
	%   \gamma:[0,1] -> [\gamma_0,\gamma_1],
	%            t   ->  \gamma_0 + t(\gamma_1 - \gamma_0)
	% and
	%   C(\gamma(t)) which is defined on [0,1].
	%
	% I'd like to approximate the arc by one or more cubic bezier
	% splines which interpolate through the last and first provided
	% points.
	%
	% In general, a Bezier spline C:[0,1] -> \R of order n fulfills
	% C'(0) = n ( P_1 - P_0 ),
	% C'(1) = n ( P_n - P_{n-1} ).
	% For n=3 and given P_0 and P_3, I can directly compute P_1 and P_2 once I know
	% the derivatives at t=0 and t=1.
	%
	% The derivatives in our case are 
	%   ( C \circ \gamma )'(t) = C'[\gamma(t)] * \gamma'(t) 
	%   	= ( -a pi/180 sin(\gamma(t)),  b pi/180 cos(\gamma(t)) ) * (\gamma_1 - \gamma_0).
	% The pi/180 comes into play since we are working with degrees.
	%
	% Expression (C\circ\gamma)'(0) using P_0 and (C \circ \gamma)'(1)
	% using P_3 yields the expressions
	%   (C \circ \gamma)'(0) = 
	%   	pi/180 * (\gamma_1 - \gamma_0)* [ - a/b(P_0^y - my), b/a (P_0^x - mx) ]
	%   (C \circ \gamma)'(1) = 
	%   	pi/180 * (\gamma_1 - \gamma_0)* [ - a/b(P_3^y - my), b/a (P_3^x - mx) ]
	%
	% defining 
	%  scaleA = a/b * pi / (3*180) * (\gamma_1 - \gamma_0)
	% and
	%  scaleB = b/a * pi / (3*180) * (\gamma_1 - \gamma_0)
	% yields the direct expressions for the intermediate bezier
	% control points
	%
	% P_1 = [
	%   P_0^x - scaleA* ( P_0^y -my),
	%   P_0^y + scaleB* ( P_0^x -mx) ]
	% and
	% P_2 = [
	%   P_3^x + scaleA* ( P_3^y -my),
	%   P_3^y - scaleB* ( P_3^x -mx) ].
	%
	% This works fast, with few operations, if
	% - a/b and b/a are known in advance
	% - P_0 and P_3 are known in advance
	% - \gamma_0 and \gamma_1 are known.
	%
	% It is also reliable if (\gamma_1 - \gamma_0) is small
	%
	\pgf@process{#1}%
	\edef\pgfpath@center@x{\the\pgf@x}%
	\edef\pgfpath@center@y{\the\pgf@y}%
	\def\pgfpath@completearcend{#4}%
	% compute scale (#3-#2) * pi/(3*180) = (#3 - #2) * pi/27 * 1/20
	% splitting pi/(3*180) into two scales has higher TeX accuracy
	\pgf@xa=#2pt
	\pgf@xb=#3pt
	\edef\pgfpath@startangle{#2pt}%
	\edef\pgfpath@endangle{\pgf@sys@tonumber\pgf@xb}%
	%
	\pgf@ya=\pgf@xb
	\advance\pgf@ya by-\pgf@xa
	%
	\ifx\pgfpatharctomaxstepsize\pgfutil@empty
		\def\pgfpath@N{1}%
		\pgf@xc=\pgf@ya
	\else
		\pgf@xc=\pgf@ya% compute N = floor((gamma_1 - gamma_0) / max) +1
		\ifdim\pgf@xc<0pt
			\multiply\pgf@xc by-1
		\fi
		\divide\pgf@xc by\pgfpatharctomaxstepsize\relax
		\afterassignment\pgfutil@gobble@until@relax
		\c@pgf@counta=\the\pgf@xc\relax
		\advance\c@pgf@counta by1
		\edef\pgfpath@N{\the\c@pgf@counta}%
		%
		\pgf@xc=\pgf@ya
		\divide\pgf@xc by\c@pgf@counta
	\fi
	%
	\edef\pgfpath@h{\pgf@sys@tonumber\pgf@xc}%
	%
%\message{pgfpathellipse: using N =\pgfpath@N\space spline points y0 = \pgfpath@startangle, y0+i*h, yN=\pgfpath@endangle, i=1,...,(\pgfpath@N-1), with h=\pgfpath@h\space mesh width (total arc angle \pgf@sys@tonumber\pgf@ya).}%
	%
	%
	\pgf@xc=0.116355283466289\pgf@xc % pi/27
	\divide\pgf@xc by20
	\pgf@xa=#7\pgf@xc
	\edef\pgfpath@scale@A{\pgf@sys@tonumber\pgf@xa}%
	\pgf@xa=#8\pgf@xc
	\edef\pgfpath@scale@B{\pgf@sys@tonumber\pgf@xa}%
	%
	% compute intermediate spline segments for
	%  i = 1,...,N-1
	% this is a no-op for N=1.
	\c@pgf@countd=1
	\pgfutil@loop
	\ifnum\c@pgf@countd<\pgfpath@N\relax
		%
		\pgf@xa=\pgfpath@startangle % compute \pgf@xa = y_0 + i*h
		\pgf@xb=\pgfpath@h pt
		\multiply\pgf@xb by\c@pgf@countd
		\advance\pgf@xa by\pgf@xb
		\edef\pgfpath@angle@i{\pgf@sys@tonumber\pgf@xa}%
%\message{angle \the\c@pgf@countd: \pgfpath@angle@i...}%
		%
		\pgfpatharcofellipse@{%
			\pgfpoint
				{\pgfpath@center@x + #5*cos(\pgfpath@angle@i)}
				{\pgfpath@center@y + #6*sin(\pgfpath@angle@i)}%
		}%
		%
		\advance\c@pgf@countd by1
	\pgfutil@repeat
	%
	% compute final spline segment. It only differs insofar as the
	% final point is already known explicitly and should be
	% interpolated without additional math error.
%\message{angle \pgfpath@N: \pgfpath@endangle...}%
	\pgfpatharcofellipse@{\pgfpath@completearcend}%
	\endgroup
}%
\def\pgfpatharcofellipse@#1{%
	\begingroup
	\pgf@process{#1}%
	\edef\pgfpath@endpt{\global\pgf@x=\the\pgf@x\space\global\pgf@y=\the\pgf@y\space}%
	%
	\pgfpathcurveto{
		\begingroup
		\global\pgf@x=\pgf@path@lastx
		\global\pgf@y=\pgf@path@lasty
		\pgf@xa=\pgf@x \advance\pgf@xa by-\pgfpath@center@x
		\pgf@ya=\pgf@y \advance\pgf@ya by-\pgfpath@center@y
		\global\advance\pgf@x by-\pgfpath@scale@A\pgf@ya
		\global\advance\pgf@y by \pgfpath@scale@B\pgf@xa
		\endgroup
	}{%
		\begingroup
		\pgfpath@endpt
		\pgf@xa=\pgf@x \advance\pgf@xa by-\pgfpath@center@x
		\pgf@ya=\pgf@y \advance\pgf@ya by-\pgfpath@center@y
		\global\advance\pgf@x by \pgfpath@scale@A\pgf@ya
		\global\advance\pgf@y by-\pgfpath@scale@B\pgf@xa
		\endgroup
	}{%
		\pgfpath@endpt
	}%
	\endgroup
}









% Append  an ellipse to the current path.
%
% #1 = center
% #2 = first axis
% #3 = second axis
%  
% Example:
%
% % Add a circle of radius 3cm around the origin
% \pgfpathellipse{\pgforigin}{\pgfxy(2,0)}{\pgfxy(0,1)}
%
% % Draw a non-filled circle of radius 1cm around the point (1,1)
% \pgfpathellipse{\pgfxy(1,1)}{\pgfxy(1,1)}{\pgfxy(-2,2)}
% \pgfstroke

\def\pgfpathellipse#1#2#3{%
  \pgfpointtransformed{#1}% store center in xc/yc
  \pgf@xc=\pgf@x%
  \pgf@yc=\pgf@y%
  \pgfpointtransformed{#2}%
  \pgf@xa=\pgf@x% store first axis in xa/ya
  \pgf@ya=\pgf@y%
  \advance\pgf@xa by-\pgf@pt@x%
  \advance\pgf@ya by-\pgf@pt@y%
  \pgfpointtransformed{#3}%
  \pgf@xb=\pgf@x% store second axis in xb/yb
  \pgf@yb=\pgf@y%
  \advance\pgf@xb by-\pgf@pt@x%
  \advance\pgf@yb by-\pgf@pt@y%
  {%
    \advance\pgf@xa by\pgf@xc%
    \advance\pgf@ya by\pgf@yc%
    \pgf@nlt@moveto{\pgf@xa}{\pgf@ya}%
  }%
  \pgf@x=0.55228475\pgf@xb% first arc
  \pgf@y=0.55228475\pgf@yb%
  \advance\pgf@x by\pgf@xa%
  \advance\pgf@y by\pgf@ya%
  \advance\pgf@x by\pgf@xc%
  \advance\pgf@y by\pgf@yc%
  \edef\pgf@temp{\pgf@xc\the\pgf@x\pgf@yc\the\pgf@y}%
  \pgf@x=0.55228475\pgf@xa%
  \pgf@y=0.55228475\pgf@ya%
  \advance\pgf@x by\pgf@xb%
  \advance\pgf@y by\pgf@yb%
  {%
    \advance\pgf@x by\pgf@xc%
    \advance\pgf@y by\pgf@yc%
    \advance\pgf@xb by\pgf@xc%
    \advance\pgf@yb by\pgf@yc%
    \pgf@temp%
    \pgf@nlt@curveto{\pgf@xc}{\pgf@yc}{\pgf@x}{\pgf@y}{\pgf@xb}{\pgf@yb}%
  }%
  \pgf@xa=-\pgf@xa% flip first axis
  \pgf@ya=-\pgf@ya%
  \pgf@x=0.55228475\pgf@xa% second arc
  \pgf@y=0.55228475\pgf@ya%
  \advance\pgf@x by\pgf@xb%
  \advance\pgf@y by\pgf@yb%
  \advance\pgf@x by\pgf@xc%
  \advance\pgf@y by\pgf@yc%
  \edef\pgf@temp{\pgf@xc\the\pgf@x\pgf@yc\the\pgf@y}%
  \pgf@x=0.55228475\pgf@xb%
  \pgf@y=0.55228475\pgf@yb%
  \advance\pgf@x by\pgf@xa%
  \advance\pgf@y by\pgf@ya%
  {%
    \advance\pgf@x by\pgf@xc%
    \advance\pgf@y by\pgf@yc%
    \advance\pgf@xa by\pgf@xc%
    \advance\pgf@ya by\pgf@yc%
    \pgf@temp%
    \pgf@nlt@curveto{\pgf@xc}{\pgf@yc}{\pgf@x}{\pgf@y}{\pgf@xa}{\pgf@ya}%
  }%
  \pgf@xb=-\pgf@xb% flip second axis
  \pgf@yb=-\pgf@yb%
  \pgf@x=0.55228475\pgf@xb% third arc
  \pgf@y=0.55228475\pgf@yb%
  \advance\pgf@x by\pgf@xa%
  \advance\pgf@y by\pgf@ya%
  \advance\pgf@x by\pgf@xc%
  \advance\pgf@y by\pgf@yc%
  \edef\pgf@temp{\pgf@xc\the\pgf@x\pgf@yc\the\pgf@y}%
  \pgf@x=0.55228475\pgf@xa%
  \pgf@y=0.55228475\pgf@ya%
  \advance\pgf@x by\pgf@xb%
  \advance\pgf@y by\pgf@yb%
  {%
    \advance\pgf@x by\pgf@xc%
    \advance\pgf@y by\pgf@yc%
    \advance\pgf@xb by\pgf@xc%
    \advance\pgf@yb by\pgf@yc%    
    \pgf@temp%
    \pgf@nlt@curveto{\pgf@xc}{\pgf@yc}{\pgf@x}{\pgf@y}{\pgf@xb}{\pgf@yb}%
  }%
  \pgf@xa=-\pgf@xa% flip first axis once more
  \pgf@ya=-\pgf@ya%
  \pgf@x=0.55228475\pgf@xa% fourth arc
  \pgf@y=0.55228475\pgf@ya%
  \advance\pgf@x by\pgf@xb%
  \advance\pgf@y by\pgf@yb%
  \advance\pgf@x by\pgf@xc%
  \advance\pgf@y by\pgf@yc%
  \edef\pgf@temp{\pgf@xc\the\pgf@x\pgf@yc\the\pgf@y}%
  \pgf@x=0.55228475\pgf@xb%
  \pgf@y=0.55228475\pgf@yb%
  \advance\pgf@x by\pgf@xa%
  \advance\pgf@y by\pgf@ya%
  {%
    \advance\pgf@x by\pgf@xc%
    \advance\pgf@y by\pgf@yc%
    \advance\pgf@xa by\pgf@xc%
    \advance\pgf@ya by\pgf@yc%    
    \pgf@temp%
    \pgf@nlt@curveto{\pgf@xc}{\pgf@yc}{\pgf@x}{\pgf@y}{\pgf@xa}{\pgf@ya}%
  }%
  \pgf@nlt@closepath%
  \pgf@nlt@moveto{\pgf@xc}{\pgf@yc}%
}



% Append a circle to the current path
%
% #1 = center
% #2 = radius
%  
% Example:
%
% % Append a circle of radius 3cm around the the point (1,1)
% \pgfpathcircle{\pgxy(1,1)}{3cm}

\def\pgfpathcircle#1#2{\pgfpathellipse{#1}{\pgfpoint{#2}{0pt}}{\pgfpoint{0pt}{#2}}}




% Append a rectangle to the current path
%
% #1 = lower left corner point of rectangle
% #2 = width and height vector
%  
% Example:
%
% % A rectangle with corners (2,2) and (3,3)
% \pgfpathrectangle{\pgfpointxy{2}{2}}{\pgfpointxy{1}{1}}

\def\pgfpathrectangle{%
  \let\pgfrect@next=\pgf@specialrect%
  \ifpgf@pt@identity%
    \ifpgf@arccorners%
    \else%
      \ifx\pgf@nlt@list\pgfutil@empty%
        \let\pgfrect@next=\pgf@normalrect%
      \fi%
    \fi%
  \fi%
  \pgfrect@next%
}

\def\pgf@normalrect#1#2{%
  \pgf@process{#2}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \pgfpointtransformed{#1}%
  \pgfsyssoftpath@rect{\the\pgf@x}{\the\pgf@y}{\the\pgf@xa}{\the\pgf@ya}%
  \pgf@protocolsizes{\pgf@x}{\pgf@y}%
  \advance\pgf@x by\pgf@xa\relax%
  \advance\pgf@y by\pgf@ya\relax%
  \pgf@protocolsizes{\pgf@x}{\pgf@y}%
}

\def\pgf@specialrect#1#2{%
  \pgf@process{#2}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \pgf@process{#1}%
  \pgf@xb=\pgf@x%
  \pgf@yb=\pgf@y%
  \advance\pgf@xa by\pgf@xb%
  \advance\pgf@ya by\pgf@yb%
  \pgfpathmoveto{\pgfqpoint{\pgf@xa}{\pgf@ya}}%
  \pgfpathlineto{\pgfqpoint{\pgf@xb}{\pgf@ya}}%
  \pgfpathlineto{\pgfqpoint{\pgf@xb}{\pgf@yb}}%
  \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@yb}}%
  \pgfpathclose%
  \pgfpathmoveto{\pgfqpoint{\pgf@xb}{\pgf@yb}}%
}

% Append a rectangle to the current path
%
% #1 = one corner of the rectangle
% #2 = opposite corner of the rectangle
%  
% Example:
%
% % A rectangle with corners (2,2) and (3,3)
% \pgfpathrectanglecorners{\pgfpointxy{2}{2}}{\pgfpointxy{3}{3}}

\def\pgfpathrectanglecorners#1#2{%
  \pgf@process{#2}%
  \pgf@xc=\pgf@x%
  \pgf@yc=\pgf@y%
  \pgf@process{#1}%
  \advance\pgf@xc by-\pgf@x%
  \advance\pgf@yc by-\pgf@y%
  \pgfpathrectangle{#1}{\pgfqpoint{\pgf@xc}{\pgf@yc}}%
}


% Append a grid to the current path.
%
% #1 = first corner point of grid
% #2 = second corner point of grid
%  
% Options: 
%  
% stepx = x-step dimension (default 1cm)
% stepy = y-step dimension (default 1cm)
% step  = dimesion vector
%  
% Example:
%
% \pgfsetlinewidth{0.8pt}
% \pgfgrid{\pgfxy(0,0)}{\pgfxy(3,2)}
% \pgfsetlinewidth{0.4pt}
% \pgfgrid[stepx=1cm,stepy=1cm]{\pgfxy(0,0)}{\pgfxy(3,2)}

\pgfkeys{
  /pgf/stepx/.initial=1cm,
  /pgf/stepy/.initial=1cm,
  /pgf/step/.code={\pgf@process{#1}\pgfkeysalso{/pgf/stepx/.expanded=\the\pgf@x,/pgf/stepy/.expanded=\the\pgf@y}},
  /pgf/step/.value required
}

\def\pgfpathgrid{\pgfutil@ifnextchar[{\pgf@pathgrid}{\pgf@pathgrid[]}}
\def\pgf@pathgrid[#1]#2#3{%
  \pgfset{#1}%
  \pgfmathsetlength\pgf@xc{\pgfkeysvalueof{/pgf/stepx}}%
  \pgfmathsetlength\pgf@yc{\pgfkeysvalueof{/pgf/stepy}}%
  \pgf@process{#3}%
  \pgf@xb=\pgf@x%
  \pgf@yb=\pgf@y%
  \pgf@process{#2}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  % Swap coordinates if one of them is smaller than the other:
  \ifdim\pgf@xa>\pgf@xb%
    \pgf@x=\pgf@xb%
    \pgf@xb=\pgf@xa%
    \pgf@xa=\pgf@x%
  \fi%
  \ifdim\pgf@ya>\pgf@yb%
    \pgf@y=\pgf@yb%
    \pgf@yb=\pgf@ya%
    \pgf@ya=\pgf@y%
  \fi%
  \c@pgf@counta=\pgf@ya\relax%
  \c@pgf@countb=\pgf@yc\relax%
  \divide\c@pgf@counta by\c@pgf@countb\relax%
  \pgfutil@tempdima=\c@pgf@counta\pgf@yc\relax%
  \ifdim\pgfutil@tempdima<\pgf@ya%
    \advance\pgfutil@tempdima by\pgf@yc%
  \fi%
  \pgfutil@tempdimb\pgf@x
  \pgfutil@loop% horizontal lines
    {%
      \pgf@xa=\pgfutil@tempdimb%
      \pgf@ya=\pgfutil@tempdima%
      \pgf@pos@transform{\pgf@xa}{\pgf@ya}
      \pgf@nlt@moveto{\pgf@xa}{\pgf@ya}%
      \pgf@xa=\pgf@xb%
      \pgf@ya=\pgfutil@tempdima%
      \pgf@pos@transform{\pgf@xa}{\pgf@ya}
      \pgf@nlt@lineto{\pgf@xa}{\pgf@ya}%
    }%
  \advance\pgfutil@tempdima by\pgf@yc%
  \ifdim\pgfutil@tempdima<\pgf@yb%
  \pgfutil@repeat%
  \advance\pgfutil@tempdima by-0.01pt\relax%
  \ifdim\pgfutil@tempdima<\pgf@yb%
    {%
      \pgf@xa=\pgfutil@tempdimb%
      \pgf@ya=\pgfutil@tempdima%
      \pgf@pos@transform{\pgf@xa}{\pgf@ya}
      \pgf@nlt@moveto{\pgf@xa}{\pgf@ya}%
      \pgf@xa=\pgf@xb%
      \pgf@ya=\pgfutil@tempdima%
      \pgf@pos@transform{\pgf@xa}{\pgf@ya}
      \pgf@nlt@lineto{\pgf@xa}{\pgf@ya}%
    }%
  \fi%
  \c@pgf@counta=\pgfutil@tempdimb\relax%
  \c@pgf@countb=\pgf@xc\relax%
  \divide\c@pgf@counta by\c@pgf@countb\relax%
  \pgfutil@tempdimb=\c@pgf@counta\pgf@xc\relax%
  \ifdim\pgfutil@tempdimb<\pgf@xa%
    \advance\pgfutil@tempdimb by\pgf@xc%
  \fi%
  \pgfutil@loop% vertical lines
    {%
      \pgf@xc=\pgfutil@tempdimb%
      \pgf@yc=\pgf@ya%
      \pgf@pos@transform{\pgf@xc}{\pgf@yc}
      \pgf@nlt@moveto{\pgf@xc}{\pgf@yc}%
      \pgf@xc=\pgfutil@tempdimb%
      \pgf@yc=\pgf@yb%
      \pgf@pos@transform{\pgf@xc}{\pgf@yc}
      \pgf@nlt@lineto{\pgf@xc}{\pgf@yc}%
    }%
    \advance\pgfutil@tempdimb by\pgf@xc%
  \ifdim\pgfutil@tempdimb<\pgf@xb%
  \pgfutil@repeat%
  \advance\pgfutil@tempdimb by-0.01pt\relax%
  \ifdim\pgfutil@tempdimb<\pgf@xb%
    {%
      \pgf@xc=\pgfutil@tempdimb%
      \pgf@yc=\pgf@ya%
      \pgf@pos@transform{\pgf@xc}{\pgf@yc}
      \pgf@nlt@moveto{\pgf@xc}{\pgf@yc}%
      \pgf@xc=\pgfutil@tempdimb%
      \pgf@yc=\pgf@yb%
      \pgf@pos@transform{\pgf@xc}{\pgf@yc}
      \pgf@nlt@lineto{\pgf@xc}{\pgf@yc}%
    }%
  \fi%
}



% Append two half-parabolas to the path
%
% #1 = bend (relative to current point)
% #2 = end point (relative to bend point)
%  
% Description:
%  
% This command appends a half-parabola that starts at the current point
% and has its bend at #1+current point. Then, a second parabola is
% appended that starts at #1+current point, where it also has its
% minimum/maximum, and ends at #1+current point+#2, which becomes the
% new current point. 
%  
% By setting #2 = (0,0) you draw only a half parabola that goes from the
% current point to the bend; by setting #1 = (0,0)
% you draw a half parabola that going to current point + #2 and has its
% bend at the current point. 
%  
% Examples:
%
% % Half-parabola going ``up and right''
% \pgfpathmoveto{\pgfpointorigin}
% \pgfpathparabola{\pgfpointorigin}{\pgfpoint{2cm}{4cm}}
%
% % Half-parabola going ``down and right''
% \pgfpathmoveto{\pgfpointorigin}
% \pgfpathparabola{\pgfpoint{-2cm}{4cm}}}{\pgfpointorigin}
%
% % Full parabola
% \pgfpathmoveto{\pgfpointorigin}
% \pgfpathparabola{\pgfpoint{-2cm}{4cm}}{\pgfpoint{2cm}{4cm}}

\def\pgfpathparabola#1#2{%
  {%
    \pgf@process{#2}% untransformed
    \pgf@xb=\pgf@x%
    \pgf@yb=\pgf@y%
    \pgf@process{#1}% untransformed
    \pgf@xc=\pgf@x%
    \pgf@yc=\pgf@y%
    \pgfutil@tempswatrue%
    \ifdim\pgf@xb=0pt\relax%
      \ifdim\pgf@yb=0pt\relax%
        \pgfutil@tempswafalse%
      \fi%
    \fi%  
    {%
      \ifpgfutil@tempswa%
        \pgf@arccornersfalse
      \else%
      \fi%
      \pgfutil@tempswatrue%
      \ifdim\pgf@xc=0pt\relax%
        \ifdim\pgf@yc=0pt\relax%
          \pgfutil@tempswafalse%
        \fi%
      \fi%
      \ifpgfutil@tempswa  
      {%
        \pgf@pt@x=\pgf@path@lastx%
        \pgf@pt@y=\pgf@path@lasty%
        \pgfpathcurveto%
          {\pgfqpoint{.1125\pgf@xc}{.225\pgf@yc}}% found by trial and error
          {\pgfqpoint{.5\pgf@xc}{\pgf@yc}}% found by trial and error
          {\pgfqpoint{\pgf@xc}{\pgf@yc}}%
      }%
      \fi%
    }%
    \ifpgfutil@tempswa%
      \pgf@xc=\pgf@xb%
      \pgf@yc=\pgf@yb%
      {%
        \pgf@pt@x=\pgf@path@lastx%
        \pgf@pt@y=\pgf@path@lasty%
        \pgfpathcurveto%
          {\pgfqpoint{.5\pgf@xc}{0\pgf@yc}}% found by trial and error
          {\pgfqpoint{.8875\pgf@xc}{.775\pgf@yc}}% found by trial and error
          {\pgfqpoint{\pgf@xc}{\pgf@yc}}%
      }%
    \fi%
  }%  
}  




% Append a sine curve between 0 and \pi/2 to the path.
%
% #1 = vector, describing the width and height of the curve
%  
% Description:
%  
% This command appends a sine curve in the interval 0 and \pi/2 to the
% current path. The sine curve ends at currentpoint+#1.
%  
% Examples:
%
% % One complete sine in the interval [0,\pi]
% \pgfpathmoveto{\pgfpointorigin}
% \pgfpathsine{\pgfpoint{1.57cm}{1cm}}
% \pgfpathcosine{\pgfpoint{3.141cm}{0cm}}

\def\pgfpathsine#1{%
  {%
    \pgf@process{#1}% untransformed
    \pgf@xc=\pgf@x%
    \pgf@yc=\pgf@y%
    \pgf@pt@x=\pgf@path@lastx% evil trickery to transform to the last point
    \pgf@pt@y=\pgf@path@lasty%
    \pgfpathcurveto%
      {\pgfqpoint{.31831\pgf@xc}{.5\pgf@yc}}% found by trial and error
      {\pgfqpoint{.63503\pgf@xc}{\pgf@yc}}% found by trial and error
      {\pgfqpoint{\pgf@xc}{\pgf@yc}}%
  }%  
}  

% Append a cosine curve between 0 and \pi/2 to the path.
%
% #1 = vector, describing the width and height of the curve
%  
% Examples:
%
% % One complete sine in the interval [0,\pi]
% \pgfpathmoveto{\pgfpointorigin}
% \pgfpathsine{\pgfpoint{1.57cm}{1cm}}
% \pgfpathcosine{\pgfpoint{3.141cm}{0cm}}

\def\pgfpathcosine#1{%
  {%
    \pgf@process{#1}% untransformed
    \pgf@xc=\pgf@x%
    \pgf@yc=\pgf@y%
    \pgf@pt@x=\pgf@path@lastx% evil trickery to transform to the last point
    \pgf@pt@y=\pgf@path@lasty%
    \pgfpathcurveto%
      {\pgfqpoint{.36497\pgf@xc}{0pt}}% found by trial and error
      {\pgfqpoint{.68169\pgf@xc}{.5\pgf@yc}}% found by trial and error
      {\pgfqpoint{\pgf@xc}{\pgf@yc}}%
  }%  
}  



% Draw part of a curve between two specified times s and t.
%
% #1 - a start time s.
% #2 - an end time t.
% #3 - start point of the curve
% #4 - first control
% #5 - second control
% #6 - end point of the curve
%
% There are two versions, \pgfpathcurvebetweentime and 
% \pgfpathcurvebetweentimecontinue. The latter does not insert a
% moveto to the first point.
%
\def\pgfpathcurvebetweentime{\pgf@ignoremovetofalse\pgf@@pathcurvebetweentime}
\def\pgfpathcurvebetweentimecontinue{\pgf@ignoremovetotrue\pgf@@pathcurvebetweentime}
\newif\ifpgf@ignoremoveto

\def\pgf@@pathcurvebetweentime#1#2#3#4#5#6{%
  \pgfmathparse{#1}%
  \let\pgf@time@s=\pgfmathresult%
  \pgfmathparse{#2}%
  \let\pgf@time@t=\pgfmathresult%
  \ifdim\pgf@time@s pt>\pgf@time@t pt\relax%
    \pgfmathsetmacro\pgf@time@s{1-#1}%
    \pgfmathsetmacro\pgf@time@t{1-#2}%
    \pgf@@@pathcurvebetweentime{\pgf@time@t}{#6}{#5}{#4}{#3}%
  \else%
    \pgf@@@pathcurvebetweentime{\pgf@time@t}{#3}{#4}{#5}{#6}%
  \fi%
}

\def\pgf@@@pathcurvebetweentime#1#2#3#4#5{%
  % Q1 = P1.
  \pgf@process{#2}% 
  \pgf@xc=\pgf@x%
  \pgf@yc=\pgf@y%
  % Q2 = P1 + t*(P2-P1).
  \pgf@process{%
    \pgf@process{#3}%
    \pgf@xa=#1\pgf@x%
    \pgf@ya=#1\pgf@y%
    \pgf@process{#2}%
    \pgf@xb=\pgf@x%
    \pgf@yb=\pgf@y%
    \advance\pgf@x by-#1\pgf@xb%
    \advance\pgf@y by-#1\pgf@yb%
    \advance\pgf@x by\pgf@xa%
    \advance\pgf@y by\pgf@ya%
  }%
  \pgf@xb=\pgf@x%
  \pgf@yb=\pgf@y%
  % Q3 = Q2 + t*((P2 + t*(P3-P2)) - Q2).
  \pgf@process{%
    \pgf@process{#4}%
    \pgf@xa=#1\pgf@x%
    \pgf@ya=#1\pgf@y%  
    %
    \pgf@process{#3}%
    \pgf@xc=\pgf@x%
    \pgf@yc=\pgf@y%
    \advance\pgf@xc by-#1\pgf@x%
    \advance\pgf@yc by-#1\pgf@y%
    %
    \pgf@x=\pgf@xb%
    \pgf@y=\pgf@yb%
    \advance\pgf@x by#1\pgf@xa%
    \advance\pgf@y by#1\pgf@ya%    
    \advance\pgf@x by-#1\pgf@xb%
    \advance\pgf@y by-#1\pgf@yb%
    \advance\pgf@x by#1\pgf@xc%
    \advance\pgf@y by#1\pgf@yc%
  }%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  % Q4 = (1-t)^3*P1 + 3*t(1-t)^2*P2 + 3*t^2(1-t)*P3 + t^3*P4.
  \pgf@process{\pgfpointcurveattime{#1}{#2}{#3}{#4}{#5}}% 
  \ifx#1\pgf@time@t%
    % First time round...
    \pgfmathdivide@{\pgf@time@s}{\pgf@time@t}%
    \pgfmathadd@{-\pgfmathresult}{1}%
    \let\pgf@time@s=\pgfmathresult%
    \edef\pgf@marshal{%
      \noexpand\pgf@@@pathcurvebetweentime{\noexpand\pgf@time@s}%
        {\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}{\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}%
        {\noexpand\pgfqpoint{\the\pgf@xb}{\the\pgf@yb}}{\noexpand\pgfqpoint{\the\pgf@xc}{\the\pgf@yc}}%
    }%
  \else%
    % ...second time round.
    \ifpgf@ignoremoveto%
      \edef\pgf@marshal{%
        \noexpand\pgfpathcurveto{\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}%
          {\noexpand\pgfqpoint{\the\pgf@xb}{\the\pgf@yb}}{\noexpand\pgfqpoint{\the\pgf@xc}{\the\pgf@yc}}%
      }%
    \else%
      \edef\pgf@marshal{%
        \noexpand\pgfpathmoveto{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
        \noexpand\pgfpathcurveto{\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}%
          {\noexpand\pgfqpoint{\the\pgf@xb}{\the\pgf@yb}}{\noexpand\pgfqpoint{\the\pgf@xc}{\the\pgf@yc}}%
      }%
    \fi%
  \fi%
  \pgf@marshal%
}


\endinput

pgfcorepathprocessing.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/basiclayer/pgfcorepathprocessing.code.tex,v 1.9 2013/09/09 10:05:41 tantau Exp $


% Split a path at the last subpath of a path
%
% #1 = a macro that stores a path
% 
% Description:
%
% This command will split the path into two parts:
%
% \pgfprocessresultpathprefix
%   The part of the path before the last subpath.
%   
% \pgfprocessresultpathsuffix
%   The last subpath on the path.
%
% #1 will always be equal to the contents of the two above macros
% concatenated. Normally, your objective will be to modify the
% \pgfprocessresultpathsuffix and then concatenate the result.

\def\pgfprocesssplitpath#1{%
  \let\pgfprocessresultpathprefix\pgfutil@empty%
  \let\pgfprocessresultpathsuffix\pgfutil@empty%
  \let\pgf@next\pgf@process@split%      
  \expandafter\pgf@process@split#1\pgfsyssoftpath@movetotoken{}{}\pgf@stop%
}

\def\pgf@process@split#1\pgfsyssoftpath@movetotoken#2#3#4{%
  \ifx#4\pgf@stop% ok, end reached!
    \expandafter\def\expandafter\pgfprocessresultpathsuffix\expandafter{\pgfprocessresultpathsuffix#1}%
    \let\pgf@next\pgfutil@gobble%
  \else%
    \expandafter\expandafter\expandafter\def%
    \expandafter\expandafter\expandafter\pgfprocessresultpathprefix%
    \expandafter\expandafter\expandafter{\expandafter\pgfprocessresultpathprefix\pgfprocessresultpathsuffix#1}%
    \def\pgfprocessresultpathsuffix{\pgfsyssoftpath@movetotoken{#2}{#3}}%
  \fi%
  \pgf@next#4%
}



% Split a subpath at the end
% 
% #1 = a macro that stores an open subpath that contains at least two
%      path commands (so, not just a moveto);
% 
% Description:
% 
% Splits the supath into two parts:
%
% \pgfprocessresultsubpathsuffix
%   This macro contains the last two "relevant" path commands: The end
%   of the path command that led to the last path command and this
%   last path command. In essence, this macro contains everything you
%   "need to modify" if you wish to modify the end of the path.
%
% \pgfprocessresultsubpathprefix
%   Everything before the previous macro on the subpath.

\def\pgfprocesssplitsubpath#1{%
  % First, we need to find the end:
  \let\pgf@tempa\pgfutil@emtpy%
  \let\pgf@tempb\pgfutil@emtpy%
  \let\pgf@tempc\pgfutil@emtpy%
  \let\pgf@tempd\pgfutil@emtpy%
  \let\pgfprocessresultsubpathprefix\pgfutil@empty%
  \let\pgfprocessresultsubpathsuffix\pgfutil@empty%
  \let\pgf@next\pgf@split@subpath%
  \expandafter\pgf@split@subpath#1\pgf@stop%
}

\newif\ifpgf@split@move

\def\pgf@split@subpath#1#2#3#4{%
  \ifx#4\pgf@stop%
    \expandafter\def\expandafter\pgfprocessresultsubpathsuffix\expandafter{\pgfprocessresultsubpathsuffix#1{#2}{#3}}%
    \let\pgf@next\pgfutil@gobble%
  \else%
    \pgf@split@movetrue%  
    \ifx#1\pgfsyssoftpath@curvetosupportatoken%
      \pgf@split@movefalse%
    \else
      \ifx#1\pgfsyssoftpath@curvetosupportbtoken%
        \pgf@split@movefalse%
      \fi%
    \fi%
    \ifpgf@split@move%
      \expandafter\expandafter\expandafter\def%
      \expandafter\expandafter\expandafter\pgfprocessresultsubpathprefix%
      \expandafter\expandafter\expandafter{%
        \expandafter\pgfprocessresultsubpathprefix\pgfprocessresultsubpathsuffix}%
      \def\pgfprocessresultsubpathsuffix{#1{#2}{#3}}%
    \else%
      \expandafter\def\expandafter\pgfprocessresultsubpathsuffix\expandafter{\pgfprocessresultsubpathsuffix#1{#2}{#3}}%
    \fi%
  \fi%
  \pgf@next#4%
}




% Extract start and end vectors of a path
%
% #1 = a macro that stores a path
%
% Description:
%
% This command will extract the first and second coordinate on the
% path as well as the last and second-last. These coordinates will be
% put in the pgfpoint-macros \pgfpointfirstonpath,
% \pgfpointsecondonpath, \pgfpointsecondlastonpath, and
% \pgfpointlastonpath. If the path is empty, these macros are set to
% \pgfpointorigin. 
%
% Example:
%
% \pgfsyssoftpath@moveto{0}{0}
% \pgfsyssoftpath@lineto{10}{10}
% \pgfsyssoftpath@curveto{20}{20}{30}{30}{40}{40}
% \pgfsyssoftpath@getcurrentpath\mypath
% \pgfprocesspathextractpoints\mypath
% 
% % \pgfpointfirstonpath is now \pgfpoint{0}{0}
% % \pgfpointsecondonpath is now \pgfpoint{10bp}{10bp}
% % \pgfpointsecondlastonpath is now \pgfpoint{30bp}{30bp}
% % \pgfpointlastonpath is now \pgfpoint{40bp}{40bp}

\def\pgfprocesspathextractpoints#1{%
  \ifx#1\pgfutil@empty%
    \let\pgfpointfirstonpath=\pgfpointorigin%
    \let\pgfpointsecondonpath=\pgfpointorigin%
    \let\pgfpointsecondlastonpath=\pgfpointorigin%
    \let\pgfpointlastonpath=\pgfpointorigin%
  \else%
    \expandafter\pgf@extractprocessorfirst#1\pgf@stop%
  \fi%
}

\def\pgf@extractprocessorfirst#1#2#3#4{%
  \def\pgfpointfirstonpath{\pgfqpoint{#2}{#3}}%
  \ifx#4\pgf@stop%
    % pretty short path...
    \let\pgfpointsecondonpath=\pgfpointfirstonpath%
    \let\pgfpointsecondlastonpath=\pgfpointfirstonpath%
    \let\pgfpointlastonpath=\pgfpointfirstonpath%
    \let\next=\pgfutil@gobble%
  \else
    \let\next=\pgf@extractprocessorsecond%
  \fi%
  \next#4%
}

\def\pgf@extractprocessorsecond#1{%
  \ifx#1\pgfsyssoftpath@movetotoken%
    % Reset things...
    \let\pgf@next=\pgf@extractprocessorfirst%
  \else%
    \let\pgf@next=\pgf@@extractprocessorsecond%
  \fi%
  \pgf@next#1%
}
\def\pgf@@extractprocessorsecond#1#2#3#4{%
  \def\pgfpointsecondonpath{\pgfqpoint{#2}{#3}}%
  \let\pgfpointsecondlastonpath=\pgfpointfirstonpath%
  \let\pgfpointlastonpath=\pgfpointsecondonpath%
  \ifx#4\pgf@stop%
    % short path...
    \let\next=\pgfutil@gobble%
  \else
    \let\next=\pgf@extractprocessorother%
  \fi%
  \next#4%
}

\def\pgf@extractprocessorother#1{%
  \ifx#1\pgfsyssoftpath@movetotoken%
    % Reset things...
    \let\pgf@next=\pgf@extractprocessorfirst%
  \else%
    \let\pgf@next=\pgf@@extractprocessorother%
  \fi%
  \pgf@next#1%
}
\def\pgf@@extractprocessorother#1#2#3#4{%
  \let\pgfpointsecondlastonpath=\pgfpointlastonpath%
  \def\pgfpointlastonpath{\pgfqpoint{#2}{#3}}%
  \ifx#4\pgf@stop%
    % end!
    \let\next=\pgfutil@gobble%
  \fi%
  \next#4%
}



% Check for closepath and rectangles
%
% #1 = a macro that stores a path
% #2 = command to be executed when a closepath or a rectangle is encountered
%
% Example:
%
% \pgfsyssoftpath@moveto{0}{0}
% \pgfsyssoftpath@lineto{10}{10}
% \pgfsyssoftpath@curveto{20}{20}{30}{30}{40}{40}
% \pgfsyssoftpath@getcurrentpath\mypath
% \pgfprocesscheckclosed{\mypath}{\pgf@drawarrowsfalse}

\def\pgfprocesscheckclosed#1#2{%
  {%
    \global\let\pgf@proc@todo=\relax%
    \let\pgfsyssoftpath@movetotoken=\pgfutil@gobbletwo%
    \let\pgfsyssoftpath@linetotoken=\pgfutil@gobbletwo%
    \let\pgfsyssoftpath@curvetosupportatoken=\pgfutil@gobbletwo%
    \let\pgfsyssoftpath@curvetosupportbtoken=\pgfutil@gobbletwo%
    \let\pgfsyssoftpath@curvetotoken=\pgfutil@gobbletwo%
    \def\pgfsyssoftpath@rectcornertoken{\gdef\pgf@proc@todo{#2}\pgfutil@gobbletwo}%
    \def\pgfsyssoftpath@rectsizetoken{\gdef\pgf@proc@todo{#2}\pgfutil@gobbletwo}%
    \def\pgfsyssoftpath@closepathtoken{\gdef\pgf@proc@todo{#2}\pgfutil@gobbletwo}%
    #1%
  }%
  \pgf@proc@todo%
}

  
% Resolve specialround
%
% #1 = a macro that stores a path
% #2 = a macro that stores the new path
%
% Description:
%
% Resolves all specialround tokens. When such a token is encountered,
% the objective is to replace the next corner by a rounded corner. 
%

\def\pgfprocessround#1#2{%
  % first, check whether #1 contains \pgfsyssoftpath@specialroundtoken.
  % if not, do quick assignment!
  \expandafter\pgf@processroundcheck\expandafter#1\expandafter#2#1\pgfsyssoftpath@specialroundtoken\pgf@stop%
}

\def\pgf@processroundcheck#1#2#3\pgfsyssoftpath@specialroundtoken#4\pgf@stop{%
  \def\pgf@test{#4}%
  \ifx\pgf@test\pgfutil@empty%
    % ok, nothing to be done!
    \let#2=#1%
  \else%
    % very well...
    \pgf@@processround#1#2%
  \fi%
}


\def\pgf@@processround#1#2{%  
  \let\pgfprocess@newpath\pgfutil@empty%
  \let\pgfprocess@moveto\pgfutil@empty%
  \let\pgfprocess@firstto\pgfutil@empty%
  \let\pgfprocess@segment\pgfutil@empty%
  \pgf@xa=0pt%
  \pgf@ya=0pt%
  \expandafter\pgfprocess@round#1\pgf@stop{0pt}{0pt}%
  \expandafter\pgfutil@g@addto@macro\expandafter\pgfprocess@newpath\expandafter{\pgfprocess@moveto}%
  \expandafter\pgfutil@g@addto@macro\expandafter\pgfprocess@newpath\expandafter{\pgfprocess@segment}%
  \let#2=\pgfprocess@newpath%
}

\def\pgfprocess@round#1#2#3{%
  \ifx#1\pgf@stop%
    \let\next=\relax%
  \else%
    \ifx#1\pgfsyssoftpath@specialroundtoken%
      \def\pgfprocess@savex{#2}%
      \def\pgfprocess@savey{#3}%
      \let\next=\pgfprocess@specialround%
      \ifdim#2=0pt%
        \ifdim#3=0pt%
          \let\next=\pgfprocess@round% skip!
        \fi%
      \fi%
    \else%
      \ifx\pgfprocess@firstto\pgfutil@empty%
        \def\pgfprocess@firstto{{#2}{#3}}%
      \fi%
      \pgf@xa=#2%
      \pgf@ya=#3%
      \ifx#1\pgfsyssoftpath@movetotoken%
        % ok, move old segment to newpath
        \expandafter\pgfutil@g@addto@macro\expandafter\pgfprocess@newpath\expandafter{\pgfprocess@moveto}%
        \expandafter\pgfutil@g@addto@macro\expandafter\pgfprocess@newpath\expandafter{\pgfprocess@segment}%
        \def\pgfprocess@moveto{#1{#2}{#3}}%
        \let\pgfprocess@firstto=\pgfutil@empty%
        \let\pgfprocess@segment=\pgfutil@empty%
      \else%
        \pgfutil@g@addto@macro\pgfprocess@segment{#1{#2}{#3}}%
      \fi%
      \let\next=\pgfprocess@round%
    \fi%
  \fi%
  \next%  
}

\def\pgfprocess@specialround#1#2#3{%
  \ifx\pgfprocess@firstto\pgfutil@empty%
    \def\pgfprocess@firstto{{#2}{#3}}%
  \fi%
  \let\next=\pgfprocess@round% default: do nothing
  \ifx#1\pgfsyssoftpath@linetotoken%
    % Ok, round a lineto
    \let\next=\pgfprocess@specialroundcope%
  \else%
    \ifx#1\pgfsyssoftpath@curvetosupportatoken%
      % Ok, round a curveto. 
      \let\next=\pgfprocess@specialroundcurveto%
    \else%
      \ifx#1\pgfsyssoftpath@closepathtoken%
        % Ok, round a closepath (this is tricky...)
        \let\next=\pgfprocess@specialroundclose%
      \fi%
    \fi%
  \fi%
  \next#1{#2}{#3}%
}%

\def\pgfprocess@specialroundcope#1#2#3#4#5#6{%
  \let\next=\pgfprocess@round% do nothing by default
  \let\pgfprocess@continueafterrounding=\pgfprocess@round%
  \ifx#4\pgfsyssoftpath@linetotoken%
    % ok, let's get kicking...
    \pgf@xc=#5%
    \pgf@yc=#6%
    \let\next=\pgfprocess@@specialround%
  \else%
    \ifx#4\pgfsyssoftpath@curvetosupportatoken%  
      \pgf@xc=#5%
      \pgf@yc=#6%
      \let\next=\pgfprocess@@specialround%
    \else%
      \ifx#4\pgfsyssoftpath@closepathtoken%  
        \pgf@xc=#5%
        \pgf@yc=#6%
        \let\next=\pgfprocess@@specialround%
      \else
        \ifx#4\pgfsyssoftpath@specialroundtoken%  
          \let\next=\pgfprocess@@findrightcoordinates%
        \fi%
      \fi%
    \fi%
  \fi%
  \next#1{#2}{#3}#4{#5}{#6}%
}

\def\pgfprocess@@findrightcoordinates#1#2#3#4#5#6#7#8#9{%
  \pgf@xc=#8%
  \pgf@yc=#9%
  \pgfprocess@@specialround#1{#2}{#3}#4{#5}{#6}#7{#8}{#9}%
}

\def\pgfprocess@@specialround#1#2#3{%
  \pgfutil@g@addto@macro\pgfprocess@segment{#1}%
  % calculate start coordinate of the curve
  \pgf@xb=#2%
  \pgf@yb=#3%
  %
  \edef\pgf@marshal%
  {\noexpand\pgfpointlineatdistance{\pgfprocess@savex}%
    {\noexpand\pgfqpoint{\the\pgf@xb}{\the\pgf@yb}}%
    {\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}}%
  \pgf@process{\pgf@marshal}%
  \pgf@xa=\pgf@x% save start point of added curve
  \pgf@ya=\pgf@y%
  \edef\pgfprocess@addition{{\the\pgf@x}{\the\pgf@y}}%
  \expandafter\pgfutil@g@addto@macro\expandafter\pgfprocess@segment\expandafter{\pgfprocess@addition}%
  %
  % now add curve
  %
  \edef\pgf@marshal%
  {\noexpand\pgfpointlineatdistance{\pgfprocess@savey}%
    {\noexpand\pgfqpoint{\the\pgf@xb}{\the\pgf@yb}}%
    {\noexpand\pgfqpoint{\the\pgf@xc}{\the\pgf@yc}}}%
  \pgf@process{\pgf@marshal}%
  \pgf@xc=\pgf@x% save end point of added curve
  \pgf@yc=\pgf@y%
  % calculate first support:
  {%
    \pgf@x=\pgf@xb%
    \pgf@y=\pgf@yb%
    \advance\pgf@x by-\pgf@xa%
    \advance\pgf@y by-\pgf@ya%
    \advance\pgf@xa by 0.5522847\pgf@x%
    \advance\pgf@ya by 0.5522847\pgf@y%
    \edef\pgfprocess@addition{\noexpand\pgfsyssoftpath@curvetosupportatoken{\the\pgf@xa}{\the\pgf@ya}}%
    \expandafter\pgfutil@g@addto@macro\expandafter\pgfprocess@segment\expandafter{\pgfprocess@addition}%
  }%
  % calculate second support:
  {%
    \pgf@x=\pgf@xb%
    \pgf@y=\pgf@yb%
    \advance\pgf@x by-\pgf@xc%
    \advance\pgf@y by-\pgf@yc%
    \advance\pgf@xc by 0.5522847\pgf@x%
    \advance\pgf@yc by 0.5522847\pgf@y%
    \edef\pgfprocess@addition{\noexpand\pgfsyssoftpath@curvetosupportbtoken{\the\pgf@xc}{\the\pgf@yc}}%
    \expandafter\pgfutil@g@addto@macro\expandafter\pgfprocess@segment\expandafter{\pgfprocess@addition}%
  }%
  % add end:
  \edef\pgfprocess@addition{\noexpand\pgfsyssoftpath@curvetotoken{\the\pgf@xc}{\the\pgf@yc}}%
  \expandafter\pgfutil@g@addto@macro\expandafter\pgfprocess@segment\expandafter{\pgfprocess@addition}%
  %
  % continue!
  %
  \pgf@xa=#2%
  \pgf@ya=#3%
  \pgfprocess@continueafterrounding%
}

\def\pgfprocess@specialroundcurveto#1#2#3#4#5#6{%
  \pgfutil@g@addto@macro\pgfprocess@segment{#1{#2}{#3}#4{#5}{#6}}% supports
  \pgf@xa=#5%
  \pgf@ya=#6%
  \pgfprocess@specialroundcope}

\def\pgfprocess@specialroundclose{%
  \let\next=\pgfprocess@round%
  \ifx\pgfprocess@moveto\pgfutil@empty%
  \else%
    \ifx\pgfprocess@firstto\pgfutil@empty%
    \else%
      \expandafter\pgfprocess@@specialclosetarget\pgfprocess@firstto%
      \let\pgfprocess@continueafterrounding=\pgfprocess@cleanupafterclose%
      \edef\next{%
        \noexpand\pgfprocess@@specialround%
        \expandafter\expandafter\expandafter\noexpand\expandafter\pgfprocess@@specialclosemoveto\pgfprocess@moveto%
      }%
    \fi%
  \fi%  
  \next%
}

\def\pgfprocess@@specialclosetarget#1#2{%
  \pgf@xc=#1%
  \pgf@yc=#2%
}

\def\pgfprocess@@specialclosemoveto#1#2#3{%
  \pgfsyssoftpath@linetotoken{#2}{#3}%
}


\def\pgfprocess@cleanupafterclose#1#2#3{%
  \edef\pgfprocess@moveto{\noexpand\pgfsyssoftpath@movetotoken{\the\pgf@xc}{\the\pgf@yc}}%
  \edef\pgf@marshal{\noexpand\pgfprocess@round\noexpand\pgfsyssoftpath@closepathtoken{\the\pgf@xc}{\the\pgf@yc}}%
  \pgf@marshal%  
}


% Replace start and end coordinates of a path
%
% #1 = new start coordinate
% #2 = new end coordinate
%
% Description:
%
% This command will replace the first and last coordinates on a path
% by the given coordinates.
%
% Example:
%
% \pgfsyssoftpath@moveto{0}{0}
% \pgfsyssoftpath@lineto{10}{10}
% \pgfsyssoftpath@curveto{20}{20}{30}{10}{40}{0}
% \pgfsyssoftpath@getcurrentpath\mypath
% \pgfsetlinewidth{2pt}
% \pgfusepath{stroke}
% \pgfprocesspathextractpoints{\mypath}
% \pgfprocesspathreplacestartandend{\mypath}
%   {\pgfpointlineatdistance{2pt}{\pgfpointfirstonpath}{\pgfpointsecondonpath}}%
%   {\pgfpointlineatdistance{2pt}{\pgfpointlastonpath}{\pgfpointsecondlastonpath}}%
% \pgfsyssoftpath@setcurrentpath\mypath
% \pgfsetlinewidth{1pt}
% \color{red}
% \pgfusepath{stroke}

\def\pgfprocesspathreplacestartandend#1#2#3{%
  \ifx#1\pgfutil@empty%
  \else%
  {%
    % We (mis)use the current path to store (in a buffered manner) the
    % rest path.
    \pgfsyssoftpath@getcurrentpath\pgf@replace@origpath%
    \let\pgf@prepath=\pgfutil@empty%
    \pgf@process{#3}%
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgf@process{#2}%
    \expandafter\pgf@replaceprocessfirst#1\pgf@stop%
    \pgfsyssoftpath@getcurrentpath\pgf@restpath%
    \expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\gdef%
    \expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter#1%
    \expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter{%
      \expandafter\expandafter\expandafter\pgf@prepath%
      \expandafter\pgf@newstart\pgf@restpath}%
    % Restore current path
    \pgfsyssoftpath@setcurrentpath\pgf@replace@origpath%
  }%
  \fi%
}

\def\pgf@replaceprocessfirst#1#2#3#4{%
  \def\pgf@origstart{#1{#2}{#3}}%
  \edef\pgf@newstart{\noexpand#1{\the\pgf@x}{\the\pgf@y}}%
  \pgfsyssoftpath@setcurrentpath\pgfutil@empty%
  \ifx#4\pgf@stop%
    \let\pgf@next=\pgfutil@gobble%
  \else%
    \let\pgf@next=\pgf@replaceprocessother%
    \let\pgf@@next=\pgf@@replaceprocessother%
  \fi%
  \pgf@next#4%
}

\def\pgf@replaceprocessother#1{%
  \ifx#1\pgfsyssoftpath@movetotoken%
    \pgf@replace@handle@move%
  \fi%
  \pgf@@next#1%
}
\def\pgf@@replaceprocessother#1#2#3#4{%
  \ifx#4\pgf@stop%
    \edef\pgf@restpathaddition{{\noexpand#1{\the\pgf@xa}{\the\pgf@ya}}}%
    \expandafter\pgfsyssoftpath@addtocurrentpath\pgf@restpathaddition%
    \let\pgf@next=\pgfutil@gobble%
  \else%
    \pgfsyssoftpath@addtocurrentpath{#1{#2}{#3}}%
  \fi%
  \pgf@next#4%
}  

\def\pgf@replace@handle@move{%
  \pgfsyssoftpath@getcurrentpath\pgf@restpath%
  % Arggghh! Must reset everything!
  \expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\gdef%
  \expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\pgf@prepath%
  \expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter{%
    \expandafter\expandafter\expandafter\pgf@prepath%
    \expandafter\pgf@origstart\pgf@restpath}%
  % Redo first.
  \let\pgf@@next=\pgf@replaceprocessfirst%
}
  
\endinput

pgfcorepathusage.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/basiclayer/pgfcorepathusage.code.tex,v 1.23 2013/12/13 15:11:58 tantau Exp $


% Stroke/fill/clip/etc. the current path. Depending on the options,
% the current path will be stroked/filled/clipped/etc. If no options
% are given, the path is stroked. If multiple options are given, all
% of them are performed (in a sensible order).
%
% #1 = action(s) to be applied to the current path. Valid actions are: 
%      stroke -  strokes the path.
%      draw -    strokes the path and adds arrow tips.
%      tips -    adds arrow tips.
%      fill -    fills the path.
%      clip -    clip the path.
%      discard - Discards the path. Same effect as having an empty
%                options list.
%
% Example:
%
% % Draws an edge.
% \pgfpathmoveto{\pgfxy(0,0)}
% \pgfpathlineto{\pgfxy(0,1)}
% \pgfpathlineto{\pgfxy(1,0)}
% \pgfusepath{stroke}

\pgfkeys{
  /pgf/stroke/.code=\let\pgf@up@stroke\pgf@up@stroke@text\pgf@up@path@neededtrue,
  /pgf/draw/.code=\let\pgf@up@stroke\pgf@up@stroke@text\pgf@up@path@neededtrue,
  /pgf/fill/.code=\let\pgf@up@fill\pgf@up@fill@text\pgf@up@path@neededtrue,
  /pgf/clip/.code=\let\pgf@up@clip\pgf@up@clip@text\pgf@up@path@neededtrue,
  /pgf/discard/.code=,
  /pgf/use as bounding box/.code=\let\pgf@up@bb\pgf@do@up@bb,
  /pgf/arrow keys/flex/.code=\pgferror{You need to say \string\usetikzlibrary{bending} for flexing and bending arrows},
  /pgf/arrow keys/flex'/.code=\pgferror{You need to say \string\usetikzlibrary{bending} for flexing and bending arrows},
  /pgf/arrow keys/bend/.code=\pgferror{You need to say \string\usetikzlibrary{bending} for flexing and bending arrows},
  /pgf/arrow keys/quick/.code=\pgfarrowsaddtooptions{\let\pgf@arrow@flex@mode\pgf@arrow@mode@is@quick},
}

\pgfkeys{
  /pgf/.cd,
  tips/.is choice,
  tips/.default=true,
  tips/proper/.code=\let\pgf@tips@mode\pgf@tips@mode@onproper,
  tips/on proper draw/.code=\let\pgf@tips@mode\pgf@tips@mode@onproperdraw,
  tips/true/.code=\let\pgf@tips@mode\pgf@tips@mode@true,
  tips/on draw/.code=\let\pgf@tips@mode\pgf@tips@mode@ondraw,
  tips/never/.code=\let\pgf@tips@mode\pgf@tips@mode@false,
  tips/false/.code=\let\pgf@tips@mode\pgf@tips@mode@false,
}
\def\pgf@tips@mode@onproper{4}
\def\pgf@tips@mode@onproperdraw{3}
\def\pgf@tips@mode@true{2}
\def\pgf@tips@mode@ondraw{1}
\def\pgf@tips@mode@false{0}
\let\pgf@tips@mode\pgf@tips@mode@ondraw


% The following can only be set to "true" using the options in the
% module "bending"
\newif\ifpgf@precise@shortening
\def\pgf@arrow@mode@is@quick{0}
\let\pgf@arrow@flex@mode\pgf@arrow@mode@is@quick

\newif\ifpgf@up@path@needed
\newif\ifpgf@up@draw@arrows
\def\pgf@up@stroke@text{stroke}
\def\pgf@up@fill@text{fill}
\def\pgf@up@clip@text{clip}
\def\pgf@do@up@bb{\pgf@relevantforpicturesizefalse}

\def\pgfusepath#1{%
  \pgf@up@path@neededfalse%
  \pgf@up@draw@arrowsfalse%
  \let\pgf@up@stroke\pgfutil@empty%
  \let\pgf@up@fill\pgfutil@empty%
  \let\pgf@up@clip\pgfutil@empty%
  \let\pgf@up@bb\pgfutil@empty%
  \pgfset{#1}%
  \expandafter\def\expandafter\pgf@up@action\expandafter{\csname pgfsys@\pgf@up@fill\pgf@up@stroke\endcsname}%
  \ifnum\pgf@tips@mode=2\relax%
    \pgf@up@path@neededtrue%
  \fi%
  \ifnum\pgf@tips@mode=4\relax%
    \pgf@up@path@neededtrue%
  \fi%
  \ifpgf@up@path@needed%
  \else%
    \pgfsyssoftpath@setcurrentpath\pgfutil@empty%
  \fi%
  \ifx\pgf@up@stroke\pgfutil@empty%
    \ifx\pgf@up@fill\pgfutil@empty%
      \let\pgf@up@action=\pgfutil@empty%
      \ifx\pgf@up@clip\pgfutil@empty%
      \else%
        % only clipping  
        \let\pgf@up@action=\pgfsys@discardpath%
      \fi%
    \fi%
  \fi%  
  \pgfsyssoftpath@getcurrentpath\pgf@last@processed@path
  \pgfprocessround{\pgf@last@processed@path}{\pgf@last@processed@path}% change the path
  \pgfsyssoftpath@setcurrentpath\pgf@last@processed@path%
  %
  % Check whether the path is stroked. If so, add half the line width
  % to the bounding box.
  %
  \ifpgf@relevantforpicturesize%
    \ifx\pgf@up@stroke\pgfutil@empty%
    \else%
      \ifdim\pgf@picmaxx=-16000pt\relax%
      \else%
        \pgf@x=\pgf@pathminx\advance\pgf@x by-.5\pgflinewidth%
        \ifdim\pgf@x<\pgf@picminx\global\pgf@picminx\pgf@x\fi%
        \pgf@y=\pgf@pathminy\advance\pgf@y by-.5\pgflinewidth%
        \ifdim\pgf@y<\pgf@picminy\global\pgf@picminy\pgf@y\fi%
        \pgf@x=\pgf@pathmaxx\advance\pgf@x by.5\pgflinewidth%
        \ifdim\pgf@x>\pgf@picmaxx\global\pgf@picmaxx\pgf@x\fi%
        \pgf@y=\pgf@pathmaxy\advance\pgf@y by.5\pgflinewidth%
        \ifdim\pgf@y>\pgf@picmaxy\global\pgf@picmaxy\pgf@y\fi%
      \fi%
    \fi%
  \fi%
  %
  \ifx\pgf@up@clip\pgfutil@empty%
    \ifx\pgf@up@stroke\pgfutil@empty%
      \ifx\pgf@up@action\pgfutil@empty%
        \ifnum\pgf@tips@mode=2\relax%
          \pgf@up@draw@arrows@only%
        \fi%
        \ifnum\pgf@tips@mode=4\relax%
          \pgf@up@draw@arrows@only%
        \fi%
      \else%  
        \pgfsyssoftpath@invokecurrentpath%
        \pgf@up@action%
      \fi%
    \else%
      \pgfgetpath\pgf@arrowpath%
      \pgf@path@setup@tempswa%
      \pgfprocesscheckclosed{\pgf@arrowpath}{\pgfutil@tempswafalse}%
      \pgf@path@check@proper%
      \ifpgfutil@tempswa%
        \pgf@prepare@end@of@path%
        \begingroup%
          \pgf@prepare@start@of@path%
      \fi%
         \pgfsyssoftpath@invokecurrentpath%
          \pgf@up@action%
          \pgf@stroke@inner@line@if@needed%
      \ifpgfutil@tempswa%
          \pgf@add@arrow@at@start%
        \endgroup%
        \pgf@add@arrow@at@end%
      \fi%
    \fi%
  \else%
    \pgfsyssoftpath@invokecurrentpath%
    \pgfsys@clipnext%
    \pgf@up@action%
    \pgf@relevantforpicturesizefalse%
  \fi%
  \pgf@up@bb%
  \pgfsyssoftpath@setcurrentpath\pgfutil@empty%
  \pgf@resetpathsizes%
  \ignorespaces%
}
\def\pgf@path@setup@tempswa{%
  \ifnum\pgf@tips@mode>0\relax
    \pgfutil@tempswatrue%
  \else
    \pgfutil@tempswafalse%
  \fi%
}
\def\pgf@up@draw@arrows@only{%
  \pgfgetpath\pgf@arrowpath%
  \pgfutil@tempswatrue%
  \pgfprocesscheckclosed{\pgf@arrowpath}{\pgfutil@tempswafalse}%
  \pgf@path@check@proper%
  \ifpgfutil@tempswa%
    \pgf@prepare@end@of@path%
    \begingroup%
      \pgf@prepare@start@of@path%
      \pgf@add@arrow@at@start%
    \endgroup%
    \pgf@add@arrow@at@end%
  \fi%
}

\def\pgf@path@check@proper{%
  \ifpgfutil@tempswa%
    \ifnum\pgf@tips@mode>2\relax%
      \pgf@path@check@proper@%
    \fi%
  \fi%
}


\def\pgf@path@check@proper@{%
  {%
    \pgf@x0pt\pgf@y\pgf@x%
    \pgfutil@tempswatrue%
    \let\pgfsyssoftpath@movetotoken\pgf@path@proper@init%
    \let\pgfsyssoftpath@linetotoken\pgf@path@proper@test%%
    \let\pgfsyssoftpath@curvetosupportatoken\pgf@path@proper@test%
    \let\pgfsyssoftpath@curvetosupportbtoken=\pgf@path@proper@test%
    \let\pgfsyssoftpath@curvetotoken\pgf@path@proper@test%
    \let\pgfsyssoftpath@rectcornertoken\pgf@path@proper@test%
    \let\pgfsyssoftpath@rectsizetoken\pgf@path@proper@zero@test%
    \let\pgfsyssoftpath@closepathtoken\pgf@path@proper@test%
    % Execute the path:
    \pgf@arrowpath%
    \expandafter
  }%
  \ifpgfutil@tempswa\pgfutil@tempswafalse\else\pgfutil@tempswatrue\fi%
}

\def\pgf@path@proper@init#1#2{\pgfutil@tempswatrue\pgf@x#1\pgf@y#2}%
\def\pgf@path@proper@test#1#2{%
  \ifdim\pgf@x=#1\relax\else\pgfutil@tempswafalse\fi%
  \ifdim\pgf@y=#2\relax\else\pgfutil@tempswafalse\fi}
\def\pgf@path@proper@zero@test#1#2{%
  \ifdim\pgf@x=0pt\relax\else\pgfutil@tempswafalse\fi%
  \ifdim\pgf@y=0pt\relax\else\pgfutil@tempswafalse\fi}




\def\pgf@stroke@inner@line@if@needed{%
  \ifdim\pgfinnerlinewidth>0pt\relax%
    \expandafter\let\expandafter\pgf@temp@save\csname\string\color@pgfstrokecolor\endcsname%
    \pgfsys@beginscope%
    {%
      \pgfsys@setlinewidth{\pgfinnerlinewidth}%
      \pgfsetstrokecolor{\pgfinnerstrokecolor}%
      \pgfsyssoftpath@invokecurrentpath%
      \pgfsys@stroke%
    }%
    \pgfsys@endscope%
    \expandafter\global\expandafter\let\csname\string\color@pgfstrokecolor\endcsname\pgf@temp@save%
  \fi%
}

\let\pgf@prepare@start@of@path\relax%
\let\pgf@add@arrow@at@end\relax%
\let\pgf@add@arrow@at@start\relax%




% Shorten start/end of paths by a certain amount.
%
% #1 = amount by which paths should be shortened.
%
% Example:
%
% \pgfpathmoveto{\pgfpointorigin}
% \pgfpathlineto{\pgfpoint{10pt}{0pt}
%
% % The following has the same effect:
% \pgfsetshortenstart{1pt}
% \pgfpathmoveto{\pgfpointorigin}
% \pgfpathlineto{\pgfpoint{11pt}{0pt}

\def\pgfsetshortenstart#1{\pgfmathsetlength\pgf@shorten@start@additional{#1}}
\def\pgfsetshortenend#1{\pgfmathsetlength\pgf@shorten@end@additional{#1}}

\newdimen\pgf@shorten@end@additional
\newdimen\pgf@shorten@start@additional



% 
% 
% Handling the end of a path 
% 
%  
% The "handling" consists of first testing whether we need to do
% anything at all, namely because either an arrow tip should be drawn
% at the end or because the path should be shortened at the end. If
% so, we shorten the path if needed and, later on, add the arrow tip.
%

\newif\ifpgf@worry


% Prepare the end of the path: Test whether anything must be done
% (step 0) and, if so, split the path (step 1), extract the interesting points from
% the path (step 2), prepare further computations (step 3), shorten
% the path (step 4) if necessary, and add the arrow tip (step 4 in
% macro \pgf@add@arrow@at@end, which is called later). 

\def\pgf@prepare@end@of@path{%
  \let\pgfprocessresultpathsuffix\relax% flag that nothing has happened...
  \let\pgfprocessresultsubpathsuffix\relax%
  \pgfsyssoftpath@getcurrentpath\pgf@arrowpath%
  % 
  % Step 0 start:
  % 
  % Do we need to worry about the end? 
  % 
  \ifx\pgf@arrowpath\pgfutil@empty\else%
    \pgf@worryfalse%
    \ifx\pgf@end@tip@sequence\pgfutil@empty\else\pgf@worrytrue\fi% Yes, worry if we have to draw an arrow
    \pgf@precise@shorteningfalse%
    \pgf@arrow@compute@shortening\pgf@end@tip@sequence%
    \advance\pgf@xa by\pgf@shorten@end@additional%
    \advance\pgf@xb by\pgf@shorten@end@additional%
    \ifdim\pgf@xa=0pt\relax\else\pgf@worrytrue\fi% Also, worry if shortening is requested
    \edef\pgf@path@shortening@distance{\the\pgf@xa}%
    \edef\pgf@arrow@tip@total@length{\the\pgf@xb}%
    % 
    % Step 0 done.
    % 
    \ifpgf@worry%
      % Ok, need to "worry" about the end, either because we need to
      % shorten it or to draw an arrow head.
      %
      % Step 1: Split
      % 
      \pgfprocesssplitpath{\pgf@arrowpath}%
      \pgfprocesssplitsubpath{\pgfprocessresultpathsuffix}%
      % 
      % Step 2: extract
      %
      \expandafter\pgf@parse@end\pgfprocessresultsubpathsuffix\pgf@stop\pgf@stop\pgf@stop%
      % 
      % Step 3: prep 
      % 
      \pgf@prep@end%
      % 
      % Step 4: shorten
      % 
      \ifdim\pgf@path@shortening@distance=0pt\else\pgf@do@shorten@end\fi%
      \expandafter\expandafter\expandafter\def%
      \expandafter\expandafter\expandafter\pgf@arrowpath%
      \expandafter\expandafter\expandafter{\expandafter\pgfprocessresultpathprefix\pgfprocessresultpathsuffix}%
      \pgfsyssoftpath@setcurrentpath\pgf@arrowpath%
    \fi%
  \fi%
}

\def\pgf@parse@end#1#2#3#4#5#6{%
  \ifx#4\pgf@stop% Only a moveto! -> do nothing!
    \def\pgfpointlastonpath{\pgfqpoint{#2}{#3}}%
    \let\pgf@next\relax%
    \let\pgf@do@shorten@end\relax%
    \let\pgf@do@draw@end\pgf@do@draw@straightend%
    \let\pgf@prep@end\pgf@prep@movetoend%
  \else\ifx#4\pgfsyssoftpath@curvetosupportatoken% A curve -> this will get complicated...
    \def\pgfsubpathfourthlasttoken{#1}%
    \def\pgfpointfourthlastonpath{\pgfqpoint{#2}{#3}}%
    \def\pgfpointthirdlastonpath{\pgfqpoint{#5}{#6}}%
    \ifpgf@precise@shortening%
      \let\pgf@do@shorten@end\pgf@do@shorten@curvedend%
      \let\pgf@do@draw@end\pgf@do@draw@curvedend%
      \let\pgf@prep@end\pgf@prep@curveend%
    \else%
      \def\pgfsubpathstart{\noexpand#1{#2}{#3}\noexpand#4{#5}{#6}}%
      \let\pgf@do@shorten@end\pgf@do@shorten@straightend%
      \let\pgf@do@draw@end\pgf@do@draw@straightend%
      \let\pgf@prep@end\pgf@prep@straightend%
    \fi%
    \let\pgf@next\pgf@parse@end@curve@cont%
  \else% A straight line -> great!
    \def\pgfsubpathstart{\noexpand#1{#2}{#3}\noexpand#4}%
    \def\pgfpointsecondlastonpath{\pgfqpoint{#2}{#3}}%
    \def\pgfpointlastonpath{\pgfqpoint{#5}{#6}}%
    \let\pgfpointfourthlastonpath\relax%
    \let\pgfpointthirdlastonpath\relax%
    \let\pgf@next\pgf@parse@end@gobble@three%  
    \let\pgf@do@shorten@end\pgf@do@shorten@straightend%
    \let\pgf@do@draw@end\pgf@do@draw@straightend%
    \let\pgf@prep@end\pgf@prep@straightend%
  \fi\fi%
  \pgf@next% Needed for reading rest of path...
}

\def\pgf@parse@end@gobble@three#1#2#3{}%
\def\pgf@parse@end@curve@cont#1#2#3#4#5#6#7#8#9{%
  \def\pgfpointsecondlastonpath{\pgfqpoint{#2}{#3}}%
  \def\pgfpointlastonpath{\pgfqpoint{#5}{#6}}%
  \ifpgf@precise@shortening%
  \else%
    \expandafter\def\expandafter\pgfsubpathstart\expandafter{\pgfsubpathstart\noexpand#1{#2}{#3}\noexpand#4}%
  \fi%
}

% 
% Preps 
%
\def\pgf@prep@movetoend{%
  \pgf@process{\pgfpointlastonpath}%
  \pgf@xb\pgf@x
  \pgf@yb\pgf@y
  \pgf@xc\pgf@x
  \pgf@yc\pgf@y
}
\def\pgf@prep@straightend{%
  \let\pgf@ref\pgfpointsecondlastonpath
  \ifx\pgfpointlastonpath\pgfpointsecondlastonpath% degenerate!
    \ifx\pgfpointthirdlastonpath\relax% cannot help it: really a zero-length path
    \else%
      \ifx\pgfpointlastonpath\pgfpointthirdlastonpath% double degenerate!
        \let\pgf@ref\pgfpointfourthlastonpath% Use third point for reference.
      \else
        \let\pgf@ref\pgfpointthirdlastonpath% Use third point for reference.
      \fi%
    \fi%
  \fi%
  \pgfpointlineatdistance{\pgf@path@shortening@distance}{\pgfpointlastonpath}{\pgf@ref}%
  \pgf@xa\pgf@x%
  \pgf@ya\pgf@y%
}


% 
% Line shortening for straight lines:
%
\def\pgf@do@shorten@straightend{%
  \edef\pgfprocessresultsubpathsuffix{\pgfsubpathstart{\the\pgf@xa}{\the\pgf@ya}}%
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\pgfprocessresultpathsuffix%
  \expandafter\expandafter\expandafter{\expandafter\pgfprocessresultsubpathprefix\pgfprocessresultsubpathsuffix}%
}


% 
% Draw an end arrow by calling an appropriate subfunction, if necessary
% 

\def\pgf@add@arrow@at@end{%
  \ifx\pgf@arrowpath\pgfutil@empty\else%
    \ifx\pgf@end@tip@sequence\pgfutil@empty\else%
      \pgf@do@draw@end%
    \fi%    
  \fi%
}

% 
% Draw an end arrow at the end of a straight line
% 
\def\pgf@do@draw@straightend{%
  {%
    \pgftransformreset%
    \pgftransformarrow{\pgfqpoint{\pgf@xc}{\pgf@yc}}{\pgfqpoint{\pgf@xb}{\pgf@yb}}%
    \pgf@arrow@draw@arrow\pgf@end@tip@sequence\pgf@arrow@tip@total@length%
  }%
}



% 
% 
% Handling the start of a path 
% 
%  
% The "handling" is similar to the case for the start of the path. We
% may be able to skip the splitting if that was done already for the
% end. Otherwise, things are basically the same.
%

% Prepare the start of the path: Test whether anything must be done
% (step 0) and, if so, split the path (step 1) if necesssary, extract
% the interesting points from the path (step 2), prepare computations
% (step 3) needed for both shortening and tip adding, shorten the path
% (step 4), and add the arrow tip (step 5 in macro
% \pgf@add@arrow@at@start, which is called later). 

\def\pgf@prepare@start@of@path{%
  % 
  % Step 0 start:
  % 
  % Do we need to worry about the start? 
  % 
  \ifx\pgf@arrowpath\pgfutil@empty\else%
    \pgf@worryfalse%
    \ifx\pgf@start@tip@sequence\pgfutil@empty\else\pgf@worrytrue\fi% Yes, worry if we have to draw an arrow
    \pgf@precise@shorteningfalse%
    \pgf@arrow@compute@shortening\pgf@start@tip@sequence%
    \advance\pgf@xa by\pgf@shorten@start@additional%
    \advance\pgf@xb by\pgf@shorten@start@additional%
    \ifdim\pgf@xa=0pt\relax\else\pgf@worrytrue\fi% Also, worry if shortening is requested
    \edef\pgf@path@shortening@distance{\the\pgf@xa}%
    \edef\pgf@arrow@tip@total@length{\the\pgf@xb}%
    % 
    % Step 0 done.
    % 
    \ifpgf@worry%
      % Ok, need to "worry" about the start, either because we need to
      % shorten it or to draw an arrow head.
      %
      % Step 1: Split
      % 
      \ifx\pgfprocessresultpathsuffix\relax%
        % Ok, still need to compute the split:
        \pgfprocesssplitpath{\pgf@arrowpath}%
      \fi%
      % 
      % Step 2: extract
      %
      \expandafter\pgf@parse@start\pgfprocessresultpathsuffix\pgf@stop\pgf@stop\pgf@stop%
      % 
      % Step 3: prep
      %
      \pgf@prep@start%
      % 
      % Step 4: shorten
      % 
      \ifdim\pgf@path@shortening@distance=0pt\else\pgf@do@shorten@start\fi%
      \expandafter\expandafter\expandafter\def%
      \expandafter\expandafter\expandafter\pgf@arrowpath%
      \expandafter\expandafter\expandafter{\expandafter\pgfprocessresultpathprefix\pgfprocessresultpathsuffix}%
      \pgfsyssoftpath@setcurrentpath\pgf@arrowpath%
    \fi%
  \fi%
}

\def\pgf@parse@start#1#2#3#4#5#6{%
  \def\pgfpointfirstonpath{\pgfqpoint{#2}{#3}}%
  \def\pgfpointsecondonpath{\pgfqpoint{#5}{#6}}%
  \let\pgfpointthirdonpath\relax%
  \let\pgfpointfourthonpath\relax%
  \def\pgfsubpathfirsttoken{\noexpand#1}%
  \def\pgfsubpathsecondtoken{\noexpand#4}%
  \ifx#4\pgf@stop% Only a moveto! -> do nothing!
    \let\pgf@next\relax%
    \let\pgf@do@shorten@start\relax%
    \let\pgf@prep@start\pgf@prep@movetostart%
    \let\pgf@do@draw@start\pgf@do@draw@straightstart%
  \else\ifx#4\pgfsyssoftpath@curvetosupportatoken% A curve -> this will get complicated...
    \ifpgf@precise@shortening%
      \let\pgf@next\pgf@parse@start@curve@cont%
      \let\pgf@do@shorten@start\pgf@do@shorten@curvedstart%
      \let\pgf@do@draw@start\pgf@do@draw@curvedstart%
      \let\pgf@prep@start\pgf@prep@curvedstart%
    \else% can treat the end like a straight line...
      \let\pgf@next\pgf@parse@start@curve@cont@straight%
      \let\pgf@do@shorten@start\pgf@do@shorten@straightstart%
      \let\pgf@do@draw@start\pgf@do@draw@straightstart%
      \let\pgf@prep@start\pgf@prep@straightstart%
    \fi%
  \else% A straight line -> great!
    \let\pgf@next\pgf@parse@start@till@stop%  
    \let\pgf@do@shorten@start\pgf@do@shorten@straightstart%
    \let\pgf@do@draw@start\pgf@do@draw@straightstart%
    \let\pgf@prep@start\pgf@prep@straightstart%
  \fi\fi%
  \pgf@next% Needed for reading rest of path...
}

\def\pgf@parse@start@till@stop#1\pgf@stop\pgf@stop\pgf@stop{\def\pgfsubpathend{#1}}%

\def\pgf@parse@start@curve@cont#1#2#3#4#5#6#7\pgf@stop\pgf@stop\pgf@stop{%
  \def\pgfpointthirdonpath{\pgfqpoint{#2}{#3}}%
  \def\pgfpointfourthonpath{\pgfqpoint{#5}{#6}}%
  \def\pgfsubpathend{#7}%
}

\def\pgf@parse@start@curve@cont@straight#1#2#3#4#5#6#7\pgf@stop\pgf@stop\pgf@stop{%
  \def\pgfpointthirdonpath{\pgfqpoint{#2}{#3}}%
  \def\pgfpointfourthonpath{\pgfqpoint{#5}{#6}}%
  \def\pgfsubpathend{#1{#2}{#3}#4{#5}{#6}#7}%
}

% 
% Preps 
%
\def\pgf@prep@movetostart{%
  \pgf@process{\pgfpointfirstonpath}%
  \pgf@xb\pgf@x
  \pgf@yb\pgf@y
  \pgf@xc\pgf@x
  \pgf@yc\pgf@y
}
\def\pgf@prep@straightstart{%
  \let\pgf@ref\pgfpointsecondonpath
  \ifx\pgfpointfirstonpath\pgfpointsecondonpath% degenerate!
    \ifx\pgfpointthirdonpath\relax% cannot help it: really a zero-length path
    \else%
      \ifx\pgfpointfirstonpath\pgfpointthirdonpath% double degenerate!
        \let\pgf@ref\pgfpointfourthonpath% Use third point for reference.
      \else
        \let\pgf@ref\pgfpointthirdonpath% Use third point for reference.
      \fi%
    \fi%
  \fi%
  \pgfpointlineatdistance{\pgf@path@shortening@distance}{\pgfpointfirstonpath}{\pgf@ref}%
  \pgf@xa\pgf@x%
  \pgf@ya\pgf@y%
}

% 
% Line shortening for straight lines:
%
\def\pgf@do@shorten@straightstart{%
  \edef\pgfprocessresultpathsuffix{\pgfsubpathfirsttoken{\the\pgf@xa}{\the\pgf@ya}\pgfsubpathsecondtoken{\the\pgf@xc}{\the\pgf@yc}}%
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\pgfprocessresultpathsuffix%
  \expandafter\expandafter\expandafter{\expandafter\pgfprocessresultpathsuffix\pgfsubpathend}%
}


% 
% Draw a start arrow by calling an appropriate subfunction, if necessary
% 

\def\pgf@add@arrow@at@start{%
  \ifx\pgf@arrowpath\pgfutil@empty\else%
    \ifx\pgf@start@tip@sequence\pgfutil@empty\else%
      \pgf@do@draw@start%
    \fi%    
  \fi%
}

% 
% Draw an start arrow at the start of a straight line
% 
\def\pgf@do@draw@straightstart{%
  {%
    \pgftransformreset%
    \pgftransformarrow{\pgfqpoint{\pgf@xc}{\pgf@yc}}{\pgfqpoint{\pgf@xb}{\pgf@yb}}%
    \pgf@arrow@draw@arrow\pgf@start@tip@sequence\pgf@arrow@tip@total@length%
  }%
}



\let\pgf@shorten@end=\pgfutil@empty
\let\pgf@shorten@start=\pgfutil@empty


\endinput%






pgfcorepatterns.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/basiclayer/pgfcorepatterns.code.tex,v 1.5 2013/11/07 15:45:46 tantau Exp $

% Creates a new uncolored pattern
%
% [#1] = optional list of variables.
% #2   = pattern name
% #3   = lower left of bounding box
% #4   = upper right of bounding box
% #5   = step vector
% #6   = pattern code
%
% Description:
%
% Declares a new uncolored pattern. An uncolored pattern is a pattern
% that has no inherent color. When the pattern is used, a color for
% the pattern must be supplied.
%
% See the pdf-manual for more details on uncolored patterns.
%
% Specifying a variable list makes the pattern ``mutable''.
%
% The bounding box must be a bounding box of the pattern cell.
%
% The step vector must provide the x- and y-step by which the cells
% are spaced.
%
% The pattern code should be pgf code that can be protocolled.
%
% The transformation matrix will be reset prior to invoking the
% pattern code.
%
% Example:
%
% \pgfdeclarepatternformonly{stars}{\pgfpointorigin}{\pgfpoint{1cm}{1cm}}
% {\pgfpoint{1cm}{1cm}}{
%   \pgftransformshift{\pgfpoint{.5cm}{.5cm}}
%   \pgfpathmoveto{\pgfpointpolar{0}{4mm}}
%   \pgfpathlineto{\pgfpointpolar{144}{4mm}}
%   \pgfpathlineto{\pgfpointpolar{288}{4mm}}
%   \pgfpathlineto{\pgfpointpolar{72}{4mm}}
%   \pgfpathlineto{\pgfpointpolar{216}{4mm}}
%   \pgfpathclose%
%   \pgfusepath{stroke}
% }
%
\def\pgfdeclarepatternformonly{%
  \def\pgf@pattern@type{formonly}%
  \pgfutil@ifnextchar[{\pgf@declarepattern@checkarg}{\pgf@declarepattern@checkarg[]}%
}


% Creates a new colored pattern
%
% [#1] = optional list of variables.
% #2   = pattern name
% #3   = lower left of bounding box
% #4   = upper right of bounding box
% #5   = step vector
% #6   = pattern code
%
% Description:
%
% Declares a new colored pattern. Such patterns have a one or more
% fixed inherent colors. See the pdf-manual for more details on
% uncolored patterns.
%
% The parameters have the same effect as for uncolored patterns.
%
% Example:
%
% \pgfdeclarepatterninherentlycolored{red stars}{\pgfpointorigin}{\pgfpoint{1cm}{1cm}}
% {\pgfpoint{1cm}{1cm}}{
%   \pgfsetfillcolor{red}
%   \pgfsetstrokecolor{black}
%   \pgftransformshift{\pgfpoint{.5cm}{.5cm}}
%   \pgfpathmoveto{\pgfpointpolar{0}{4mm}}
%   \pgfpathlineto{\pgfpointpolar{144}{4mm}}
%   \pgfpathlineto{\pgfpointpolar{288}{4mm}}
%   \pgfpathlineto{\pgfpointpolar{72}{4mm}}
%   \pgfpathlineto{\pgfpointpolar{216}{4mm}}
%   \pgfpathclose%
%   \pgfusepath{stroke,fill}
% }
%
\def\pgfdeclarepatterninherentlycolored{%
  \def\pgf@pattern@type{inherentlycolored}%
  \pgfutil@ifnextchar[{\pgf@declarepattern@checkarg}{\pgf@declarepattern@checkarg[]}%
}





\def\pgf@declarepattern@checkarg[#1]{%
  \def\pgf@pattern@tempvars{#1}%
  \ifx\pgf@pattern@tempvars\pgfutil@empty%
    \expandafter\let\expandafter\pgf@next\csname pgf@declarepattern\pgf@pattern@type\endcsname%
  \else%
    \expandafter\let\expandafter\pgf@next\csname pgf@declarepattern\pgf@pattern@type @mutable\endcsname%
  \fi%
  \pgf@next}

\long\def\pgf@declarepatternformonly#1#2#3#4#5{\pgf@declarepattern{#1}{#2}{#3}{#4}{#5}{0}}
  
\long\def\pgf@declarepatterninherentlycolored#1#2#3#4#5{\pgf@declarepattern{#1}{#2}{#3}{#4}{#5}{1}}
  
\long\def\pgf@declarepatternformonly@mutable#1#2#3#4#5{%
  \def\pgf@marshal{\pgf@declarepatternmutable{#1}}%  
  \expandafter\pgf@marshal\expandafter{\pgf@pattern@tempvars}{#2}{#3}{#4}{#5}{2}%
}

\long\def\pgf@declarepatterninherentlycolored@mutable#1#2#3#4#5#6{%
  \def\pgf@marshal{\pgf@declarepatternmutable{#1}}%  
  \expandafter\pgf@marshal\expandafter{\pgf@pattern@tempvars}{#2}{#3}{#4}{#5}{3}%
}

\def\pgf@declarepattern#1#2#3#4#5#6{%
  \pgfutil@ifundefined{pgf@pattern@name@#1}{%
  \pgfsysprotocol@getcurrentprotocol\pgf@pattern@temp%
  {%
    \pgfinterruptpath%
      \pgfpicturetrue%
      \pgf@relevantforpicturesizefalse%
      \pgftransformreset%
      \pgfsysprotocol@setcurrentprotocol\pgfutil@empty%
      \pgfsysprotocol@bufferedtrue%
      \pgfsys@beginscope%
      \pgfsetarrows{-}%
      #5%
      \pgfsys@endscope%
      \pgfsysprotocol@getcurrentprotocol\pgf@pattern@code%
      \global\let\pgf@pattern@code=\pgf@pattern@code%
    \endpgfinterruptpath%
    \pgf@process{#2}%
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgf@process{#3}%
    \pgf@xb=\pgf@x%
    \pgf@yb=\pgf@y%
    \pgf@process{#4}%
    \pgf@xc=\pgf@x%
    \pgf@yc=\pgf@y%
    % Now, build a name for the pattern
    \pgfutil@tempcnta=\pgf@pattern@number%
    \advance\pgfutil@tempcnta by1\relax%
    \xdef\pgf@pattern@number{\the\pgfutil@tempcnta}%
    \expandafter\xdef\csname pgf@pattern@name@#1\endcsname{\the\pgfutil@tempcnta}%
    \expandafter\gdef\csname pgf@pattern@type@#1\endcsname{#6}%
    \xdef\pgf@marshal{\noexpand\pgfsys@declarepattern
      {\csname pgf@pattern@name@#1\endcsname}
      {\the\pgf@xa}{\the\pgf@ya}{\the\pgf@xb}{\the\pgf@yb}{\the\pgf@xc}{\the\pgf@yc}{\pgf@pattern@code}{#6}}%
  }%
  \pgfsysprotocol@setcurrentprotocol\pgf@pattern@temp%
  \expandafter\global\expandafter\let\csname pgf@pattern@instantiate@#1\endcsname=\pgf@marshal%
  }
  {%
    \pgferror{Pattern `#1' already defined}%
  }%
}

\def\pgf@pattern@number{0}%

\def\pgf@declarepatternmutable#1#2#3#4#5#6#7{%
  \pgfutil@ifundefined{pgf@pattern@name@#1}{%
    \expandafter\gdef\csname pgf@pattern@name@#1\endcsname{#1}%
    \expandafter\gdef\csname pgf@pattern@variables@#1\endcsname{#2}%
    \expandafter\gdef\csname pgf@pattern@lowerleft@#1\endcsname{#3}%
    \expandafter\gdef\csname pgf@pattern@upperright@#1\endcsname{#4}%
    \expandafter\gdef\csname pgf@pattern@tilesize@#1\endcsname{#5}%
    \expandafter\long\expandafter\gdef\csname pgf@pattern@code@#1\endcsname{#6}%
    \expandafter\gdef\csname pgf@pattern@type@#1\endcsname{7}%    
  }{\pgferror{The pattern `#1' is already defined}}%
}

\def\pgf@ifpatternisinherentlycolored#1#2#3{%
  \expandafter\ifodd\csname pgf@pattern@type@#1\endcsname\relax#2\else#3\fi%
}

\def\pgf@ifpatternismutable#1#2#3{%
  \expandafter\ifnum\csname pgf@pattern@type@#1\endcsname>1\relax#2\else#3\fi%
}

\def\pgfpatternreleasename#1{\expandafter\let\csname pgf@pattern@name@#1\endcsname\relax}






% Set an pattern as fill color
%
% #1 = Name of the pattern
% #2 = Color to be used for the pattern. If the pattern is already
%      colored, this parameter is ignored.
%
% Description:
%
% Sets the pattern for subsequent filling operations.
%
% Example:
%
% \pgfsetfillpattern{stars}{red}
%
\def\pgfsetfillpattern#1#2{%
  \pgfutil@ifundefined{pgf@pattern@name@#1}%
  {%
    \pgferror{Undefined pattern `#1'}%
  }%
  {%
    \pgf@ifpatternismutable{#1}%
    {%
      % So, a mutable pattern. Check to see if the pattern 
      % has been used with the current variable values...
      \let\pgf@pattern@tempvars\pgfutil@empty%
      \expandafter\expandafter\expandafter\pgf@pattern@check@vars%
        \csname pgf@pattern@variables@#1\endcsname,\pgf@stop,%
      \edef\pgf@pattern@nametemp{pgf@pattern@#1@\pgf@pattern@tempvars}%
      \expandafter\pgfutil@ifundefined\expandafter{\pgf@pattern@nametemp}%
      {%
        % ...Nope. So declare a new instance of the mutable pattern.
        \pgf@ifpatternisinherentlycolored{#1}%
          {\let\pgf@set@fillpattern@declare\pgfdeclarepatterninherentlycolored}%
          {\let\pgf@set@fillpattern@declare\pgfdeclarepatternformonly}%
        \pgf@set@fillpattern@declare%
          {\pgf@pattern@nametemp}%
          {\csname pgf@pattern@lowerleft@#1\endcsname}%
          {\csname pgf@pattern@upperright@#1\endcsname}%
          {\csname pgf@pattern@tilesize@#1\endcsname}%
          {\csname pgf@pattern@code@#1\endcsname}%
      }%
      {%
        % ...Yep. So do nothing.
      }%
      \expandafter\pgf@set@fillpattern\expandafter{\pgf@pattern@nametemp}{#2}%
      \expandafter\gdef\csname\pgf@pattern@nametemp\endcsname{#1}%
    }%
    {%
      % A non-mutable pattern.
      \pgf@set@fillpattern{#1}{#2}%
    }%
  }%
}


\def\pgf@set@fillpattern#1#2{%
  \pgfutil@ifundefined{pgf@pattern@name@#1}{%
    \pgferror{Undefined pattern `#1'}}
  {%
    \csname pgf@pattern@instantiate@#1\endcsname%
    \expandafter\global\expandafter\let\csname pgf@pattern@instantiate@#1\endcsname=\relax%
    \pgf@ifpatternisinherentlycolored{#1}{%
      \pgfsys@setpatterncolored{\csname pgf@pattern@name@#1\endcsname}%
    }{%
      \pgfutil@colorlet{pgf@tempcolor}{#2}%
      \pgfutil@ifundefined{applycolormixins}{}{\applycolormixins{pgf@tempcolor}}%
      \pgfutil@extractcolorspec{pgf@tempcolor}{\pgf@tempcolor}%
      \expandafter\pgfutil@convertcolorspec\pgf@tempcolor{rgb}{\pgf@rgbcolor}%
      \expandafter\pgf@set@fill@patternuncolored\pgf@rgbcolor\relax{#1}%
    }%
  }%
}

\def\pgf@set@fill@patternuncolored#1,#2,#3\relax#4{%
  \pgfsys@setpatternuncolored{\csname pgf@pattern@name@#4\endcsname}{#1}{#2}{#3}%
}

\def\pgf@pattern@check@vars#1,{%
  \ifx#1\pgf@stop%
    \let\pgf@next\relax%
  \else%
    \afterassignment\pgfmath@gobbletilpgfmath@%
    \expandafter\let\expandafter\pgf@pattern@char#1#1\pgfmath@%
    \ifx\pgf@pattern@char/%
      \edef\pgf@pattern@tempvar{(\pgfkeysvalueof{#1})}%
    \else%
      \expandafter\ifcat\pgf@pattern@char\relax%
        \edef\pgf@pattern@tempvar{(\the#1)}%
      \else%
        \edef\pgf@pattern@tempvar{(#1)}%
      \fi%
    \fi%
    \edef\pgf@pattern@tempvars{\pgf@pattern@tempvars\pgf@pattern@tempvar}%
    \let\pgf@next\pgf@pattern@check@vars%
  \fi%
  \pgf@next%
}

\endinput

pgfcorepoints.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/basiclayer/pgfcorepoints.code.tex,v 1.27 2013/10/07 15:51:46 tantau Exp $

\newdimen\pgf@picminx
\newdimen\pgf@picmaxx
\newdimen\pgf@picminy
\newdimen\pgf@picmaxy

\newdimen\pgf@pathminx
\newdimen\pgf@pathmaxx
\newdimen\pgf@pathminy
\newdimen\pgf@pathmaxy

\newif\ifpgf@relevantforpicturesize

\def\pgf@process#1{{#1\global\pgf@x=\pgf@x\global\pgf@y=\pgf@y}}

% Save a point.
%
% #1 = macro for storing point.
% #2 = code for point (should define x and y)
%
% Example:
%
% \pgfextract@process\mypoint{\pgf@x=10pt \pgf@y10pt}
% \pgfextract@process\myarcpoint{\pgfpointpolar{30}{5cm and 2cm}}

\def\pgfextract@process#1#2{%
	\pgf@process{#2}%
	\edef#1{\noexpand\pgf@x=\the\pgf@x\noexpand\relax\noexpand\pgf@y=\the\pgf@y\noexpand\relax}%
}
% This needed until old shapes code changed.
\let\pgfsavepgf@process\pgfextract@process%


% Return a point
%  
% #1 = x-coordinate of the point 
% #2 = y-coordinate of the point 
%  
% x = #1
% y = #2
%
% Example:
%
% \pgfpathmoveto{\pgfpoint{2pt+3cm}{3cm}}

\def\pgfpoint#1#2{%
  \pgfmathsetlength\pgf@x{#1}%
  \pgfmathsetlength\pgf@y{#2}\ignorespaces}


% Quickly a point
%  
% #1 = x-coordinate of the point (no calculations done)
% #2 = y-coordinate of the point (no calculations done)
%  
% x = #1
% y = #2
%
% Example:
%
% \pgfpathmoveto{\pgfqpoint{2pt}{3cm}}

\def\pgfqpoint#1#2{\pgf@x=#1\pgf@y=#2}



% Return the origin.
%  
% x = 0
% y = 0
%
% Example:
%
% \pgfpathmoveto{\pgfpointorigin}

\def\pgfpointorigin{\pgf@x=0pt\pgf@y=\pgf@x\ignorespaces}



% Return a transformed point
%  
% #1 = a point
%
% Description:
%
% This command applies pgf's current transformation matrix to the
% given point. Normally, this is done automatically by commands like
% lineto or moveto, but sometimes you may wish to access a transformed
% point yourself. In the below example, this command is used for a low level
% coordinate system shift.
%
% Example:
%
% \begin{pgflowleveltransformshiftscope}{\pgfpointtransformed{\pgfpointorigin}}
%   \pgfbox[center,center]{Hi!}
% \end{pgflowleveltransformshiftscope}

\def\pgfpointtransformed#1{%
  \pgf@process{%
    #1%
    \pgf@pos@transform{\pgf@x}{\pgf@y}%
  }%
}


% Return the difference vector of two points.
%  
% #1 = start of vector  
% #2 = end of vector  
%  
% x = x-component of difference 
% y = y-component of difference 
%
% Example:
%
% \pgfpathmoveto{\pgfpointdiff{\pgfpointxy{1}{1}}{\pgfpointxy{2}{3}}}

\def\pgfpointdiff#1#2{%
  \pgf@process{#1}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \pgf@process{#2}%
  \advance\pgf@x by-\pgf@xa\relax%
  \advance\pgf@y by-\pgf@ya\relax\ignorespaces}

% Add two vectors. 
%  
% #1 = first vector  
% #2 = second vector  
%  
% x = x-component of addition
% y = y-component of addition
%
% Example:
%
% \pgfpathmoveto{\pgfpointadd{\pgfpointxy{0}{1}}{\pgfpointxy{2}{3}}}

\def\pgfpointadd#1#2{%
  \pgf@process{#1}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \pgf@process{#2}%
  \advance\pgf@x by\pgf@xa%
  \advance\pgf@y by\pgf@ya}



% Multiply a vector by a factor.
%  
% #1 = factor  
% #2 = vector  
%
% Example:
%
% \pgfpointscale{2}{\pgfpointxy{0}{1}}

\def\pgfpointscale#1#2{%
  \pgf@process{#2}%
  \pgfmathparse{#1}%
  \pgf@x=\pgfmathresult\pgf@x%
  \pgf@y=\pgfmathresult\pgf@y%
}
% A "quick" variant of \pgfpointscale which doesn't invoke the math parser for '#1'.
% #1 must be a number without units, no registers are accepted.
\def\pgfqpointscale#1#2{%
  \pgf@process{#2}%
  \pgf@x=#1\pgf@x%
  \pgf@y=#1\pgf@y%
}


% The intersection of two lines
%  
% #1 = point on first line
% #2 = another point on first line
% #3 = point on second line
% #4 = another point on second line
%
% Returns the intersection of the two lines. If there is no
% intersection or if the points #1 and #2 or the points #3 and #4 are
% identical, the behaviour is not specified.
%
% Example:
%
% \pgfpointintersectionoflines{\pgfpointxy{0}{1}}{\pgfpointxy{1}{0}}{\pgfpointxy{2}{2}}{\pgfpointxy{3}{4}}

\def\pgfpointintersectionoflines#1#2#3#4{%
  {%
    % 
    % Compute orthogonal vector to #1--#2
    % 
    \pgf@process{#2}%
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgf@process{#1}%
    \advance\pgf@xa by-\pgf@x%
    \advance\pgf@ya by-\pgf@y%
    \pgf@ya=-\pgf@ya%
    % Normalise a bit
    \c@pgf@counta=\pgf@xa%
    \ifnum\c@pgf@counta<0\relax%
      \c@pgf@counta=-\c@pgf@counta\relax%
    \fi%
    \c@pgf@countb=\pgf@ya%
    \ifnum\c@pgf@countb<0\relax%
      \c@pgf@countb=-\c@pgf@countb\relax%
    \fi%
    \advance\c@pgf@counta by\c@pgf@countb\relax%
    \divide\c@pgf@counta by 65536\relax%
    \ifnum\c@pgf@counta>0\relax%
      \divide\pgf@xa by\c@pgf@counta\relax%
      \divide\pgf@ya by\c@pgf@counta\relax%
    \fi%
    %
    % Compute projection
    %
    \pgf@xc=\pgf@sys@tonumber{\pgf@ya}\pgf@x%
    \advance\pgf@xc by\pgf@sys@tonumber{\pgf@xa}\pgf@y%
    % 
    % The orthogonal vector is (\pgf@ya,\pgf@xa)
    % 
    % 
    % Compute orthogonal vector to #3--#4
    % 
    \pgf@process{#4}%
    \pgf@xb=\pgf@x%
    \pgf@yb=\pgf@y%
    \pgf@process{#3}%
    \advance\pgf@xb by-\pgf@x%
    \advance\pgf@yb by-\pgf@y%
    \pgf@yb=-\pgf@yb%
    % Normalise a bit
    \c@pgf@counta=\pgf@xb%
    \ifnum\c@pgf@counta<0\relax%
      \c@pgf@counta=-\c@pgf@counta\relax%
    \fi%
    \c@pgf@countb=\pgf@yb%
    \ifnum\c@pgf@countb<0\relax%
      \c@pgf@countb=-\c@pgf@countb\relax%
    \fi%
    \advance\c@pgf@counta by\c@pgf@countb\relax%
    \divide\c@pgf@counta by 65536\relax%
    \ifnum\c@pgf@counta>0\relax%
      \divide\pgf@xb by\c@pgf@counta\relax%
      \divide\pgf@yb by\c@pgf@counta\relax%
    \fi%
    %
    % Compute projection
    %
    \pgf@yc=\pgf@sys@tonumber{\pgf@yb}\pgf@x%
    \advance\pgf@yc by\pgf@sys@tonumber{\pgf@xb}\pgf@y%
    % 
    % The orthogonal vector is (\pgf@yb,\pgf@xb)
    % 
    % Setup transformation matrx (this is just to use the matrix
    % inversion)
    % 
    \pgfsettransform{{\pgf@sys@tonumber\pgf@ya}{\pgf@sys@tonumber\pgf@yb}{\pgf@sys@tonumber\pgf@xa}{\pgf@sys@tonumber\pgf@xb}{0pt}{0pt}}%
    \pgftransforminvert%
    \pgf@process{\pgfpointtransformed{\pgfpoint{\pgf@xc}{\pgf@yc}}}%
  }%
}


% The intersection of two circles
%  
% #1 = center of first circle
% #2 = center of second circle
% #3 = radius of first circle
% #4 = radius of second circle
% #5 = solution number
%
% Returns the intersection of the two circles. If #5 is to "1", the
% first intersection is returned, otherwise the second. If the circles
% do not intersect, an error may occur.
%
% Example:
%
% \pgfpointintersectionofcircles{\pgfpointxy{0}{1}}{\pgfpointxy{1}{0}}{1cm}{1cm}{1}

\def\pgfpointintersectionofcircles#1#2#3#4#5{%
  {%
    % Store first point in (xa,ya) and radius in xc.
    \pgf@process{#1}%
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgfmathsetlength{\pgf@xc}{#3}%
    % Store second point in (xb,yb) and radius in yc.
    \pgf@process{#2}%
    \pgf@xb=\pgf@x%
    \pgf@yb=\pgf@y%
    \pgfmathsetlength{\pgf@yc}{#4}%
    %
    % Ok, now make numbers smaller, in case they are too large
    %
    \c@pgf@counta=1\relax%
    \loop%
      \pgf@scale@downfalse%
      \ifdim\pgf@xc>50pt\relax%
        \pgf@scale@downtrue%
      \fi%
      \ifdim\pgf@yc>50pt\relax%
        \pgf@scale@downtrue%
      \fi%
    \ifpgf@scale@down%
      \multiply\c@pgf@counta by2\relax%
      \divide\pgf@xa by2\relax%
      \divide\pgf@ya by2\relax%
      \divide\pgf@xb by2\relax%
      \divide\pgf@yb by2\relax%
      \divide\pgf@xc by2\relax%
      \divide\pgf@yc by2\relax%
    \repeat%
    % The following code is taken from the Dr. Math internet forum:
    %
    % Let the centers be: (a,b), (c,d)
    % Let the radii be: r, s
    %
    % e = c - a                          [difference in x coordinates]
    % f = d - b                          [difference in y coordinates]
    % p = sqrt(e^2 + f^2)                [distance between centers]
    % k = (p^2 + r^2 - s^2)/(2p)         [distance from center 1 to line
    %                                     joining points of intersection]
    % x = a + ek/p + (f/p)sqrt(r^2 - k^2)
    % y = b + fk/p - (e/p)sqrt(r^2 - k^2)
    % OR
    % x = a + ek/p - (f/p)sqrt(r^2 - k^2)
    % y = b + fk/p + (e/p)sqrt(r^2 - k^2)
    %
    % Since we are running low on registers, use
    % \dimen0 for e
    % \dimen1 for f
    % \dimen2 for p
    % \dimen3 for p^2
    % \dimen4 for k
    % \dimen5 for 1/p
    % \dimen6 for sqrt(r^2 - k^2)
    % \dimen7 for k^2
    % \dimen8 for k/p
    % \dimen9 for sqrt(r^2 - k^2)/p
    % Also note that:
    % \pgf@xa for a
    % \pgf@ya for b
    % \pgf@xb for c
    % \pgf@yb for d
    % \pgf@xc for r
    % \pgf@yc for s
    %
    % Now:
    % e = c - a
    \dimen0=\pgf@xb%
    \advance\dimen0 by-\pgf@xa%
    % f = d - b
    \dimen1=\pgf@yb%
    \advance\dimen1 by-\pgf@ya%
    % p^2 = e^2 + f^2
    \pgf@x=\dimen0\relax%
    \pgf@x=\pgf@sys@tonumber{\pgf@x}\pgf@x%
    \dimen3=\pgf@x%
    \pgf@x=\dimen1\relax%
    \advance\dimen3 by\pgf@sys@tonumber{\pgf@x}\pgf@x%
    % p = sqrt(p^2)
    \pgfmathparse{sqrt(\the\dimen3)}%
    \dimen2=\pgfmathresult pt%
    % 1/p = 1/p
    \pgfmathreciprocal@{\pgfmathresult}%
    \dimen5=\pgfmathresult pt%
    % k = (p^2 + r^2 - s^2)/(2p)
    \dimen4=\dimen3\relax%
    \pgf@x=\pgf@xc%
    \advance\dimen4 by\pgf@sys@tonumber{\pgf@x}\pgf@x\relax%
    \pgf@x=\pgf@yc%
    \advance\dimen4 by-\pgf@sys@tonumber{\pgf@x}\pgf@x\relax%
    \dimen4=.5\dimen4%
    \dimen4=\pgf@sys@tonumber{\dimen5}\dimen4%
    % dimen7 is k^2
    \dimen7=\pgf@sys@tonumber{\dimen4}\dimen4\relax%
    % dimen6 is sqrt(r^2 - k^2)
    \pgfmathparse{sqrt(\pgf@sys@tonumber{\pgf@xc}\pgf@xc-\the\dimen7)}%
    \dimen6=\pgfmathresult pt%
    % dimen8 is k/p
    \dimen8=\pgf@sys@tonumber{\dimen4}\dimen5\relax%
    % dimen9 is sqrt(r^2 - k^2)/p
    \dimen9=\pgf@sys@tonumber{\dimen6}\dimen5\relax%
    \ifnum#5=1\relax%
      % x = a + ek/p + (f/p)sqrt(r^2 - k^2)
      \pgf@x=\pgf@xa%
      \advance\pgf@x by\pgf@sys@tonumber{\dimen0}\dimen8\relax%
      \advance\pgf@x by\pgf@sys@tonumber{\dimen1}\dimen9\relax%
      % y = b + fk/p - (e/p)sqrt(r^2 - k^2)
      \pgf@y=\pgf@ya%
      \advance\pgf@y by\pgf@sys@tonumber{\dimen1}\dimen8\relax%
        %temp
        \pgf@xb=\pgf@sys@tonumber{\dimen0}\dimen9%
        \pgf@xb=-\pgf@xb%
      \advance\pgf@y by\pgf@xb\relax%
    \else%  
      % x = a + ek/p - (f/p)sqrt(r^2 - k^2)
      \pgf@x=\pgf@xa%
      \advance\pgf@x by\pgf@sys@tonumber{\dimen0}\dimen8\relax%
        %temp
        \pgf@xb=\pgf@sys@tonumber{\dimen1}\dimen9%
        \pgf@xb=-\pgf@xb%
      \advance\pgf@x by\pgf@xb\relax%
      % y = b + fk/p + (e/p)sqrt(r^2 - k^2)
      \pgf@y=\pgf@ya%
      \advance\pgf@y by\pgf@sys@tonumber{\dimen1}\dimen8\relax%
      \advance\pgf@y by\pgf@sys@tonumber{\dimen0}\dimen9\relax%
    \fi%
    \pgf@x=\c@pgf@counta\pgf@x%
    \pgf@y=\c@pgf@counta\pgf@y%
    \pgf@process{}% get results outside
  }%
}
\newif\ifpgf@scale@down


% Returns point on a line from #2 to #3 at time #1.
%  
% #1 = a time, where 0 is the start and 1 is the end
% #2 = start point
% #3 = end point 
%  
% x = x-component of #1*start + (1-#1)*end
% y = y-component of #1*start + (1-#1)*end 
% xa/ya = #1*start + (1-#1)*end
% xb/yb = start point
% xc/yc = end point
%
% Example:
%
% % Middle of (1,1) and (2,3)
% \pgfpathmoveto{\pgfpointlineattime{0.5}{\pgfpointxy{0}{1}}{\pgfpointxy{2}{3}}}

\def\pgfpointlineattime#1#2#3{%
  \pgf@process{#3}%
  \pgf@xa\pgf@x%
  \pgf@ya\pgf@y%
  \pgf@xc\pgf@x%
  \pgf@yc\pgf@y%
  \pgf@process{#2}%
  \pgf@xb\pgf@x%
  \pgf@yb\pgf@y%
  \pgfmathsetmacro\pgf@temp{#1}%
  \advance\pgf@xa by-\pgf@x%
  \advance\pgf@ya by-\pgf@y%
  \advance\pgf@x by\pgf@temp\pgf@xa%
  \advance\pgf@y by\pgf@temp\pgf@ya%  
}


% Move point #2 #1 many units in the direction of #3.
%  
% #1 = a distance
% #2 = start point
% #3 = end point 
%
% Description:
%
% Computes
%  
% x/y = start + #1*(normalise(end-start))
%
% and additionally
%
% xa/ya = #1*(normalise(end-start))
% xb/yb = start
% xc/yc = end
%
% Example:
%
% \pgfpathmoveto{\pgfpointlineatdistance{2pt}{\pgfpointxy{0}{1}}{\pgfpointxy{2}{3}}}
% \pgfpathlineto{\pgfpointlineatdistance{3pt}{\pgfpointxy{2}{3}}{\pgfpointxy{0}{1}}}

\def\pgfpointlineatdistance#1#2#3{%
  \pgfmathsetlength\pgf@xa{#1}%
  \pgf@process{#2}%
  \pgf@xb\pgf@x% xb/yb = start point
  \pgf@yb\pgf@y%
  \pgf@process{#3}%
  \pgf@xc\pgf@x%
  \pgf@yc\pgf@y%
  \advance\pgf@x by-\pgf@xb\relax%
  \advance\pgf@y by-\pgf@yb\relax%
  \pgf@process{\pgfpointnormalised{}}% x/y = normalised vector
  \pgf@ya=\pgf@xa\relax%
  \pgf@xa=\pgf@sys@tonumber{\pgf@x}\pgf@xa%
  \pgf@ya=\pgf@sys@tonumber{\pgf@y}\pgf@ya%
  \pgf@x=\pgf@xb\relax%
  \pgf@y=\pgf@yb\relax%
  \advance\pgf@x by\pgf@xa\relax%
  \advance\pgf@y by\pgf@ya\relax%
}


% Returns point on a curve from #2 to #5 with controls #3 and #4 at time #1.
%  
% #1 = a time
% #2 = start point
% #3 = first control point
% #4 = second control point
% #5 = end point 
%  
% x = x-component of place on the curve at time t
% y = y-component of place on the curve at time t
%
% Additionally, (\pgf@xa,\pgf@ya) and (\pgf@xb,\pgf@yb) will be on a
% tangent to the point on the curve (this can be useful for computing
% a label rotation). (\pgf@xc,\pgf@yc) will be equal to the end
% point. \pgf@time@s will equal the value of #1 and \pgf@time@t will
% equal 1-#1.
%
% Example:
%
% % Middle of (1,1) and (2,3)
% \pgfpathmoveto{\pgfpointcurveattime{0.5}{\pgfpointxy{0}{1}}{\pgfpointxy{1}{1}}{\pgfpointxy{1}{1}}{\pgfpointxy{2}{3}}}

\def\pgfpointcurveattime#1#2#3#4#5{%
  \pgfmathparse{#1}%
  \let\pgf@time@s=\pgfmathresult%
  \pgf@x=\pgfmathresult pt%
  \pgf@x=-\pgf@x%
  \advance\pgf@x by 1pt%
  \edef\pgf@time@t{\pgf@sys@tonumber{\pgf@x}}%
  \pgf@process{#5}%
  \pgf@xc=\pgf@x%
  \pgf@yc=\pgf@y%
  \pgf@process{#4}%
  \pgf@xb=\pgf@x%
  \pgf@yb=\pgf@y%
  \pgf@process{#3}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \pgf@process{#2}%
  % First iteration:
  \pgf@x=\pgf@time@t\pgf@x\advance\pgf@x by\pgf@time@s\pgf@xa%
  \pgf@y=\pgf@time@t\pgf@y\advance\pgf@y by\pgf@time@s\pgf@ya%
  \pgf@xa=\pgf@time@t\pgf@xa\advance\pgf@xa by\pgf@time@s\pgf@xb%
  \pgf@ya=\pgf@time@t\pgf@ya\advance\pgf@ya by\pgf@time@s\pgf@yb%
  \pgf@xb=\pgf@time@t\pgf@xb\advance\pgf@xb by\pgf@time@s\pgf@xc%
  \pgf@yb=\pgf@time@t\pgf@yb\advance\pgf@yb by\pgf@time@s\pgf@yc%
  % Second iteration:
  \pgf@x=\pgf@time@t\pgf@x\advance\pgf@x by\pgf@time@s\pgf@xa%
  \pgf@y=\pgf@time@t\pgf@y\advance\pgf@y by\pgf@time@s\pgf@ya%
  \pgf@xa=\pgf@time@t\pgf@xa\advance\pgf@xa by\pgf@time@s\pgf@xb%
  \pgf@ya=\pgf@time@t\pgf@ya\advance\pgf@ya by\pgf@time@s\pgf@yb%
  % Save x/y
  \pgf@xb=\pgf@x%
  \pgf@yb=\pgf@y%
  % Third iteration:
  \pgf@x=\pgf@time@t\pgf@x\advance\pgf@x by\pgf@time@s\pgf@xa%
  \pgf@y=\pgf@time@t\pgf@y\advance\pgf@y by\pgf@time@s\pgf@ya%
}



% Returns point on an arc at a certain "time"
%  
% #1 = a time 
% #2 = center of a ellipse
% #3 = 0-degree exis of the ellipse
% #4 = 90-degree exis of the ellipse
% #5 = start angle of an arc on the ellipse
% #6 = end angle of an arc on the ellipse
%
% Result:
%
% \pgf@x = x-component of place on the arc at time t
% \pgf@y = y-component of place on the arc at time t
%
% Additionally, (\pgf@xa,\pgf@ya) will be a tangent to the
% point on the arc (this can be useful for computing a label rotation).
%
% Example:
%
% \pgfpointarcaxesattime{0.25}{\pgfpoint{1cm}{1cm}}{\pgfpoint{1cm}{0cm}}{\pgfpoint{0cm}{1cm}}{1cm}{30}{40}

\def\pgfpointarcaxesattime#1#2#3#4#5#6{%
  \pgfmathsetmacro\pgf@angle@start{#5}%
  \pgfmathsetmacro\pgf@angle@end{#6}%
  \pgfmathparse{#1}%
  \pgf@x=\pgfmathresult pt%
  \pgf@x=-\pgf@x%
  \advance\pgf@x by 1pt%
  \pgfmathsetmacro\pgf@angle@mid{\pgf@angle@end*\pgfmathresult+\pgf@angle@start*\pgf@sys@tonumber{\pgf@x}}%
  \pgfmathcos@{\pgf@angle@mid}%
  \let\pgf@angle@cos\pgfmathresult%
  \pgfmathsin@{\pgf@angle@mid}%
  \let\pgf@angle@sin\pgfmathresult%
  \pgf@process{#3}%
  \edef\pgf@angle@zero@axis{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}
  \pgf@process{#4}%
  \edef\pgf@angle@ninety@axis{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}
  % Compute tangent
  \pgf@process{\pgfpointadd{\pgfpointscale{\pgf@angle@sin}{\pgf@angle@zero@axis}}%
    {\pgfpointscale{-\pgf@angle@cos}{\pgf@angle@ninety@axis}}}%
  \ifdim\pgf@angle@start pt>\pgf@angle@end pt%
    \pgf@xa=\pgf@x%  
    \pgf@ya=\pgf@y%  
  \else%
    \pgf@xa=-\pgf@x%  
    \pgf@ya=-\pgf@y%  
  \fi%
  % Compute position
  \pgf@process{\pgfpointadd{#2}{%
      \pgfpointadd{\pgfpointscale{\pgf@angle@cos}{\pgf@angle@zero@axis}}%
    {\pgfpointscale{\pgf@angle@sin}{\pgf@angle@ninety@axis}}}}%
}



% Internal registers
\newdimen\pgf@xx
\newdimen\pgf@xy
\newdimen\pgf@yx
\newdimen\pgf@yy
\newdimen\pgf@zx
\newdimen\pgf@zy



% A polar coordinate
%
% #1 = a degree
% #2 = a radius -- either a dimension or two dimensions separated by 
%      " and ". 
%
% x = (first dimension in #2) * cos(#1)
% y = (second dimension in #2) * sin(#2)
% 
% Example:
%
% \pgfpathmoveto{\pgfpointpolar{30}{1cm}}
% \pgfpathlineto{\pgfpointpolar{30}{1cm and 2cm}}

\def\pgfpointpolar#1#2{%
  \pgfutil@in@{and }{#2}%
  \ifpgfutil@in@%
    \pgf@polar@#2\@@%
  \else%
    \pgf@polar@#2 and #2\@@%
  \fi%  
  \pgfmathparse{#1}%
  \let\pgfpoint@angle=\pgfmathresult%
  \pgfmathcos@{\pgfpoint@angle}%
  \pgf@x=\pgfmathresult\pgf@x%
  \pgfmathsin@{\pgfpoint@angle}%
  \pgf@y=\pgfmathresult\pgf@y%
}

\def\pgf@polar@#1and #2\@@{%
  \pgfmathsetlength{\pgf@y}{#2}%
  \pgfmathsetlength{\pgf@x}{#1}%  
}

% Quick version of the polar coordinate method

\def\pgfqpointpolar#1#2{%
  \pgf@x=#2%
  \pgf@y=\pgf@x%
  \pgfmathcos@{#1}%
  \pgf@x=\pgfmathresult\pgf@x%
  \pgfmathsin@{#1}%
  \pgf@y=\pgfmathresult\pgf@y\relax%
}




% A polar coordinate in the xy plane.
%
% #1 = a degree
% #2 = a radius given as a number or two radi
%
% result = (first dim in #2) * x-vector * cos(#1) +
%          (second dim in #2) * y-vector * sin(#1)
% 
% Example:
%
% \pgfpathmoveto{\pgfpointpolarxy{30}{2}}

\def\pgfpointpolarxy#1#2{%
  \pgfutil@in@{and }{#2}%
  \ifpgfutil@in@%
    \pgf@polarxy@#2\@@%
  \else%
    \pgf@polarxy@#2and #2\@@%
  \fi%  
  \pgfmathparse{#1}%
  \let\pgfpoint@angle=\pgfmathresult%
  \pgfmathcos@{\pgfpoint@angle}%
  \pgf@xa=\pgfmathresult\pgf@xa%
  \pgfmathsin@{\pgfpoint@angle}%
  \pgf@ya=\pgfmathresult\pgf@ya%
  \pgf@x=\pgf@sys@tonumber{\pgf@xa}\pgf@xx%
  \advance\pgf@x by \pgf@sys@tonumber{\pgf@ya}\pgf@yx%
  \pgf@y=\pgf@sys@tonumber{\pgf@xa}\pgf@xy%
  \advance\pgf@y by \pgf@sys@tonumber{\pgf@ya}\pgf@yy}

\def\pgf@polarxy@#1and #2\@@{%
  \pgfmathsetlength{\pgf@xa}{#1}%
  \pgfmathsetlength{\pgf@ya}{#2}%
}



% A cylindrical coordinate.
%
% #1 = a degree
% #2 = a radius given as a number
% #3 = a height given as a number
%
% result = #2*(x-vector * cos(#1) + y-vector * sin(#1)) + #3*z-vector
% 
% Example:
%
% \pgfpathmoveto{\pgfpointcylindrical{30}{2}{1}}

\def\pgfpointcylindrical#1#2#3{%
  \pgfpointpolarxy{#1}{#2}%
  \pgfmathparse{#3}%
  \advance\pgf@x by \pgfmathresult\pgf@zx%
  \advance\pgf@y by \pgfmathresult\pgf@zy}


% A spherical coordinate.
%
% #1 = a longitude
% #2 = a latitude
% #3 = a radius
%
% result = #3*(cos(#2)*(x-vector * cos(#1) + y-vector * sin(#1)) + sin(#2)*z-vector)
% 
% Example:
%
% \pgfpathmoveto{\pgfpointspherical{30}{30}{2}}

\def\pgfpointspherical#1#2#3{%
  \pgfmathparse{#1}%
  \let\pgfpoint@angle=\pgfmathresult%
  \pgfmathsin@{\pgfpoint@angle}%
  \pgf@xb=\pgfmathresult\pgf@xx%
  \pgf@yb=\pgfmathresult\pgf@xy%
  \pgfmathcos@{\pgfpoint@angle}%
  \advance\pgf@xb by \pgfmathresult\pgf@yx%
  \advance\pgf@yb by \pgfmathresult\pgf@yy%
  %
  \pgfmathparse{#2}%
  \let\pgfpoint@angle=\pgfmathresult%
  \pgfmathcos@{\pgfpoint@angle}%
  \pgf@xc=\pgfmathresult\pgf@xb%
  \pgf@yc=\pgfmathresult\pgf@yb%
  \pgfmathsin@{\pgfpoint@angle}%
  \advance\pgf@xc by \pgfmathresult\pgf@zx%
  \advance\pgf@yc by \pgfmathresult\pgf@zy%
  \pgfmathparse{#3}%
  \pgf@x=\pgfmathresult\pgf@xc%
  \pgf@y=\pgfmathresult\pgf@yc\relax%
}


% Store the vector #1 * x-vec + #2 * y-vec
%
% #1 = a factor for the x-vector
% #2 = a factor fot the y-vector
%
% x = x-component of result vector
% y = y-component of result vector
%
% Description:
% 
% This command can be used to create a new coordinate system
% without using the rotate/translate/scale commands. This
% may be useful, if you do not want arrows and line width to
% be scaled/transformed together with the coordinate system.
% 
% Example:
%
% % Create a slanted rectangle
%
% \pgfsetxvec{\pgfpoint{1cm}{1cm}}
% \pgfsetyvec{\pgfpoint{0cm}{1cm}}
% 
% \pgfpathmoveto{\pgfpointxy{0}{0}}
% \pgfpathlineto{\pgfpointxy{1}{0}}
% \pgfpathlineto{\pgfpointxy{1}{1}}
% \pgfpathlineto{\pgfpointxy{0}{1}}
% \pgfclosestroke

\def\pgfpointxy#1#2{%
  \pgfmathparse{#1}%
  \let\pgftemp@x=\pgfmathresult%
  \pgfmathparse{#2}%
  \let\pgftemp@y=\pgfmathresult%
  \pgf@x=\pgftemp@x\pgf@xx%
  \advance\pgf@x by \pgftemp@y\pgf@yx%
  \pgf@y=\pgftemp@x\pgf@xy%
  \advance\pgf@y by \pgftemp@y\pgf@yy}


% "Quick" variant for \pgfpointxy.
%
% Only numbers without unit are allowed here.
\def\pgfqpointxy#1#2{%
  \pgf@x=#1\pgf@xx%
  \advance\pgf@x by #2\pgf@yx%
  \pgf@y=#1\pgf@xy%
  \advance\pgf@y by #2\pgf@yy}

% Store the vector #1 * x-vec + #2 * y-vec + #3 * z-vec
%
% #1 = a factor for the x-vector
% #2 = a factor fot the y-vector
% #3 = a factor fot the z-vector
%
% x = x-component of result vector
% y = y-component of result vector
%
%
% Description:
% 
% This command allows you to use a 3d coordinate system.
% 
%
% Example:
%
% % Draw a cubus
% 
% \pgfline{\pgfpointxyz{0}{0}{0}}{\pgfpointxyz{0}{0}{1}}
% \pgfline{\pgfpointxyz{0}{1}{0}}{\pgfpointxyz{0}{1}{1}}
% \pgfline{\pgfpointxyz{1}{0}{0}}{\pgfpointxyz{1}{0}{1}}
% \pgfline{\pgfpointxyz{1}{1}{0}}{\pgfpointxyz{1}{1}{1}}
% \pgfline{\pgfpointxyz{0}{0}{0}}{\pgfpointxyz{0}{1}{0}}
% \pgfline{\pgfpointxyz{0}{0}{1}}{\pgfpointxyz{0}{1}{1}}
% \pgfline{\pgfpointxyz{1}{0}{0}}{\pgfpointxyz{1}{1}{0}}
% \pgfline{\pgfpointxyz{1}{0}{1}}{\pgfpointxyz{1}{1}{1}}
% \pgfline{\pgfpointxyz{0}{0}{0}}{\pgfpointxyz{1}{0}{0}}
% \pgfline{\pgfpointxyz{0}{0}{1}}{\pgfpointxyz{1}{0}{1}}
% \pgfline{\pgfpointxyz{0}{1}{0}}{\pgfpointxyz{1}{1}{0}}
% \pgfline{\pgfpointxyz{0}{1}{1}}{\pgfpointxyz{1}{1}{1}}

\def\pgfpointxyz#1#2#3{%
  \pgfmathparse{#1}%
  \let\pgftemp@x=\pgfmathresult%
  \pgfmathparse{#2}%
  \let\pgftemp@y=\pgfmathresult%
  \pgfmathparse{#3}%
  \let\pgftemp@z=\pgfmathresult%
  \pgf@x=\pgftemp@x\pgf@xx%
  \advance\pgf@x by \pgftemp@y\pgf@yx%
  \advance\pgf@x by \pgftemp@z\pgf@zx%
  \pgf@y=\pgftemp@x\pgf@xy%
  \advance\pgf@y by \pgftemp@y\pgf@yy%
  \advance\pgf@y by \pgftemp@z\pgf@zy}

% "Quick" variant for \pgfpointxyz.
%
% Only numbers without unit are allowed.
\def\pgfqpointxyz#1#2#3{%
  \pgf@x=#1\pgf@xx%
  \advance\pgf@x by #2\pgf@yx%
  \advance\pgf@x by #3\pgf@zx%
  \pgf@y=#1\pgf@xy%
  \advance\pgf@y by #2\pgf@yy%
  \advance\pgf@y by #3\pgf@zy}



% Set the x-vector
%
% #1 = a point the is the new x-vector
%
% Example:
%
% \pgfsetxvec{\pgfpoint{1cm}{0cm}}

\def\pgfsetxvec#1{%
  \pgf@process{#1}%
  \pgf@xx=\pgf@x%
  \pgf@xy=\pgf@y%
  \ignorespaces}


% Set the y-vector
%
% #1 = a point the is the new y-vector
%
% Example:
%
% \pgfsetyvec{\pgfpoint{0cm}{1cm}}

\def\pgfsetyvec#1{%
  \pgf@process{#1}%
  \pgf@yx=\pgf@x%
  \pgf@yy=\pgf@y%
  \ignorespaces}


% Set the z-vector
%
% #1 = a point the is the new z-vector
%
% Example:
%
% \pgfsetzvec{\pgfpoint{-0.385cm}{-0.385cm}}

\def\pgfsetzvec#1{%
  \pgf@process{#1}%
  \pgf@zx=\pgf@x%
  \pgf@zy=\pgf@y%
  \ignorespaces}



% Default values
\pgfsetxvec{\pgfpoint{1cm}{0cm}}
\pgfsetyvec{\pgfpoint{0cm}{1cm}}
\pgfsetzvec{\pgfpoint{-0.385cm}{-0.385cm}}




% Normalise a point.
%
% #1 = point with coordinates (a,b)
%
% x  = a/\sqrt(a*a+b*b)
% y  = b/\sqrt(a*a+b*b)
%
% Example:
%
% \pgfpointnormalised{\pgfpointxy{2}{1}}

\def\pgfpointnormalised#1{%
  \pgf@process{#1}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \ifdim\pgf@x<0pt\relax% move into first quadrant
    \pgf@x=-\pgf@x%
  \fi%
  \ifdim\pgf@y<0pt\relax%
    \pgf@y=-\pgf@y%
  \fi%
  \ifdim\pgf@x>\pgf@y% x > y
    % make point small
    \c@pgf@counta=\pgf@x%
    \divide\c@pgf@counta by 65536\relax%
    \ifnum\c@pgf@counta=0\relax%
      \c@pgf@counta=1\relax%
    \fi%
    \divide\pgf@x by\c@pgf@counta%
    \divide\pgf@y by\c@pgf@counta%
    \divide\pgf@xa by\c@pgf@counta%
    \divide\pgf@ya by\c@pgf@counta%
    % ok.
    \pgf@x=.125\pgf@x%
    \pgf@y=.125\pgf@y%
    \c@pgf@counta=\pgf@x%
    \c@pgf@countb=\pgf@y%
    \multiply\c@pgf@countb by 100%
    \ifnum\c@pgf@counta<64\relax%
      \pgf@x=1pt\relax%
      \pgf@y=0pt\relax%
    \else%
      \divide\c@pgf@countb by \c@pgf@counta%
      \pgf@x=\csname pgf@cosfrac\the\c@pgf@countb\endcsname pt%
      \pgf@xc=8192pt%
      \divide\pgf@xc by\c@pgf@counta%
      \pgf@y=\pgf@sys@tonumber{\pgf@xc}\pgf@ya%
      \pgf@y=\pgf@sys@tonumber{\pgf@x}\pgf@y%
    \fi%
    \ifdim\pgf@xa<0pt%
      \pgf@x=-\pgf@x%
    \fi%
  \else% x <= y
    % make point small
    \c@pgf@counta=\pgf@y%
    \divide\c@pgf@counta by 65536\relax%
    \ifnum\c@pgf@counta=0\relax%
      \c@pgf@counta=1\relax%
    \fi%
    \divide\pgf@x by\c@pgf@counta%
    \divide\pgf@y by\c@pgf@counta%
    \divide\pgf@xa by\c@pgf@counta%
    \divide\pgf@ya by\c@pgf@counta%
    % ok.
    \pgf@x=.125\pgf@x%
    \pgf@y=.125\pgf@y%
    \c@pgf@counta=\pgf@y%
    \c@pgf@countb=\pgf@x%
    \multiply\c@pgf@countb by 100%
    \ifnum\c@pgf@counta<64\relax%
      \pgf@y=1pt\relax%
      \pgf@x=0pt\relax%
    \else%
      \divide\c@pgf@countb by \c@pgf@counta%
      \pgf@y=\csname pgfmath@cosfrac@\the\c@pgf@countb\endcsname pt%
      \pgf@xc=8192pt%
      \divide\pgf@xc by\c@pgf@counta%
      \pgf@x=\pgf@sys@tonumber{\pgf@xc}\pgf@xa%
      \pgf@x=\pgf@sys@tonumber{\pgf@y}\pgf@x%
    \fi%
    \ifdim\pgf@ya<0pt%
      \pgf@y=-\pgf@y%
    \fi%
  \fi\ignorespaces%
}





% A point on a rectangle in a certain direction.
%
% #1 = a point pointing in some direction (length should be about 1pt,
%      but need not be exact)
% #2 = upper right corner of a rectangle centered at the origin
%
% Returns the intersection of a line starting at the origin going in
% the given direction and the rectangle's border.
%
% Example:
%
% \pgfpointborderrectangle{\pgfpointnormalised{\pgfpointxy{2}{1}}
%   {\pgfpoint{1cm}{2cm}}

\def\pgfpointborderrectangle#1#2{%
  \pgf@process{#2}%
  \pgf@xb=\pgf@x%
  \pgf@yb=\pgf@y%
  \pgf@process{#1}%
  % Ok, let's find out about the direction:
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \ifnum\pgf@xa<0\relax% move into first quadrant
    \pgf@x=-\pgf@x%
  \fi%
  \ifnum\pgf@ya<0\relax%
    \pgf@y=-\pgf@y%
  \fi%
  \pgf@xc=.125\pgf@x%
  \pgf@yc=.125\pgf@y%
  \c@pgf@counta=\pgf@xc%
  \c@pgf@countb=\pgf@yc%
  \ifnum\c@pgf@countb<\c@pgf@counta%
    \ifnum\c@pgf@counta<255\relax%
      \pgf@y=\pgf@yb\relax%
      \pgf@x=0pt\relax%
    \else%
      \pgf@xc=8192pt%
      \divide\pgf@xc by\c@pgf@counta% \pgf@xc = 1/\pgf@x
      \pgf@y=\pgf@sys@tonumber{\pgf@xc}\pgf@y%
      \pgf@y=\pgf@sys@tonumber{\pgf@xb}\pgf@y%
      \ifnum\pgf@y<\pgf@yb%
        \pgf@x=\pgf@xb%
      \else% rats, calculate intersection on upper side
        \ifnum\c@pgf@countb<255\relax%
          \pgf@x=\pgf@xb\relax%
          \pgf@y=0pt\relax%
        \else%
          \pgf@yc=8192pt%
          \divide\pgf@yc by\c@pgf@countb% \pgf@xc = 1/\pgf@x
          \pgf@x=\pgf@sys@tonumber{\pgf@yc}\pgf@x%
          \pgf@x=\pgf@sys@tonumber{\pgf@yb}\pgf@x%
          \pgf@y=\pgf@yb%
        \fi%
      \fi%  
    \fi%
  \else%
    \ifnum\c@pgf@countb<255\relax%
      \pgf@x=\pgf@xb\relax%
      \pgf@y=0pt\relax%
    \else%
      \pgf@yc=8192pt%
      \divide\pgf@yc by\c@pgf@countb% \pgf@xc = 1/\pgf@x
      \pgf@x=\pgf@sys@tonumber{\pgf@yc}\pgf@x%
      \pgf@x=\pgf@sys@tonumber{\pgf@yb}\pgf@x%
      \ifnum\pgf@x<\pgf@xb%
        \pgf@y=\pgf@yb%
      \else%
        \ifnum\c@pgf@counta<255\relax%
          \pgf@y=\pgf@yb\relax%
          \pgf@x=0pt\relax%
        \else%
          \pgf@xc=8192pt%
          \divide\pgf@xc by\c@pgf@counta% \pgf@xc = 1/\pgf@x
          \pgf@y=\pgf@sys@tonumber{\pgf@xc}\pgf@y%
          \pgf@y=\pgf@sys@tonumber{\pgf@xb}\pgf@y%
          \pgf@x=\pgf@xb%
        \fi%
      \fi%  
    \fi%
  \fi%  
  \ifnum\pgf@xa<0\relax\pgf@x=-\pgf@x\fi%
  \ifnum\pgf@ya<0\relax\pgf@y=-\pgf@y\fi%    
}




% An approximation to a point on an ellipse in a certain
% direction. Will be exact only if the ellipse is a circle. 
%
% #1 = a point pointing in some direction
% #2 = upper right corner of a bounding box for the ellipse
%
% Returns the intersection of a line starting at the origin going in
% the given direction and the ellipses border.
%
% Example:
%
% \pgfpointborderellipse{\pgfpointnormalised{\pgfpointxy{2}{1}}
%   {\pgfpoint{1cm}{2cm}}

\def\pgfpointborderellipse#1#2{%
  \pgf@process{#2}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \ifdim\pgf@xa=\pgf@ya% circle. that's easy!
    \pgf@process{\pgfpointnormalised{#1}}%
    \pgf@x=\pgf@sys@tonumber{\pgf@xa}\pgf@x%
    \pgf@y=\pgf@sys@tonumber{\pgf@xa}\pgf@y%
  \else%
    \ifdim\pgf@xa<\pgf@ya%
      % Ok, first, let's compute x/y:
      \c@pgf@countb=\pgf@ya%
      \divide\c@pgf@countb by65536\relax%
      \divide\pgf@x by\c@pgf@countb%
      \divide\pgf@y by\c@pgf@countb%
      \pgf@xc=\pgf@x%
      \pgf@yc=8192pt%
      \pgf@y=.125\pgf@y%
      \c@pgf@countb=\pgf@y%
      \divide\pgf@yc by\c@pgf@countb%
      \pgf@process{#1}%
      \pgf@y=\pgf@sys@tonumber{\pgf@yc}\pgf@y%
      \pgf@y=\pgf@sys@tonumber{\pgf@xc}\pgf@y%
      \pgf@process{\pgfpointnormalised{}}%
      \pgf@x=\pgf@sys@tonumber{\pgf@xa}\pgf@x%
      \pgf@y=\pgf@sys@tonumber{\pgf@ya}\pgf@y%
    \else%
      % Ok, now let's compute y/x:
      \c@pgf@countb=\pgf@xa%
      \divide\c@pgf@countb by65536\relax%
      \divide\pgf@x by\c@pgf@countb%
      \divide\pgf@y by\c@pgf@countb%
      \pgf@yc=\pgf@y%
      \pgf@xc=8192pt%
      \pgf@x=.125\pgf@x%
      \c@pgf@countb=\pgf@x%
      \divide\pgf@xc by\c@pgf@countb%
      \pgf@process{#1}%
      \pgf@x=\pgf@sys@tonumber{\pgf@yc}\pgf@x%
      \pgf@x=\pgf@sys@tonumber{\pgf@xc}\pgf@x%
      \pgf@process{\pgfpointnormalised{}}%
      \pgf@x=\pgf@sys@tonumber{\pgf@xa}\pgf@x%
      \pgf@y=\pgf@sys@tonumber{\pgf@ya}\pgf@y%
    \fi%  
  \fi%
}





% Extract the x-coordinate of a point to a dimensions
%  
% #1 = a TeX dimension
% #2 = a point
%
% Example:
%
% \newdimen\mydim
% \pgfextractx{\mydim}{\pgfpoint{2cm}{4pt}}
% % \mydim is now 2cm

\def\pgfextractx#1#2{%
  \pgf@process{#2}%
  #1=\pgf@x\relax}


% Extract the y-coordinate of a point to a dimensions
%  
% #1 = a TeX dimension
% #2 = a point
%
% Example:
%
% \newdimen\mydim
% \pgfextracty{\mydim}{\pgfpoint{2cm}{4pt}}
% % \mydim is now 4pt

\def\pgfextracty#1#2{%
  \pgf@process{#2}%
  #1=\pgf@y\relax}


% Stores the most recently used (x,y) coordinates into two macros, #1
% and #2.
\def\pgfgetlastxy#1#2{%
	\edef#1{\the\pgf@x}%
	\edef#2{\the\pgf@y}%
}%


\def\pgf@def#1#2#3{\expandafter\def\csname pgf@#1#2\endcsname{#3}}
\pgf@def{cosfrac}{0}{1}
\pgf@def{cosfrac}{1}{0.99995}    \pgf@def{cosfrac}{2}{0.9998}
\pgf@def{cosfrac}{3}{0.99955}    \pgf@def{cosfrac}{4}{0.999201}
\pgf@def{cosfrac}{5}{0.998752}   \pgf@def{cosfrac}{6}{0.998205}
\pgf@def{cosfrac}{7}{0.997559}   \pgf@def{cosfrac}{8}{0.996815}
\pgf@def{cosfrac}{9}{0.995974}   \pgf@def{cosfrac}{10}{0.995037}
\pgf@def{cosfrac}{11}{0.994004}  \pgf@def{cosfrac}{12}{0.992877}
\pgf@def{cosfrac}{13}{0.991656}  \pgf@def{cosfrac}{14}{0.990342}
\pgf@def{cosfrac}{15}{0.988936}  \pgf@def{cosfrac}{16}{0.987441}
\pgf@def{cosfrac}{17}{0.985856}  \pgf@def{cosfrac}{18}{0.984183}
\pgf@def{cosfrac}{19}{0.982424}  \pgf@def{cosfrac}{20}{0.980581}
\pgf@def{cosfrac}{21}{0.978653}  \pgf@def{cosfrac}{22}{0.976644}
\pgf@def{cosfrac}{23}{0.974555}  \pgf@def{cosfrac}{24}{0.972387}
\pgf@def{cosfrac}{25}{0.970143}  \pgf@def{cosfrac}{26}{0.967823}
\pgf@def{cosfrac}{27}{0.965429}  \pgf@def{cosfrac}{28}{0.962964}
\pgf@def{cosfrac}{29}{0.960429}  \pgf@def{cosfrac}{30}{0.957826}
\pgf@def{cosfrac}{31}{0.955157}  \pgf@def{cosfrac}{32}{0.952424}
\pgf@def{cosfrac}{33}{0.949629}  \pgf@def{cosfrac}{34}{0.946773}
\pgf@def{cosfrac}{35}{0.943858}  \pgf@def{cosfrac}{36}{0.940887}
\pgf@def{cosfrac}{37}{0.937862}  \pgf@def{cosfrac}{38}{0.934784}
\pgf@def{cosfrac}{39}{0.931655}  \pgf@def{cosfrac}{40}{0.928477}
\pgf@def{cosfrac}{41}{0.925252}  \pgf@def{cosfrac}{42}{0.921982}
\pgf@def{cosfrac}{43}{0.918669}  \pgf@def{cosfrac}{44}{0.915315}
\pgf@def{cosfrac}{45}{0.911922}  \pgf@def{cosfrac}{46}{0.90849}
\pgf@def{cosfrac}{47}{0.905024}  \pgf@def{cosfrac}{48}{0.901523}
\pgf@def{cosfrac}{49}{0.89799}   \pgf@def{cosfrac}{50}{0.894427}
\pgf@def{cosfrac}{51}{0.890835}  \pgf@def{cosfrac}{52}{0.887217}
\pgf@def{cosfrac}{53}{0.883573}  \pgf@def{cosfrac}{54}{0.879905}
\pgf@def{cosfrac}{55}{0.876216}  \pgf@def{cosfrac}{56}{0.872506}
\pgf@def{cosfrac}{57}{0.868777}  \pgf@def{cosfrac}{58}{0.865031}
\pgf@def{cosfrac}{59}{0.861269}  \pgf@def{cosfrac}{60}{0.857493}
\pgf@def{cosfrac}{61}{0.853704}  \pgf@def{cosfrac}{62}{0.849903}
\pgf@def{cosfrac}{63}{0.846092}  \pgf@def{cosfrac}{64}{0.842271}
\pgf@def{cosfrac}{65}{0.838444}  \pgf@def{cosfrac}{66}{0.834609}
\pgf@def{cosfrac}{67}{0.83077}   \pgf@def{cosfrac}{68}{0.826927}
\pgf@def{cosfrac}{69}{0.82308}   \pgf@def{cosfrac}{70}{0.819232}
\pgf@def{cosfrac}{71}{0.815383}  \pgf@def{cosfrac}{72}{0.811534}
\pgf@def{cosfrac}{73}{0.807687}  \pgf@def{cosfrac}{74}{0.803842}
\pgf@def{cosfrac}{75}{0.8}       \pgf@def{cosfrac}{76}{0.796162}
\pgf@def{cosfrac}{77}{0.792329}  \pgf@def{cosfrac}{78}{0.788502}
\pgf@def{cosfrac}{79}{0.784682}  \pgf@def{cosfrac}{80}{0.780869}
\pgf@def{cosfrac}{81}{0.777064}  \pgf@def{cosfrac}{82}{0.773268}
\pgf@def{cosfrac}{83}{0.769481}  \pgf@def{cosfrac}{84}{0.765705}
\pgf@def{cosfrac}{85}{0.761939}  \pgf@def{cosfrac}{86}{0.758185}
\pgf@def{cosfrac}{87}{0.754443}  \pgf@def{cosfrac}{88}{0.750714}
\pgf@def{cosfrac}{89}{0.746997}  \pgf@def{cosfrac}{90}{0.743294}
\pgf@def{cosfrac}{91}{0.739605}  \pgf@def{cosfrac}{92}{0.735931}
\pgf@def{cosfrac}{93}{0.732272}  \pgf@def{cosfrac}{94}{0.728628}
\pgf@def{cosfrac}{95}{0.724999}  \pgf@def{cosfrac}{96}{0.721387}
\pgf@def{cosfrac}{97}{0.717792}  \pgf@def{cosfrac}{98}{0.714213}
\pgf@def{cosfrac}{99}{0.710651}  \pgf@def{cosfrac}{100}{0.707107}




% Forward declarations for nonlinear stuff (have no effect till module
% nonlineartransformations is loaded)

\let\pgfpointtransformednonlinear\pgfpointtransformed


\endinput

pgfcorequick.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/basiclayer/pgfcorequick.code.tex,v 1.3 2008/10/09 16:46:56 tantau Exp $

% Quick version of basic drawing commands. Most high-level commands
% are not available if these commands are used.

% Move current point to (#1,#2).
%
% #1 = x dimension of new current point
% #2 = y dimension of new current point
% 
% Example:
%
% \pgfpathqmoveto{0pt}{0pt}
% \pgfpathqlineto{1pt}{1pt}
% \pgfpathqcurveto{2pt}{1pt}{2pt}{2pt}{3pt}{2pt}
% \pgfqstroke

\def\pgfpathqmoveto#1#2{\pgfsyssoftpath@moveto{#1}{#2}}


% Append a line to (#1,#2) to the current path.
%
% #1 = x dimension of target
% #2 = y dimension of target
% 
% Example:
%
% \pgfpathqmoveto{0pt}{0pt}
% \pgfpathqlineto{1pt}{1pt}
% \pgfpathqcurveto{2pt}{1pt}{2pt}{2pt}{3pt}{2pt}
% \pgfqstroke

\def\pgfpathqlineto#1#2{\pgfsyssoftpath@lineto{#1}{#2}}


% Append a bezier spline to the current path.
%
% #1 = x dimension of first support point
% #2 = y dimension of first support point
% #3 = x dimension of second support point
% #4 = y dimension of second support point
% #5 = x dimension of target point
% #6 = y dimension of target point
% 
% Example:
%
% \pgfpathqmoveto{0pt}{0pt}
% \pgfpathqlineto{1pt}{1pt}
% \pgfpathqcurveto{2pt}{1pt}{2pt}{2pt}{3pt}{2pt}
% \pgfqstroke

\def\pgfpathqcurveto#1#2#3#4#5#6{\pgfsyssoftpath@curveto{#1}{#2}{#3}{#4}{#5}{#6}}




% Append a circle of the given radius around the origin.
%
% #1 = radius
% 
% Example:
%
% \pgfpathqcircle{10pt}
% is quicker than
% \pgfpathcircle{\pgforigin}{10pt}

\def\pgfpathqcircle#1{%
  {%
    \pgf@x=#1%
    \pgf@y=0.5522847\pgf@x%
    \pgfsyssoftpath@moveto{\the\pgf@x}{0pt}%
    \pgfsyssoftpath@curveto{\the\pgf@x}{\the\pgf@y}{\the\pgf@y}{\the\pgf@x}{0pt}{\the\pgf@x}%
    \pgfsyssoftpath@curveto{-\the\pgf@y}{\the\pgf@x}{-\the\pgf@x}{\the\pgf@y}{-\the\pgf@x}{0pt}%
    \pgfsyssoftpath@curveto{-\the\pgf@x}{-\the\pgf@y}{-\the\pgf@y}{-\the\pgf@x}{0pt}{-\the\pgf@x}%
    \pgfsyssoftpath@curveto{\the\pgf@y}{-\the\pgf@x}{\the\pgf@x}{-\the\pgf@y}{\the\pgf@x}{0pt}%
    \pgfsyssoftpath@closepath%
  }%
}



% Stroke current path. No hooks called.
% 
% Example:
%
% \pgfpathqmoveto{0cm}{0cm}
% \pgfpathqlineto{1cm}{1cm}
% \pgfpathqcurveto{2cm}{1cm}{2cm}{2cm}{3cm}{2cm}
% \pgfqstroke

\def\pgfusepathqstroke{%
  \pgfsyssoftpath@flushcurrentpath%
  \pgfsys@stroke%
  \pgf@resetpathsizes%
}


% Quickly fill current path.

\def\pgfusepathqfill{%
  \pgfsyssoftpath@flushcurrentpath%
  \pgfsys@fill%
  \pgf@resetpathsizes%
}


% Quickly fill and stroke current path.

\def\pgfusepathqfillstroke{%
  \pgfsyssoftpath@flushcurrentpath%
  \pgfsys@fillstroke%
  \pgf@resetpathsizes%
}

% Quickly clip current path.

\def\pgfusepathqclip{%
  \pgfsyssoftpath@flushcurrentpath%
  \pgfsys@clipnext%
  \pgfsys@discardpath%
  \pgf@resetpathsizes%
}


\endinput

pgfcorescopes.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/basiclayer/pgfcorescopes.code.tex,v 1.44 2013/10/09 18:30:27 tantau Exp $

% Globals

\newbox\pgfpic
\newbox\pgf@hbox

\newbox\pgf@layerbox@main

\newcount\pgf@picture@serial@count



% This if decides whether the position of pictures on the page is
% protocolled or not. Normally,
% this is switched off as it works only with certain drivers and it
% causes external files to be written. When switched on, the position
% of pgfpictures are protocolled and can be referenced using
% \pgfsys@getposition{XXX} where XXX is the value of \pgfpictureid
% inside the picture.
\newif\ifpgfrememberpicturepositiononpage




% Scopes


% Pgf scope environment. All changes of the graphic state are local to
% the scope.
%  
% Example:
%
% \begin{pgfscope}
%    \pgfsetlinewidth{3pt}
%    \pgfline{\pgfxy(0,0)}{\pgfxy(3,3)}
% \end{pgfscope}

\def\pgfscope{%
  \pgfsyssoftpath@setcurrentpath\pgfutil@empty%
  \pgfsys@beginscope%
    \pgf@resetpathsizes%
    \edef\pgfscope@linewidth{\the\pgflinewidth}%
    \expandafter\let\expandafter\pgfscope@stroke@color\csname\string\color@pgfstrokecolor\endcsname%
    \expandafter\let\expandafter\pgfscope@fill@color\csname\string\color@pgffillcolor\endcsname%
    \begingroup}
\def\endpgfscope{%
    \endgroup%
    \global\pgflinewidth=\pgfscope@linewidth%
    \expandafter\global\expandafter\let\csname\string\color@pgfstrokecolor\endcsname\pgfscope@stroke@color%
    \expandafter\global\expandafter\let\csname\string\color@pgffillcolor\endcsname\pgfscope@fill@color%
  \pgfsys@endscope}




% Quickly insert a box can contain normal TeX text at the origin.
% 
% #1 = box of width/height and depth 0pt
% 
% Example:
%
% \pgfqbox{\mybox}

\def\pgfqbox#1{%
  \pgfsys@hbox#1%
} 


% Insert a box that can contain normal TeX text at the origin, but
% with the current coordinate transformation matrix synced with the
% low-level transformation matrix.
% 
% #1 = box of width/height and depth 0pt
%
% In essence, this command does the same as if you first said
% \pgflowlevelsynccm and then \pgfqbox. However, pgf will use a
% ``TeX-translation'' for the translation part of the transformation
% cm. This will ensure that hyperlinks ``survive'' at least
% translations. 
% 
% Example:
%
% \pgfqboxsynced{\mybox}

\def\pgfqboxsynced#1{%
  \pgfsys@hboxsynced#1%
}


% Puts some text in a box and inserts it with the current
% transformations applied.
% 
% #1 = List of optional positioning. Possible values are ``left'', ``right'',
%      ``top'', ``bottom'' and ``base''.
% #2 = TeX text. May contain verbatims.
% 
% Example:
%
% \pgftransformshift{\pgfpoint{1cm}{0cm}}
% \pgftext{Hello World!}

\def\pgftext{\pgfutil@ifnextchar[\pgf@text{\pgf@text[]}}%
\def\pgf@text[#1]{%
  \def\pgf@text@options{#1}%
  \pgf@maketext\pgf@after@text}
\def\pgf@after@text{%
  {%
  \def\pgf@text@hshift{center}%
  \def\pgf@text@vshift{center}%
  \expandafter\pgf@text@setkeys\expandafter{\pgf@text@options}%
  \csname pgf@halign\pgf@text@hshift\endcsname%
  \csname pgf@valign\pgf@text@vshift\endcsname%
  %
  \pgfapproximatenonlineartransformation%
  % Protocol sizes:
  \pgf@process{\pgfpointtransformed{\pgfqpoint{0pt}{\dp\pgf@hbox}}}%
  \pgf@protocolsizes{\pgf@x}{\pgf@y}%
  \pgf@process{\pgfpointtransformed{\pgfqpoint{\wd\pgf@hbox}{\dp\pgf@hbox}}}%
  \pgf@protocolsizes{\pgf@x}{\pgf@y}%
  \pgf@process{\pgfpointtransformed{\pgfqpoint{0pt}{\ht\pgf@hbox}}}%
  \pgf@protocolsizes{\pgf@x}{\pgf@y}%
  \pgf@process{\pgfpointtransformed{\pgfqpoint{\wd\pgf@hbox}{\ht\pgf@hbox}}}%
  \pgf@protocolsizes{\pgf@x}{\pgf@y}%
  \pgfqboxsynced{\pgf@hbox}%
  }%
}
\def\pgf@text@setkeys{\pgfqkeys{/pgf/text}}%

\pgfkeys{/pgf/text/left/.code=\def\pgf@text@hshift{left}}
\pgfkeys{/pgf/text/center/.code=}
\pgfkeys{/pgf/text/right/.code=\def\pgf@text@hshift{right}}
\pgfkeys{/pgf/text/top/.code=\def\pgf@text@vshift{top}}
\pgfkeys{/pgf/text/bottom/.code=\def\pgf@text@vshift{bottom}}
\pgfkeys{/pgf/text/base/.code=\def\pgf@text@vshift{base}}
\pgfkeys{/pgf/text/at/.cd,.code=\pgftransformshift{#1},.value required}
\pgfkeys{/pgf/text/x/.cd,.code=\pgftransformxshift{#1},.value required}
\pgfkeys{/pgf/text/y/.cd,.code=\pgftransformyshift{#1},.value required}
\pgfkeys{/pgf/text/rotate/.cd,.code=\pgftransformrotate{#1},.value required}

\def\pgf@halignleft{}% do nothing
\def\pgf@haligncenter{\pgftransformxshift{+-.5\wd\pgf@hbox}}
\def\pgf@halignright{\pgftransformxshift{+-\wd\pgf@hbox}}%
\def\pgf@valignbase{}% do nothing
\def\pgf@valignbottom{\pgftransformyshift{+\dp\pgf@hbox}}%
\def\pgf@valigncenter{\pgftransformyshift{+.5\dp\pgf@hbox}\pgftransformyshift{+-.5\ht\pgf@hbox}}%
\def\pgf@valigntop{\pgftransformyshift{+-\ht\pgf@hbox}}%


% Internal function for creating a hbox.
\def\pgf@maketext#1{%
  \def\pgf@@maketextafter{#1}%
  \setbox\pgf@hbox=\hbox\bgroup%
    \pgfinterruptpicture%
      \bgroup%
        \aftergroup\pgf@collectresetcolor%
        \let\next=%
}
\def\pgf@collectresetcolor{%
  \pgfutil@ifnextchar\reset@color%
  {\reset@color\afterassignment\pgf@collectresetcolor\let\pgf@temp=}%
  {\pgf@textdone}%
}
\def\pgf@textdone{%
    \endpgfinterruptpicture%
  \egroup%
  \pgf@@maketextafter%  
}

\long\def\pgf@makehbox#1{%
  \setbox\pgf@hbox=\hbox{{%
    \pgfinterruptpicture%
      #1%
    \endpgfinterruptpicture%
    }}}



% Picture environment
%
% Example:
%
% \begin{pgfpicture}
%   \pgfsetendarrow{\pgfarrowto}
%   \pgfpathmoveto{\pgfpointxy{-0.9}{0.2}}
%   \pgfpathlineto{\pgfpointxy{0.9}{0.4}}
%   \pgfusepath{stroke}
% \end{pgfpicture}

\def\pgfresetboundingbox{%
    \global\pgf@picmaxx=-16000pt\relax%
    \global\pgf@picminx=16000pt\relax%
    \global\pgf@picmaxy=-16000pt\relax%
    \global\pgf@picminy=16000pt\relax%
}%

\def\pgfpicture{%
  \begingroup%
    \pgfpicturetrue%
    \global\advance\pgf@picture@serial@count by1\relax%
    \edef\pgfpictureid{pgfid\the\pgf@picture@serial@count}%
    \let\pgf@nodecallback=\pgfutil@gobble%
    \pgf@picmaxx=-16000pt\relax%
    \pgf@picminx=16000pt\relax%
    \pgf@picmaxy=-16000pt\relax%
    \pgf@picminy=16000pt\relax%
    \pgf@relevantforpicturesizetrue%
    \pgf@resetpathsizes%
    \pgfutil@ifnextchar\bgroup\pgf@oldpicture\pgf@picture}
\def\pgf@oldpicture#1#2#3#4{%
  \pgfmathsetlength\pgf@picminx{#1}%
  \pgfmathsetlength\pgf@picminy{#2}%
  \pgfmathsetlength\pgf@picmaxx{#3}%
  \pgfmathsetlength\pgf@picmaxy{#4}%
  \pgf@relevantforpicturesizefalse%
  \pgf@picture}

\def\pgf@picture{%
  \setbox\pgfpic\hbox to0pt\bgroup%
    \begingroup%
    \pgfsys@beginpicture%
      \pgfsys@beginscope%
        \begingroup%
        \pgfsetcolor{.}%
        \pgfsetlinewidth{0.4pt}%
        \pgftransformreset%
        \pgfsyssoftpath@setcurrentpath\pgfutil@empty%
        \begingroup%
          \let\pgf@setlengthorig=\setlength%
          \let\pgf@addtolengthorig=\addtolength%
          \let\pgf@selectfontorig=\selectfont%
          \let\setlength=\pgf@setlength%
          \let\addtolength=\pgf@addtolength%
          \let\selectfont=\pgf@selectfont%
          \nullfont\spaceskip0pt\xspaceskip0pt%
          \setbox\pgf@layerbox@main\hbox to0pt\bgroup%
            \begingroup%
  }
\def\endpgfpicture{%
              \ifpgfrememberpicturepositiononpage%
                \hbox to0pt{\pgfsys@markposition{\pgfpictureid}}%
              \fi%    
              % ok, now let's position the box
              \ifdim\pgf@picmaxx=-16000pt\relax%
                % empty picture. make size 0.  
                \global\pgf@picmaxx=0pt\relax%
                \global\pgf@picminx=0pt\relax%
                \global\pgf@picmaxy=0pt\relax%
                \global\pgf@picminy=0pt\relax%
              \fi%
              % Shift baseline outside:
              \pgf@relevantforpicturesizefalse%
              \pgf@process{\pgf@baseline}%
              \xdef\pgf@shift@baseline{\the\pgf@y}%
              % 
              \pgf@process{\pgf@trimleft}%
              \global\advance\pgf@x by-\pgf@picminx
              % prepare \hskip\pgf@trimleft@final.
              % note that \pgf@trimleft@final is also queried
              % by the pgf image externalization.
              \xdef\pgf@trimleft@final{-\the\pgf@x}%
              % 
              \pgf@process{\pgf@trimright}%
              \global\advance\pgf@x by-\pgf@picmaxx
              % prepare \hskip\pgf@trimright@final.
              % note that \pgf@trimright@final is also queried
              % by the pgf image externalization.
              \xdef\pgf@trimright@final{\the\pgf@x}%
        %
        \pgf@remember@layerlist@globally
            \endgroup%
            \hss%
          \egroup%
      \pgf@restore@layerlist@from@global
          \pgf@insertlayers%
        \endgroup%    
        \pgfsys@discardpath%
        \endgroup%
      \pgfsys@endscope%
    \pgfsys@endpicture%
    \endgroup%
    \hss
  \egroup%
  \pgfsys@typesetpicturebox\pgfpic%
  \endgroup%
}

\def\pgf@remember@layerlist@globally{%
  \global\let\pgf@layerlist@=\pgf@layerlist
}%
\def\pgf@restore@layerlist@from@global{%
  \let\pgf@layerlist=\pgf@layerlist@
}%
\def\pgf@insertlayers{%
  \box\pgf@layerbox@main%
}

\def\pgf@selectfont{\pgf@selectfontorig\nullfont}

\def\pgf@setlength#1#2{% these will be used only when \nullfont is active
  \begingroup% keep font setting local
    \pgfutil@selectfont% restore font
    \pgf@setlengthorig#1{#2}% calculate dimension (possibly using calc)
    \expandafter%
  \endgroup%
  \expandafter#1\expandafter=\the#1\relax}
\def\pgf@addtolength#1#2{%
  \begingroup% keep font setting local
    \pgfutil@selectfont% restore font
    \pgf@addtolengthorig#1{#2}% calculate dimension (possibly using calc)
    \expandafter%
  \endgroup%
  \expandafter#1\expandafter=\the#1\relax}


% Sets the baseline at the y-coordinate of a given point
%
% #1 = point
%
% Sets the baseline of the picture to the y-coordinate of a given
% point. However, the point will be evaluated *at the end of the
% picture*. 
%
% Example:
%
% \pgfsetbaselinepointlater{\pgfpointanchor{mynode}{base}}

\def\pgfsetbaselinepointlater#1{\def\pgf@baseline{#1}}


% Sets the baseline at the y-coordinate of a given point, now
%
% #1 = point
%
% Sets the baseline of the picture to the y-coordinate of a given
% point.
%
% Example:
%
% \pgfsetbaselinepointnow{\pgfpoint{1cm}{2pt}}

\def\pgfsetbaselinepointnow#1{%
  \pgf@process{#1}%
  \edef\pgf@setter@baseline{\noexpand\pgfpoint{\the\pgf@x}{\the\pgf@y}}%
  \pgfsetbaselinepointlater{\pgf@setter@baseline}%
}

\def\pgf@default@text{default}%

% Sets the baseline
%
% #1 = baseline
%
% Sets the baseline of the picture. Default is the lower border, which
% is the same as \pgf@picminy
%
% Example:
%
% \pgfsetbaseline{1cm+2pt}
% \pgfsetbaseline{default}% resets to default value

\def\pgfsetbaseline#1{%
  \def\pgf@temp{#1}%
  \ifx\pgf@temp\pgf@default@text
    \pgfsetbaseline{\pgf@picminy}%
  \else
    \pgfsetbaselinepointlater{\pgfpoint{0pt}{#1}}%
  \fi
}
\pgfsetbaseline{\pgf@picminy}

% controls how the image externalization implements trim:
\newif\ifpgf@trim@lowlevel
\pgfkeys{
  /pgf/trim lowlevel/.is if=pgf@trim@lowlevel,
  /pgf/trim lowlevel/.default=true,
}

% Same as the y-baseline for horizontal alignment.
% The effect is different, though: it is some kind of trimming which
% leaves the bounding box intact.
\def\pgfsettrimleftpointlater#1{\def\pgf@trimleft{#1}}
\def\pgfsettrimleftpointnow#1{%
  \pgf@process{#1}%
  \edef\pgf@setter@baseline{\noexpand\pgfpoint{\the\pgf@x}{\the\pgf@y}}%
  \pgfsettrimleftpointlater{\pgf@setter@baseline}%
}
% \pgfsettrimleft{<x coord>}
% or
% \pgfsettrimleft{default}
\def\pgfsettrimleft#1{%
  \def\pgf@temp{#1}%
  \ifx\pgf@temp\pgf@default@text
    \pgfsettrimleft{\pgf@picminx}
  \else
    \pgfsettrimleftpointlater{\pgfpoint{#1}{0pt}}%
  \fi
}
\pgfsettrimleft{\pgf@picminx}

\def\pgfsettrimrightpointlater#1{\def\pgf@trimright{#1}}
\def\pgfsettrimrightpointnow#1{%
  \pgf@process{#1}%
  \edef\pgf@setter@baseline{\noexpand\pgfpoint{\the\pgf@x}{\the\pgf@y}}%
  \pgfsettrimrightpointlater{\pgf@setter@baseline}%
}
% \pgfsettrimright{<x coord>}
% or
% \pgfsettrimright{default}
\def\pgfsettrimright#1{%
  \def\pgf@temp{#1}%
  \ifx\pgf@temp\pgf@default@text
    \pgfsettrimright{\pgf@picmaxx}%
  \else
    \pgfsettrimrightpointlater{\pgfpoint{#1}{0pt}}%
  \fi
}
\pgfsettrimright{\pgf@picmaxx}


% Interrupt path
%
% Description:
%
% The environment can be used to insert some drawing commands while
% constructing a path. The drawing commands inside the environment
% will not interfere with the path being constructed ``outside.''
% However, you must ward against graphic state changes using a scope. 
%
% Example: Draw two parallel lines
%
% \pgfmoveto{\pgfpoint{0cm}{0cm}}
% \begin{pgfinterruptpath}
%   \pgfmoveto{\pgfpoint{1cm}{0cm}}
%   \pgfmoveto{\pgfpoint{1cm}{1cm}}
%   \pgfusepath{stroke}
% \end{pgfinterruptpath}
% \pgflineto{\pgfpoint{0cm}{1cm}}
% \pgfusepath{stroke}

\def\pgfinterruptpath
{%
  \begingroup%
  % save all sorts of things...
  \edef\pgf@interrupt@savex{\the\pgf@path@lastx}%
  \edef\pgf@interrupt@savey{\the\pgf@path@lasty}%
  \pgf@getpathsizes\pgf@interrupt@pathsizes%
  \pgfsyssoftpath@getcurrentpath\pgf@interrupt@path%
  \pgfsyssoftpath@setcurrentpath\pgfutil@empty%
  \edef\pgfscope@linewidth{\the\pgflinewidth}%
  \let\pgf@interrupt@lastmoveto=\pgfsyssoftpath@lastmoveto%
  \let\pgf@interrupt@nlt@infos=\pgf@nlt@infos%
  \begingroup%
}
\def\endpgfinterruptpath
{%
  \endgroup%
  \global\pgflinewidth=\pgfscope@linewidth%
  \pgfsyssoftpath@setcurrentpath\pgf@interrupt@path%
  \pgf@setpathsizes\pgf@interrupt@pathsizes%
  \global\pgf@path@lastx\pgf@interrupt@savex%
  \global\pgf@path@lasty\pgf@interrupt@savey%
  \global\let\pgfsyssoftpath@lastmoveto\pgf@interrupt@lastmoveto%
  \global\let\pgf@nlt@infos=\pgf@interrupt@nlt@infos%
  \endgroup%
}



% Interrupt bounding box
%
% Description:
%
% The environment can be used to temporarily setup a new bounding box
% computation. The bounding box will be made empty at the beginning of
% the environment and will be reset to its old value after the
% environment. 
%
% Example: 
%
% \begin{pgfinterruptboundinbox}
%   \pgfmoveto{\pgfpoint{1cm}{0cm}}
%   \pgfmoveto{\pgfpoint{1cm}{1cm}}
%   \pgfusepath{stroke}
% \end{pgfinterruptboundinbox}

\def\pgfinterruptboundingbox
{%
  \begingroup%
    \edef\pgf@interrupt@savemaxx{\the\pgf@picmaxx}%
    \edef\pgf@interrupt@saveminx{\the\pgf@picminx}%
    \edef\pgf@interrupt@savemaxy{\the\pgf@picmaxy}%
    \edef\pgf@interrupt@saveminy{\the\pgf@picminy}%
    \pgf@picmaxx=-16000pt\relax%
    \pgf@picminx=16000pt\relax%
    \pgf@picmaxy=-16000pt\relax%
    \pgf@picminy=16000pt\relax%
    \pgf@size@hookedfalse%
    \let\pgf@path@size@hook=\pgfutil@empty%
}
\def\endpgfinterruptboundingbox
{%
    \global\pgf@picmaxx=\pgf@interrupt@savemaxx%
    \global\pgf@picmaxy=\pgf@interrupt@savemaxy%
    \global\pgf@picminx=\pgf@interrupt@saveminx%
    \global\pgf@picminy=\pgf@interrupt@saveminy%
  \endgroup%
}





% Interrupts a picture
%
% Description:
%
% This environment interrupts a picture and temporarily returns to
% normal TeX mode. All sorts of things are saved and restored by this
% environment.
%
% WARNING: Using this environment in conjuction with low level
% transformations can *strongly* upset the typesetting. Typically, the
% contents of this environment should have size/height/depth 0pt in
% the end.
%
% WARNING: This environment should only be used inside typesetting a
% box and this box must in turn be inserted using \pgfqbox.
%
% Example: Draw two parallel lines
%
% \pgfmoveto{\pgfpoint{0cm}{0cm}}
% \setbox\mybox=\hbox{
%    \begin{pgfinterruptpicture}
%      This is normal text.
%      \begin{pgfpicture} % a subpicture
%        \pgfmoveto{\pgfpoint{1cm}{0cm}}
%        \pgfmoveto{\pgfpoint{1cm}{1cm}}
%        \pgfusepath{stroke}
%      \end{pgfpicture}
%      More text.
%    \end{pgfinterruptpicture}
%  }
% \ht\mybox=0pt
% \wd\mybox=0pt
% \dp\mybox=0pt
% \pgfqbox{\mybox}%
% \pgfpathlineto{\pgfpoint{0cm}{1cm}}
% \pgfusepath{stroke}

\def\pgfinterruptpicture
{%
  \begingroup%
    \pgfinterruptboundingbox%
      \pgftransformreset%
      \pgfinterruptpath%
        \ifx\pgf@selectfontorig\@undefined%
        \else%
          \let\setlength\pgf@setlengthorig%
          \let\addtolength\pgf@addtolengthorig%
          \let\selectfont\pgf@selectfontorig%
        \fi%
        \pgfutil@selectfont%
        \pgfpicturefalse%
        \let\pgf@positionnodelater@macro\relax%
        \pgf@savelayers%
}
\def\endpgfinterruptpicture
{%
        \pgf@restorelayers%
      \endpgfinterruptpath%
    \endpgfinterruptboundingbox%
  \endgroup%
}

\let\pgf@savelayers=\relax
\let\pgf@restorelayers=\relax

\endinput

pgfcoreshade.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/basiclayer/pgfcoreshade.code.tex,v 1.15 2013/07/15 14:24:02 tantau Exp $

%
% Parsing functions
%
\newdimen\pgf@max
\newcount\pgf@sys@shading@range@num
\def\pgf@parsefunc#1{%
  \edef\temp{{#1}}%
  \expandafter\pgf@convertrgbstring\temp%
  \edef\temp{{\pgf@rgbconv}}%
  \expandafter\pgf@@parsefunc\temp}
\def\pgf@@parsefunc#1{%
  \let\pgf@bounds=\pgfutil@empty%
  \let\pgf@funcs=\pgfutil@empty%
  \let\pgf@psfuncs=\pgfutil@empty%
  \let\pgf@encode=\pgfutil@empty%
  \let\pgf@sys@shading@ranges=\pgfutil@empty%
  \pgf@sys@shading@range@num=0\relax%
  \pgf@parsefirst[#1; ]%
  \pgf@parselastdom[#1; ]%
  \pgf@parsemid[#1; ]%
  \ifx\pgf@bounds\pgfutil@empty%
    \edef\pgf@pdfparseddomain{0 1}%
    \edef\pgf@pdfparsedfunction{\pgf@singlefunc\space}%
  \else%
    \edef\pgf@pdfparseddomain{\pgf@doma\space\pgf@domb}%
    \edef\pgf@pdfparsedfunction{%
      << /FunctionType 3 /Domain [\pgf@doma\space\pgf@domb] /Functions
      [\pgf@funcs\space] /Bounds [\pgf@bounds] /Encode [0 1 \pgf@encode]
      >> }% <<
  \fi%
  \xdef\pgf@psfuncs{\pgf@psfuncs}%
  }
\def\pgf@parsefirst[rgb(#1)=(#2,#3,#4)#5]{%
  \pgfmathsetlength\pgf@x{#1}%
  \edef\pgf@sys@shading@start@pos{\the\pgf@x}%
  \pgf@sys@bp@correct\pgf@x%
  \edef\pgf@doma{\pgf@sys@tonumber{\pgf@x}}%
  \edef\pgf@prevx{\pgf@sys@tonumber{\pgf@x}}%
  \pgf@getrgbtuplewithmixin{#2}{#3}{#4}%
  \edef\pgf@sys@shading@start@rgb{\pgf@sys@rgb}%
  \let\pgf@sys@prevcolor=\pgf@sys@shading@start@rgb%
  \let\pgf@sys@prevpos=\pgf@sys@shading@start@pos%
  \edef\pgf@prevcolor{\pgf@rgb}%
  \edef\pgf@firstcolor{\pgf@rgb}}
\def\pgf@parselastdom[rgb(#1)=(#2,#3,#4); {%
  \pgfutil@ifnextchar]{%
    \pgfmathsetlength\pgf@x{#1}%
    \edef\pgf@sys@shading@end@pos{\the\pgf@x}%
    \pgf@max=\pgf@x\relax%
    \pgf@sys@bp@correct\pgf@x%
    \edef\pgf@domb{\pgf@sys@tonumber{\pgf@x}}%
    \pgf@getrgbtuplewithmixin{#2}{#3}{#4}%
    \edef\pgf@sys@shading@end@rgb{\pgf@sys@rgb}%
    \pgfutil@gobble}{\pgf@parselastdom[}}
\def\pgf@parsemid[rgb(#1)=(#2,#3,#4); {\pgf@parserest[}
\def\pgf@parserest[rgb(#1)=(#2,#3,#4); {%
  \advance\pgf@sys@shading@range@num by1\relax%
  \pgfutil@ifnextchar]{%
    \pgf@getrgbtuplewithmixin{#2}{#3}{#4}%
    \edef\pgf@singlefunc{\space%
      << /FunctionType 2 /Domain [0 1] /C0
      [\pgf@prevcolor] /C1 [\pgf@rgb] /N 1 >> }% <<
    \edef\pgf@funcs{\pgf@funcs\space%
      << /FunctionType 2 /Domain [\pgf@doma\space\pgf@domb] /C0
      [\pgf@prevcolor] /C1 [\pgf@rgb] /N 1 >> }% <<
    \edef\pgf@psfuncs{\pgf@prevx\space \pgf@rgb\space \pgf@prevcolor\space pgfshade \pgf@psfuncs}%
    \pgfmathsetlength\pgf@x{#1}%
    \edef\pgf@sys@shading@ranges{\pgf@sys@shading@ranges{{\pgf@sys@prevpos}{\the\pgf@x}{\pgf@sys@prevcolor}{\pgf@sys@rgb}}}%
    \edef\pgf@sys@prevpos{\the\pgf@x}%
    \let\pgf@sys@prevcolor=\pgf@sys@rgb%
    \pgfutil@gobble}{%
    \pgfmathsetlength\pgf@x{#1}%
    \pgf@getrgbtuplewithmixin{#2}{#3}{#4}%
    \edef\pgf@sys@shading@ranges{\pgf@sys@shading@ranges{{\pgf@sys@prevpos}{\the\pgf@x}{\pgf@sys@prevcolor}{\pgf@sys@rgb}}}%
    \edef\pgf@sys@prevpos{\the\pgf@x}%
    \let\pgf@sys@prevcolor=\pgf@sys@rgb%
    \edef\pgf@psfuncs{\pgf@prevx\space \pgf@rgb\space \pgf@prevcolor\space pgfshade \pgf@psfuncs}%
    \pgf@sys@bp@correct\pgf@x%
    \edef\pgf@prevx{\pgf@sys@tonumber{\pgf@x}}%
    \edef\pgf@bounds{\pgf@bounds\space\pgf@sys@tonumber{\pgf@x}}%
    \edef\pgf@encode{\pgf@encode\space0 1}%
    \edef\pgf@singlefunc{\space%
      << /FunctionType 2 /Domain [0 1] /C0
      [\pgf@prevcolor] /C1 [\pgf@rgb] /N 1 >> }% <<
    \edef\pgf@funcs{\pgf@funcs\space%
      << /FunctionType 2 /Domain [\pgf@doma\space\pgf@domb] /C0
      [\pgf@prevcolor] /C1 [\pgf@rgb] /N 1 >> }% <<
    \edef\pgf@prevcolor{\pgf@rgb}%
    \pgf@parserest[}}

\def\pgf@getrgbtuplewithmixin#1#2#3{%
  \pgfutil@definecolor{pgfshadetemp}{rgb}{#1,#2,#3}%
  \pgfutil@ifundefined{applycolormixins}{}{\applycolormixins{pgfshadetemp}}%
  \pgfutil@extractcolorspec{pgfshadetemp}{\pgf@tempcolor}%
  \expandafter\pgfutil@convertcolorspec\pgf@tempcolor{rgb}{\pgf@rgbcolor}%
  \expandafter\pgf@getrgb@@\pgf@rgbcolor!}
\def\pgf@getrgb@@#1,#2,#3!{%
  \def\pgf@rgb{#1 #2 #3}%
  \def\pgf@sys@rgb{{#1}{#2}{#3}}%
}


% Normalized a <color specification> argument for shadings into a
% series of rgb color specifications and writes the result into
% \pgf@rgbconv.
%
% Example:
% \pgf@convertrgbstring{rgb(0cm)=(1,0,0); rgb(2cm)=(0,1,0); rgb(4cm)=(0,0,1); gray(1cm)=(3);  color(2cm)=(green); }
% ->
% \pgf@rgbconv = macro:->'rgb(0cm)=(1,0,0); rgb(2cm)=(0,1,0); rgb(4cm)=(0,0,1); rgb(1cm)=(3,3,3); rgb(2cm)=(0,1,0); '
\def\pgf@convertrgbstring#1{%
  \def\pgf@rgbconv{}%
  \pgf@converttorgb#1]%
  }
\def\pgf@converttorgb{%
  \pgfutil@ifnextchar]{\pgfutil@gobble}%done!
  {%
    \pgfutil@ifnextchar;{\pgf@grabsemicolor}%
    {%
      \pgfutil@ifnextchar r{\pgf@grabrgb}%
      {%
        \pgfutil@ifnextchar g{\pgf@grabgray}%
        {%
          \pgfutil@ifnextchar c{\pgf@grabcolor}%
          {\pgferror{Illformed shading
              specification}\pgf@converttorgb}%
        }%
      }%
    }%
  }%
}
\def\pgf@grabsemicolor;{%
  \edef\pgf@rgbconv{\pgf@rgbconv; }\pgf@converttorgb}
\def\pgf@grabrgb rgb(#1)=(#2,#3,#4){%
  \edef\pgf@rgbconv{\pgf@rgbconv rgb(#1)=(#2,#3,#4)}\pgf@converttorgb}
\def\pgf@grabgray gray(#1)=(#2){%
  \edef\pgf@rgbconv{\pgf@rgbconv rgb(#1)=(#2,#2,#2)}\pgf@converttorgb}
\def\pgf@grabcolor color(#1)=(#2){%
  \pgfutil@colorlet{pgf@tempcol}{#2}%
  \pgfutil@extractcolorspec{pgf@tempcol}{\pgf@tempcolor}%
  \expandafter\pgfutil@convertcolorspec\pgf@tempcolor{rgb}{\pgf@rgbcolor}%
  \expandafter\pgf@convgetrgb@\expandafter{\pgf@rgbcolor}{#1}%
}
\def\pgf@convgetrgb@#1#2{%
  \edef\pgf@rgbconv{\pgf@rgbconv rgb(#2)=(#1)}\pgf@converttorgb}




% Declares a horizontal shading for later use. The shading is a
% horizontal bar that changes its color.
%
% #1 = optional dependencies
% #2 = name of the shading for later use
% #3 = height of the shading
% #4 = color specification in the following format: A list of colors
%      that the bar should have at certain points. If the bar should
%      be red at 1cm, this is specified as
%      "rgb(1cm)=(1,0,0)". Multiple specifications are separated by a
%      semicolon and a space. At least two specifications must be
%      given. The specified positions must be given in increasing
%      order. 
%
% Description:
%
% The optional dependecies have the following effect: If present, it
% should consist of a list of colors, separated by commas. Each time
% the shading is used, these colors will be reevaluated. It will be
% checked whether the colors still have their "original meaning". If
% the colors have changed, a new shading will be created internally to
% reflect the changed color's values.
%
% Example:
%
% \pgfdeclarehorizontalshading{redtogreentoblue}{1cm}{%
%   rgb(0cm)=(1,0,0); % red
%   rgb(1cm)=(0,1,0); % green
%   rgb(2cm)=(0,0,1)}
%
% \begin{document}
%   The following bar is 2cm long: \pgfuseshading{redtogreentoblue}.
% \end{document}

\def\pgfdeclarehorizontalshading{\pgfutil@ifnextchar[\pgf@declarehorizontalshading{\pgf@declarehorizontalshading[]}}%
\def\pgf@declarehorizontalshading[#1]#2#3#4{%
  \expandafter\def\csname pgf@deps@pgfshading#2!\endcsname{#1}%
  \expandafter\ifx\csname pgf@deps@pgfshading#2!\endcsname\pgfutil@empty%
    \pgfsys@horishading{#2}{#3}{#4}%
  \else%
    \expandafter\def\csname pgf@func@pgfshading#2!\endcsname{\pgfsys@horishading}%
    \expandafter\def\csname pgf@args@pgfshading#2!\endcsname{{#3}{#4}}%
    \expandafter\let\csname @pgfshading#2!\endcsname=\pgfutil@empty%
  \fi}


% Declares a vertical shading for later use. 
%
% #1 = optinal dependecies
% #2 = name of the shading for later use
% #3 = height of the shading
% #4 = color specification 
%
% Example:
%
% \pgfdeclareverticalshading{redtogreentoblue}{1cm}{%
%   rgb(0cm)=(1,0,0); % red
%   rgb(1cm)=(0,1,0); % green
%   rgb(2cm)=(0,0,1)}
%
% \begin{document}
%   The following bar is 2cm high: \pgfuseshading{redtogreentoblue}.
% \end{document}

\def\pgfdeclareverticalshading{\pgfutil@ifnextchar[\pgf@declareverticalshading{\pgf@declareverticalshading[]}}%
\def\pgf@declareverticalshading[#1]#2#3#4{%
  \expandafter\def\csname pgf@deps@pgfshading#2!\endcsname{#1}%
  \expandafter\ifx\csname pgf@deps@pgfshading#2!\endcsname\pgfutil@empty%
    \pgfsys@vertshading{#2}{#3}{#4}%
  \else%
    \expandafter\def\csname pgf@func@pgfshading#2!\endcsname{\pgfsys@vertshading}%
    \expandafter\def\csname pgf@args@pgfshading#2!\endcsname{{#3}{#4}}%
    \expandafter\let\csname @pgfshading#2!\endcsname=\pgfutil@empty%
  \fi}


% Declares a radial shading for later use. 
%
% #1 = optional dependencies
% #2 = name of the shading for later use
% #3 = center of inner circle
% #4 = color specification 
%
% Description:
%
% A radial shading creates a smooth color transition between two
% circles. The center of the inner circle is at the give position. Its
% radius is the start of the color specification. The
% center of the outer circle is at the center of the whole shading,
% whose radius is the end of the color specification. For example,
% suppose the color specification is "rgb(1cm)=(1,1,1); rgb(2cm)=(0,0,0)".  
% Then the shading would be 4cm times 4cm large. The inner circle would
% have diameter 1cm and the outer circle would have diameter 2cm. The
% outer circle would be centered in the middle of the shading, whereas
% the outer circle would be centered at the given position.
%
% Example:
%
% \pgfdeclareradialshading{redtogreentoblue}{\pgfpoint{2cm}{2cm}}{%
%   rgb(10pt)=(1,0,0); % red
%   rgb(2cm)=(0,1,0); % green
%   rgb(3cm)=(0,0,1)}
%
% \begin{document}
%   The following ball has diameter 3cm: \pgfuseshading{redtogreentoblue}.
% \end{document}

\def\pgfdeclareradialshading{\pgfutil@ifnextchar[\pgf@declareradialshading{\pgf@declareradialshading[]}}%
\def\pgf@declareradialshading[#1]#2#3#4{%
  \expandafter\def\csname pgf@deps@pgfshading#2!\endcsname{#1}%
  \expandafter\ifx\csname pgf@deps@pgfshading#2!\endcsname\pgfutil@empty%
    \pgfsys@radialshading{#2}{#3}{#4}%
  \else%
    \expandafter\def\csname pgf@func@pgfshading#2!\endcsname{\pgfsys@radialshading}%
    \expandafter\def\csname pgf@args@pgfshading#2!\endcsname{{#3}{#4}}%
    \expandafter\let\csname @pgfshading#2!\endcsname=\pgfutil@empty%
  \fi}




% Declares a functional shading for later use. 
%
% #1 = optional dependecies
% #2 = name of the shading for later use
% #3 = lower left corner of the shading as a pgfpoint.
% #4 = upper right corner of the shading as a pgfpoint.
% #5 = Preparation code
% #6 = a PDF type 4 function (restricted Postscript function), see the 
%      PDF-specification 1.7, section 3.9.4
%
% Description:
%
% This command creates a so-called functional shading. For such a
% shading the color of each point is calculated by calling a function
% for each point that gets the coordinates as input and yields the
% color as an output. Note that the function is evaluated by the
% *renderer*, not by PGF or TeX or someone else at compile-time. This
% means that the evaluation of this function has to be done *extremely
% quickly* and the funciton should be *very simple*. For this reason,
% only a very restricted set of operations are possible in the
% function (see 3.9.4 of the PDF-spec 1.7). Also functions should be
% kept small. Any errors in the function will only be noticed by the
% renderer.
%
% The function gets the coordinates of a point as input (as bp). This
% input consists of the top two elements of an otherwise empty
% (virtual, PostScript) stack. The function should then replace these
% two values by three values, representing the red, green, and blue
% color of the point. The numbers should be real values, not integers
% since Apple's PDF renderer is broken in this regard (use cvr at the
% end if necessary).
%
% Conceptually, the function will be evaluated once for each point of
% the rectangle (#3) to (#4). A renderer may choose to evaluate the
% function at less points, but, in principle, the function will be
% evaluated for each pixel independently.
%
% Because of the rather difficult PostScript syntax, use this macro
% only *if you know what you are doing* (or if you are advanterous, of
% course). 
%
% As for other shadings, the optional depencies argument is used to
% determine whether a shading needs to be recalculated when a color
% has changed.
%
% The code #5 is executed each time a shading is
% (re)calculated. Typically, it will contain code to extract
% coordinates from colors (see below).
%
% Inside the PostScript function #6 you cannot use colors
% directly. Rather, you must push the color components on the
% stack. For this, it is useful to call \pgfshadergb in the startup
% code #4. The macro takes a color name as input and stores the color's 
% red/green/blue components real numbers between 0.0 and 1.0 separated
% by spaces (which is exactly what you need if you want to push it on
% a stack) in a macro. 
%
% Example:
%
%\pgfdeclarefunctionalshading{twospots}{\pgfpointorigin}{\pgfpoint{200bp}{200bp}}{}{
%  2 copy
%  90 sub dup mul exch
%  80 sub dup mul add sqrt
%  dup mul neg 1.0005 exch exp 1.0 exch sub
%  3 1 roll
%  120 sub dup mul exch
%  100 sub dup mul add sqrt
%  dup mul neg 1.002 exch exp 1.0 exch sub
%  1.0
%}
%
% \pgfdeclarefunctionalshading[mycol]{sweep}{\pgfpointorigin}{\pgfpoint{100bp}{100bp}}
% {\pgfshadecolortorgb{mycol}{\myrgb}}{
%   add 150 div   % not very useful...
%   dup
%   \myrgb        % push mycol
%   5 4 roll      % multiply all components by calculated value
%   mul
%   3 1 roll
%   3 index
%   mul
%   3 1 roll
%   4 3 roll
%   mul
%   3 1 roll
% }
%
% \begin{document}
%   Have a look at this: \pgfuseshading{twospots}.
%   Here is \colorlet{mycol}{green!50}\pgfuseshading{sweep} in green
%   and in \colorlet{mycol}{red!50!blue}\pgfuseshading{sweep} in red/blue.
% \end{document}

\def\pgfdeclarefunctionalshading{\pgfutil@ifnextchar[\pgf@declarefunctionalshading{\pgf@declarefunctionalshading[]}}%
\def\pgf@declarefunctionalshading[#1]#2#3#4#5#6{%
  \expandafter\def\csname pgf@deps@pgfshading#2!\endcsname{#1}%
  \expandafter\ifx\csname pgf@deps@pgfshading#2!\endcsname\pgfutil@empty%
    \pgfshade@functionaldo{#2}{#3}{#4}{#5}{#6}%
  \else%
    \expandafter\def\csname pgf@func@pgfshading#2!\endcsname{\pgfshade@functionaldo}%
    \expandafter\def\csname pgf@args@pgfshading#2!\endcsname{{#3}{#4}{#5}{#6}}%
    \expandafter\let\csname @pgfshading#2!\endcsname=\pgfutil@empty%
  \fi}
\def\pgfshade@functionaldo#1#2#3#4#5{%
  {%
    #4%
    \pgfsys@functionalshading{#1}{#2}{#3}{#5}%
  }%
}

\def\pgfshadecolortorgb#1#2{%
  \pgfutil@colorlet{pgf@tempcol}{#1}%
  \pgfutil@extractcolorspec{pgf@tempcol}{\pgf@tempcolor}%
  \expandafter\pgfutil@convertcolorspec\pgf@tempcolor{rgb}{\pgf@rgbcolor}%
  \expandafter\pgfshading@rgb\pgf@rgbcolor\relax%
  \edef#2{\pgf@sys@tonumber{\pgf@xa}\space\pgf@sys@tonumber{\pgf@xb}\space\pgf@sys@tonumber{\pgf@xc}\space}%
  \c@pgf@counta\escapechar%
  \escapechar-1\relax%
  \expandafter\edef\csname\string#2red\endcsname{\pgf@sys@tonumber{\pgf@xa}\space}%
  \expandafter\edef\csname\string#2green\endcsname{\pgf@sys@tonumber{\pgf@xb}\space}%
  \expandafter\edef\csname\string#2blue\endcsname{\pgf@sys@tonumber{\pgf@xc}\space}%
  \escapechar\c@pgf@counta%
}
\def\pgfshading@rgb#1,#2,#3\relax{%
  \pgf@xa=#1pt%
  \pgf@xb=#2pt%
  \pgf@xc=#3pt%
}




% Inserts a box into the text that contains a previously defined
% shading. 
%
% #1 = Name of a shading
%
% Example:
%
% \pgfuseshading{redtogreentoblue}

\def\pgfuseshading#1{%
  \edef\pgf@shadingname{@pgfshading#1}%
  \pgf@tryextensions{\pgf@shadingname}{\pgfalternateextension}%
  \expandafter\pgfutil@ifundefined\expandafter{\pgf@shadingname}%
  {\pgferror{Undefined shading "#1"}}%
  {%
    {%
      \pgfutil@globalcolorsfalse%
      \def\pgf@shade@adds{}%
      \pgfutil@ifundefined{pgf@deps\pgf@shadingname}%
      {}%
      {%
        \edef\@list{\csname pgf@deps\pgf@shadingname\endcsname}%
        \pgfutil@for\@temp:=\@list\do{%
          {%
            \pgfutil@ifundefined{applycolormixins}{}{\applycolormixins{\@temp}}%
            \pgfutil@extractcolorspec{\@temp}{\pgf@tempcolor}%
            \expandafter\pgfutil@convertcolorspec\pgf@tempcolor{rgb}{\pgf@rgbcolor}%
            \xdef\pgf@shade@adds{\pgf@shade@adds,\pgf@rgbcolor}%
          }%
        }%
      }%
      \expandafter\pgf@strip@shadename\pgf@shadingname!!%
      \pgfutil@ifundefined{@pgfshading\pgf@basename\pgf@shade@adds!}%
      {%
        {%
          \expandafter\def\expandafter\@temp\expandafter{\csname pgf@func\pgf@shadingname\endcsname}%
          \edef\@args{{\pgf@basename\pgf@shade@adds}}%
          \expandafter\expandafter\expandafter\def%
          \expandafter\expandafter\expandafter\@@args%
          \expandafter\expandafter\expandafter{\csname pgf@args\pgf@shadingname\endcsname}%
          \expandafter\expandafter\expandafter\@temp\expandafter\@args\@@args%
          %
        }%
      }%
      {}%
      \pgf@invokeshading{\csname @pgfshading\pgf@basename\pgf@shade@adds!\endcsname}%
    }%
  }%
}

\def\pgf@strip@shadename @pgfshading#1!!!{\def\pgf@basename{#1}}

\def\pgf@invokeshading#1{%
  \ifpgfpicture%
    \pgfsys@shadinginsidepgfpicture{#1}%
  \else%
    \pgfsys@shadingoutsidepgfpicture{#1}%  
  \fi%
}


% Create an alias name for a shading
%
% #1 = name of the alias
% #2 = name of the original
%
% Example:
%
% \pgfaliasshading{shading!25}{shadingshaded}

\def\pgfaliasshading#1#2{%
  \expandafter\let\expandafter\pgf@temp\expandafter=\csname @pgfshading#2!\endcsname%
  \expandafter\let\csname @pgfshading#1!\endcsname=\pgf@temp%
  \expandafter\let\expandafter\pgf@temp\expandafter=\csname pgf@deps@pgfshading#2!\endcsname%
  \expandafter\let\csname pgf@deps@pgfshading#1!\endcsname=\pgf@temp%
  \expandafter\let\expandafter\pgf@temp\expandafter=\csname pgf@func@pgfshading#2!\endcsname%
  \expandafter\let\csname pgf@func@pgfshading#1!\endcsname=\pgf@temp%
  \expandafter\let\expandafter\pgf@temp\expandafter=\csname pgf@args@pgfshading#2!\endcsname%
  \expandafter\let\csname pgf@args@pgfshading#1!\endcsname=\pgf@temp%
}




% Shades the current path, but does not discard it.
%
% #1 - a shading (see below)
% #2 - an angle
%
% Description:
%
% \pgfshadepath  ``tries'' to fill the
% current path with a shading. The shading's original size should
% completely cover the area between (0,0) and (100bp,100bp). The
% shading will be rotated by #2 and then rescaled so that it
% completely covers the path. Then the path will be used (locally) for
% clipping and the shading is drawn.
%
% In addition to the rotation, any transformation set by the
%\pgfsetadditionalshadetransform will also be applied.
%
% After all this, the path can still be used for the normal
% stroking/clipping operations.
%
% The shading is rotated around its middle. If no rotation occurs, the
% lower left corner of the path will lie on (25bp, 25bp), the upper
% right corner on (75bp, 75bp).
%
% Example:
%
% \pgfdeclareverticalshading{myshading}{100bp}{color(0pt)=(red); color(100bp)=(green)}
%
% \pgfpathmoveto{\pgforigin}
% \pgfpathlineto{\pgfxy(1,0)}
% \pgfpathlineto{\pgfxy(1,1)}
% \pgfshadepath{myshading}{0}
% \pgfusepath{stroke}

\def\pgfshadepath#1#2{%
  \ifdim\pgf@pathminx=16000pt%
    \pgfwarning{No path specified that can be filled}%
  \else%
    \begingroup%  
      % Calculate center:
      \pgf@xb=.5\pgf@pathmaxx%
      \advance\pgf@xb by.5\pgf@pathminx%
      \pgf@yb=.5\pgf@pathmaxy%
      \advance\pgf@yb by.5\pgf@pathminy%
      % Calculate scaling:
      \pgf@xc=\pgf@pathmaxx%
      \advance\pgf@xc by-\pgf@pathminx%
      \pgf@yc=\pgf@pathmaxy%
      \advance\pgf@yc by-\pgf@pathminy%
      \pgf@xc=.01992528\pgf@xc%
      \pgf@yc=.01992528\pgf@yc%
      \ifdim\pgf@xc<0.0001pt\relax\ifdim\pgf@xc>-0.0001pt\relax\pgf@no@shadetrue\fi\fi%
      \ifdim\pgf@yc<0.0001pt\relax\ifdim\pgf@yc>-0.0001pt\relax\pgf@no@shadetrue\fi\fi%
      \ifpgf@no@shade\else%
      \pgfsys@beginscope%
        \pgfsyssoftpath@invokecurrentpath%
        \pgfsys@clipnext%
        \pgfsys@discardpath%
        % Compute new transformation matrix:
        \pgfsys@transformcm{1}{0}{0}{1}{\pgf@xb}{\pgf@yb}%
        \pgfsys@transformcm%
        {\pgf@sys@tonumber{\pgf@xc}}{0}%
        {0}{\pgf@sys@tonumber{\pgf@yc}}{0pt}{0pt}%
        \pgfmathparse{#2}%
        \let\pgfshade@angle=\pgfmathresult%
        \pgfmathsin@{\pgfshade@angle}%
        \let\pgfshade@sin=\pgfmathresult%
        \pgfmathcos@{\pgfshade@angle}%
        \let\pgfshade@cos=\pgfmathresult%
        \pgf@x=\pgfshade@sin pt%
        \pgf@xa=-\pgf@x%
        \pgfsys@transformcm{\pgfshade@cos}{\pgfshade@sin}{\pgf@sys@tonumber{\pgf@xa}}{\pgfshade@cos}{0pt}{0pt}%
        \ifx\pgf@shade@extra@transform\pgfutil@empty%
        \else%
          \pgflowlevel{\pgf@shade@extra@transform}%
        \fi%
        \pgfuseshading{#1}%
      \pgfsys@endscope%
      \fi%  
    \endgroup%
  \fi%
}

\newif\ifpgf@no@shade

% Additionally transform shade paths
%
% #1 = Transformation code that is used in addition to the normal
%      shading transformation.
%
% Example:
%
% \pgfsetadditionalshadetransform{\pgftransformrotate{30}}

\def\pgfsetadditionalshadetransform#1{\def\pgf@shade@extra@transform{#1}}
\let\pgf@shade@extra@transform=\pgfutil@empty





\endinput

pgfcoretransformations.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/basiclayer/pgfcoretransformations.code.tex,v 1.17 2013/10/10 08:53:09 tantau Exp $


% Position transformations

\newdimen\pgf@pt@x
\newdimen\pgf@pt@y

\newdimen\pgf@pt@temp

\newif\ifpgf@pt@identity
\pgf@pt@identitytrue

\def\pgf@pt@aa{1.0} \def\pgf@pt@ab{0.0}
\def\pgf@pt@ba{0.0} \def\pgf@pt@bb{1.0}



% Store the current transformation matrix in a macro.
%
% #1 = macro name
%
% Example:
%
% \pgfgettransform\mytransform

\def\pgfgettransform#1{%
  \edef#1{{\pgf@pt@aa}{\pgf@pt@ab}{\pgf@pt@ba}{\pgf@pt@bb}{\the\pgf@pt@x}{\the\pgf@pt@y}}
}

% Store the current transformation matrix in a set of macros, one for
% each single entry.
%
% #1-#4 are macro which store the matrix entries (0,0), (0,1), (1,0),
% (1,1) (in this order). It is the same order as for \pgftransformcm.
%
% #5 is a macro which will be filled with the x shift and
% #6 is a macro which will be filled with the y shift.
%
% Example:
% \pgfgettransform\aa\ab\ba\bb\shiftx\shifty
%
% ->
% 
% \pgftransformcm\aa\ab\ba\bb{\pgfqpoint{\shiftx}{\shifty}}
%
% or
%
% \pgfsettransformentries\aa\ab\ba\bb\shiftx\shifty
\def\pgfgettransformentries#1#2#3#4#5#6{%
  \edef#1{\pgf@pt@aa}%
  \edef#2{\pgf@pt@ab}%
  \edef#3{\pgf@pt@ba}%
  \edef#4{\pgf@pt@bb}%
  \edef#5{\the\pgf@pt@x}%
  \edef#6{\the\pgf@pt@y}%
}%
\def\pgfsettransformentries#1#2#3#4#5#6{%
  \pgfsettransform{{#1}{#2}{#3}{#4}{#5}{#6}}%
}%

% Restore the current transformation matrix from a macro.
%
% #1 = macro name, previously used with \pgfgettransform
%
% Example:
%
% \pgfsettransform\mytransform

\def\pgfsettransform#1{%
  \edef\pgf@temp{#1}%
  \expandafter\pgf@settransform\pgf@temp%
}
\def\pgf@settransform#1#2#3#4#5#6{%
  \def\pgf@pt@aa{#1}%
  \def\pgf@pt@ab{#2}%
  \def\pgf@pt@ba{#3}%
  \def\pgf@pt@bb{#4}%
  \pgf@pt@x=#5%
  \pgf@pt@y=#6%
  \edef\pgf@idtest{#1,#2,#3,#4}%
  \ifx\pgf@idtest\pgf@idmatrixtext%
    \pgf@pt@identitytrue%
  \else%
    \pgf@pt@identityfalse%
  \fi%
}

\def\pgf@idmatrixtext{1.0,0.0,0.0,1.0}
\def\pgf@zerozerotext{0.0,0.0}

% Transformation command
%
% #1 = x dimension
% #2 = y dimension
%
% Description:
%
% Applies the pgfs transformation matrix to the point (#1,#2). The
% result is once more stored in the point.
%
%
% Example:
%
% \pgf@pos@transform{\pgf@x}{\pgf@y}

\def\pgf@pos@transform#1#2{%
  \ifpgf@pt@identity%
  \else%
    \pgf@pt@temp=#1%
    #1=\pgf@pt@aa#1%
    \advance#1 by\pgf@pt@ba#2%
    #2=\pgf@pt@bb#2%
    \advance#2 by\pgf@pt@ab\pgf@pt@temp%
  \fi%
  \advance#1 by\pgf@pt@x%
  \advance#2 by\pgf@pt@y%
}


% Invert the current transformation matrix
%
% Description:
%
% This command replaces the current transformation matrix by its
% inverse. The inversion is not very exact if the matrix is nearly
% singular. 
%
% Example:
%
% \pgftransforminvert

\def\pgftransforminvert{%
  % First, invert the shift. That's easy
  \pgf@pt@x=-\pgf@pt@x
  \pgf@pt@y=-\pgf@pt@y
  \ifpgf@pt@identity%
  \else%
    % Sigh. Have to calculate the inverse of the matrix.
    % Perhaps we are lucky and ba and bb are zero?
    \edef\pgf@zerotest{\pgf@pt@ab,\pgf@pt@ba}%
    \ifx\pgf@zerotest\pgf@zerozerotext%
      % Ha! Just invert aa and bb
      \pgfmathreciprocal@{\pgf@pt@aa}%
      \let\pgf@pt@aa\pgfmathresult%
      \pgfmathreciprocal@{\pgf@pt@bb}%
      \let\pgf@pt@bb\pgfmathresult%
    \else%
      % Start with determinant
      % Matrix = (aa ab
      %           ba bb)
      {%
        \pgfutil@tempdima=\pgf@pt@aa pt%
        \pgfutil@tempdima=\pgf@pt@bb\pgfutil@tempdima% aa * bb
        \pgfutil@tempdimb=\pgf@pt@ba pt%
        \pgfutil@tempdimb=\pgf@pt@ab\pgfutil@tempdimb% ba * ab
        \advance\pgfutil@tempdima by -\pgfutil@tempdimb% aa*bb - ba*ab
        % Invert
        \pgfmathreciprocal@{\pgf@sys@tonumber{\pgfutil@tempdima}}%
        \pgfutil@tempdima=\pgfmathresult pt%
        \pgf@x=\pgf@pt@bb\pgfutil@tempdima% bb/(det A)
        \xdef\pgf@new@pt@aa{\pgf@sys@tonumber{\pgf@x}}%
        \pgf@x=\pgf@pt@aa\pgfutil@tempdima% aa/(det A)
        \xdef\pgf@new@pt@bb{\pgf@sys@tonumber{\pgf@x}}%
        \pgfutil@tempdima=-\pgfutil@tempdima%
        \pgf@x=\pgf@pt@ba\pgfutil@tempdima% -ba/(det A)
        \xdef\pgf@new@pt@ba{\pgf@sys@tonumber{\pgf@x}}%
        \pgf@x=\pgf@pt@ab\pgfutil@tempdima% -ab/(det A)
        \xdef\pgf@new@pt@ab{\pgf@sys@tonumber{\pgf@x}}%
      }%
      \let\pgf@pt@aa\pgf@new@pt@aa%
      \let\pgf@pt@ab\pgf@new@pt@ab%
      \let\pgf@pt@ba\pgf@new@pt@ba%
      \let\pgf@pt@bb\pgf@new@pt@bb%
    \fi%
    \pgf@pt@temp=\pgf@pt@x%
    \pgf@pt@x=\pgf@pt@aa\pgf@pt@x%
    \advance\pgf@pt@x by\pgf@pt@ba\pgf@pt@y%
    \pgf@pt@y=\pgf@pt@bb\pgf@pt@y%
    \advance\pgf@pt@y by\pgf@pt@ab\pgf@pt@temp%
  \fi%
}




% PGF-Level concatenation of the transformation matrix with a given
% matrix. 
%
% #1 - #5 = a concatenation matrix (see pdf spec). Entry #5 is a
%           translation point.
%
% Description:
%
% All coordinates given to subsequent path construction commands will
% be transformed additionally by the given transformation matrix. If
% the command is followed by a 6th argument, the transformation is
% only applied to this argument.
%
%
% Example:
%
% \pgftransformcm{1}{0}{0}{1}{\pgfpoint{100pt}{0pt}} % 100pt to the right.
%
% \pgftransformcm{2}{0}{0}{2}{\pgfpointorigin} % double in in size
% \pgfpathmoveto{\pgfpoint{0cm}{0cm}}
% \pgfpathlineto{\pgflineto{1cm}{1cm}} % actually 2cm/2cm

\def\pgftransformcm#1#2#3#4#5{%
  \edef\pgf@marshal{\noexpand\pgf@transformcm{#1}{#2}{#3}{#4}}%
  \pgf@marshal{#5}%
}
\def\pgf@transformcm#1#2#3#4#5{%
  {%
    \pgf@process{#5}%
    \pgf@xc=\pgf@x%
    \pgf@yc=\pgf@y%
    %
    \pgfmathsetlength\pgf@x{#1}%
    \pgfmathsetlength\pgf@y{#2}%
    %
    \pgf@xa=\pgf@pt@aa\pgf@x%
    \advance\pgf@xa by \pgf@pt@ba\pgf@y%
    %
    \pgf@ya=\pgf@pt@ab\pgf@x%
    \advance\pgf@ya by \pgf@pt@bb\pgf@y%
    %
    \pgfmathsetlength\pgf@x{#3}%
    \pgfmathsetlength\pgf@y{#4}%
    %
    \pgf@xb=\pgf@pt@aa\pgf@x%
    \advance\pgf@xb by \pgf@pt@ba\pgf@y%
    %
    \pgf@yb=\pgf@pt@ab\pgf@x%
    \advance\pgf@yb by \pgf@pt@bb\pgf@y%
    %
    \pgf@x=\pgf@pt@aa\pgf@xc%
    \advance\pgf@x by\pgf@pt@ba\pgf@yc%
    \advance\pgf@x by\pgf@pt@x%
    %
    \pgf@y=\pgf@pt@ab\pgf@xc%
    \advance\pgf@y by\pgf@pt@bb\pgf@yc%
    \advance\pgf@y by\pgf@pt@y%
    %
    \global\pgf@x=\pgf@x%
    \global\pgf@y=\pgf@y%
    \xdef\pgf@tempaa{\pgf@sys@tonumber{\pgf@xa}}%
    \xdef\pgf@tempab{\pgf@sys@tonumber{\pgf@ya}}%
    \xdef\pgf@tempba{\pgf@sys@tonumber{\pgf@xb}}%
    \xdef\pgf@tempbb{\pgf@sys@tonumber{\pgf@yb}}%
  }%
  \pgf@pt@x=\pgf@x%
  \pgf@pt@y=\pgf@y%
  \let\pgf@pt@aa=\pgf@tempaa%
  \let\pgf@pt@ba=\pgf@tempba%
  \let\pgf@pt@ab=\pgf@tempab%
  \let\pgf@pt@bb=\pgf@tempbb%
  \edef\pgf@idtest{\pgf@pt@aa,\pgf@pt@ba,\pgf@pt@ab,\pgf@pt@bb}%
  \ifx\pgf@idtest\pgf@idmatrixtext%
    \pgf@pt@identitytrue%
  \else%
    \pgf@pt@identityfalse%
  \fi%
}



% Transformation into a given triangle. The three corners of the
% triangle are called "origin", "x" and "y" are given. After this
% transformation has been applied, the canvas origin is at "origin",
% the vector (1pt,0pt) lies at "x" and the vector (0pt,1pt) lies at
% "y". 
%
% #1 = origin
% #2 = x
% #3 = y
%
% Example:
%
% \pgftransformtriangle{\pgfpointorigin}{\pgfpoint{1cm}{1cm}}{\pgfpoint{-1cm}{1cm}}

\def\pgftransformtriangle#1#2#3{%
  \pgf@process{#2}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \pgf@process{#3}%
  \pgf@xb=\pgf@x%
  \pgf@yb=\pgf@y%
  \pgf@process{#1}%
  \advance\pgf@xa by-\pgf@x%
  \advance\pgf@ya by-\pgf@y%
  \advance\pgf@xb by-\pgf@x%
  \advance\pgf@yb by-\pgf@y%
  \pgftransformcm%
  {\pgf@sys@tonumber\pgf@xa}{\pgf@sys@tonumber\pgf@ya}%
  {\pgf@sys@tonumber\pgf@xb}{\pgf@sys@tonumber\pgf@yb}%
  {\pgfpoint{\pgf@x}{\pgf@y}}%
}



% Undo all transformations
%
% Example:
%
% \pgftansformreset

\def\pgftransformreset{%
  \pgf@pt@x=0pt%
  \pgf@pt@y=0pt%
  \def\pgf@pt@aa{1.0}%
  \def\pgf@pt@ba{0.0}%
  \def\pgf@pt@ab{0.0}%
  \def\pgf@pt@bb{1.0}%
  \pgf@pt@identitytrue%
}


% Undo all slanting/rotation, but not translations
%
% Example:
%
% \pgftansformreset

\def\pgftransformresetnontranslations{%
  \def\pgf@pt@aa{1.0}%
  \def\pgf@pt@ba{0.0}%
  \def\pgf@pt@ab{0.0}%
  \def\pgf@pt@bb{1.0}%
  \pgf@pt@identitytrue%
}




% Shifting command and environment
%
% #1 = vector by which all subsequent points should be moved.
%
% Example:
%
% \pgftansformshift{\pgfpoint{1cm}{1cm}}

\def\pgftransformshift#1{\pgftransformcm{1}{0}{0}{1}{#1}}
\def\pgftransformxshift#1{\pgftransformcm{1}{0}{0}{1}{\pgfpoint{#1}{+0pt}}}
\def\pgftransformyshift#1{\pgftransformcm{1}{0}{0}{1}{\pgfpoint{+0pt}{#1}}}




% Scaling commands
%
% #1 = scaling for all subsequent points.
%
% Example:
%
% \pgftransformscale{2}
% \pgftransformxscale{2}
% \pgftransformyscale{2}

\def\pgftransformscale#1{\pgftransformcm{#1}{0}{0}{#1}{\pgfpointorigin}}
\def\pgftransformxscale#1{\pgftransformcm{#1}{0}{0}{1.0}{\pgfpointorigin}}
\def\pgftransformyscale#1{\pgftransformcm{1.0}{0}{0}{#1}{\pgfpointorigin}}



% Slanting commands
%
% #1 = slanting in x-direction. 1 means 45 degrees.
%
% Example:
%
% \pgftransformxslant{2}
% \pgftransformyslant{2}

\def\pgftransformxslant#1{\pgftransformcm{1.0}{0}{#1}{1.0}{\pgfpointorigin}}
\def\pgftransformyslant#1{\pgftransformcm{1.0}{#1}{0}{1.0}{\pgfpointorigin}}



% Rotation commands
%
% #1 = degrees for the rotation
%
% Example:
%
% \pgftransformrotate{30}

\def\pgftransformrotate#1{%
  \pgfmathparse{#1}%
  \let\pgftransform@angle=\pgfmathresult%
  \pgfmathsin@{\pgftransform@angle}%
  \let\pgftransform@sin=\pgfmathresult%
  \pgfmathcos@{\pgftransform@angle}%
  \let\pgftransform@cos=\pgfmathresult%
  \pgf@x=\pgftransform@sin pt%
  \pgf@xa=-\pgf@x%
  \pgftransformcm{\pgftransform@cos}{\pgftransform@sin}{\pgf@sys@tonumber{\pgf@xa}}{\pgftransform@cos}{\pgfpointorigin}%
}



% The following if's have the following effect:
%
% \ifpgfslopedattime decides whether the coordinate system of an
% xxxattime transformation command should be rotated such that text
% drawn on the line should be tangent to the line
%
% \ifpgfallowupsidedowattime decides whether the transformation should
% be done in such a way that the text is always ``upright,'' that is,
% text drawn in this coordiante system is never upside-down. 
%
% \ifpgfresetnontranslationattime decides whether the coordinate
% system of an xxxattime transformation command should be reset
% (concerning the non-translations) before a possible rotation is
% applied. This is useful, for example, if the main coordinate system
% is scaled by, say, a factor of 2 and you do not want that to apply
% to the text, but you do want the rotation to applyu.

\newif\ifpgfslopedattime
\newif\ifpgfallowupsidedownattime
\newif\ifpgfresetnontranslationattime


% Transform to the coordinate system of a point on a line
%
% #1 = a time fraction of line where to put the label, where 0 means start,
%      1 means end, and for example 0.5 means the middle.
% #2 = start of line
% #3 = end of line
%
% Example:
%
% {
%   \pgftransformlineattime{.5}{\pgfxy(0,0)}{\pgfxy(3,2)}
%   \pgftext{Hi!}
% }
%
% {
%   \pgftransformlineattime{.75}{\pgfxy(0,0)}{\pgfxy(3,2)}
%   \pgftransformresetnontranslations
%   \pgftext{Hi!}
% }
%
\def\pgftransformlineattime#1#2#3{%
  \pgf@process{#2}%
  \pgf@xb=\pgf@x% xb/yb = start point
  \pgf@yb=\pgf@y%
  \pgf@process{#3}%
  \pgf@xc=\pgf@x% xc/yc = end point
  \pgf@yc=\pgf@y%
  \pgftransformshift{\pgfpointlineattime{#1}{\pgfqpoint{\pgf@xb}{\pgf@yb}}{\pgfqpoint{\pgf@xc}{\pgf@yc}}}%
  \ifpgfresetnontranslationattime%
    \pgftransformresetnontranslations%
  \fi%
  \ifpgfslopedattime%
    \advance\pgf@xc by-\pgf@xb%
    \advance\pgf@yc by-\pgf@yb%
    \ifpgfallowupsidedownattime%
    \else%
      \ifdim\pgf@xc<0pt%   
        \pgf@xc=-\pgf@xc%
        \pgf@yc=-\pgf@yc%
      \fi%
    \fi%
    \pgf@x=\pgf@xc%
    \pgf@y=\pgf@yc%
    \pgfpointnormalised{}% x/y = normalised vector
    \pgf@ya=-\pgf@y%
    \pgftransformcm%
    {\pgf@sys@tonumber{\pgf@x}}{\pgf@sys@tonumber{\pgf@y}}%
    {\pgf@sys@tonumber{\pgf@ya}}{\pgf@sys@tonumber{\pgf@x}}{\pgfpointorigin}%
  \fi%
}


% Transform to the coordinate system of a point on an arc
%
% #1 = a time fraction of line where to put the label, where 0 means start,
%      1 means end, and for example 0.5 means the middle.
% #2 = center of an ellipse
% #3 = 0-degree axis of the ellipse
% #4 = 90-degree axis of the ellipse
% #4 = start angle of the arc on this ellipse
% #5 = end angle of the arc on this ellipse
%
% Example:
%
% {
%   \pgftransformlineattime{.5}{\pgfpoint{1cm}{1cm}}{\pgfpoint{1cm}{0cm}}{\pgfpoint{0cm}{1cm}}{30}{40}
%   \pgftext{Hi!}
% }

\def\pgftransformarcaxesattime#1#2#3#4#5#6{%
  \pgfpointarcaxesattime{#1}{#2}{#3}{#4}{#5}{#6}%        
  \pgftransformshift{\pgfqpoint{\pgf@x}{\pgf@y}}%
  \ifpgfresetnontranslationattime%
    \pgftransformresetnontranslations%
  \fi%
  \ifpgfslopedattime%
    \pgf@x=\pgf@xa%
    \pgf@y=\pgf@ya%
    \pgf@process{\pgfpointnormalised{}}%
    \ifpgfallowupsidedownattime%
    \else%
      \ifdim\pgf@x<0pt%
        \pgf@x=-\pgf@x%
        \pgf@y=-\pgf@y%
      \fi%
    \fi%
    \pgf@ya=-\pgf@y%
    \pgftransformcm%
    {\pgf@sys@tonumber{\pgf@x}}{\pgf@sys@tonumber{\pgf@y}}%
    {\pgf@sys@tonumber{\pgf@ya}}{\pgf@sys@tonumber{\pgf@x}}{\pgfpointorigin}%
  \fi%
}




% Transform to the coordinate system of a point on a curve
%
% #1 = a time fraction of line where to put the label, where 0 means start,
%      1 means end, and for example 0.5 means the middle.
% #2 = start of line
% #3 = first control
% #4 = second control
% #5 = end of line
%
% Example:
%
% {
%   \pgftransformcurveattime{.5}{\pgfxy(0,0)}{\pgfxy(3,2)}
%   \pgftext{Hi!}
% }
%
% {
%   \pgftransformcurveattime{.75}{\pgfxy(0,0)}{\pgfxy(3,2)}
%   \pgftransformresetnontranslations
%   \pgftext{Hi!}
% }
%
\def\pgftransformcurveattime#1#2#3#4#5{%
  \pgfpointcurveattime{#1}{#2}{#3}{#4}{#5}%
  \pgftransformshift{\pgfqpoint{\pgf@x}{\pgf@y}}%
  \ifpgfresetnontranslationattime%
    \pgftransformresetnontranslations%
  \fi%
  \ifpgfslopedattime%
    \pgf@x=\pgf@xa%
    \pgf@y=\pgf@ya%
    \advance\pgf@x by-\pgf@xb%
    \advance\pgf@y by-\pgf@yb%
    \ifpgfallowupsidedownattime%
    \else%
      \ifdim\pgf@x<0pt%
        \pgf@x=-\pgf@x%
        \pgf@y=-\pgf@y%
      \fi%
    \fi%
    \pgfpointnormalised{}% x/y = normalised vector
    \pgf@ya=-\pgf@y%
    \pgftransformcm%
    {\pgf@sys@tonumber{\pgf@x}}{\pgf@sys@tonumber{\pgf@y}}%
    {\pgf@sys@tonumber{\pgf@ya}}{\pgf@sys@tonumber{\pgf@x}}{\pgfpointorigin}%
  \fi%
}





% Transform to the coordinate system of an arrow at the end of the
% line going from point #1 to point #2 with the correct rotation.
%
% #1 = a start point an (invisible) line
% #2 = an end point an (invisible) line
%
% Example:
%
% \pgftransformarrow{\pgfpointorigin}{\pgfpoint{1cm}{0cm}}

\def\pgftransformarrow#1#2{%
  \pgf@process{#2}%
  \pgftransformshift{}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \pgf@process{#1}%
  \advance\pgf@xa by-\pgf@x%
  \advance\pgf@ya by-\pgf@y%
  \pgf@x=\pgf@xa%
  \pgf@y=\pgf@ya%
  \pgfpointnormalised{}%
  \pgf@ya=-\pgf@y%
  \pgftransformcm%
  {\pgf@sys@tonumber{\pgf@x}}{\pgf@sys@tonumber{\pgf@y}}%
  {\pgf@sys@tonumber{\pgf@ya}}{\pgf@sys@tonumber{\pgf@x}}{\pgfqpoint{0pt}{0pt}}%
}



% Low-level transformations

% Causes the current high-level transformation command to be applied
% to the low-level.
%
% Description:
%
% All subsequent drawing will be transformed additionally by the
% current high-level transformation. Thus, the high-level
% transformation becomes the low-level transformation. The high-level
% transformation is reset at this point.

\def\pgflowlevelsynccm{%
  \pgfsys@transformcm%
  {\pgf@pt@aa}{\pgf@pt@ab}%
  {\pgf@pt@ba}{\pgf@pt@bb}%
  {\pgf@pt@x}{\pgf@pt@y}%
  \pgftransformreset%
  \pgf@relevantforpicturesizefalse%
}  



% Causes a transformation command to be applied to the ``lowlevel''
% transformation matrix. 
%
% #1 - a high-level transformation command
%
% Description:
%
% All subsequent drawing will be transformed additionally by the given
% transformation matrix. Note that PGF will no longer be able to
% ``keep track'' of the coordinates. Also, transformations are applied
% to *everything*, including line thickness and line endings. Most
% often, this is not desirable.
%
% Example:
%
% \pgflowlevel{\pgftransformcm{1}{0}{0}{1}{\pgfpoint{100pt}{0pt}}} % 100bp to the right.
%
% \begin{pgflowlevelscope}{\pgftransformcm{2}{0}{0}{2}{\pgfpointorigin}} % double in in size
%  \pgfmoveto{\pgfpoint{0cm}{0cm}}
%  \pgflineto{\pgflineto{1cm}{1cm}} % actually 2cm/2cm
% \end{pgflowlevelscope}

\def\pgflowlevel#1{%
  {%
    \pgftransformreset%
    #1%
    \pgflowlevelsynccm%
  }%
  \pgf@relevantforpicturesizefalse%
}

\def\pgflowlevelscope#1{\pgfscope\pgflowlevel{#1}}
\def\endpgflowlevelscope{\endpgfscope}

\long\def\pgflowlevelobj#1#2{\pgfscope{\pgflowlevel{#1}#2}\endpgfscope}



% Forward declarations for nonlinear stuff (have no effect till module
% nonlineartransformations is loaded)

\let\pgfapproximatenonlineartranslation\relax
\let\pgfapproximatenonlineartransformation\relax
\def\pgftransformnonlinear#1{\pgferror{You need to say
    \string\usepgfmodule{nonlineartransformation} to use nonlinear transformations}}


\endinput

pgfcoretransparency.code.tex
% Copyright 2007 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/basiclayer/pgfcoretransparency.code.tex,v 1.5 2013/09/30 18:30:15 tantau Exp $


% Sets the opacity of stroking operations.
% 
% #1 = opacity, where 1 means fully opaque and 0 means fully
% transparent. 
%
% Example:
%
% \pgfsetstrokeopacity{0.5}

\def\pgfsetstrokeopacity#1{%
  \pgfmathparse{#1}%
  \expandafter\pgfsys@stroke@opacity\expandafter{\pgfmathresult}}


% Sets the opacity of stroking operations.
% 
% #1 = opacity, where 1 means fully opaque and 0 means fully
% transparent. 
%
% Example:
%
% \pgfsetfillopacity{0.5}

\def\pgfsetfillopacity#1{%
  \pgfmathparse{#1}%
  \expandafter\pgfsys@fill@opacity\expandafter{\pgfmathresult}}



% Sets the current blend mode. See Section 7.2.4 of the PDF
% Specification 1.7 for an introduction to blend modes in general. 
% 
% #1 = One of the following modes, see also section 7.2.4 of the
% PDF Specification 1.7. (The PGF names, which are all lowercase with
% spaces as usual, must be mapped to the PDF or SVG by the drivers.)
%
% normal
% multiply
% screen
% overlay
% darken
% lighten
% color dodge
% color burn
% hard light
% soft light
% difference
% exclusion
% saturation
% color
% hue
% luminosity
%
% Example:
%
% \pgfsetblendmode{multiply}

\def\pgfsetblendmode#1{\pgfsys@blend@mode{#1}}


% Declares a new fading based on the contents of a box.
%
% #1 = name of the fading
% #2 = content of a TeX box that specifies the fading
%
% Description:
%
% This command declares a new fading based on the contents of
% the TeX box. The mask can later be used to mask other graphics.
%
% The box is used to determine where the mask is opaque: At the
% beginning, the mask is completely transparent. Whereever the box
% contains something (like text or a picture or whatever), the
% luminosity of the text/graphic is used to determine how opaque the
% point will be. The greater the luminosity, the more opaque. The net
% effect is that white corresponds to "completely opaque" and black to
% "completely transparent". This is rather counterintuitive. Because
% of this, the special color "pgftransparent" is defined, which is the
% same as black. By setting the color to, say,
% \color{pgftransparent!10} you get something that is 10% transparent
% and \color{pgftransparent!90} gives you 90% transparency.
%
% By default, the drawing color is set to opaque.
%
% Example:
%
% \pgfdeclarefading{mymask}{
%  \fontsize{200}{200}\bfseries
%  Ti\emph{k}Z
% }
% \pgfdeclarefading{myothermask}{
%  \tikz \shade [left color=transparent,right color=transparent!0]
%    (0,0) rectangle (5,5);
% }

\def\pgfdeclarefading#1#2{%
  \setbox\pgfutil@tempboxa=\hbox{{\pgfsys@beginscope\pgfutil@color{white}\ignorespaces#2\pgfsys@endscope}}%
  \pgfsys@fadingfrombox{#1}\pgfutil@tempboxa%
}

\pgfutil@colorlet{pgftransparent}{black}


% Use a previously declared fading.
%
% #1 = name of the fading
% #2 = transformation code
%
% Description:
%
% The command should be used *inside* a pgfpicture to install a
% fading. The fading is a part of the graphic state. (This command 
% works much like \pgfsetstrokeopacity).
%
% The mask will be centered on the origin. The transformation code #2 is
% applied to the mask (but not the contents of the actual picture).

\def\pgfsetfading#1#2{%
  {%
    \pgftransformreset%
    #2%
    \pgfgettransform{\pgftrans@temp}%
    \edef\pgf@marshal{\noexpand\pgfsys@usefading{#1}\pgftrans@temp}%
    \pgf@marshal%
  }%
}



% Use a previously declared fading scaled for the current path.
%
% #1 - an fading
% #2 - extra transformations
%
% Description:
%
% This command works a bit like \pgfshadepath. "Works a bit like"
% means the following: The masks's original size should
% completely cover the area between (0,0) and (100bp,100bp). The
% mask is then rescaled so that it completely covers the path. Then
% the additional transformation #2 is applied. Finally, the mask is
% made part of the graphic state (as with \pgfsetfading). The path
% used for computation purposes only -- it is not drawn or otherwise
% used.  
%
% If no transformations occur, the lower left corner of the path will
% lie on (25bp, 25bp), the upper right corner on (75bp, 75bp).
%
% If the path was empty, the fading will be used at its natural size,
% centered on the origin.
%
% Example:
%
% \pgfdeclarefading{fade right}
% {\tikz[left color=transparent!0,right color=transparent!100]
%    (0,0) rectangle (100bp,100bp);}
%
% \pgfpathmoveto{\pgforigin}
% \pgfpathlineto{\pgfxy(1,0)}
% \pgfpathlineto{\pgfxy(1,1)}
% \pgfsetfadingforcurrentpath{fade right}{}
% \pgfusepath{fill}

\def\pgfsetfadingforcurrentpath#1#2{%
  \ifdim\pgf@pathminx=16000pt%
    % Path was empty -> use natural size
    \pgfsetfading{#1}{#2}%
  \else%
    \pgfsetfading{#1}{%
      % Calculate center:
      \pgf@xb=.5\pgf@pathmaxx%
      \advance\pgf@xb by.5\pgf@pathminx%
      \pgf@yb=.5\pgf@pathmaxy%
      \advance\pgf@yb by.5\pgf@pathminy%
      % Calculate scaling:
      \pgf@xc=\pgf@pathmaxx%
      \advance\pgf@xc by-\pgf@pathminx%
      \ifdim\pgf@xc<0.1pt\pgf@xc=0.1pt\fi%
      \pgf@yc=\pgf@pathmaxy%
      \advance\pgf@yc by-\pgf@pathminy%
      \ifdim\pgf@yc<0.1pt\pgf@yc=0.1pt\fi%
      \pgf@xc=.02\pgf@xc%
      \pgf@yc=.02\pgf@yc%
      % Compute new transformation matrix:
      \pgftransformcm{1}{0}{0}{1}{\pgfqpoint{\pgf@xb}{\pgf@yb}}%
      \pgftransformcm{\pgf@sys@tonumber{\pgf@xc}}{0}{0}{\pgf@sys@tonumber{\pgf@yc}}{\pgfpointorigin}%
      #2%
    }%
  \fi%
}




% Use a previously declared fading scaled for the current path.
%
% #1 - an fading
% #2 - extra transformations
%
% Description:
%
% This command works like \pgfsetfadingforcurrentpath, only it takes
% the current line width into account: Before the path is considered,
% it is enlarged by half the line width in all directions.

\def\pgfsetfadingforcurrentpathstroked#1#2{%
  \ifdim\pgf@pathminx=16000pt%
    % Path was empty -> use natural size
    \pgfsetfading{#1}{#2}%
  \else%
    \pgfsetfading{#1}{%
      % Calculate center:
      \pgf@xb=.5\pgf@pathmaxx%
      \advance\pgf@xb by.5\pgf@pathminx%
      \pgf@yb=.5\pgf@pathmaxy%
      \advance\pgf@yb by.5\pgf@pathminy%
      % Calculate scaling:
      \pgf@xc=\pgf@pathmaxx%
      \advance\pgf@xc by-\pgf@pathminx%
      \advance\pgf@xc by\pgflinewidth%
      \ifdim\pgf@xc<0.1pt\pgf@xc=0.1pt\fi%
      \pgf@yc=\pgf@pathmaxy%
      \advance\pgf@yc by-\pgf@pathminy%
      \advance\pgf@yc by\pgflinewidth%
      \ifdim\pgf@yc<0.1pt\pgf@yc=0.1pt\fi%
      \pgf@xc=.02\pgf@xc%
      \pgf@yc=.02\pgf@yc%
      % Compute new transformation matrix:
      \pgftransformcm{1}{0}{0}{1}{\pgfqpoint{\pgf@xb}{\pgf@yb}}%
      \pgftransformcm{\pgf@sys@tonumber{\pgf@xc}}{0}{0}{\pgf@sys@tonumber{\pgf@yc}}{\pgfpointorigin}%
      #2%
    }%
  \fi%
}



% Group things in a a transparency group
%
% Description:
%
% This takes groups pgf commands inside a pgfpicture in a transparency
% group. This means that any transparency settings apply to commands a
% whole. For instance, if a box contains two overlapping black 
% circles and you draw them normally with 50% transparency, then the
% overlap will be darker than the rest. By comparison, if the circles
% are part of a transparency group, the overlap will get the same
% color as the rest.
%
% 

\def\pgftransparencygroup{%
  \pgfutil@ifnextchar[{\pgftransparencygroup@}{\pgftransparencygroup@[]}%
}
\def\pgftransparencygroup@[#1]{%
  \begingroup%
    \pgfkeys{/pgf/transparency group options/.cd,%
      isolated=false,
      knockout=false,
      #1}%
    \setbox\pgfutil@tempboxa=\hbox\bgroup%
}
\pgfkeys{
  /pgf/transparency group options/.cd,
  isolated/.is if=pgfsys@transparency@group@isolated,
  knockout/.is if=pgfsys@transparency@group@knockout
}
  
\def\endpgftransparencygroup{%
    \egroup%
    % Now compute the correct position. This is a bit tricky...
    \ifdim\pgf@picminx=16000pt%
      % Nothing needs to be done
    \else%
      % Safety margin to avoid clipping:
      \advance\pgf@picminx by-1cm%
      \advance\pgf@picmaxx by1cm%
      \advance\pgf@picminy by-1cm%
      \advance\pgf@picmaxy by1cm%
      % Ok, set the box size to current picture size.
      \setbox\pgfutil@tempboxa=\hbox{%
        \vrule width0pt height\pgf@picmaxy depth-\pgf@picminy%
        \hskip-\pgf@picminx%
        \box\pgfutil@tempboxa%
        \hskip\pgf@picmaxx%
      }%
      \pgfsys@transparencygroupfrombox\pgfutil@tempboxa%
      \wd\pgfutil@tempboxa=0pt%
      \ht\pgfutil@tempboxa=0pt%
      \dp\pgfutil@tempboxa=0pt%
      \hskip\pgf@picminx\box\pgfutil@tempboxa\hskip-\pgf@picminx%
    \fi%
  \endgroup%
}

\let\startpgftransparencygroup=\pgftransparencygroup
\let\stoppgftransparencygroup=\endpgftransparencygroup

\endinput

pgffor.code.tex
% Copyright 2008 by Till Tantau and Mark Wibrow
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesPackageRCS[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/utilities/pgffor.code.tex,v 1.25 2013/12/13 11:40:27 tantau Exp $

% pgfmath is needed
\input pgfmath.code.tex

\newdimen\pgffor@iter
\newdimen\pgffor@skip
\newif\ifpgffor@continue


\def\pgffor@reset@hooks{%
  \let\pgffor@beginhook=\relax%
  \let\pgffor@endhook=\relax%
  \let\pgffor@afterhook=\relax%
}
\pgffor@reset@hooks


% Stack emulation
%
\newtoks\pgffor@stack
\pgffor@stack={{}{}{}}

\def\pgffor@stackpush#1{%
	\def\pgffor@stacktemp{#1}%
	\expandafter\expandafter\expandafter\pgffor@stack\expandafter\expandafter\expandafter=%
	\expandafter\expandafter\expandafter{\expandafter\expandafter\expandafter%
		{\expandafter\pgffor@stacktemp\expandafter}\the\pgffor@stack}%
}

\def\pgffor@stackpop{\expandafter\pgffor@@stackpop\the\pgffor@stack\pgffor@stackstop}
\def\pgffor@@stackpop#1#2\pgffor@stackstop{\pgffor@stack{#2}#1}

\def\pgffor@emptyvalues{, \pgffor@stop,}%

\def\pgffor@foreach{%
	\pgffor@atbeginforeach%
	\let\pgffor@assign@before@code=\pgfutil@empty%
	\let\pgffor@assign@after@code=\pgfutil@empty%
	\let\pgffor@assign@once@code=\pgfutil@empty%
	\let\pgffor@remember@code=\pgfutil@empty%
	\let\pgffor@remember@once@code=\pgfutil@empty%
	\pgffor@alphabeticsequencefalse%
	\pgffor@contextfalse%	
	%	
	\let\pgffor@var=\pgfutil@empty
	%
	\pgffor@vars%
}
	
\let\foreach=\pgffor@foreach

\def\pgffor@vars{%
	\pgfutil@ifnextchar i{\pgffor@@vars@end}{%
		\pgfutil@ifnextchar[{\pgffor@@vars@opt}{%]
			\pgfutil@ifnextchar/{\pgffor@@vars@slash@gobble}{%	
				\pgffor@@vars}}}}%
				
\def\pgffor@@vars@end in{\pgfutil@ifnextchar\bgroup{\pgffor@normal@list}{\pgffor@macro@list}}
\def\pgffor@@vars@opt[#1]{\pgfkeys{/pgf/foreach/.cd,#1}\pgffor@vars}
\def\pgffor@@vars#1{\pgffor@var@add#1\pgffor@stop\pgffor@vars}
\def\pgffor@@vars@slash@gobble/{\pgffor@@vars}

\def\pgffor@var@add#1#2\pgffor@stop{%
	\ifx\pgffor@var\pgfutil@empty%
		\def\pgffor@var{#1}%
		\def\pgffor@mainvar{#1}%
	\else%
		\expandafter\def\expandafter\pgffor@var\expandafter{\pgffor@var/#1}%
	\fi%
}

\def\pgffor@macro@list#1{%
  \expandafter\pgffor@normal@list\expandafter{#1}}
\def\pgffor@normal@list#1{%
  \def\pgffor@values{#1, \pgffor@stop,}%
  \ifx\pgffor@values\pgffor@emptyvalues
    \def\pgffor@values{\pgffor@stop,}%
  \fi%
  \let\pgffor@body=\pgfutil@empty%
  \global\pgffor@continuetrue%
  \pgffor@collectbody}
\def\pgffor@collectbody{%
  \pgfutil@ifnextchar\foreach{\pgffor@collectforeach}{%
    \pgfutil@ifnextchar\bgroup{\pgffor@collectargument}{\pgffor@collectsemicolon}}%
}

\def\pgffor@collectforeach\foreach#1in{%
  \pgfutil@ifnextchar\bgroup{\pgffor@collectforeach@normal{#1}}{\pgffor@collectforeach@macro{#1}}}
\def\pgffor@collectforeach@macro#1#2{%
  \expandafter\long\expandafter\def\expandafter\pgffor@body\expandafter{\pgffor@body\foreach#1in#2}%
  \pgffor@collectbody%
}
\def\pgffor@collectforeach@normal#1#2{%
  \expandafter\long\expandafter\def\expandafter\pgffor@body\expandafter{\pgffor@body\foreach#1in{#2}}%
  \pgffor@collectbody%
}
\long\def\pgffor@collectargument#1{%
	\expandafter\pgfutil@in@\expandafter\foreach\expandafter{\pgffor@body}%
	\ifpgfutil@in@%
		\expandafter\long\expandafter\def\expandafter\pgffor@body\expandafter%
  	{\pgffor@body{#1}}%
	\else%
		\expandafter\long\expandafter\def\expandafter\pgffor@body\expandafter%
  	{\pgffor@body#1}%
	\fi%
  \pgffor@iterate%
}

\def\pgffor@collectsemicolon{%
  \let\pgffor@next=\pgffor@collectnormalsemicolon%
  \ifnum\the\catcode`\;=\active\relax%
    \let\pgffor@next=\pgffor@collectactivesemicolon%
  \fi%
  \pgffor@next%
}

\def\pgffor@collectnormalsemicolon#1;{%
  \expandafter\long\expandafter\def\expandafter\pgffor@body\expandafter{\pgffor@body#1;}%
  \pgffor@iterate%
}

{
  \catcode`\;=\active
  
  \gdef\pgffor@collectactivesemicolon#1;{%
    \expandafter\long\expandafter\def\expandafter\pgffor@body\expandafter{\pgffor@body#1;}%
    \pgffor@iterate%
  }
}  

\def\pgffor@iterate{%
  % Must do all of these in case the internal stack is used.
  \let\pgffor@last=\pgfutil@empty%
  \let\pgffor@prevlast=\pgfutil@empty%
  \let\pgffor@dotsend=\pgfutil@empty%
  \let\pgffor@dots@pre=\pgfutil@empty%
  \let\pgffor@dots@post=\pgfutil@empty%
  % 
  \expandafter\pgffor@scan\pgffor@values}

\def\pgffor@stop{\pgffor@stop}%
\def\pgffor@dots{...}%

\def\pgffor@scan{\pgfutil@ifnextchar({\pgffor@scanround}{\pgffor@scanone}}
\def\pgffor@scanround(#1)#2,{\def\pgffor@value{(#1)#2}\pgffor@scanned}
\def\pgffor@scanone#1,{\def\pgffor@value{#1}\pgffor@scanned}


% Check for dots.
\newif\ifpgffor@dots@in@
\def\pgffor@dots@in@#1...#2#3\pgffor@stop{%
	\ifx\pgffor@dots@@#2%
		\pgffor@dots@in@false%
	\else%
		\pgffor@dots@in@true%
	\fi%
}

\def\pgffor@dots@@{\pgffor@dots@@}

\def\pgffor@scanned{%
  \ifx\pgffor@value\pgffor@stop%
    \let\pgffor@next=\pgffor@after% Done!
  \else%
  	% Check for dots. Quicker than \pgfutil@in@ and not suceptable 
		% to false-positives when a token sequence ends in a single full-stop.
  	\expandafter\pgffor@dots@in@\pgffor@value\pgffor@dots@...\pgffor@dots@@\pgffor@stop%
    \ifpgffor@dots@in@%
      \let\pgffor@next=\pgffor@handledots%
    \else%
      \let\pgffor@next=\pgffor@handlevalue%
    \fi%
    \ifpgffor@continue%
    \else%
      \let\pgffor@next=\pgffor@scan% Done!
    \fi%
  \fi%
  \pgffor@next}


\def\pgffor@after{%
  \global\pgffor@continuetrue%
  \pgffor@atendforeach%
  \pgffor@afterhook}
  
\def\pgffor@handlevalue{%
	\let\pgffor@prevlast=\pgffor@last%
  \let\pgffor@last=\pgffor@value%
  \pgffor@invokebody%
  \pgffor@scan%
}

	
\def\pgffor@invokebody{%
	\pgffor@begingroup%
    \expandafter\pgfutil@in@\expandafter/\expandafter{\pgffor@var}%
    \ifpgfutil@in@%
      \expandafter\def\expandafter\pgffor@valuerest\expandafter{\pgffor@value//\relax}%
      \expandafter\pgffor@multiassign\pgffor@var/\pgffor@stop/\pgffor@stop/\relax%
    \else%
      \expandafter\expandafter\expandafter\def\expandafter\pgffor@var\expandafter{\pgffor@value}%
    \fi%
    % Execute assign once code.
    \ifx\pgffor@assign@once@code\pgfutil@empty%
  	\else%
  		\pgffor@assign@once@code%
  	\fi%
    % Execute assign before code.
    \ifx\pgffor@assign@before@code\pgfutil@empty%
    \else%
    	\pgffor@assign@before@code%
    \fi%  
    %  
    \expandafter\expandafter\expandafter\pgffor@reset@hooks\expandafter\pgffor@beginhook\expandafter\pgffor@body\pgffor@endhook%
    % Execute assign after code.
    \ifx\pgffor@assign@after@code\pgfutil@empty%
    \else%
    	\pgffor@assign@after@code%
    \fi%  
    %
  \pgffor@endgroup%
}


\def\pgffor@multiassign#1/#2/\relax{%
  \def\pgffor@currentvar{#1}%
  \def\pgffor@rest{#2}%
  \ifx\pgffor@currentvar\pgffor@stop%
    \let\pgffor@next=\relax%
  \else%
    \let\pgffor@next=\pgffor@multiassignrest%
  \fi%
  \pgffor@next%
}

\def\pgffor@multiassignrest{\expandafter\pgffor@multiassignfinal\pgffor@valuerest}
\def\pgffor@multiassignfinal#1/#2/\relax{%
	\def\pgffor@temp{#1}%
	\ifx\pgffor@currentvar\pgffor@mainvar%
		\ifpgffor@alphabeticsequence%
  		\pgffor@makealphabetic\pgffor@temp%
  	\fi%
  \fi%
  \def\pgffor@test{#2}%
  \ifx\pgffor@test\pgfutil@empty%
  	\expandafter\def\expandafter\pgffor@valuerest\expandafter{\pgffor@temp//\relax}% repeat
  \else%
    \def\pgffor@valuerest{#2/\relax}%
  \fi%
  \expandafter\expandafter\expandafter\def\expandafter\pgffor@currentvar\expandafter{\pgffor@temp}%
	%
  \expandafter\pgffor@multiassign\pgffor@rest/\relax%
}    		

\def\pgffor@gobblespaces#1{\pgfutil@ifnextchar x{#1}{#1}}

\def\pgffor@handledots{%
	\pgffor@gobblespaces{\expandafter\pgffor@@handledots\pgffor@value\pgffor@@stop}%
}

\newif\ifpgffor@context

\def\pgffor@@handledots#1...#2\pgffor@@stop{%
	% Define the context if any.
	\def\pgffor@dots@pre{#1}%
	\def\pgffor@dots@post{#2}%
	\def\pgffor@dots@stripcontext#1##1#2\pgffor@@stop{\def\pgffor@dotsvalue{##1}}%
	\pgffor@contexttrue%
	\ifx\pgffor@dots@pre\pgfutil@empty%
		\ifx\pgffor@dots@post\pgfutil@empty%
			\pgffor@contextfalse%
			\def\pgffor@dots@stripcontext##1\pgffor@@stop{\def\pgffor@dotsvalue{##1}}%
		\fi%
	\fi%
	\pgffor@gobblespaces{\pgffor@dotsscanend}%
}

\def\pgffor@dots@value@process#1{%
	\expandafter\pgffor@dots@stripcontext#1\pgffor@@stop%
	\expandafter\pgffor@dots@charcheck\pgffor@dotsvalue\pgffor@@stop%
  \let#1=\pgffor@dotsvalue% 
}

\def\pgffor@dotsscanend#1,{%
	\pgffor@alphabeticsequencefalse%
	% Strip context and check for a character sequence.
	\def\pgffor@dotsend{#1}%
	\pgffor@dots@value@process{\pgffor@dotsend}% 
  %
  \pgffor@dots@value@process{\pgffor@last}%
  %
  % calculate skip%
  \ifx\pgffor@prevlast\pgfutil@empty%
    \ifdim\pgffor@dotsend pt>\pgffor@last pt%
      \pgffor@skip=1pt%
    \else%
      \pgffor@skip=-1pt%
    \fi%
  \else%
  	\pgffor@dots@value@process{\pgffor@prevlast}%
    \pgffor@skip=\pgffor@last pt%
    \pgffor@iter=\pgffor@prevlast pt%
    \advance\pgffor@skip by-\pgffor@iter%
  \fi%
  \pgffor@iter=\pgffor@last pt%
  % do loop
  \pgffor@loop%
}

\def\pgffor@loop{%
  \advance\pgffor@iter by\pgffor@skip%
  \let\pgffor@next=\pgffor@doloop%
  \ifdim\pgffor@skip<0pt%
    \ifdim\pgffor@iter<\pgffor@dotsend pt%
      \let\pgffor@next=\pgffor@endloop%
    \fi%
  \else%
    \ifdim\pgffor@iter>\pgffor@dotsend pt%
      \let\pgffor@next=\pgffor@endloop%
    \fi%
  \fi%
  \ifpgffor@continue%
  \else%
    \let\pgffor@next=\pgffor@endloop% Done!
  \fi%
  \pgffor@next%
}

\def\pgffor@endloop{%
	\pgffor@alphabeticsequencefalse%
	\pgffor@scan%
}

{\catcode`\p=12\catcode`\t=12\gdef\Pgffor@geT#1pt{#1}}

\def\pgffor@doloop{%
  \pgffor@begingroup
    \edef\pgffor@temp{\expandafter\Pgffor@geT\the\pgffor@iter}%
    \edef\pgffor@incheck{{.0/}{\pgffor@temp/}}%
    \expandafter\pgfutil@in@\pgffor@incheck%
    \ifpgfutil@in@%
      \expandafter\pgffor@strip\pgffor@temp%
    \fi%
    \expandafter\pgfutil@in@\expandafter/\expandafter{\pgffor@var}%
    \ifpgfutil@in@%
      \expandafter\def\expandafter\pgffor@valuerest\expandafter{\pgffor@temp//\relax}%
      \expandafter\pgffor@multiassign\pgffor@var/\pgffor@stop/\pgffor@stop/\relax%
    \else%
    	% Convert to alphabetic sequence, if necessary.
    	\ifpgffor@alphabeticsequence%
    		\pgffor@makealphabetic\pgffor@temp%
    		\expandafter\let\pgffor@var=\pgffor@temp%    						
    	\else%
    		\expandafter\expandafter\expandafter\def\expandafter\pgffor@var\expandafter{\pgffor@temp}%
      \fi%
    \fi%
    % Insert any context, if any.
    \ifpgffor@context%
      \let\pgffor@temp=\pgffor@dots@pre%
	    \expandafter\pgfutil@append@macrotomacro\expandafter%
	    	{\expandafter\pgffor@temp\expandafter}\expandafter{\pgffor@var}%
	    \expandafter\pgfutil@append@macrotomacro\expandafter%
	    	{\expandafter\pgffor@temp\expandafter}\expandafter{\pgffor@dots@post}%
	    \expandafter\let\pgffor@var=\pgffor@temp%
	  \fi%
	  % Perform assignments before loop body.
	  \ifx\pgffor@assign@before@code\pgfutil@empty%
    \else%
    	\pgffor@assign@before@code%
    \fi% 
    %  
    \expandafter\expandafter\expandafter\pgffor@reset@hooks\expandafter\pgffor@beginhook\expandafter\pgffor@body\pgffor@endhook%
    %
    % Perform assignments after loop body.
	  \ifx\pgffor@assign@after@code\pgfutil@empty%
    \else%
    	\pgffor@assign@after@code%
    \fi% 
  \pgffor@endgroup%
  \pgffor@loop%  
}

\def\pgffor@strip#1.0{\def\pgffor@temp{#1}}

\def\breakforeach{\global\pgffor@continuefalse}
  
\def\pgffor@gobbletil@pgffor@@stop#1\pgffor@@stop{}


\newif\ifpgffor@registeriscount

\def\pgffor@ifcsregister#1{%
	\expandafter\pgffor@@ifcsregister\meaning#1\pgffor@stop}

\def\pgffor@@ifcsregister#1#2#3#4#5\pgffor@stop{%
	\if#1m% It is an ordinary (m)acro.
		\pgffor@registeriscountfalse%
		\let\pgffor@csnext=\pgfutil@secondoftwo%
	\else%
		\if#1u% It is (u)ndefined.
			\let\pgffor@csnext=\pgfutil@secondoftwo%
			\pgffor@registeriscountfalse%
		\else%
			\let\pgffor@csnext=\pgfutil@firstoftwo%
			\if#4u% It is a co(u)nt
				\pgffor@registeriscounttrue%
			\else% Assume it is a dimen or skip (bad assumption in the general case).
				\pgffor@registeriscountfalse%
				\let\pgffor@csnext=\pgfutil@firstoftwo%
			\fi%
		\fi%
	\fi%
	\pgffor@csnext}
	
\newif\ifpgffor@alphabeticsequence

% 
\def\pgffor@dots@charcheck#1\pgffor@@stop{%
  \edef\pgffor@dots@charcheck@temp{#1}%
  \expandafter\expandafter\expandafter\pgffor@@dotscharcheck\expandafter\meaning\pgffor@dots@charcheck@temp\pgffor@@stop%
}
\def\pgffor@@dotscharcheck#1#2\pgffor@@stop{%
	\if#1t%
  	\afterassignment\pgffor@gobbletil@pgffor@@stop%	
	  \expandafter\chardef\expandafter\pgffor@char\expandafter=\expandafter`\pgffor@dots@charcheck@temp\relax\pgffor@@stop%
	  \edef\pgffor@char{\the\pgffor@char}%
	  \ifnum\pgffor@char>64\relax% From A-Z?
	    \ifnum\pgffor@char<91\relax%
	      \let\pgffor@dotsvalue=\pgffor@char%
	      \pgffor@alphabeticsequencetrue%		
	    \else%
	      \ifnum\pgffor@char>96\relax% From a-z?
	        \ifnum\pgffor@char<123\relax%
	          \let\pgffor@dotsvalue=\pgffor@char%
	          \pgffor@alphabeticsequencetrue%	
	        \fi%
	      \fi%
	    \fi%
	  \fi%
	\fi%
}

\def\pgffor@makealphabetic#1{%
	% Convert the number in the macro passed as #1 to a-z or A-Z.
	\pgfutil@tempcnta=#1\relax%
	\ifnum\pgfutil@tempcnta>95\relax%
		\advance\pgfutil@tempcnta by-96\relax%
		\edef#1{\pgffor@alpha\pgfutil@tempcnta}%   		
	\else%
		\advance\pgfutil@tempcnta by-64 %
		\edef#1{\pgffor@Alpha\pgfutil@tempcnta}%    						
	\fi%
}

\def\pgffor@Alpha#1{%
	\ifcase#1\relax\or A\or B\or C\or D\or E\or F\or G\or H\or I\or J\or K\or L\or M%
	\or N\or O\or P\or Q\or R\or S\or T\or U\or V\or W\or X\or Y\or Z\else?\fi%
}

\def\pgffor@alpha#1{%
	\ifcase#1\relax\or a\or b\or c\or d\or e\or f\or g\or h\or i\or j\or k\or l\or m%
	\or n\or o\or p\or q\or r\or s\or t\or u\or v\or w\or x\or y\or z\else?\fi%
}

\newtoks\pgffor@toks

\def\pgffor@addcstotoks#1{%
	\expandafter\def\expandafter\pgffor@tokstemp\expandafter{\expandafter\def\expandafter#1\expandafter{#1}}%
	\pgffor@@addcstotoks}

\def\pgffor@addregtotoks#1{%
	\expandafter\def\expandafter\pgffor@tokstemp\expandafter{\expandafter#1\expandafter=\the#1}%
	\pgffor@@addcstotoks}

\def\pgffor@addiftotoks#1{%
	\begingroup%
		\escapechar=-1\relax%
			\expandafter\pgffor@@addiftotoks\string#1\pgffor@stop}
\def\pgffor@@addiftotoks#1#2#3#4\pgffor@stop{%
	\endgroup
	\csname if#3#4\endcsname%
		\expandafter\def\expandafter\pgffor@tokstemp\expandafter{\csname#3#4true\endcsname}%
	\else%
		\expandafter\def\expandafter\pgffor@tokstemp\expandafter{\csname#3#4false\endcsname}%
	\fi%
	\pgffor@@addcstotoks%
}

\def\pgffor@@addcstotoks{%
	\expandafter\expandafter\expandafter\pgffor@toks\expandafter\expandafter\expandafter=%
	\expandafter\expandafter\expandafter{\expandafter\pgffor@tokstemp\the\pgffor@toks}%
}

% Set up the pgffor scopes.

\def\pgffor@atbeginforeach{%
	\begingroup%
}

\def\pgffor@atendforeach{%
		\global\edef\pgffor@remember@expanded{\pgffor@remember@code}%
  \endgroup%
  \ifx\pgffor@remember@expanded\pgfutil@empty%
  \else%
  	\pgffor@remember@expanded%
  	\global\let\pgffor@remember@expanded=\pgfutil@empty%
  \fi%
}
\def\pgffor@default@begingroup{%
	\begingroup%
}

\let\pgffor@remember@once@expanded=\pgfutil@empty
\let\pgffor@remember@expanded=\pgfutil@empty

\def\pgffor@default@endgroup{%
   \ifx\pgffor@remember@once@code\pgfutil@empty
   \else
     \xdef\pgffor@remember@once@expanded{\pgffor@remember@once@code}%
   \fi
   \ifx\pgffor@remember@code\pgfutil@empty
   \else
     \xdef\pgffor@remember@expanded{\pgffor@remember@code}%
   \fi
 \endgroup
 %
 \ifx\pgffor@remember@once@expanded\pgfutil@empty
 \else
   \pgffor@remember@once@expanded%
   % \let\pgffor@assign@once@code=\pgfutil@empty % Not needed anymore? (CJ)
   \global\let\pgffor@remember@once@expanded=\pgfutil@empty
 \fi
 \ifx\pgffor@assign@once@code\pgfutil@empty
 \else
   \global\let\pgffor@assign@once@code=\pgfutil@empty
 \fi
 %
 \ifx\pgffor@remember@expanded\pgfutil@empty
 \else
   \pgffor@remember@expanded%
   \global\let\pgffor@remember@expanded=\pgfutil@empty
 \fi
}

\let\pgffor@begingroup=\pgffor@default@begingroup
\let\pgffor@endgroup=\pgffor@default@endgroup

	
\def\pgffor@stack@begingroup{%
	\pgffor@toks={}%
	\pgffor@addcstotoks{\pgffor@mainvar}%
	\pgffor@addcstotoks{\pgffor@var}%
	\pgffor@addcstotoks{\pgffor@body}%
	%
	\pgffor@addcstotoks{\pgffor@last}%
	\pgffor@addcstotoks{\pgffor@prevlast}%
	\pgffor@addcstotoks{\pgffor@dotsend}%
	%
	\pgffor@addcstotoks{\pgffor@assign@before@code}%
	\pgffor@addcstotoks{\pgffor@assign@after@code}%
	\pgffor@addcstotoks{\pgffor@remember@code}%
	\pgffor@addcstotoks{\pgffor@remember@once@code}%
	\pgffor@addcstotoks{\pgffor@dots@pre}%
	\pgffor@addcstotoks{\pgffor@dots@post}%
	%
	\pgffor@addregtotoks{\pgffor@iter}%
	\pgffor@addregtotoks{\pgffor@skip}%
	%
	\pgffor@addiftotoks{\ifpgffor@alphabeticsequence}%
	\pgffor@addiftotoks{\ifpgffor@context}%
	\expandafter\pgffor@stackpush\expandafter{\the\pgffor@toks}%
}

\def\pgffor@stack@endgroup{\pgffor@stackpop}

% Keys stuff.

\newif\ifpgffor@assign@evaluate
\newif\ifpgffor@assign@once

\pgfkeys{/pgf/foreach/.cd,
	var/.code=\pgffor@var@add#1\pgffor@stop,
	scope iterations/.code={
		\csname if#1\endcsname%
			\let\pgffor@begingroup=\pgffor@default@begingroup%
			\let\pgffor@endgroup=\pgffor@default@endgroup%
		\else%
			\let\pgffor@begingroup=\pgffor@stack@begingroup%
			\let\pgffor@endgroup=\pgffor@stack@endgroup%	
		\fi%
	},
	evaluate/.code=\pgffor@assign@evaluatetrue\pgffor@assign@oncefalse\pgffor@assign@parse{#1},%
	assign/.code=\pgffor@assign@evaluatefalse\pgffor@assign@oncefalse\pgffor@assign@parse{#1},%
	evaluate once/.code=\pgffor@assign@evaluatetrue\pgffor@assign@oncetrue\pgffor@assign@parse{#1},%
	assign once/.code=\pgffor@assign@evaluatefalse\pgffor@assign@oncetrue\pgffor@assign@parse{#1},%
	remember/.code=\pgffor@remember@parse{#1},%
	count/.code=\pgffor@count@parse#1\pgffor@stop
}

\def\pgffor@assign@parse#1{%
	\pgfutil@in@;{#1}%
	\ifpgfutil@in@%
	\else%
		\pgfutil@in@={#1}%
	\fi%
	\ifpgfutil@in@%
		\pgffor@assign@@parse#1;\pgffor@stop;%
	\else%
		\pgffor@assign@parse@old#1\pgffor@stop%%
	\fi%
}

\def\pgffor@stop{\pgffor@stop}
\def\pgffor@assign@@parse#1;{%
	\def\pgffor@test{#1}%
	\ifx\pgffor@test\pgffor@stop%
		\let\pgffor@next=\relax%
	\else%
		\let\pgffor@next=\pgffor@assign@@parse%
		\ifx\pgffor@test\pgfutil@empty%
		\else%
			\pgfutil@in@={#1}%
			\ifpgfutil@in@%
				\pgffor@assign@@@parse#1\pgffor@stop%
			\else%
				\pgffor@assign@@@parse#1=#1\pgffor@stop%
			\fi%
		\fi%
	\fi%
	\pgffor@next}
	
\def\pgffor@assign@@@parse#1=#2\pgffor@stop{%
	\ifpgffor@assign@evaluate%
		\ifpgffor@assign@once%
			\pgfutil@append@tomacro{\pgffor@assign@once@code}{\pgfmathparse{#2}\let#1=\pgfmathresult}%
			\pgfutil@append@tomacro{\pgffor@remember@once@code}{\noexpand\def\noexpand#1{#2}}%
		\else
			\pgfutil@append@tomacro{\pgffor@assign@before@code}{\pgfmathparse{#2}\let#1=\pgfmathresult}%
		\fi%
	\else%
		\ifpgffor@assign@once%
			\pgfutil@append@tomacro{\pgffor@assign@once@code}{\def#1{#2}}%
			\pgfutil@append@tomacro{\pgffor@remember@once@code}{\noexpand\def\noexpand#1{#2}}%
		\else
			\pgfutil@append@tomacro{\pgffor@assign@before@code}{\def#1{#2}}%
		\fi%
	\fi%
}

\def\pgffor@assign@parse@old#1#2\pgffor@stop{%
	\pgffor@assign@@parse@old#2\pgffor@stop as#1using #1\pgffor@@stop}

\def\pgffor@assign@@parse@old#1as#2#3\pgffor@@stop{%
	\pgffor@assign@@@parse@old{#2}#1#3\pgffor@stop\pgffor@@stop}

\def\pgffor@assign@@@parse@old#1#2using #3\pgffor@stop#4\pgffor@@stop{%
	\pgffor@assign@@@parse#1=#3\pgffor@stop}
	


\def\pgffor@remember@parse#1{%
	\pgfutil@in@ a{#1}% This matches the 'a' in 'as' or 'intially'.
	\ifpgfutil@in@%
		\pgffor@remember@parse@old#1\pgffor@stop%
	\else%
		\pgffor@remember@@parse#1;\pgffor@stop;%
	\fi%
}

\def\pgffor@remember@@parse#1;{%
	\def\pgffor@test{#1}%
	\ifx\pgffor@test\pgffor@stop%
		\let\pgffor@next=\relax%
	\else%
		\let\pgffor@next=\pgffor@remember@@parse%
		\ifx\pgffor@test\pgfutil@empty%
		\else%
			\pgfutil@in@={#1}%
			\ifpgfutil@in@%
				\pgffor@remember@@@parse#1\pgffor@stop%
			\else%
				\pgffor@ifcsregister{#1}{%
					\pgfutil@append@tomacro{\pgffor@remember@code}{\noexpand#1=\the#1\noexpand\relax}%			
				}%
				{%
					\pgfutil@append@tomacro{\pgffor@remember@code}{\noexpand\def\noexpand#1{#1}}%
				}%
			\fi%
		\fi%
	\fi%
	\pgffor@next%
}

\def\pgffor@remember@@@parse#1=#2\pgffor@stop{%
	\pgffor@ifcsregister{#2}{%
		\pgfutil@append@tomacro{\pgffor@assign@after@code}{\expandafter\def\expandafter#1\expandafter{\the#2}}%
		\pgfutil@append@tomacro{\pgffor@remember@code}{\noexpand\def\noexpand#1{#1}}%			
	}%
	{%
		\pgfutil@append@tomacro{\pgffor@assign@after@code}{\expandafter\def\expandafter#1\expandafter{#2}}%
		\pgfutil@append@tomacro{\pgffor@remember@code}{\noexpand\def\noexpand#1{#1}}%
	}%
}

\def\pgffor@remember@parse@old#1#2\pgffor@stop{%
	\pgffor@remember@@parse@old#1#2\pgffor@stop as#1(initially )\pgffor@@stop}

\def\pgffor@remember@@parse@old#1#2as#3#4\pgffor@@stop{%
	\pgffor@remember@@@parse@old{#1}{#3}#2#4\pgffor@stop\pgffor@@stop}

\def\pgffor@remember@@@parse@old#1#2#3(initially #4)#5\pgffor@stop#6\pgffor@@stop{%
	\pgfutil@append@tomacro{\pgffor@assign@after@code}{\edef#2{#1}}%
	\pgfutil@append@tomacro{\pgffor@remember@code}{\noexpand\def\noexpand#2{#2}}%
	\def\pgffor@test{#4}%
	\ifx\pgffor@test\pgfutil@empty%
	\else%
		\pgfutil@append@tomacro{\pgffor@assign@once@code}{\def#2{#4}}%
	\fi%
}

\def\pgffor@count@parse#1#2\pgffor@stop{%
	\pgffor@count@@parse#1#2\pgffor@stop from 1\pgffor@stop\pgffor@@stop}

\def\pgffor@count@@parse#1#2from#3\pgffor@stop#4\pgffor@@stop{%
	\pgfutil@append@tomacro\pgffor@remember@code{\noexpand\def\noexpand#1{#1}}%
	\pgfutil@append@tomacro\pgffor@assign@before@code{\pgfmathparse{int(#1+1)}\let#1=\pgfmathresult}%
	\pgfmathparse{int(#3-1)}\let#1=\pgfmathresult%
}


\def\pgfutil@append@macrotomacro#1#2{%
	\expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter%
		#1\expandafter\expandafter\expandafter{\expandafter#1#2}}

\def\pgfutil@append@tomacro#1#2{%
	\expandafter\def\expandafter#1\expandafter{#1#2}}
	

\endinput

pgfkeys.code.tex
% Copyright 2007 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.


% The files pgfkeys.code.tex and pgfkeysfiltered.code.tex are
% perfectly self-contained, except that the catcode of @ 
% should be made a letter. 


% Guard against reading twice
\ifx\pgfkeysloaded\undefined
  \let\pgfkeysloaded=\relax
\else
  \expandafter\endinput
\fi
  
% The purpose of this file is to provide a general settings engine that 
% works with all TeX formats and has no save-stack impact


% This is useful:
\newif\ifpgfkeys@csname@test%

\def\pgfkeys@ifcsname#1\endcsname#2\else#3\fi{%
  \pgfkeys@csname@testfalse%
  \expandafter\ifx\csname#1\endcsname\relax\else\expandafter\ifx\csname#1\endcsname\@undefined\else\pgfkeys@csname@testtrue\fi\fi%
  \ifpgfkeys@csname@test#2\else#3\fi%
}%

\ifx\eTeXrevision\undefined%
\else%
  \expandafter\let\expandafter\pgfkeys@ifcsname\csname ifcsname\endcsname%
\fi

\def\pgfkeys@empty{}

% This also:

\ifx\PackageError\undefined
  \def\pgfkeys@error#1{\errmessage{Package pgfkeys Error: #1.}}%
\else
  \def\pgfkeys@error#1{\PackageError{pgfkeys}{#1}{}}%
\fi

% Set a key to a value
%
% #1 = key
% #2 = tokens
%
% Description:
%
% This command sets the key to the given tokens. The tokens are stored as
% is and can even contain things like #9. 
%
% Keys are organized hierarchically using something similar to Unix
% paths. Thus, a typically key might be called "/tikz/length" or
% "/tikz/length dimension/.@cmd". Some keys starting with a dot are
% special, so they should not be used as normal key names (they are
% similar to Unix files starting with a dot -- you can use them, but
% be careful).
%
% Keys are always local to the current TeX group.
%
% Example:
%
% \pgfkeyssetvalue{/tikz/length}{2cm-3cm}
% \pgfkeyssetvalue{/algo/swap}{{#2}{#1}}

\long\def\pgfkeyssetvalue#1#2{%
  \pgfkeys@temptoks{#2}\expandafter\edef\csname pgfk@#1\endcsname{\the\pgfkeys@temptoks}%
}



% Add text to a key at the end
%
% #1 = key
% #2 = a value to be added at the beginning
% #3 = a value to be added at the end
%
% Description:
%
% This command adds #2 to the definition of the key. The key should
% have been set previously using \pgfkeyssetvalue.
%
% Example:
%
% \pgfkeysaddvalue{/tikz/length}{}{-3cm}

\long\def\pgfkeysaddvalue#1#2#3{%
  {%
    \toks0{#2}%
    \pgfkeysifdefined{#1}
    {\pgfkeys@temptoks\expandafter\expandafter\expandafter{\csname pgfk@#1\endcsname}}%
    {\pgfkeys@temptoks{}}%
    \toks1{#3}%
    \xdef\pgfkeys@global@temp{\the\toks0 \the\pgfkeys@temptoks \the\toks1}% believe or don't: the spaces are important
  }%
  \pgfkeyslet{#1}\pgfkeys@global@temp%
}



% Makes a key equal a given code
%
% #1 = key
% #2 = a code name
%
% Description:
%
% This command executes a \let command so that a key gets the same
% value as the parameter #2.
%
% Keys are always local to the current TeX group.
%
% Example:
%
% \pgfkeyslet{/algo/swap}{\myswap}

\def\pgfkeyslet#1#2{%
  \expandafter\let\csname pgfk@#1\endcsname#2%
}


% Retrieve the code stored in a key into a code
%
% #1 = key
% #2 = code
%
% Description:
%
% This command will set #2 to "point" to the value stored in the key.
%
% Example:
%
% \pgfkeysgetvalue{/tikz/swap}{\myswap}

\def\pgfkeysgetvalue#1#2{\expandafter\let\expandafter#2\csname pgfk@#1\endcsname}



% Retrieve the value stored in a key
%
% #1 = key
%
% Description:
%
% This command will expand to the value stored in the key. The key
% should previously have been set using \pgfkeyasetkey or \pgfkeyslet. 
%
% Example:
%
% The length is \pgfkeysvalue{/tikz/length}.

\def\pgfkeysvalueof#1{\csname pgfk@#1\endcsname}



% If for testing whether a key exists
%
% #1 = key
% #2 = if-case
% #3 = else-case
%
% Description:
%
% This if will be executed if the key exists. In eTeX mode this works
% like a normal if, in normal TeX mode you need to provide an \else.
%
% Example:
%
% \pgfkeysifdefined{/tikz/length}{key exists}{does not exist}

\long\def\pgfkeysifdefined#1#2#3{\pgfkeys@ifcsname pgfk@#1\endcsname#2\else#3\fi}

% Tests whether a key is assignable. For standard keys which just
% store their value, this is identical to \pgfkeysifdefined.
%
% But \pgfkeysifassignable is true for command keys as well (but not
% for handled keys).
\long\def\pgfkeysifassignable#1#2#3{%
  \pgfkeysifdefined{#1}%
    {#2}
  {\pgfkeysifdefined{#1/.@cmd}%
    {#2}%
    {#3}}%
}%



% Execute settings
%
% #1 = list of settings
%
% Description:
%
% The list of settings should contain comma-separated settings. Each
% setting has the following form:
%
% /path/key=value
%
% The parts "/path/" and "=value" are optional. When the path is not
% specified, the value of the token register "\pgfkeypath" is used. If
% "=value" is missing, the value of the setting "/path/key/.@def" is used
% instead. If this key is set to "\pgfvaluerequired", the key
% "/errors/value required/.@cmd" is executed. Theis error handler,
% like all other error handlers, will get the current key as its first
% parameter (unexpanded) and the current value as its second value
% (also unexpanded).
%
% Any spaces at the beginning and at the end and around the
% equals-sign are removed. The key with the complete path is set to
% the code \pgfcurrentkey.
%
% The setting is then processed according to the following rules:
%
% 1) If the key /path/key/.@cmd" is present, its code is executed
%    with the value computed above, followed by \pgfeov (end of
%    value). So, to handle
%
%    "/stuff/height=  1.5 ,"
%
%    /stuff/height/.@cmd should be set to some code, that can
%    handle the parameter
%
%    "1.5\pgfeov"
%
%    For instance, saying
%
%    \pgfkeys{/stuff/height/.@cmd}{#1\pgfeov}{\def\myheight{#1}}
%
%    will do nicely.
%
% 2) Otherwise, if the key /path/key is present, this key is
%    set to the value computed above.
%
% 3) Otherwise, if the key /handlers/key/.@cmd is present, it is executed
%    with the same parameters as in 1). Additionally, the
%    token register \pgfcurrentkeypath will be set to "/path/" and the
%    macor \pgfcurrentkeywithoutpath to "key". So, in the above
%    example if neither "/stuff/height/.@cmd" nor
%    "/stuff/height" is present, but "/handlers/height" is,
%    then "/handlers/height" is executed with the parameters:
%
%    "1.5\pgfeov"
%
%    and \pgfcurrentkey is set to "/stuff/height" and \pgfcurrentkeypath
%    is set to "/stuff/" and \pgfcurrentkeywithoutpath to "height".
%
% 4) Otherwise, if the key "/path/.unknown/.@cmd" is present, its code is
%    executed with the same parameters as in 3).
%
% 5) Otherwise, the key "/handlers/.unknown/.@cmd" is executed with the same
%    parameters as in 1).
%
% After all settings have been processed, the value of the token
% register \pgfdefaultkeypath is set to its original value. Thus, any local
% change of this token register has no effect outside the call.
%
% Example:
%
% \pgfkeys{/tikz/.is family}
% \pgfkeys{/tikz/line width/.cd,
%         .def=\pgfsetlinewidth{##1},
%         .set default=.4pt}
% \pgfkeys{tikz,line width=1pt}

\newtoks\pgfkeys@pathtoks
\def\pgfkeyscurrentpath{\the\pgfkeys@pathtoks}
\newtoks\pgfkeys@temptoks

\def\pgfkeys@root{/}
\let\pgfkeysdefaultpath\pgfkeys@root

\def\pgfkeys{\expandafter\pgfkeys@@set\expandafter{\pgfkeysdefaultpath}}%
\long\def\pgfkeys@@set#1#2{%
  \let\pgfkeysdefaultpath\pgfkeys@root%
  \pgfkeys@parse#2,\pgfkeys@mainstop%
  \def\pgfkeysdefaultpath{#1}}

\def\pgfkeys@parse{\futurelet\pgfkeys@possiblerelax\pgfkeys@parse@main}
\def\pgfkeys@parse@main{%
  \ifx\pgfkeys@possiblerelax\pgfkeys@mainstop%
    \expandafter\pgfkeys@cleanup%
  \else%
    \expandafter\pgfkeys@normal%
  \fi%
}
\newif\ifpgfkeys@syntax@handlers
\def\pgfkeys@normal{%
  \ifpgfkeys@syntax@handlers%
    \expandafter\pgfkeys@syntax@handlers%
  \else%
    \expandafter\pgfkeys@@normal%
  \fi%
}
\def\pgfkeys@syntax@handlers{\pgf@keys@utilifnextchar\relax\pgfkeys@syntax@@handlers\pgfkeys@syntax@@handlers}%get rid of spaces
\def\pgfkeys@syntax@@handlers{\futurelet\pgfkeys@first@char\pgfkeys@syntax@handlers@test}
\def\pgfkeys@syntax@handlers@test{%
  \pgfkeysgetvalue{/handlers/first char syntax/\meaning\pgfkeys@first@char}\pgfkeys@the@handler%
  \ifx\pgfkeys@the@handler\relax%
    \expandafter\pgfkeys@@normal%
  \else%
    \expandafter\pgfkeys@use@handler%
  \fi%
}
\long\def\pgfkeys@use@handler#1,{%
  \pgfkeys@the@handler{#1}%
  \pgfkeys@parse%
}

\long\def\pgfkeys@@normal#1,{%
  \pgfkeys@unpack#1=\pgfkeysnovalue=\pgfkeys@stop%
  \pgfkeys@parse%
}
\def\pgfkeys@cleanup\pgfkeys@mainstop{}

\def\pgfkeys@mainstop{\pgfkeys@mainstop} % equals only itself
\def\pgfkeys@novalue{} 
\def\pgfkeysnovalue{\pgfkeys@novalue} % equals only itself
\def\pgfkeysnovalue@text{\pgfkeysnovalue}
\def\pgfkeysvaluerequired{\pgfkeysvaluerequired} % equals only itself

\long\def\pgfkeys@unpack#1=#2=#3\pgfkeys@stop{%
  \pgfkeys@spdef\pgfkeyscurrentkey{#1}%
  \edef\pgfkeyscurrentkey{\pgfkeyscurrentkey}%
  \ifx\pgfkeyscurrentkey\pgfkeys@empty%
    % Skip
  \else%
    \pgfkeys@add@path@as@needed%
    \pgfkeys@spdef\pgfkeyscurrentvalue{#2}%
    \ifx\pgfkeyscurrentvalue\pgfkeysnovalue@text% Hmm... no value
      \pgfkeysifdefined{\pgfkeyscurrentkey/.@def}%
      {\pgfkeysgetvalue{\pgfkeyscurrentkey/.@def}{\pgfkeyscurrentvalue}}
      {}% no default, so leave it
    \fi%
    \ifx\pgfkeyscurrentvalue\pgfkeysvaluerequired%
      \def\pgf@marshal{\pgfkeysvalueof{/errors/value required/.@cmd}}%
      \expandafter\pgf@marshal\expandafter{\pgfkeyscurrentkey}{}\pgfeov%
    \else%
      \pgfkeys@case@one%
    \fi%
  \fi}

\def\pgfkeys@case@one{%
  \pgfkeysifdefined{\pgfkeyscurrentkey/.@cmd}%
  {\pgfkeysgetvalue{\pgfkeyscurrentkey/.@cmd}{\pgfkeys@code}%
   \expandafter\pgfkeys@code\pgfkeyscurrentvalue\pgfeov}
  {\pgfkeys@case@two}%
}

\def\pgfkeys@case@two{%
  \pgfkeysifdefined{\pgfkeyscurrentkey}%
  {\pgfkeys@case@two@extern}%
  {\pgfkeys@case@three}%
}

\def\pgfkeys@case@two@extern{%
  \ifx\pgfkeyscurrentvalue\pgfkeysnovalue@text%
    \pgfkeysvalueof{\pgfkeyscurrentkey}%
  \else%
    \pgfkeyslet{\pgfkeyscurrentkey}\pgfkeyscurrentvalue%
  \fi%
}


% either handled key or unknown.
%
% This macro will be replaced by the /handler config/handle only existing
% configuration, see below.
\def\pgfkeys@case@three{%
  \pgfkeys@split@path%
  \pgfkeysifdefined{/handlers/\pgfkeyscurrentname/.@cmd}%
  {\pgfkeysgetvalue{/handlers/\pgfkeyscurrentname/.@cmd}{\pgfkeys@code}%
    \expandafter\pgfkeys@code\pgfkeyscurrentvalue\pgfeov}
  {\pgfkeys@unknown}%
}
\let\pgfkeys@case@three@handleall=\pgfkeys@case@three
\def\pgfkeys@case@three@handle@restricted{%
  \pgfkeys@split@path%
  \pgfkeysifdefined{/handlers/\pgfkeyscurrentname/.@cmd}{%
    \pgfkeys@ifexecutehandler{%
    \pgfkeysgetvalue{/handlers/\pgfkeyscurrentname/.@cmd}{\pgfkeys@code}%
      \expandafter\pgfkeys@code\pgfkeyscurrentvalue\pgfeov
  }{%
      % this here is necessary:  /my search path/key/.code
      % won't be called, so \pgfkeyscurrentpath == '/my search path/key'
      % -> it should be one directory higher! We want to invoke the
    %  .unknown handler in
    % '/my search path'
    %
    % Idea:
    % set 
    % - path := '/my search path'
    % - name := 'key/.code'
    % - key = '/my search path/key/.code'
    \let\pgfkeys@temp=\pgfkeyscurrentkey
    \let\pgfkeys@tempb=\pgfkeyscurrentname
      \edef\pgfkeyscurrentkey{\pgfkeyscurrentpath}%
      \pgfkeys@split@path%
    \let\pgfkeyscurrentkey=\pgfkeys@temp
    \edef\pgfkeyscurrentname{\pgfkeyscurrentname/\pgfkeys@tempb}%
      \pgfkeys@unknown
  }%
  }{%
    \pgfkeys@unknown
  }%
}

% this macro is to implement the |handly only existing| key in key filtering:
% #1: the code to invoke IF the key handler shall be executed
% #2: the code to invoke if it shall not run.
\def\pgfkeys@ifexecutehandler#1#2{#1}%
\let\pgfkeys@ifexecutehandler@handleall=\pgfkeys@ifexecutehandler
\def\pgfkeys@ifexecutehandler@handleonlyexisting#1#2{%
  \pgfkeys@ifcsname pgfk@excpt@\pgfkeyscurrentname\endcsname%
     #1% ok, this particular key handler is known and should be processed in any case (for example .try)
  \else
     % implement the 'only existing' feature here:
     \pgfkeysifdefined{\pgfkeyscurrentpath}{#1}{%
    \pgfkeysifdefined{\pgfkeyscurrentpath/.@cmd}{#1}{#2}%
     }{}%
  \fi%
}%
\def\pgfkeys@ifexecutehandler@handlefullorexisting#1#2{%
  \ifpgfkeysaddeddefaultpath
    \pgfkeys@ifcsname pgfk@excpt@\pgfkeyscurrentname\endcsname%
       #1% ok, this particular key handler is known and be processed in any case (for example .try)
    \else
       % implement the 'only existing' feature here:
       \pgfkeysifdefined{\pgfkeyscurrentpath}{%
         #1%
       }{%
         \pgfkeysifdefined{\pgfkeyscurrentpath/.@cmd}{%
           #1%
         }{%
           #2%
         }%
       }%
    \fi%
  \else
    #1% ok, always true if the USER explicitly provided the full key path.
  \fi
}%
\def\pgfkeysaddhandleonlyexistingexception#1{\expandafter\def\csname pgfk@excpt@#1\endcsname{1}}%

\def\pgfkeys@unknown{%
  \pgfkeysifdefined{\pgfkeyscurrentpath/.unknown/.@cmd}%
  {%
    \pgfkeysgetvalue{\pgfkeyscurrentpath/.unknown/.@cmd}{\pgfkeys@code}%
    \expandafter\pgfkeys@code\pgfkeyscurrentvalue\pgfeov}
  {%
    \pgfkeysgetvalue{/handlers/.unknown/.@cmd}{\pgfkeys@code}%
    \expandafter\pgfkeys@code\pgfkeyscurrentvalue\pgfeov%
  }%
}


\long\def\pgfkey@argumentisspace#1{%
  \long\def\pgfkeys@spdef##1##2{%
    \futurelet\pgfkeys@possiblespace\pgfkeys@sp@a##2\pgfkeys@stop\pgfkeys@stop#1\pgfkeys@stop\relax##1}%
  \def\pgfkeys@sp@a{%
    \ifx\pgfkeys@possiblespace\pgfkeys@sptoken%
      \expandafter\pgfkeys@sp@b%
    \else%
      \expandafter\pgfkeys@sp@b\expandafter#1%
    \fi}%
  \long\def\pgfkeys@sp@b#1##1 \pgfkeys@stop{\pgfkeys@sp@c##1}%
}
\pgfkey@argumentisspace{ }
\long\def\pgfkeys@sp@c#1\pgfkeys@stop#2\relax#3{\pgfkeys@temptoks{#1}\edef#3{\the\pgfkeys@temptoks}}
{\def\:{\global\let\pgfkeys@sptoken= } \: }



\def\pgfkeys@add@path@as@needed{% Should add the path if the
  % \pgfkeyscurrentkey does not start with /
  \expandafter\futurelet\expandafter\pgfkeys@possibleslash\expandafter\pgfkeys@check@slash\pgfkeyscurrentkey\relax%
}
\newif\ifpgfkeysaddeddefaultpath
\def\pgfkeys@check@slash{%
  \ifx\pgfkeys@possibleslash/%
    \expandafter\pgfkeys@nevermind%
  \else%
    \expandafter\pgfkeys@addpath%
  \fi%
}

\def\pgfkeys@nevermind#1\relax{%
  \pgfkeysaddeddefaultpathfalse
  \let\pgfkeyscurrentkeyRAW\pgfkeyscurrentkey
}
\def\pgfkeys@addpath#1\relax{%
  \pgfkeysaddeddefaultpathtrue
  \def\pgfkeyscurrentkeyRAW{#1}%
  \edef\pgfkeyscurrentkey{\pgfkeysdefaultpath#1}%
}


\def\pgfkeys@split@path{% Should assign the two codes
                       % \pgfkeyscurrentname and \pgfcurrentlkeypath
  \pgfkeys@pathtoks{}%
  \expandafter\pgfkeys@splitter\pgfkeyscurrentkey//%
}
\def\pgfkeys@splitter#1/#2/{%
  \def\pgfkeys@temp{#2}%
  \ifx\pgfkeys@temp\pgfkeys@empty%
    % Ah. done
    \def\pgfkeyscurrentname{#1}%
    \expandafter\pgfkeys@gobbletoslash%
  \else%
    \expandafter\pgfkeys@pathtoks\expandafter{\the\pgfkeys@pathtoks#1/}%
  \fi%
  \pgfkeys@splitter#2/%
}
\def\pgfkeys@gobbletoslash\pgfkeys@splitter/{\expandafter\pgfkeys@remove@slash\the\pgfkeys@pathtoks\relax}%
\def\pgfkeys@remove@slash#1/\relax{\pgfkeys@pathtoks{#1}}



% Quickly set keys
%
% #1 = default path
% #2 = key-value pairs
%
% Desscription:
%
% This command starts the execution with the default path set to
% #1. This command should only be used when speed is important (like
% in a heavily used macro like \tikzset). Normally, keys should be
% used to set the path. Note that if #1 equals /, then \pgfkeys will
% actually be quicker!
%
% Example:
%
% \pgfqkeys{/tikz}{myother length/.code=\def\myotherlength{#1}\pgfkeysalso{length=#1}}

\def\pgfqkeys{\expandafter\pgfkeys@@qset\expandafter{\pgfkeysdefaultpath}}%
\long\def\pgfkeys@@qset#1#2#3{\def\pgfkeysdefaultpath{#2/}\pgfkeys@parse#3,\pgfkeys@mainstop\def\pgfkeysdefaultpath{#1}}


% Sets keys while setting keys
%
% #1 = key-value pairs
%
% Desscription:
%
% This code may only be called inside the code that is executed for a
% key. The #1 should be a list of settings pairs. They will be executed
% as if they had been given as the argument to the \pgfkeys command.
%
% Example:
%
% \pgfkeys{tikz,myother length/.code=\def\myotherlength{#1}\pgfkeysalso{length=#1}}

\long\def\pgfkeysalso#1{\pgfkeys@parse#1,\pgfkeys@mainstop}



% Quickly sets keys while setting keys
%
% #1 = default path
% #2 = key-value pairs
%
% Desscription:
%
% This command executes #2 with the default path set to #1. This
% command will cause chaos if used incorrectly. The only safe
% place to use it instead of \pgfkeys is at the beginning of a TeX group.
%
% Example:
%
% \begingroup
%   \pgfqkeysalso{/tikz}{myother length/.code=\def\myotherlength{#1}\pgfkeysalso{length=#1}}

\long\def\pgfqkeysalso#1#2{\def\pgfkeysdefaultpath{#1/}\pgfkeys@parse#2,\pgfkeys@mainstop}




% Now setup the default handelers and keys:

% Define a key macro with one argument (\def or \edef)
%
% #1 = key
% #2 = code
%
% Description:
%
% This command will setup things so the key/.@cmd contains a macro
% that takes one parameter and has #2 as its code.
%
% Example:
%
% \pgfkeysdef{/my key}{\show#1}

\long\def\pgfkeysdef#1#2{%
  \long\def\pgfkeys@temp##1\pgfeov{#2}%
  \pgfkeyslet{#1/.@cmd}{\pgfkeys@temp}%
  \pgfkeyssetvalue{#1/.@body}{#2}%
}
\long\def\pgfkeysedef#1#2{%
  \long\edef\pgfkeys@temp##1\pgfeov{#2}%
  \pgfkeyslet{#1/.@cmd}{\pgfkeys@temp}%
  \pgfkeyssetvalue{#1/.@body}{#2}%
}


% Define a key macro with mutliple arguments (\def or \edef)
%
% #1 = key
% #2 = argument pattern
% #2 = code
%
% Description:
%
% This command will setup things so the key/.@cmd contains a macro
% that takes #2 as its parameter pattern and has #3 as its code.
%
% Example:
%
% \pgfkeysdefargs{/swap}{#1#2}{#2#1}

\long\def\pgfkeysdefargs#1#2#3{%
  \long\def\pgfkeys@temp#2\pgfeov{#3}%
  \pgfkeyslet{#1/.@cmd}{\pgfkeys@temp}%
  \pgfkeyssetvalue{#1/.@args}{#2\pgfeov}%
  \pgfkeyssetvalue{#1/.@body}{#3}%
}
\long\def\pgfkeysedefargs#1#2#3{%
  \long\edef\pgfkeys@temp#2\pgfeov{#3}%
  \pgfkeyslet{#1/.@cmd}{\pgfkeys@temp}%
  \pgfkeyssetvalue{#1/.@args}{#2\pgfeov}%
  \pgfkeyssetvalue{#1/.@body}{#3}%
}

% Like \pgfkeysdefargs, but `#2' is an integer denoting the expected
% *number* of arguments.
%
% There is a subtle difference between the 'args' command, when it
% comes to spaces:
%  a key defined with defargs{#1#2} must not have spaces between the
%  arguments when it is used.
%
% See this:
%
%--------------------------------------------------
% % defnargs:
% \pgfkeysdefnargs{/a}{2}{1=`#1', 2=`#2'}
% \pgfkeys{
%   /a=
%     {1}
%     {2}
% }
% ->defnargs: 1=`1', 2=`2'
% 
% defargs:
% \pgfkeysdefargs{/b}{#1#2}{1=`#1', 2=`#2'}
% \pgfkeys{
%   /b=
%     {1}
%     {2}
% }
% ->defargs: 1=`1', 2=` 2'  (note the space!)
%
% defargs:
% \pgfkeysdefargs{/b}{#1#2}{1=`#1', 2=`#2'}
% \pgfkeys{
%   /b=
%     {1}% 
%     {2}
% }
% ->defargs: 1=`1', 2=`2'
%-------------------------------------------------- 
\long\def\pgfkeysdefnargs#1#2#3{\pgfkeysdefnargs@{#1}{#2}{#3}{\def}}%
\long\def\pgfkeysedefnargs#1#2#3{\pgfkeysdefnargs@{#1}{#2}{#3}{\edef}}%
\long\def\pgfkeysdefnargs@#1#2#3#4{%
  \ifcase#2\relax
    \pgfkeyssetvalue{#1/.@args}{}%
  \or
    \pgfkeyssetvalue{#1/.@args}{##1}%
  \or
    \pgfkeyssetvalue{#1/.@args}{##1##2}%
  \or
    \pgfkeyssetvalue{#1/.@args}{##1##2##3}%
  \or
    \pgfkeyssetvalue{#1/.@args}{##1##2##3##4}%
  \or
    \pgfkeyssetvalue{#1/.@args}{##1##2##3##4##5}%
  \or
    \pgfkeyssetvalue{#1/.@args}{##1##2##3##4##5##6}%
  \or
    \pgfkeyssetvalue{#1/.@args}{##1##2##3##4##5##6##7}%
  \or
    \pgfkeyssetvalue{#1/.@args}{##1##2##3##4##5##6##7##8}%
  \or
    \pgfkeyssetvalue{#1/.@args}{##1##2##3##4##5##6##7##8##9}%
  \else
    \pgfkeys@error{\string\pgfkeysdefnargs: expected  <= 9 arguments, got #2}%
  \fi
  \pgfkeysgetvalue{#1/.@args}\pgfkeys@tempargs
  \def\pgfkeys@temp{\expandafter\long\expandafter#4\csname pgfk@#1/.@@body\endcsname}%
  \expandafter\pgfkeys@temp\pgfkeys@tempargs{#3}%
  % eliminate the \pgfeov at the end such that TeX gobbles spaces
  % by using
  % \pgfkeysdef{#1}{\pgfkeysvalueof{#1/.@@body}##1}
  % (with expansion of '#1'):
  \edef\pgfkeys@tempargs{\noexpand\pgfkeysvalueof{#1/.@@body}}%
  \def\pgfkeys@temp{\pgfkeysdef{#1}}%
  \expandafter\pgfkeys@temp\expandafter{\pgfkeys@tempargs##1}%
  \pgfkeyssetvalue{#1/.@body}{#3}%
}



% Defining a key command

\pgfkeysdef{/handlers/.code}{\pgfkeysdef{\pgfkeyscurrentpath}{#1}}
\pgfkeysdef{/handlers/.code 2 args}{\pgfkeysdefargs{\pgfkeyscurrentpath}{##1##2}{#1}}
\pgfkeysdef{/handlers/.ecode}{\pgfkeysedef{\pgfkeyscurrentpath}{#1}}
\pgfkeysdef{/handlers/.ecode 2 args}{\pgfkeysedefargs{\pgfkeyscurrentpath}{##1##2}{#1}}
\pgfkeysdefnargs{/handlers/.code args}{2}{\pgfkeysdefargs{\pgfkeyscurrentpath}{#1}{#2}}
\pgfkeysdefnargs{/handlers/.ecode args}{2}{\pgfkeysedefargs{\pgfkeyscurrentpath}{#1}{#2}}
\pgfkeysdefnargs{/handlers/.code n args}{2}{\pgfkeysdefnargs{\pgfkeyscurrentpath}{#1}{#2}}
\pgfkeysdefnargs{/handlers/.ecode n args}{2}{\pgfkeysedefnargs{\pgfkeyscurrentpath}{#1}{#2}}

% Adding to a key command

\pgfkeys{/handlers/.add code/.code 2 args=%
  % Find out, whether with args or not.
  \pgfkeysifdefined{\pgfkeyscurrentpath/.@args}%
  {% Yes, so add to body and reuse args
  \pgfkeysaddvalue{\pgfkeyscurrentpath/.@body}{#1}{#2}%
  % Redefine code
  {%
    \pgfkeysgetvalue{\pgfkeyscurrentpath/.@args}{\pgfkeys@tempargs}%
    \pgfkeysgetvalue{\pgfkeyscurrentpath/.@body}{\pgfkeys@tempbody}%
    \def\pgfkeys@marshal{\expandafter\gdef\expandafter\pgfkeys@global@temp\pgfkeys@tempargs}%
    \expandafter\pgfkeys@marshal\expandafter{\pgfkeys@tempbody}%
  }%
    \pgfkeysifdefined{\pgfkeyscurrentpath/.@@body}{%
    % support for \pgfkeysndefargs:
    \pgfkeyslet{\pgfkeyscurrentpath/.@@body}{\pgfkeys@global@temp}%
  }{%
    % support for \pgfkeysdefargs:
      \pgfkeyslet{\pgfkeyscurrentpath/.@cmd}{\pgfkeys@global@temp}%
  }%
  }%
  {%
    % No, so single argument (simple \pgfkeysdef). Redefine accordingly.
    \edef\pgf@expanded@path{\pgfkeyscurrentpath}%
    {%
      \toks0{#1}%
      \pgfkeysifdefined{\pgf@expanded@path/.@cmd}%
      {\expandafter\expandafter\expandafter\pgfkeys@temptoks\expandafter\expandafter\expandafter{\csname pgfk@\pgf@expanded@path/.@body\endcsname}}%
      {\expandafter\pgfkeys@temptoks\expandafter{\expandafter\pgfkeyssetvalue\expandafter{\pgf@expanded@path}{##1}}}%
      \toks1{#2}%
      \xdef\pgfkeys@global@temp{\the\toks0 \the\pgfkeys@temptoks \the\toks1 }%
    }%
    \def\pgf@temp{\pgfkeyssetvalue{\pgf@expanded@path/.@body}}%
    \expandafter\pgf@temp\expandafter{\pgfkeys@global@temp}%
    \expandafter\long\expandafter\def\expandafter\pgfkeys@temp\expandafter##\expandafter1\expandafter\pgfeov\expandafter{\pgfkeys@global@temp}%
    \pgfkeyslet{\pgf@expanded@path/.@cmd}\pgfkeys@temp%
  }%
}
\pgfkeys{/handlers/.prefix code/.code=\pgfkeys{\pgfkeyscurrentpath/.add code={#1}{}}}%
\pgfkeys{/handlers/.append code/.code=\pgfkeys{\pgfkeyscurrentpath/.add code={}{#1}}}%


% Defining a style

\pgfkeys{/handlers/.style/.code=\pgfkeys{\pgfkeyscurrentpath/.code=\pgfkeysalso{#1}}}
\pgfkeys{/handlers/.estyle/.code=\pgfkeys{\pgfkeyscurrentpath/.ecode=\noexpand\pgfkeysalso{#1}}}
\pgfkeys{/handlers/.style args/.code 2 args=\pgfkeys{\pgfkeyscurrentpath/.code args={#1}{\pgfkeysalso{#2}}}}
\pgfkeys{/handlers/.estyle args/.code 2 args=\pgfkeys{\pgfkeyscurrentpath/.ecode args={#1}{\noexpand\pgfkeysalso{#2}}}}
\pgfkeys{/handlers/.style 2 args/.code=\pgfkeys{\pgfkeyscurrentpath/.code 2 args=\pgfkeysalso{#1}}}
\pgfkeys{/handlers/.style n args/.code 2 args=\pgfkeys{\pgfkeyscurrentpath/.code n args={#1}{\pgfkeysalso{#2}}}}

% Adding to a style

\pgfkeys{/handlers/.add style/.code 2 args=\pgfkeys{\pgfkeyscurrentpath/.add code={\pgfkeysalso{#1}}{\pgfkeysalso{#2}}}}%
\pgfkeys{/handlers/.prefix style/.code=\pgfkeys{\pgfkeyscurrentpath/.add code={\pgfkeysalso{#1}}{}}}%
\pgfkeys{/handlers/.append style/.code=\pgfkeys{\pgfkeyscurrentpath/.add code={}{\pgfkeysalso{#1}}}}%


% Defining a value

\pgfkeys{/handlers/.initial/.code=\pgfkeyssetvalue{\pgfkeyscurrentpath}{#1}}
\pgfkeys{/handlers/.add/.code 2 args=\pgfkeysaddvalue{\pgfkeyscurrentpath}{#1}{#2}}
\pgfkeys{/handlers/.prefix/.code=\pgfkeysaddvalue{\pgfkeyscurrentpath}{#1}{}}
\pgfkeys{/handlers/.append/.code=\pgfkeysaddvalue{\pgfkeyscurrentpath}{}{#1}}
\pgfkeys{/handlers/.get/.code=\pgfkeysgetvalue{\pgfkeyscurrentpath}{#1}}
\pgfkeys{/handlers/.link/.code=\pgfkeyssetvalue{\pgfkeyscurrentpath}{\pgfkeysvalueof{#1}}}


% Defining a default

\pgfkeys{/handlers/.default/.code=\pgfkeyssetvalue{\pgfkeyscurrentpath/.@def}{#1}}
\pgfkeys{/handlers/.value required/.code=\pgfkeyssetvalue{\pgfkeyscurrentpath/.@def}{\pgfkeysvaluerequired}}
\pgfkeys{/handlers/.value forbidden/.code=\pgfkeys{\pgfkeyscurrentpath/.add code=%
{%
  \ifx\pgfkeyscurrentvalue\pgfkeysnovalue@text%
  \else%
    \def\pgf@marshal{\pgfkeysvalueof{/errors/value forbidden/.@cmd}}%
    \expandafter\expandafter\expandafter\pgf@marshal\expandafter\expandafter\expandafter{\expandafter\pgfkeyscurrentkey\expandafter}\expandafter{\pgfkeyscurrentvalue}\pgfeov%
  \fi%
}{}}}


% High-level cmds

\pgfkeys{/handlers/.store in/.code=\pgfkeysalso{\pgfkeyscurrentpath/.code=\def#1{##1}}}
\pgfkeys{/handlers/.estore in/.code=\pgfkeysalso{\pgfkeyscurrentpath/.code=\edef#1{##1}}}

\pgfkeys{/handlers/.is if/.code=\pgfkeysalso{%
    \pgfkeyscurrentpath/.code=\pgfkeys@handle@boolean{#1}{##1},
    \pgfkeyscurrentpath/.default=true%
  }%
}
\def\pgfkeys@handle@boolean#1#2{%
  \pgfkeys@ifcsname#1#2\endcsname%
    \csname#1#2\endcsname%
  \else%
    \def\pgf@marshal{\pgfkeysvalueof{/errors/boolean expected/.@cmd}}%
    \expandafter\pgf@marshal\expandafter{\pgfkeyscurrentkey}{#2}\pgfeov%
  \fi
}

\pgfkeys{/handlers/.is choice/.code=%
  \pgfkeys{%
    \pgfkeyscurrentpath/.cd,%
    .code=\def\pgfkeys@was@choice{##1}\expandafter\pgfkeysalso\expandafter{\pgfkeyscurrentkey/##1},
    .unknown/.code={%
      \def\pgf@marshal{\pgfkeysvalueof{/errors/unknown choice value/.@cmd}}%
      {\expandafter\expandafter\expandafter\pgf@marshal\expandafter\expandafter\expandafter{\expandafter\the\expandafter\pgfkeys@pathtoks\expandafter}\expandafter{\pgfkeys@was@choice}\pgfeov}%
    }%
  }%
}


% Repeatedly setting a key

\pgfkeys{/handlers/.list/.code=%
  {%
    \ifx\foreach\@undefined%
      \pgfkeys@error{You need to load the pgffor package to use the .list key syntax.}%
    \fi%
    % Use foreach to unfold the list
    \def\pgf@keys@temp{}%
    \foreach \pgf@keys@key in{#1}%
    {\expandafter\expandafter\expandafter\gdef%
      \expandafter\expandafter\expandafter\pgf@keys@temp%
      \expandafter\expandafter\expandafter{\expandafter\pgf@keys@temp\expandafter{\pgf@keys@key}}}%
    \edef\pgf@keys@list@path{\pgfkeyscurrentpath}%
    \expandafter\expandafter\expandafter\pgf@keys@do@list%
    \expandafter\expandafter\expandafter{\expandafter\pgf@keys@list@path\expandafter}\pgf@keys@temp\pgf@stop%
  }% 
}
\def\pgf@keys@do@list#1{\pgf@keys@utilifnextchar\bgroup{\pgf@keys@do@list@item{#1}}\pgf@keys@gobble}
\def\pgf@keys@do@list@item#1#2{\pgfkeysalso{#1={#2}}\pgf@keys@do@list{#1}}


% Forwarding

\pgfkeys{/handlers/.forward to/.code=%
  \pgfkeys{\pgfkeyscurrentpath/.add code={}{\pgfkeys{#1={##1}}}}
}


% Inspection handlers

\pgfkeys{/handlers/.show value/.code=\pgfkeysgetvalue{\pgfkeyscurrentpath}{\pgfkeysshower}\show\pgfkeysshower} % inspect the value 
\pgfkeys{/handlers/.show code/.code=\pgfkeysgetvalue{\pgfkeyscurrentpath/.@cmd}{\pgfkeysshower}\show\pgfkeysshower} % inspect the body of the command


% First char syntax handlers
\pgfkeys{/handlers/first char syntax/.is if=pgfkeys@syntax@handlers}

% Path handling

% Prepares the .unknown handler used by '.search also'.
% It will be stored into \pgfkeys@global@temp.
\def\pgfkeys@searchalso@prepare@unknown@handler#1{%
  \global\def\pgfkeys@global@temp##1\pgfeov{}%
  \pgfkeys@searchalso@parse#1,\pgfkeys@mainstop
  {%
    \toks0=\expandafter{\pgfkeys@global@temp##1\pgfeov}%
  \toks1={\pgfkeysalso{/handlers/.unknown/.@cmd/.expand once=\pgfkeys@searchalso@temp@value}}%
  \xdef\pgfkeys@global@temp{%
    \noexpand\def\noexpand\pgfkeys@searchalso@temp@value{####1}%
    \noexpand\ifpgfkeysaddeddefaultpath
      \noexpand\pgfkeyssuccessfalse
      \noexpand\let\noexpand\pgfkeys@searchalso@name=\noexpand\pgfkeyscurrentkeyRAW
      \the\toks0 % one or more /.try things; one for each path. The last element won't have a /.try
      %\noexpand\ifpgfkeyssuccess
      %\noexpand\else
      %  \the\toks1 % invoke /handlers/.unknown handler
      %\noexpand\fi
    \noexpand\else
      \the\toks1 % invoke /handlers/.unknown handler
    \noexpand\fi
  }%
  \expandafter\gdef\expandafter\pgfkeys@global@temp\expandafter##\expandafter1\expandafter\pgfeov\expandafter{\pgfkeys@global@temp}%
  }%
}%

\def\pgfkeys@searchalso@parse{\futurelet\pgfkeys@possiblerelax\pgfkeys@searchalso@parse@main}
\def\pgfkeys@searchalso@parse@main{%
  \ifx\pgfkeys@possiblerelax\pgfkeys@mainstop%
    \expandafter\pgfkeys@cleanup%
  \else%
    \expandafter\pgfkeys@searchalso@appendentry%
  \fi%
}
\def\pgfkeys@searchalso@appendentry#1,#2{%
  \def\pgfkeys@searchalso@nexttok{#2}%
  \pgfkeys@spdef\pgfkeys@temp{#1}%
  {%
    \toks0=\expandafter{\pgfkeys@global@temp##1\pgfeov}%
  \toks1=\expandafter{\pgfkeys@temp}%
  \xdef\pgfkeys@global@temp{%
    \the\toks0 % the space is important!
    \noexpand\ifpgfkeyssuccess\noexpand\else
      \noexpand\pgfqkeys{\the\toks1 }{\noexpand\pgfkeys@searchalso@name
               \ifx\pgfkeys@searchalso@nexttok\pgfkeys@mainstop\else/.try\fi /.expand once=\noexpand\pgfkeys@searchalso@temp@value}%
    \noexpand\fi}%
  \expandafter\gdef\expandafter\pgfkeys@global@temp\expandafter##\expandafter1\expandafter\pgfeov\expandafter{\pgfkeys@global@temp}%
  }%
  \pgfkeys@searchalso@parse#2%
}
\pgfkeys{%
  /handlers/.is family/.code=\pgfkeys{\pgfkeyscurrentpath/.ecode=\edef\noexpand\pgfkeysdefaultpath{\pgfkeyscurrentpath/}},%
  /handlers/.cd/.code=\edef\pgfkeysdefaultpath{\pgfkeyscurrentpath/},%
  /handlers/.search also/.code={%
    \pgfkeys@searchalso@prepare@unknown@handler{#1}%
%\message{I prepared the '\pgfkeyscurrentpath/.unknown' handler \meaning\pgfkeys@global@temp\space for '#1'.}%
    \pgfkeyslet{\pgfkeyscurrentpath/.unknown/.@cmd}{\pgfkeys@global@temp}%
  }
}%


% Value expansion

\pgfkeys{/handlers/.expand once/.code=\expandafter\pgfkeys@exp@call\expandafter{#1}}
\pgfkeys{/handlers/.expand two once/.code 2 args=\expandafter\expandafter\expandafter\pgfkeys@exp@call\expandafter\expandafter\expandafter{\expandafter#1\expandafter}\expandafter{#2}}
\pgfkeys{/handlers/.expand twice/.code=\expandafter\expandafter\expandafter\pgfkeys@exp@call\expandafter\expandafter\expandafter{#1}}
\pgfkeys{/handlers/.expanded/.code=\edef\pgfkeys@temp{#1}\expandafter\pgfkeys@exp@call\expandafter{\pgfkeys@temp}}

\long\def\pgfkeys@exp@call#1{\pgfkeysalso{\pgfkeyscurrentpath={#1}}}

% Try to set a key and do nothing if not define

\newif\ifpgfkeyssuccess
\pgfkeys{/handlers/.try/.code=\pgfkeys@try}
\pgfkeys{/handlers/.retry/.code=\ifpgfkeyssuccess\else\pgfkeys@try\fi}
\def\pgfkeys@try{%
  \edef\pgfkeyscurrentkey{\pgfkeyscurrentpath}% make sure that \pgfkeys@code doesn't know about 'try'. Important for .is choice
  \ifx\pgfkeyscurrentvalue\pgfkeysnovalue@text% Hmm... no value
    \pgfkeysifdefined{\pgfkeyscurrentpath/.@def}%
    {\pgfkeysgetvalue{\pgfkeyscurrentpath/.@def}{\pgfkeyscurrentvalue}}
    {}% no default, so leave it
  \fi%
  \pgfkeysifdefined{\pgfkeyscurrentpath/.@cmd}%
  {%
    \pgfkeysgetvalue{\pgfkeyscurrentpath/.@cmd}{\pgfkeys@code}%
    \expandafter\pgfkeys@code\pgfkeyscurrentvalue\pgfeov%
    \pgfkeyssuccesstrue%
  }%
  {%
    \pgfkeysifdefined{\pgfkeyscurrentpath}%
    {%
      \ifx\pgfkeyscurrentvalue\pgfkeysnovalue@text%
        \pgfkeysvalueof{\pgfkeyscurrentpath}%
      \else%
        \pgfkeyslet{\pgfkeyscurrentpath}\pgfkeyscurrentvalue%
      \fi%
      \pgfkeyssuccesstrue%
    }%
    {%
      \pgfkeys@split@path%
      \pgfkeysifdefined{/handlers/\pgfkeyscurrentname/.@cmd}{%
      % in the standard configuration, this check here is redundand
      % because pgfkeys@ifexecutehandler === true.
    % It is only interesting for 'handle only existing'.
        \pgfkeys@ifexecutehandler{%
        \pgfkeysgetvalue{/handlers/\pgfkeyscurrentname/.@cmd}{\pgfkeys@code}%
          \expandafter\pgfkeys@code\pgfkeyscurrentvalue\pgfeov
          \pgfkeyssuccesstrue%
      }{%
        \pgfkeyssuccessfalse
      }%
      }{%
      \pgfkeyssuccessfalse
      }%
  }%
  }%
}

% Utilities

\pgfkeys{/utils/exec/.code=#1} % simply execute the given code directly.


% Errors

\pgfkeys{
  /errors/boolean expected/.code 2 args=%
  {
    \toks1={#1}
    \toks2={#2}
    \pgfkeys@error{%
      Boolean parameter of key '\the\toks1' must be 'true' or 'false', not
      '\the\toks2'. I am going to ignore it%
    }
  },
  /errors/value required/.code 2 args=%
  {
    \toks1={#1}
    \pgfkeys@error{%
      The key '\the\toks1' requires a value. I am going to ignore this
      key%
    }
  },
  /errors/value forbidden/.code 2 args=%
  {
    \toks1={#1}
    \toks2={#2}
    \pgfkeys@error{%
      You may not specify a value for the key '\the\toks1'. I am going to ignore
      the value '\the\toks2' that you provided%
    }
  },
  /errors/unknown choice value/.code 2 args=%
  {
    \toks1={#1}
    \toks2={#2}
    \pgfkeys@error{%
      Choice '\the\toks2' unknown in choice key '\the\toks1'. I am
      going to ignore this key%
    }
  },
  /errors/unknown key/.code 2 args=%
  {
    \toks1={#1}
    \toks2={#2}
    \def\pgf@temp{#2}%
    \pgfkeys@error{%
      I do not know the key '\the\toks1'\ifx\pgf@temp\pgfkeysnovalue@text\space\else, to which you passed
      '\the\toks2', \fi and I am going to ignore it. Perhaps you 
      misspelled it%
    }
  }
}

\pgfkeys{/handlers/.unknown/.code=%
  {%
    \def\pgf@marshal{\pgfkeysvalueof{/errors/unknown key/.@cmd}}%
    {\expandafter\expandafter\expandafter\pgf@marshal\expandafter\expandafter\expandafter{\expandafter\pgfkeyscurrentkey\expandafter}\expandafter{\pgfkeyscurrentvalue}\pgfeov}%
  }%
}

\pgfkeys{
  /handler config/.is choice,
  /handler config/all/.code={%
    \let\pgfkeys@case@three=\pgfkeys@case@three@handleall
    \let\pgfkeys@ifexecutehandler=\pgfkeys@ifexecutehandler@handleall
  },
  /handler config/only existing/.code={%
    \let\pgfkeys@case@three=\pgfkeys@case@three@handle@restricted
    \let\pgfkeys@ifexecutehandler=\pgfkeys@ifexecutehandler@handleonlyexisting
  },
  /handler config/full or existing/.code={%
    \let\pgfkeys@case@three=\pgfkeys@case@three@handle@restricted
    \let\pgfkeys@ifexecutehandler=\pgfkeys@ifexecutehandler@handlefullorexisting
  },
  /handler config/only existing/add exception/.code={\pgfkeysaddhandleonlyexistingexception{#1}},
}%
\pgfkeysaddhandleonlyexistingexception{.cd}%
\pgfkeysaddhandleonlyexistingexception{.try}%
\pgfkeysaddhandleonlyexistingexception{.retry}%
\pgfkeysaddhandleonlyexistingexception{.lastretry}%
\pgfkeysaddhandleonlyexistingexception{.unknown}%
\pgfkeysaddhandleonlyexistingexception{.expand once}%
\pgfkeysaddhandleonlyexistingexception{.expand two once}%
\pgfkeysaddhandleonlyexistingexception{.expand twice}%
\pgfkeysaddhandleonlyexistingexception{.expanded}%


% Utilities for self-containment
\def\pgf@keys@gobble#1{}
\long\def\pgf@keys@utilifnextchar#1#2#3{%
  \let\pgf@keys@utilreserved@d=#1%
  \def\pgf@keys@utilreserved@a{#2}%
  \def\pgf@keys@utilreserved@b{#3}%
  \futurelet\pgf@keys@utillet@token\pgf@keys@utilifnch}
\def\pgf@keys@utilifnch{%
  \ifx\pgf@keys@utillet@token\pgf@keys@utilsptoken
    \let\pgf@keys@utilreserved@c\pgf@keys@utilxifnch
  \else
    \ifx\pgf@keys@utillet@token\pgf@keys@utilreserved@d
      \let\pgf@keys@utilreserved@c\pgf@keys@utilreserved@a
    \else
      \let\pgf@keys@utilreserved@c\pgf@keys@utilreserved@b
    \fi
  \fi
  \pgf@keys@utilreserved@c}
{%
  \def\:{\global\let\pgf@keys@utilsptoken= } \:
  \def\:{\pgf@keys@utilxifnch} \expandafter\gdef\: {\futurelet\pgf@keys@utillet@token\pgf@keys@utilifnch}
}


\input pgfkeysfiltered.code.tex

\endinput

pgfkeysfiltered.code.tex
% Copyright 2008 by Christian Feuersaenger
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.
% 
% This file contains additions to pgfkeys.code.tex (loaded
% automatically at the end of pgfkeys.code.tex)
%
% Improvements:
%
% - option filtering 
%   you provide
%     - a boolean predicate
%     - a "filter handler" which will be invoked for non-matching options,
%     - a key=value list as usual.
%   The filter sets only matching options and invokes the handler for
%   unmatching ones.
%
% - Fast family support as in xkeyval.
%   - A key like /my tree/my option  can be associated with /my family
%   - You can efficiently set keys which belong to a set of "active"
%     families.
%  Remaining options can be collected into a macro.

% WARNING:
% this file overwrites
% \pgfkeys@addpath
% \pgfkeys@nevermind
%
% all other features are 'additive'


% these implementations will be switched dynamically with their
% filtered versions (in \pgfkeys@install@filter@and@invoke)
\let\pgfkeys@orig@case@one=\pgfkeys@case@one
\let\pgfkeys@orig@@set=\pgfkeys@@set
\let\pgfkeys@orig@@qset=\pgfkeys@@qset
\let\pgfkeys@orig@try=\pgfkeys@try
\let\pgfkeys@orig@unknown=\pgfkeys@unknown

\newif\ifpgfkeysfilteringisactive
\newif\ifpgfkeysfiltercontinue
\let\pgfkeys@key@predicate=\pgfkeys@empty
\let\pgfkeys@filtered@handler=\pgfkeys@empty
\newtoks\pgfkeys@tmptoks

% Performs 'filtered' key settings.
%
% For every option for which the path prefixing has already been done, 
% the current key filter predicate will be invoked. If the predicate
% returns true, pgfkeys will process this key in the normal manner.
% If not, a key filter handler will be invoked.
%
% The *predicate* and *handler* semantics are as follows:
% PRECONDITION:
% 		1. The variables
% 			\pgfkeyscurrentkey (full path including name)
% 			\pgfkeyscurrentkeyRAW (the current key as it has been
% 			                       found in the key=value list
% 			                       without path modification)
% 			\pgfkeyscurrentvalue
% 			are all set. If the current key is a handler variable,
%	 			\pgfkeyscurrentname 
%	 		and
% 				\pgfkeyscurrentpath
% 			are also set.
%		2. The type of option has already been checked, that means
%			case (1) whether '.@cmd' exists
%			case (2) whether the key as such has its value
%			case (3) it is a handler like '.code', '.cd' or whatever.
%			case (0) it is unknown.
%			The actual case number (0-3) will be provided as contents
%			of the macro
%				\pgfkeyscasenumber.
%			It is always a one-character token, so it may be compared
%			with both, \ifnum or \if.
%			Please note that unknown options will be processed with
%			the usual '.unknown' handlers unless the key filter takes
%			control over unknown options as well.
%
% POSTCONDITION:
% 		the predicate sets 
% 			\pgfkeysfiltercontinuetrue 
% 		or
% 			\pgfkeysfiltercontinuefalse
% 		(the boolean \ifpgfkeysfiltercontinue).
% Depending on this 'if', option processing will be continued or
% skipped.
%
% The handler can do anything with the option, for example collect
% unmatched ones.
%
% ATTENTION: \pgfkeysfiltered can't be nested (yet). Use the
% \pgfkeyspredicateAND if you need multiple predicates at once.
% Nesting would produce unexpected results because the current filter
% state can't be stored/restored without TeX-groups, therefor it is
% disabled.
%
% ATTENTION: you can't filter error messages.
%
% REMARK: In case (3), the macros \pgfkeyscurrentpath and
% \pgfkeyscurrentname have already been computed, you do not need to
% invoke \pgfkeyssplitpath. In any other case, neither path nor name
% are required for the options processing - if you need them for
% predicates/handlers, you need to compute them by hand.
% 
%
% Example:
%   \def\unmatched{}
%   \pgfkeys{/pgf/key filters/is descendant of/.install key filter=/my group}
%   \pgfkeys{/pgf/key filter handlers/append filtered to/.install key filter handler=\unmatched}
%   \pgfkeysfiltered%
%   	{/my group/option 1=value 1,/tikz/option 2=value 2}
% ->
%  will set '/my group/option 1' as usual, but '/tikz/option 2' will not
%  be set. Instead, it will be appended to '\unmatched' such that 
%  \unmatched = {/tikz/option 2=value2}
%  after the operation.
%
% Arguments:
% #1:  key-value list.
\def\pgfkeysfiltered{%
	% produce 
	% '{<default path>}'
	% each expanded exactly one time into the register:  
	\expandafter\pgfkeysfiltered@@install\expandafter{\pgfkeysdefaultpath}%
}

% #1: old value of default path.
% #2: key-value-list.
\long\def\pgfkeysfiltered@@install#1#2{%
	\pgfkeys@install@filter@and@invoke{%
		\let\pgfkeysdefaultpath\pgfkeys@root%
		\pgfkeys@parse#2,\pgfkeys@mainstop%
		\def\pgfkeysdefaultpath{#1}%
	}%
}

% Assuming that macro #1 contains a key=value list, this command
% performs an \pgfkeysalso command for the content of macro #1.
%
% It can be used in conjunction with 
%   - \pgfkeysfiltered and
%   - \pgfkeysappendfilterednamestomacro:
% the first pass fill only process options matching the filter, then,
% a \pgfkeysalsofrom can be used at a later time to set the remaining
% options.
%
% Example:
% \pgfkeys{/my group/.cd,/utils/exec=\pgfkeysalsofrom\filtered}
\long\def\pgfkeysalsofrom#1{%
	\expandafter\pgfkeysalso\expandafter{#1}%
}

% The same as \pgfkeysalsofrom, but it invokes \pgfkeysalsofiltered.
\long\def\pgfkeysalsofilteredfrom#1{%
	\expandafter\pgfkeysalsofiltered\expandafter{#1}%
}

% #1 = options
\long\def\pgfkeysalsofiltered#1{%
	\pgfkeys@install@filter@and@invoke{\pgfkeysalso{#1}}%
}%

% The same like \pgfkeysfiltered, but with quick search path setting.
%
% #1: default path
% #2: key-value-pairs
\long\def\pgfqkeysfiltered#1{%
	\expandafter\pgfqkeysfiltered@@install\expandafter{\pgfkeysdefaultpath}{#1}%
}

% #1: old value of default path.
% #2: default path
% #3: key-value-list.
\long\def\pgfqkeysfiltered@@install#1#2#3{%
	\pgfkeys@install@filter@and@invoke{%
		\def\pgfkeysdefaultpath{#2/}\pgfkeys@parse#3,\pgfkeys@mainstop\def\pgfkeysdefaultpath{#1}%
	}%
}

% Family management
%
% The family code provides the following features:
% 1. every key can be associated with 0 or 1 'family'.
% 2. Families are a loose association which are independend of the key
% hierarchy.
%   For example, /my tree/key1  can belong to family /tikz.
%
% 3. It is possible to "activate" or "deactivate" single families.
%    Furthermore, it is possible to set only keys which belong to 
%    active families (using \pgfkeysfiltered).
% 4. Runtime complexities:
%    If you have N options and you only want to process K active
%    families, the runtime is O( N + K ):
%      - activate every family O(K)
%      - use \pgfkeyshasactivefamily as filter predicate O(N)
%      - deactivate every family O(K)


% Activates family #1.
%
% #1 maybe a macro.
\def\pgfkeysactivatefamily#1{%
	\pgfkeysiffamilydefined
		{#1}%
		{\csname pgfk@#1/familyactivetrue\endcsname}%
		{\pgfkeysvalueof{/errors/family unknown/.@cmd}{#1}\pgfeov}%
%\message{[ACTIVATING FAMILY #1]}%
}

% Deactivates family #1.
%
% #1 maybe a macro.
\def\pgfkeysdeactivatefamily#1{%
	\pgfkeysiffamilydefined
		{#1}%
		{\csname pgfk@#1/familyactivefalse\endcsname}%
		{\pgfkeysvalueof{/errors/family unknown/.@cmd}{#1}\pgfeov}%
%\message{[DEACTIVATING FAMILY #1]}%
}

% Activates all families in the comma separated list #1.
%
% It will also generate code for deactivation of all those families
% into the command #2.
%
% #1: a comma-separated list of fully qualified family names.
% #2: a command which will be filled with a deactivate-all command.
\def\pgfkeysactivatefamilies#1#2{%
	\pgfkeyssavekeyfilterstateto\pgfkeys@cur@state
	\expandafter\pgfkeysactivatefamilies@impl\expandafter{\pgfkeys@cur@state}{#1}{#2}%
}
% #1: commands needed to restore the old filtering state
% #2: family name list
% #3: macro name for de-activate command
\def\pgfkeysactivatefamilies@impl#1#2#3{%
	\pgfkeysinstallkeyfilter{/pgf/key filters/false}{}%
	\let#3=\pgfkeys@empty%
	\def\pgfkeys@filtered@handler{\pgfkeys@family@activate@handler{#3}}%
	\pgfkeysalsofiltered{#2}%
	#1%
}

\def\pgfkeys@family@activate@handler#1{%
	\pgfkeysactivatefamily{\pgfkeyscurrentkey}%
	% produce 
	%   <old list> '\pgfkeysdeactivatefamily{' <current key> '}'
	\pgfkeys@tmptoks=\expandafter\expandafter\expandafter{\expandafter#1\expandafter\pgfkeysdeactivatefamily\expandafter{\pgfkeyscurrentkey}}%
	\edef#1{\the\pgfkeys@tmptoks}%
}

% If for testing whether a family exists.
%
% #1 = fully qualified family name
% #2 = if-case
% #3 = else-case
%
% Description:
%
% If the family exists, #2 will be executed. Otherwise, #3 will be
% called.
\long\def\pgfkeysiffamilydefined#1#2#3{\pgfkeys@ifcsname ifpgfk@#1/familyactive\endcsname#2\else#3\fi}

% Sets the TeX boolean 
%   \ifpgfkeysfiltercontinue := ( family #1 is active )
% 
% Argument:
% #1 the family name. Maybe a macro.
\def\pgfkeysisfamilyactive#1{%
	\pgfkeysiffamilydefined{#1}{%
		\expandafter\let\expandafter\ifpgfkeysfiltercontinue\csname ifpgfk@#1/familyactive\endcsname
	}{%
		\pgfkeysvalueof{/errors/family unknown/.@cmd}{#1}\pgfeov%
		\expandafter\expandafter\expandafter\let\csname ifpgfkeysfiltercontinue\endcsname\csname iffalse\endcsname
	}%
}%

% Retrieve the family of full key #1 into macro #2.
%
% Will set the TeX boolean \ifpgfkeyssuccess to whether the full key
% really has a family.
%
% The family for any key is stored in the sub-key #1/family.
%
% Parameters:
% #1:  the full key name for which the family is requested. Maybe a
%      macro.
% #2:  a macro name which will be filled with the result.
\def\pgfkeysgetfamily#1#2{%
	\pgfkeysifdefined{#1/family}{\pgfkeysgetvalue{#1/family}{#2}\pgfkeyssuccesstrue}{\pgfkeyssuccessfalse}%
}

% Equivalent to \pgfkeys{#1/.belongs to family=#2}
\def\pgfkeyssetfamily#1#2{%
	\pgfkeysiffamilydefined{#2}{%
		\pgfkeyssetvalue{#1/family}{#2}%
	}{%
		\pgfkeysalso{/errors/family unknown=#2}%
	}%
}%


% Sets \ifpgfkeysfiltercontinue to true iff the current key belongs to
% the /errors tree.
\long\def\pgfkeys@cur@is@descendant@of@errors{%
	\expandafter\pgfkeys@cur@is@descendant@of@errors@impl\pgfkeyscurrentkey/errors\pgf@@eov
}%
\long\def\pgfkeys@cur@is@descendant@of@errors@impl#1/errors#2\pgf@@eov{%
	\def\pgfkeyspred@TMP{#1}%
	\ifx\pgfkeyspred@TMP\pgfkeys@empty
%\message{[SPECIAL CHECK] '\pgfkeyscurrentkey' is descendant of '/errors': TRUE.}%
		\pgfkeysfiltercontinuetrue
	\else
%\message{[SPECIAL CHECK] '\pgfkeyscurrentkey' is descendant of '/errors': FALSE.}%
		\pgfkeysfiltercontinuefalse
	\fi
}%

% \pgfkeysinterruptkeyfilter
% ...
% \endpgfkeysinterruptkeyfilter
% temporarily interrupts key filtering and enables it in
% \endpgfkeysinterruptkeyfilter.
%
% If key filtering it not active, this has no effect at all.
%
% REMARK:
% \pgfkeysinterruptkeyfilter...\endpgfkeysinterruptkeyfilter does NOT
% introduce a \TeX-group.
\def\pgfkeysinterruptkeyfilter{%
	\ifpgfkeysfilteringisactive
		\let\pgfkeys@case@one=\pgfkeys@orig@case@one
		\let\pgfkeys@try=\pgfkeys@orig@try
		\let\pgfkeys@unknown=\pgfkeys@orig@unknown
	\fi
}

\def\endpgfkeysinterruptkeyfilter{%
	\ifpgfkeysfilteringisactive
		\let\pgfkeys@case@one=\pgfkeys@case@one@filtered
		\let\pgfkeys@try=\pgfkeys@try@filtered
		\let\pgfkeys@unknown=\pgfkeys@unknown@filtered
	\fi
}

% Activates families #1, calls \pgfkeysfiltered and deactivates the
% families afterwards.
%
% REMARK: you need to install a family-based key filter predicate
% manually to benefit from the activated families!
%
% #1: comma separated family list
% #2: key-value pairs
%
% @see \pgfkeysactivatefamiliesandfilteroptions
\def\pgfkeysactivatefamiliesandfilteroptions#1#2{%
	\pgfkeysactivatefamilies{#1}{\pgfkeys@family@deactivation}%
	\pgfkeysfiltered{#2}%
	\pgfkeys@family@deactivation
}

% The "quick" variant of \pgfkeysactivatefamiliesandfilteroptions: it
% also assigns a default path.
%
% #1: comma separated family list
% #2: default path
% #3: key-value pairs
\def\pgfqkeysactivatefamiliesandfilteroptions#1#2#3{%
	\pgfkeysactivatefamilies{#1}{\pgfkeys@family@deactivation}%
	\pgfqkeysfiltered{#2}{#3}%
	\pgfkeys@family@deactivation
}

% Public version of split path:
\def\pgfkeyssplitpath{\pgfkeys@split@path}%


% The same as \pgfkeysactivatefamiliesandfilteroptions but just for
% ONE family.
%
% #1: family (maybe a macro)
% #2: key-value pairs
\def\pgfkeysactivatesinglefamilyandfilteroptions#1#2{%
	\pgfkeysactivatefamily{#1}%
	\pgfkeysfiltered{#2}%
	\pgfkeysdeactivatefamily{#1}%
}

% The "quick" variant of \pgfkeysactivatesinglefamilyandfilteroptions
%
% #1: family (maybe a macro)
% #2: default path
% #3: key-value pairs
\def\pgfqkeysactivatesinglefamilyandfilteroptions#1#2#3{%
	\pgfkeysactivatefamily{#1}%
	\pgfqkeysfiltered{#2}{#3}%
	\pgfkeysdeactivatefamily{#1}%
}

% Installs the key filter '#1' with argument '#2'.
% This is equivalent to
%    \pgfkeys{#1/.install key filter=#2}
%
% The current values of the key filter handler is stored into the public
% macros
% \pgfkeyscurrentkeyfilter
% and
% \pgfkeyscurrentkeyfilterargs
%
% #1: a full key name; may be a macro
% #2: optional arguments for the key. If the key expects more than one
% argument, supply '{{first}{second}}'
\def\pgfkeysinstallkeyfilter#1#2{%
	\pgfkeysifdefined{#1/.@cmd}{%
		\edef\pgfkeyscurrentkeyfilter{#1}%
		\def\pgfkeyscurrentkeyfilterargs{#2}%
		\pgfkeysgetvalue{#1/.@cmd}{\pgfkeys@key@predicate@}%
		\def\pgfkeys@key@predicate{\pgfkeys@key@predicate@#2\pgfeov}%
	}{%
		\pgfkeysvalueof{/errors/no such key filter/.@cmd}{#1}{#2}\pgfeov%
	}%
}

% Installs the key filter handler '#1' with argument '#2'.
% This is equivalent to
%    \pgfkeys{#1/.install key filter handler=#2}
% 
% The current values of the key filter handler is stored into the public
% macros
% \pgfkeyscurrentkeyfilterhandler
% and
% \pgfkeyscurrentkeyfilterhandlerargs
%
% #1: a full key name; may be a macro
% #2: optional arguments for the handler. If the handler expects more than one
% argument, supply '{{first}{second}}'
\def\pgfkeysinstallkeyfilterhandler#1#2{%
	\pgfkeysifdefined{#1/.@cmd}{%
		\edef\pgfkeyscurrentkeyfilterhandler{#1}%
		\def\pgfkeyscurrentkeyfilterhandlerargs{#2}%
		\pgfkeysgetvalue{#1/.@cmd}{\pgfkeys@filtered@handler@}%
		\def\pgfkeys@filtered@handler{\pgfkeys@filtered@handler@#2\pgfeov}%
	}{%
		\pgfkeysvalueof{/errors/no such key filter handler/.@cmd}{#1}{#2}\pgfeov%
	}%
}

% Creates a macro which contains commands to re-activate the current
% key filter and key filter handler. It can be used to temporarily
% switch the key filter.
\def\pgfkeyssavekeyfilterstateto#1{%
	% produce the string
	% \pgfkeysinstallkeyfilter{...}{...}
	% \pgfkeysinstallkeyfilterhandler{...}{...}
	% where each argument is expanded once
	% FIXME: Do the same with less overhead!
	\pgfkeys@tmptoks={\pgfkeysinstallkeyfilter}%
	\pgfkeys@tmptoks=\expandafter\expandafter\expandafter{\expandafter\the\expandafter\pgfkeys@tmptoks\expandafter{\pgfkeyscurrentkeyfilter}}%
	\pgfkeys@tmptoks=\expandafter\expandafter\expandafter{\expandafter\the\expandafter\pgfkeys@tmptoks\expandafter{\pgfkeyscurrentkeyfilterargs}\pgfkeysinstallkeyfilterhandler}%
	\pgfkeys@tmptoks=\expandafter\expandafter\expandafter{\expandafter\the\expandafter\pgfkeys@tmptoks\expandafter{\pgfkeyscurrentkeyfilterhandler}}%
	\pgfkeys@tmptoks=\expandafter\expandafter\expandafter{\expandafter\the\expandafter\pgfkeys@tmptoks\expandafter{\pgfkeyscurrentkeyfilterhandlerargs}}%
	\edef#1{%
		\the\pgfkeys@tmptoks
	}%
}


\pgfkeys{%
	/errors/family unknown/.code=\pgfkeys@error{%
		Sorry, I do not know family '#1' and can't work with any assoicated family handling. Perhaps you misspelled it?},
	/errors/no such key filter/.code 2 args=\pgfkeys@error{Sorry, there is no such key filter '#1'.},
	/errors/no such key filter handler/.code 2 args=\pgfkeys@error{Sorry, there is no such key filter handler '#1'.},
	% HANDLERS:
	%
	% .is family should
	%  1. '.cd' into the families' path,
	%  2. define booleans to activate/deactive the family 
	%     (see \pgfkeysisfamilyactive)
	%  3. make sure that \pgfkeyshasactivefamily returns true for
	%     the family itsself.
	/handlers/.is family/.append code={%
		%\newif is an \outer macro in plain tex, so this here is not portable:
		%\expandafter\newif\csname if\pgfkeyscurrentpath/familyactive\endcsname
		\edef\pgfkeyspred@TMP{pgfk@\pgfkeyscurrentpath/familyactive}%
		\expandafter\pgfkeys@non@outer@newif\expandafter{\pgfkeyspred@TMP}%
		\edef\pgfkeyspred@TMP{\pgfkeyscurrentpath/.belongs to family=\pgfkeyscurrentpath}%
		\expandafter\pgfkeysalso\expandafter{\pgfkeyspred@TMP}%
	},%
	/handlers/.activate family/.code=\pgfkeysactivatefamily{\pgfkeyscurrentpath},
	/handlers/.deactivate family/.code=\pgfkeysdeactivatefamily{\pgfkeyscurrentpath},
	/handlers/.belongs to family/.code={\pgfkeyssetfamily{\pgfkeyscurrentpath}{#1}},%
	%
	%
	% An addition to the '.try' and '.retry' handlers:
	%
	% It is the same as '.retry', but if the option is still unknown, the
	% usual handlers for unknown keys will be invoked.
	/handlers/.lastretry/.code={%
		\ifpgfkeyssuccess\else
			\pgfkeys@try
			\ifpgfkeyssuccess\else
				% discard the '.lastretry' suffix:
				\edef\pgfkeyscurrentkey{\pgfkeyscurrentpath}%
				\pgfkeys@split@path%
				\pgfkeys@unknown
			\fi
		\fi
	},
	%
	%
	/handlers/.install key filter/.code={%
		\pgfkeysinstallkeyfilter{\pgfkeyscurrentpath}{#1}%
	},%
	/handlers/.install key filter handler/.code={%
		\pgfkeysinstallkeyfilterhandler{\pgfkeyscurrentpath}{#1}%
	},%
	%
	%
	% KEY FILTER HANDLERS:
	%
	/pgf/key filter handlers/append filtered to/.code={%
		% Produce
		%  <orig key> '={' <value> '}'
		% where both, the key and the value are expanded just ONCE:
		\pgfkeys@tmptoks=\expandafter\expandafter\expandafter{\expandafter\pgfkeyscurrentkeyRAW\expandafter=\expandafter{\pgfkeyscurrentvalue}}%
		\ifx#1\pgfkeys@empty
		\else
			% Produce <old list> ','  <orig key> '={' <value> '}'
			\pgfkeys@tmptoks=\expandafter\expandafter\expandafter{\expandafter#1\expandafter,\the\pgfkeys@tmptoks}%
		\fi
		\edef#1{\the\pgfkeys@tmptoks}%
	},%
	/pgf/key filter handlers/ignore/.code={},
	/pgf/key filter handlers/ignore/.install key filter handler,
	/pgf/key filter handlers/log/.code={%
		\immediate\write16{LOG: the option '\pgfkeyscurrentkey' (was originally '\pgfkeyscurrentkeyRAW') (case \pgfkeyscasenumber) has not been processed due to pgfkeysfiltered.}%
	},
	%
	% 
	% KEY FILTER PREDICATES:
	%
	% Returns true iff the currently processed key belongs to an active family.
	% A family is active if it has been activated before.
	/pgf/key filters/active families/.code={%
		\if\pgfkeyscasenumber0%
			% unknown options shall be processed with the
			% unknown-handlers.
			\pgfkeysfiltercontinuetrue
		\else
			\if\pgfkeyscasenumber3%
				\pgfkeysgetfamily\pgfkeyscurrentpath\pgfkeyspred@TMP
			\else
				\pgfkeysgetfamily\pgfkeyscurrentkey\pgfkeyspred@TMP
			\fi
			\ifpgfkeyssuccess
				\pgfkeysisfamilyactive{\pgfkeyspred@TMP}%
			\else% Ok, it does not belong to any family.
				\pgfkeysfiltercontinuefalse
			\fi
		\fi
	},%
	%
	%
	%
	% This filter works as follows:
	% 1. if the current key belongs to a family:
	% 	return whether its family is active,
	% 2. if the current key does NOT belong to a family:
	%   return the result of criterion '#1',
	% 3. the current key is unknown:
	% 	return the result of criterion '#2'.
	%
	% Arguments:
	% #1: the predicate which will be invoked in case 2.
	%   It will be invoked with the current case number as argument.
	% #2: the predicate which will be invoked in case 3 with 
	%   the current case number as argument.
	/pgf/key filters/active families or no family/.code 2 args={%
		\if\pgfkeyscasenumber0%
			\pgfkeysevalkeyfilterwith{#2}%
		\else
			\if\pgfkeyscasenumber3%
				\pgfkeysgetfamily\pgfkeyscurrentpath\pgfkeyspred@TMP
			\else
				\pgfkeysgetfamily\pgfkeyscurrentkey\pgfkeyspred@TMP
			\fi
			\ifpgfkeyssuccess
				\pgfkeysisfamilyactive{\pgfkeyspred@TMP}%
			\else% Ok, it does not belong to any family.
				\pgfkeysevalkeyfilterwith{#1}%
			\fi
		\fi
	},
	/pgf/key filters/active families or no family DEBUG/.code 2 args={%
		\if\pgfkeyscasenumber0%
			\immediate\write16{[pgfkeyshasactivefamilyornofamily(\pgfkeyscurrentkey, \pgfkeyscasenumber) invoking unknown handler '#2']}%
			\pgfkeysevalkeyfilterwith{#2}%
		\else
			\if\pgfkeyscasenumber3%
				\pgfkeysgetfamily\pgfkeyscurrentpath\pgfkeyspred@TMP
			\else
				\pgfkeysgetfamily\pgfkeyscurrentkey\pgfkeyspred@TMP
			\fi
			\ifpgfkeyssuccess
				\pgfkeysisfamilyactive{\pgfkeyspred@TMP}%
				\ifpgfkeysfiltercontinue
					\immediate\write16{[pgfkeyshasactivefamilyornofamily(\pgfkeyscurrentkey, \pgfkeyscasenumber) family is ACTIVE]}%
				\else
					\immediate\write16{[pgfkeyshasactivefamilyornofamily(\pgfkeyscurrentkey, \pgfkeyscasenumber) family is NOT active.]}%
				\fi
			\else% Ok, it does not belong to any family.
				\immediate\write16{[pgfkeyshasactivefamilyornofamily(\pgfkeyscurrentkey, \pgfkeyscasenumber) invoking has-no-family-handler '#1']}%
				\pgfkeysevalkeyfilterwith{#1}%
			\fi
		\fi
	},
	%
	% A (faster) shortcut for
	% /pgf/key filters/active families or no family=
	% 	{/pgf/keys filters/false}
	% 	{/pgf/keys filters/false}
	/pgf/key filters/active families and known/.code={%
		\if\pgfkeyscasenumber0%
			\pgfkeysfiltercontinuefalse
		\else
			\if\pgfkeyscasenumber3%
				\pgfkeysgetfamily\pgfkeyscurrentpath\pgfkeyspred@TMP
			\else
				\pgfkeysgetfamily\pgfkeyscurrentkey\pgfkeyspred@TMP
			\fi
			\ifpgfkeyssuccess
				\pgfkeysisfamilyactive{\pgfkeyspred@TMP}%
			\else% Ok, it does not belong to any family.
				\pgfkeysfiltercontinuefalse
			\fi
		\fi
	},
	% A (faster) shortcut for
	% /pgf/key filters/active families or no family=
	%	{/pgf/key filters/is descendant of=#1}% for keys without family
	% 	{/pgf/keys filters/false}
	/pgf/key filters/active families or descendants of/.code={%
		\if\pgfkeyscasenumber0%
			\pgfkeysfiltercontinuefalse
		\else
			\if\pgfkeyscasenumber3%
				\pgfkeysgetfamily\pgfkeyscurrentpath\pgfkeyspred@TMP
			\else
				\pgfkeysgetfamily\pgfkeyscurrentkey\pgfkeyspred@TMP
			\fi
			\ifpgfkeyssuccess
				\pgfkeysisfamilyactive{\pgfkeyspred@TMP}%
			\else% Ok, it does not belong to any family.
				% the 'is descendendant of' implementation has been
				% COPY PASTED here:
				%
				% string prefix comparison:
				\def\pgfkeysisdescendantof@impl##1#1##2\pgf@@eov{%
					\def\pgfkeyspred@TMP{##1}%
					\ifx\pgfkeyspred@TMP\pgfkeys@empty
						\pgfkeysfiltercontinuetrue
					\else
						\pgfkeysfiltercontinuefalse
					\fi
				}%
				\expandafter\pgfkeysisdescendantof@impl\pgfkeyscurrentkey#1\pgf@@eov
			\fi
		\fi
	},
	%
	% Processes only options which are childs of #1.
	% Example:
	%   is descendant of/.install key filter=/foo
	% will be true for
	%  /foo/bar/x=y
	%  /foo/.cd
	%  /foo/bar/.style=...
	% but not for
	%  /bar/foo/...
	/pgf/key filters/is descendant of/.code={%
		\if\pgfkeyscasenumber0%
%\message{'\pgfkeyscurrentkey' (case \pgfkeyscasenumber) is UNKNOWN. Calling unknown handler.}%
			% unknown options shall be processed with the
			% unknown-handlers.
			\pgfkeysfiltercontinuetrue
		\else
			% string prefix comparison:
			% [ note : this has been COPY-PASTED to 
			%   |active families or descendants of| ]
			\def\pgfkeysisdescendantof@impl##1#1##2\pgf@@eov{%
				\def\pgfkeyspred@TMP{##1}%
				\ifx\pgfkeyspred@TMP\pgfkeys@empty
%\message{'\pgfkeyscurrentkey' (case \pgfkeyscasenumber) is descendant of '#1': TRUE.}%
					\pgfkeysfiltercontinuetrue
				\else
%\message{'\pgfkeyscurrentkey' (case \pgfkeyscasenumber) is descendant of '#1': FALSE.}%
					\pgfkeysfiltercontinuefalse
				\fi
			}%
			\expandafter\pgfkeysisdescendantof@impl\pgfkeyscurrentkey#1\pgf@@eov
		\fi
	},%
	%
	%
	% 
	% Returns true if the currently processed full key equals #2.
	/pgf/key filters/equals/.code={%
		\if\pgfkeyscasenumber0%
			% Unknown option:
			\pgfkeysfiltercontinuetrue
		\else
			\def\pgfkeyspred@TMP{#1}%
			\ifx\pgfkeyscurrentkey\pgfkeyspred@TMP
				\pgfkeysfiltercontinuetrue
			\else
				\pgfkeysfiltercontinuefalse
			\fi
		\fi
	},%
	%
	%
	% Argument #1 can be any other (evaluated) filter predicate, its logical return
	% value will be inverted.
	% Example:
	%   not/.install key filter={is descendend of=/tikz}
	% will install a key filter which evaluates 'is descendant of' with argument '/tikz' and returns the logical negation of the result.
	%
	/pgf/key filters/not/.code={%
		\pgfkeysevalkeyfilterwith{#1}%
		\ifpgfkeysfiltercontinue
			\pgfkeysfiltercontinuefalse
		\else
			\pgfkeysfiltercontinuetrue
		\fi
	},%
	/pgf/key filters/and/.code 2 args={%
		\pgfkeysevalkeyfilterwith{#1}%
		\ifpgfkeysfiltercontinue
			\pgfkeysevalkeyfilterwith{#2}%
		\fi
	},%
	/pgf/key filters/or/.code 2 args={%
		\pgfkeysevalkeyfilterwith{#1}%
		\ifpgfkeysfiltercontinue
		\else
			\pgfkeysevalkeyfilterwith{#2}%
		\fi
	},%
	/pgf/key filters/true/.code={\pgfkeysfiltercontinuetrue},%
	/pgf/key filters/true/.install key filter,
	/pgf/key filters/false/.code={%
		\pgfkeysfiltercontinuefalse
	},%
	%
	% Returns false if the current key is unknown, which avoids calling
	% the unknown handlers.
	/pgf/key filters/defined/.code={%
		\if\pgfkeyscasenumber0%
			\pgfkeysfiltercontinuefalse
		\else
			\pgfkeysfiltercontinuetrue
		\fi
	},
}%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Private IMPLEMENTATION
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


% This command does THE SAME work as \pgfkeys@case@one,
% but it applies filtering whenever it identified the type of an
% option.
\def\pgfkeys@case@one@filtered{%
	\pgfkeys@cur@is@descendant@of@errors
	\ifpgfkeysfiltercontinue
		\pgfkeys@orig@case@one
	\else
		\pgfkeysfiltercontinuetrue
		\pgfkeysifdefined{\pgfkeyscurrentkey/.@cmd}{%
			% CASE ONE: a command option
			\def\pgfkeyscasenumber{1}%
			\pgfkeys@key@predicate%
			\ifpgfkeysfiltercontinue
%\message{PROCESSING KEY \pgfkeyscurrentkey!}%
				\pgfkeysgetvalue{\pgfkeyscurrentkey/.@cmd}{\pgfkeys@code}%
				\expandafter\pgfkeys@code\pgfkeyscurrentvalue\pgfeov
			\else
%\message{FILTERED OUT  KEY \pgfkeyscurrentkey!}%
				\pgfkeys@filtered@handler%
			\fi
		}{%
			% CASE TWO: a normal value option
			\pgfkeysifdefined{\pgfkeyscurrentkey}{%
				\def\pgfkeyscasenumber{2}%
				\pgfkeys@key@predicate%
				\ifpgfkeysfiltercontinue
%\message{PROCESSING KEY \pgfkeyscurrentkey!}%
					\pgfkeys@case@two@extern
				\else
%\message{FILTEReD OUT  KEY \pgfkeyscurrentkey!}%
					\pgfkeys@filtered@handler%
				\fi
			}{%
				\pgfkeys@split@path
				% CASE THREE: a handler
				\pgfkeysifdefined{/handlers/\pgfkeyscurrentname/.@cmd}{%
					\pgfkeys@ifexecutehandler{%
						\def\pgfkeyscasenumber{3}%
						\pgfkeys@key@predicate%
						\ifpgfkeysfiltercontinue
%\message{PROCESSING KEY \pgfkeyscurrentkey!}%
							\pgfkeysgetvalue{/handlers/\pgfkeyscurrentname/.@cmd}{\pgfkeys@code}%
							\expandafter\pgfkeys@code\pgfkeyscurrentvalue\pgfeov
						\else
%\message{FILTERED OUT  KEY \pgfkeyscurrentkey!}%
							\pgfkeys@filtered@handler%
						\fi
					}{%
						\pgfkeys@unknown
					}%
				}{%
					\pgfkeys@unknown
				}%
			}%
		}%
	\fi
}%

\def\pgfkeys@unknown@filtered{%
	% CASE ZERO: an unknown option.
	\def\pgfkeyscasenumber{0}%
	\pgfkeys@key@predicate%
	\ifpgfkeysfiltercontinue
%\message{PROCESSING  KEY \pgfkeyscurrentkey!}%
		% start normal 'unknown' handlers:
		\pgfkeys@orig@unknown
	\else
%\message{FILTEReD OUT  KEY \pgfkeyscurrentkey!}%
		\pgfkeys@filtered@handler%
	\fi
}

% Does the same as \pgfkeys@try, but it also invokes the key filters.
\def\pgfkeys@try@filtered{%
	\ifpgfkeysfiltercontinue
		\pgfkeys@orig@try
	\else
		\pgfkeysfiltercontinuetrue
		\edef\pgfkeyscurrentkey{\pgfkeyscurrentpath}% make sure that \pgfkeys@code doesn't know about 'try'. Important for .is choice
		\ifx\pgfkeyscurrentvalue\pgfkeysnovalue@text% Hmm... no value
			\pgfkeysifdefined{\pgfkeyscurrentpath/.@def}%
			{\pgfkeysgetvalue{\pgfkeyscurrentpath/.@def}{\pgfkeyscurrentvalue}}
			{}% no default, so leave it
		\fi%
		\pgfkeysifdefined{\pgfkeyscurrentpath/.@cmd}%
		{%
			% CASE ONE: a command option
			\def\pgfkeyscasenumber{1}%
			\pgfkeys@key@predicate%
			\ifpgfkeysfiltercontinue
				\pgfkeysgetvalue{\pgfkeyscurrentkey/.@cmd}{\pgfkeys@code}%
				\expandafter\pgfkeys@code\pgfkeyscurrentvalue\pgfeov%
			\else
				\pgfkeys@filtered@handler%
			\fi
			\pgfkeyssuccesstrue%
		}%
		{%
			\pgfkeysifdefined{\pgfkeyscurrentpath}%
			{% CASE TWO: a normal value option
				\def\pgfkeyscasenumber{2}%
				\pgfkeys@key@predicate%
				\ifpgfkeysfiltercontinue
					\ifx\pgfkeyscurrentvalue\pgfkeysnovalue@text%
						\pgfkeysvalueof{\pgfkeyscurrentpath}%
					\else%
						\pgfkeyslet{\pgfkeyscurrentpath}\pgfkeyscurrentvalue%
					\fi%
				\else
					\pgfkeys@filtered@handler%
				\fi
				\pgfkeyssuccesstrue%
			}%
			{%
				\pgfkeys@split@path%
				\pgfkeysifdefined{/handlers/\pgfkeyscurrentname/.@cmd}{%
					% CASE THREE: a handled key
					%
					% in the standard configuration, this check here is redundand
					% because pgfkeys@ifexecutehandler === true.
					% It is only interesting for 'handle only existing'.
					\pgfkeys@ifexecutehandler{%
						\def\pgfkeyscasenumber{3}%
						\pgfkeys@key@predicate%
						\ifpgfkeysfiltercontinue
%\message{PROCESSING KEY \pgfkeyscurrentkey!}%
							\pgfkeysgetvalue{/handlers/\pgfkeyscurrentname/.@cmd}{\pgfkeys@code}%
							\expandafter\pgfkeys@code\pgfkeyscurrentvalue\pgfeov
						\else
%\message{FILTERED OUT  KEY \pgfkeyscurrentkey!}%
							\pgfkeys@filtered@handler%
						\fi
						\pgfkeyssuccesstrue%
					}{%
						\pgfkeyssuccessfalse
					}%
				}{%
					\pgfkeyssuccessfalse
				}%
			}%
		}%
	\fi
}


% #1 the code to invoke after init and before cleanup
\long\def\pgfkeys@install@filter@and@invoke#1{%
	\ifpgfkeysfilteringisactive
		\pgfkeys@error{Sorry, nested calls to key filtering routines are not allowed. (reason: It is not possible to properly restore the previous filtering state after returning from the nested call)}%
	\fi
	\pgfkeysfilteringisactivetrue
	\let\pgfkeys@case@one=\pgfkeys@case@one@filtered
	\let\pgfkeys@try=\pgfkeys@try@filtered
	\let\pgfkeys@unknown=\pgfkeys@unknown@filtered
	#1%
	\let\pgfkeys@case@one=\pgfkeys@orig@case@one
	\let\pgfkeys@try=\pgfkeys@orig@try
	\let\pgfkeys@unknown=\pgfkeys@orig@unknown
	\pgfkeysfilteringisactivefalse
}


%--------------------------------------------------
% \def\pgfkeys@eval@key@filter@subroutine@case@one{%
% 	\pgfkeysifdefined{\pgfkeyscurrentkey/.@cmd}{%
% 		\pgfkeysgetvalue{\pgfkeyscurrentkey/.@cmd}{\pgfkeys@code}%
% 		\let\pgfkeyspred@TMP=\pgfkeyscurrentvalue
% 		\pgfkeys@eval@key@filter@subroutine@restorestate
% 		\expandafter\pgfkeys@code\pgfkeyspred@TMP\pgfeov
% 	}{%
% 		\pgfkeysvalueof{/errors/no such key filter/.@cmd}\pgfkeyscurrentkey\pgfkeyscurrentvalue\pgfeov%
% 	}%
% }
% % THIS VERSION IS TOO SLOW. See below.
% \def\pgfkeysevalkeyfilterwith#1{%
% 	\edef\pgfkeys@eval@key@filter@subroutine@restorestate{%
% 		\noexpand\def\noexpand\pgfkeyscurrentkey{\pgfkeyscurrentkey}%
% 		\noexpand\def\noexpand\pgfkeyscurrentkeyRAW{\pgfkeyscurrentkeyRAW}%
% 		\noexpand\def\noexpand\pgfkeyscurrentname{\pgfkeyscurrentname}%
% 		\noexpand\def\noexpand\pgfkeyscurrentvalue{\pgfkeyscurrentvalue}%
% 		\noexpand\pgfkeys@pathtoks={\pgfkeyscurrentpath}%
% 	}%
% 	\pgfkeysinterruptkeyfilter
% 	\let\pgfkeys@case@one=\pgfkeys@eval@key@filter@subroutine@case@one
% 	\pgfkeysalso{#1}%
% 	\endpgfkeysinterruptkeyfilter% this here also restored \pgfkeys@case@one.
% 	\pgfkeys@eval@key@filter@subroutine@restorestate
% }%
%-------------------------------------------------- 


% Evaluates a key filter '#1'. Example:
% \pgfkeysevalkeyfilterwith{/pgf/key filters/equals=/tikz}
%
% \pgfkeysevalkeyfilterwith works only if key filtering is
% active.
%
% The argument '#1' MUST be a FULL KEY.
%
% The implementation employs a subset of the \pgfkeysalso code.
\long\def\pgfkeysevalkeyfilterwith#1{%
	\pgfkeys@eval@key@filter@subroutine@unpack#1=\pgfkeysnovalue=\pgfkeys@stop
}%
\long\def\pgfkeys@eval@key@filter@subroutine@unpack#1=#2=#3\pgfkeys@stop{%
	\pgfkeys@spdef\pgfkeyspred@TMP{#1}%
	\edef\pgfkeyspred@TMP{\pgfkeyspred@TMP}%
	\pgfkeys@spdef\pgfkeyspred@TMPB{#2}% TMPB=value
	\ifx\pgfkeyspred@TMPB\pgfkeysnovalue@text% Hmm... no value
		\pgfkeysifdefined{\pgfkeyspred@TMP/.@def}%
		{\pgfkeysgetvalue{\pgfkeyspred@TMP/.@def}{\pgfkeyspred@TMPB}}
		{}% no default, so leave it
	\fi%
	\ifx\pgfkeyspred@TMPB\pgfkeysvaluerequired%
		\pgfkeysvalueof{/errors/value required/.@cmd}\pgfkeyspred@TMP\pgfkeyspred@TMPB\pgfeov%
	\else%
		\pgfkeysifdefined{\pgfkeyspred@TMP/.@cmd}{%
			\pgfkeysgetvalue{\pgfkeyspred@TMP/.@cmd}{\pgfkeys@code}%
			\expandafter\pgfkeys@code\pgfkeyspred@TMPB\pgfeov
		}{%
			\pgfkeysvalueof{/errors/no such key filter/.@cmd}\pgfkeyspred@TMP\pgfkeyspred@TMPB\pgfeov%
		}%
	\fi%
}


\def\pgfkeys@non@outer@newif@#1#2{%
	\expandafter\edef\csname #2true\endcsname{\noexpand\let\noexpand#1=\noexpand\iftrue}%
	\expandafter\edef\csname #2false\endcsname{\noexpand\let\noexpand#1=\noexpand\iffalse}%
	\csname #2false\endcsname
}%

% For latex and context, this here has the same effect as a \newif
% applied to 'if#1'. For plain tex, it has also the same effect, but
% it is not an \outer macro as the plain-tex \newif.
\def\pgfkeys@non@outer@newif#1{%
	\expandafter\pgfkeys@non@outer@newif@\csname if#1\endcsname{#1}%
}
\endinput

pgflibrarydecorations.pathmorphing.code.tex
% Copyright 2008 by Mark Wibrow
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\usepgfmodule{decorations}


%
% These decorations "morph" paths. That means that the
% orginal characteristic of the path is kept and the number of
% subpaths remains the same -- only, the lines are slightly offset or
% changed by the decoration. For instance a line might be turned into
% a squiggly line or a snaking line or a bumping line.
%


%
%
% Kind 1: Path morphing straight line decorations
%
%


% zigzag decoration.
%
\pgfdeclaredecoration{zigzag}{up from center}{
  \state{up from center}[width=+.5\pgfdecorationsegmentlength, next state=big down]
  {
    \pgfpathlineto{\pgfqpoint{.25\pgfdecorationsegmentlength}{\pgfdecorationsegmentamplitude}}
  }
  \state{big down}[switch if less than=+.5\pgfdecorationsegmentlength to center finish,
                   width=+.5\pgfdecorationsegmentlength,
                   next state=big up]
  {
    \pgfpathlineto{\pgfqpoint{.25\pgfdecorationsegmentlength}{-\pgfdecorationsegmentamplitude}}
  }
  \state{big up}[switch if less than=+.5\pgfdecorationsegmentlength to center finish,
                 width=+.5\pgfdecorationsegmentlength,
                 next state=big down]
  {
    \pgfpathlineto{\pgfqpoint{.25\pgfdecorationsegmentlength}{\pgfdecorationsegmentamplitude}}
  }
  \state{center finish}[width=0pt, next state=final]{
    \pgfpathlineto{\pgfpointorigin}
  }
  \state{final}
  {
    \pgfpathlineto{\pgfpointdecoratedpathlast}
  }
}




% saw decoration
%
% Parameters: \pgfdecorationsegmentamplitude, \pgfdecorationsegmentlength

\pgfdeclaredecoration{saw}{initial}
{
  \state{initial}[auto end on length=+\pgfdecorationsegmentlength,
                  auto corner on length=+\pgfdecorationsegmentlength,
                  width=+\pgfdecorationsegmentlength]
  {
    \pgfpathlineto{\pgfqpoint{\pgfdecorationsegmentlength}{\pgfdecorationsegmentamplitude}}
    \pgfpathlineto{\pgfqpoint{\pgfdecorationsegmentlength}{0pt}}
  }
  \state{final}
  {}
}




% random steps decoration
%
% A decoration that consists of random steps heading towards the target
%
% Parameters: \pgfdecorationsegmentamplitude, \pgfdecorationsegmentlength

\pgfdeclaredecoration{random steps}{start}
{
  \state{start}[width=+0pt,next state=step,persistent precomputation=\pgfdecoratepathhascornerstrue]{}
  \state{step}[auto end on length=1.5\pgfdecorationsegmentlength,
               auto corner on length=1.5\pgfdecorationsegmentlength,               
               width=+\pgfdecorationsegmentlength]
  {
    \pgfpathlineto{
      \pgfpointadd
      {\pgfpoint{\pgfdecorationsegmentlength}{0pt}}
      {\pgfpoint{rand*\pgfdecorationsegmentamplitude}{rand*\pgfdecorationsegmentamplitude}}
    }
  }
  \state{final}
  {}
}



% Meta-decoration line zigzag

\pgfdeclaremetadecoration{straight zigzag}{line to}{
  \state{line to}[width=\pgfmetadecorationsegmentlength, next state=zigzag]
  {
    \decoration{curveto}
  }
  \state{zigzag}[width=\pgfmetadecorationsegmentlength, next state=line to]
  {
    \decoration{zigzag}	
  }
  \state{final}
  {
    \decoration{curveto}
  }
}





%
%
% Kind 2: Path morphing curved decorations
%
%



% bent decoration
%
% A decoration that looks like someone bent the line a bit.
%
% Parameters: \pgfdecorationsegmentamplitude, \pgfdecorationsegmentaspect

\pgfdeclaredecoration{bent}{bent}
{
  \state{bent}[width=+\pgfdecoratedinputsegmentremainingdistance]
  {
    \pgfpathcurveto
    {\pgfqpoint{\pgfdecorationsegmentaspect\pgfdecoratedinputsegmentremainingdistance}{\pgfdecorationsegmentamplitude}}
    {\pgfpointadd{\pgfqpoint{\pgfdecoratedinputsegmentremainingdistance}{0pt}}
       {\pgfqpoint{-\pgfdecorationsegmentaspect\pgfdecoratedinputsegmentremainingdistance}{\pgfdecorationsegmentamplitude}}}
    {\pgfqpoint{\pgfdecoratedinputsegmentremainingdistance}{0pt}}
  }
  \state{final}
  {}
}



% decoration snake
%
% This decoration produces a hopefully optically pleasing squiggly snake. 
%
% Parameters: \pgfdecorationsegmentamplitude, \pgfdecorationsegmentlength

\pgfdeclaredecoration{snake}{initial}
{
  \state{initial}[switch if less than=+.625\pgfdecorationsegmentlength to final,
                  width=+.3125\pgfdecorationsegmentlength,
                  next state=down]
  { 
    \pgfpathcurveto
    {\pgfqpoint{.125\pgfdecorationsegmentlength}{0pt}}
    {\pgfqpoint{.1875\pgfdecorationsegmentlength}{\pgfdecorationsegmentamplitude}}
    {\pgfqpoint{.3125\pgfdecorationsegmentlength}{\pgfdecorationsegmentamplitude}}
  }
  \state{down}[switch if less than=+.8125\pgfdecorationsegmentlength to end down,
               width=+.5\pgfdecorationsegmentlength,
               next state=up]
  {
    \pgfpathcosine{\pgfqpoint{.25\pgfdecorationsegmentlength}{-1\pgfdecorationsegmentamplitude}}
    \pgfpathsine{\pgfqpoint{.25\pgfdecorationsegmentlength}{-1\pgfdecorationsegmentamplitude}}
  }               
  \state{up}[switch if less than=+.8125\pgfdecorationsegmentlength to end up,
             width=+.5\pgfdecorationsegmentlength,
             next state=down]
  {
    \pgfpathcosine{\pgfqpoint{.25\pgfdecorationsegmentlength}{\pgfdecorationsegmentamplitude}}
    \pgfpathsine{\pgfqpoint{.25\pgfdecorationsegmentlength}{\pgfdecorationsegmentamplitude}}
  }               
  \state{end down}[width=+.3125\pgfdecorationsegmentlength,
                   next state=final]
  {
    \pgfpathcurveto
    {\pgfqpoint{.125\pgfdecorationsegmentlength}{\pgfdecorationsegmentamplitude}}
    {\pgfqpoint{.1875\pgfdecorationsegmentlength}{0pt}}
    {\pgfqpoint{.3125\pgfdecorationsegmentlength}{0pt}}
  }  
  \state{end up}[width=+.3125\pgfdecorationsegmentlength,
                 next state=final]
  {
    \pgfpathcurveto
    {\pgfqpoint{.125\pgfdecorationsegmentlength}{-\pgfdecorationsegmentamplitude}}
    {\pgfqpoint{.1875\pgfdecorationsegmentlength}{0pt}}
    {\pgfqpoint{.3125\pgfdecorationsegmentlength}{0pt}}
  }  
  \state{final}
  {
    \pgfpathlineto{\pgfpointdecoratedpathlast}
  }
}


% coil decoration
%
% Parameters: \pgfdecorationsegmentamplitude, \pgfdecorationsegmentlength,

\pgfdeclaredecoration{coil}{coil}
{
  \state{coil}[switch if less than=%
    1.5\pgfdecorationsegmentlength+%
    \pgfdecorationsegmentaspect\pgfdecorationsegmentamplitude+%
    \pgfdecorationsegmentaspect\pgfdecorationsegmentamplitude to last,
               width=+\pgfdecorationsegmentlength]
  {
    \pgfpathcurveto
    {\pgfpoint@oncoil{0    }{ 0.555}{1}}
    {\pgfpoint@oncoil{0.445}{ 1    }{2}}
    {\pgfpoint@oncoil{1    }{ 1    }{3}}
    \pgfpathcurveto
    {\pgfpoint@oncoil{1.555}{ 1    }{4}}
    {\pgfpoint@oncoil{2    }{ 0.555}{5}}
    {\pgfpoint@oncoil{2    }{ 0    }{6}}
    \pgfpathcurveto
    {\pgfpoint@oncoil{2    }{-0.555}{7}}
    {\pgfpoint@oncoil{1.555}{-1    }{8}}
    {\pgfpoint@oncoil{1    }{-1    }{9}}
    \pgfpathcurveto
    {\pgfpoint@oncoil{0.445}{-1    }{10}}
    {\pgfpoint@oncoil{0    }{-0.555}{11}}
    {\pgfpoint@oncoil{0    }{ 0    }{12}}
  }
  \state{last}[width=.5\pgfdecorationsegmentlength+%
    \pgfdecorationsegmentaspect\pgfdecorationsegmentamplitude+%
    \pgfdecorationsegmentaspect\pgfdecorationsegmentamplitude,next state=final]
  {
    \pgfpathcurveto
    {\pgfpoint@oncoil{0    }{ 0.555}{1}}
    {\pgfpoint@oncoil{0.445}{ 1    }{2}}
    {\pgfpoint@oncoil{1    }{ 1    }{3}}
    \pgfpathcurveto
    {\pgfpoint@oncoil{1.555}{ 1    }{4}}
    {\pgfpoint@oncoil{2    }{ 0.555}{5}}
    {\pgfpoint@oncoil{2    }{ 0    }{6}}
  }
  \state{final}
  {
    \pgfpathlineto{\pgfpointdecoratedpathlast}
  }
}

\def\pgfpoint@oncoil#1#2#3{%
  \pgf@x=#1\pgfdecorationsegmentamplitude%
  \pgf@x=\pgfdecorationsegmentaspect\pgf@x%
  \pgf@y=#2\pgfdecorationsegmentamplitude%
  \pgf@xa=0.083333333333\pgfdecorationsegmentlength%
  \advance\pgf@x by#3\pgf@xa%
}


% bumps decoration
%
% Parameters: \pgfdecorationsegmentamplitude, \pgfdecorationsegmentlength

\pgfdeclaredecoration{bumps}{initial}
{
  \state{initial}[auto end on length=+.51\pgfdecorationsegmentlength,
                  auto corner on length=+.51\pgfdecorationsegmentlength,
                  width=+.5\pgfdecorationsegmentlength]
  {
    \pgfpathcurveto
    {\pgfqpoint{0pt}{.555\pgfdecorationsegmentamplitude}}
    {\pgfqpoint{0.11125\pgfdecorationsegmentlength}{\pgfdecorationsegmentamplitude}}
    {\pgfqpoint{.25\pgfdecorationsegmentlength}{\pgfdecorationsegmentamplitude}}
    \pgfpathcurveto
    {\pgfqpoint{.38875\pgfdecorationsegmentlength}{\pgfdecorationsegmentamplitude}}
    {\pgfqpoint{.5\pgfdecorationsegmentlength}{.5\pgfdecorationsegmentamplitude}}
    {\pgfqpoint{.5\pgfdecorationsegmentlength}{0\pgfdecorationsegmentamplitude}}
  }
  \state{final}
  {
    \pgfpathlineto{\pgfpointdecoratedpathlast}
  }
}








\endinput
pgflibrarydecorations.pathreplacing.code.tex
% Copyright 2008 by Mark Wibrow and Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\usepgfmodule{decorations}


%
% Path replacing decorations
%
% These decorations change the path by replacing it by another path.
% For instance, a line in the path might be replaced by small
% ticks or unconnected curves or crosses. Applying a chopping
% decoration to a path means that the path can no longer be used for
% filling in the original manner.
%



%
%
% Kind 1: Path chopping with open subpaths
%
%


% ticks decoration
%
% Parameters: \pgfdecorationsegmentlength, \pgfdecorationsegmentamplitude

\pgfdeclaredecoration{ticks}{ticks}
{
  \state{ticks}[width=+\pgfdecorationsegmentlength]
  {
    \pgfpathmoveto{\pgfqpoint{0pt}{\pgfdecorationsegmentamplitude}}
    \pgfpathlineto{\pgfqpoint{0pt}{-\pgfdecorationsegmentamplitude}}
  }
  \state{final}
  {
    \pgfpathmoveto{\pgfqpoint{0pt}{\pgfdecorationsegmentamplitude}}
    \pgfpathlineto{\pgfqpoint{0pt}{-\pgfdecorationsegmentamplitude}}
    \pgfpathmoveto{\pgfpointdecoratedpathlast}
  }
}



% expanding waves decoration
%
% Parameters: \pgfdecorationsegmentangle, \pgfdecorationsegmentlength

\pgfdeclaredecoration{expanding waves}{initial}
{
  \state{initial}[width=+\pgfdecorationsegmentlength,next state=wave]
  {}

  \state{wave}[switch if less than=+\pgfdecorationsegmentlength to last,
               width=+\pgfdecorationsegmentlength]
  {
    \pgfpathmoveto{
      \pgfpointadd
      {\pgfqpoint{-\pgfdecoratedcompleteddistance}{0pt}}%
      {\pgfpointpolar{\pgfdecorationsegmentangle}{+\pgfdecoratedcompleteddistance}}}%
    \pgfpatharc{\pgfdecorationsegmentangle}{-\pgfdecorationsegmentangle}{+\pgfdecoratedcompleteddistance}%
  }
  \state{last}[width=+0pt,next state=final]
  {
    \pgfpathmoveto{
      \pgfpointadd
      {\pgfqpoint{-\pgfdecoratedcompleteddistance}{0pt}}%
      {\pgfpointpolar{\pgfdecorationsegmentangle}{+\pgfdecoratedcompleteddistance}}}%
    \pgfpatharc{\pgfdecorationsegmentangle}{-\pgfdecorationsegmentangle}{+\pgfdecoratedcompleteddistance}%
  }
  \state{final}
  {
    \pgfpathmoveto{\pgfpointdecoratedpathlast}
  }
}



% waves decoration

\pgfdeclaredecoration{waves}{wave}
{
  \state{wave}[width=\pgfdecorationsegmentlength]
  {
    \pgftransformxshift{+\pgfdecorationsegmentlength}
    \pgfpathmoveto{
      \pgfpointadd
      {\pgfqpoint{-\pgfkeysvalueof{/pgf/decoration/start radius}}{0pt}}%
      {\pgfpointpolar{\pgfdecorationsegmentangle}{\pgfkeysvalueof{/pgf/decoration/start radius}}}}%
    \pgfpatharc{\pgfdecorationsegmentangle}{-\pgfdecorationsegmentangle}{\pgfkeysvalueof{/pgf/decoration/start radius}}%
  }
  \state{final}
  {
    \pgfpathmoveto{\pgfpointdecoratedpathlast}
  }
}



% border decoration
%
% Parameters: \pgfdecorationsegmentlength, \pgfdecorationsegmentamplitude, \pgfdecorationsegmentangle

\pgfdeclaredecoration{border}{tick}
{
  \state{tick}[switch if less than=+\pgfdecorationsegmentlength to last,
               width=+\pgfdecorationsegmentlength]
  {
    \pgfpathmoveto{\pgfpointorigin}
    \pgfpathlineto{\pgfpointpolar{\pgfdecorationsegmentangle}{+\pgfdecorationsegmentamplitude}}
  }
  \state{last}[width=+\pgfdecorationsegmentamplitude,next state=final]
  {
    \pgfpathmoveto{\pgfpointorigin}
    \pgfpathlineto{\pgfpointpolar{\pgfdecorationsegmentangle}{+\pgfdecorationsegmentamplitude}}
  }  
  \state{final}
  {
    \pgfpathmoveto{\pgfpointdecoratedpathlast}
  }
}






% brace decorations
%
% Parameters: \pgfdecorationsegmentamplitude

\pgfdeclaredecoration{brace}{brace}
{
  \state{brace}[width=+\pgfdecoratedremainingdistance,next state=final]
  {
    \pgfpathmoveto{\pgfpointorigin}
    \pgfpathcurveto
    {\pgfqpoint{.15\pgfdecorationsegmentamplitude}{.3\pgfdecorationsegmentamplitude}}
    {\pgfqpoint{.5\pgfdecorationsegmentamplitude}{.5\pgfdecorationsegmentamplitude}}
    {\pgfqpoint{\pgfdecorationsegmentamplitude}{.5\pgfdecorationsegmentamplitude}}
    {
      \pgftransformxshift{+\pgfdecorationsegmentaspect\pgfdecoratedremainingdistance}
      \pgfpathlineto{\pgfqpoint{-\pgfdecorationsegmentamplitude}{.5\pgfdecorationsegmentamplitude}}
      \pgfpathcurveto
      {\pgfqpoint{-.5\pgfdecorationsegmentamplitude}{.5\pgfdecorationsegmentamplitude}}
      {\pgfqpoint{-.15\pgfdecorationsegmentamplitude}{.7\pgfdecorationsegmentamplitude}}
      {\pgfqpoint{0\pgfdecorationsegmentamplitude}{1\pgfdecorationsegmentamplitude}}
      \pgfpathcurveto
      {\pgfqpoint{.15\pgfdecorationsegmentamplitude}{.7\pgfdecorationsegmentamplitude}}
      {\pgfqpoint{.5\pgfdecorationsegmentamplitude}{.5\pgfdecorationsegmentamplitude}}
      {\pgfqpoint{\pgfdecorationsegmentamplitude}{.5\pgfdecorationsegmentamplitude}}
    }
    {
      \pgftransformxshift{+\pgfdecoratedremainingdistance}
      \pgfpathlineto{\pgfqpoint{-\pgfdecorationsegmentamplitude}{.5\pgfdecorationsegmentamplitude}}
      \pgfpathcurveto
      {\pgfqpoint{-.5\pgfdecorationsegmentamplitude}{.5\pgfdecorationsegmentamplitude}}
      {\pgfqpoint{-.15\pgfdecorationsegmentamplitude}{.3\pgfdecorationsegmentamplitude}}
      {\pgfqpoint{0pt}{0pt}}
    }
  }
  \state{final}
  {}
}




% show path construction decoration
%
\pgfdeclaredecoration{show path construction}{check for moveto}{
	\state{check for moveto}[width=0pt, next state=segment,
	  persistent precomputation={%
	  	\begingroup%
	  		\pgf@lib@decoraions@installinputsegmentpoints%
			  \ifx\pgfdecorationpreviousinputsegment\pgfdecorationinputsegmentmoveto%
				  \pgfdecoratedinputsegmentmovetocode%
			  \fi%
			\endgroup%
		}]{}
	\state{segment}[width=\pgfdecoratedinputsegmentremainingdistance, next state=check for moveto,
	  persistent precomputation={%
	  	\begingroup%
	  		\pgf@lib@decoraions@installinputsegmentpoints%
				\csname pgfdecoratedinputsegment\pgfdecorationcurrentinputsegment code\endcsname%
			\endgroup%
		}]{}
	\state{final}{%
		\egroup%
		\begingroup%
  		\pgf@lib@decoraions@installinputsegmentpoints%
			\csname pgfdecoratedinputsegment\pgfdecorationcurrentinputsegment code\endcsname%
		\endgroup%
		\bgroup%
	}
}

\pgfkeys{
	/pgf/decoration/.cd,
		moveto code/.code=\def\pgfdecoratedinputsegmentmovetocode{#1},
		lineto code/.code=\def\pgfdecoratedinputsegmentlinetocode{#1},
		curveto code/.code=\def\pgfdecoratedinputsegmentcurvetocode{#1},
	  closepath code/.code=\def\pgfdecoratedinputsegmentclosepathcode{#1}
}

\let\pgfdecoratedinputsegmentmovetocode\pgfutil@empty%
\let\pgfdecoratedinputsegmentlinetocode\pgfutil@empty%
\let\pgfdecoratedinputsegmentcurvetocode\pgfutil@empty%
\let\pgfdecoratedinputsegmentclosepathcode\pgfutil@empty%

\def\pgf@lib@decoraions@installinputsegmentpoints{%
	\let\pgfpointdecoratedinputsegmentfirst\pgf@decorate@inputsegment@first%
	\let\pgfpointdecoratedinputsegmentlast\pgf@decorate@inputsegment@last%
	\let\pgfpointdecoratedinputsegmentsupporta\pgf@decorate@inputsegment@supporta%
	\let\pgfpointdecoratedinputsegmentsupportb\pgf@decorate@inputsegment@supportb%
}


\endinput
pgflibraryfillbetween.code.tex
% Copyright 2013 by Christian Feuersaenger
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Free Documentation License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.


\usepgflibrary{intersections}
% FIXME : ARCHITECTURE VIOLATION:  REQUIRES
% \usetikzlibrary{decorations.softclip} 
%
%\usepgfmodule{decorations}

\newif\ifpgfpathfillbetween@split

\pgfkeys{%
	/pgf/fill between/reverse/.is choice,
	/pgf/fill between/reverse/.default=true,
	/pgf/fill between/reverse/false/.code=\def\pgfpathfillbetween@reverse@mode{0},%
	/pgf/fill between/reverse/true/.code=\def\pgfpathfillbetween@reverse@mode{1},%
	%
	% checks the coordinates of the first two path instructions as heuristics:
	/pgf/fill between/reverse/auto/.code=\def\pgfpathfillbetween@reverse@mode{2},%
	/pgf/fill between/reverse/auto,
	/pgf/fill between/inner moveto/.is choice,
	/pgf/fill between/inner moveto/connect/.code=\def\pgfpathfillbetween@inner@moveto{1},
	/pgf/fill between/inner moveto/keep/.code=\def\pgfpathfillbetween@inner@moveto{2},
	/pgf/fill between/inner moveto/connect,
	%
	% split=true allows to generate individual result paths for every
	% region induced by the intersection points. Example: 
	% "color positive region in red and negative region in green".
	% The case split=false results in just one output path
	% (simpler+faster, but of course less powerful).
	/pgf/fill between/split/.is if=pgfpathfillbetween@split,
	/pgf/fill between/split/.default=true,
	%
	% Used to report results. This is mainly useful in conjunction
	% with split=true: each result segment will be streamed.
	%
	% Results are reported in the sequence
	%   begin
	%     next ready
	%     next ready
	%     ...
	%   end
	%
	% 'begin' has one arguments: the number of following single
	% streams.
	/pgf/fill between/result stream/begin/.code=,%
	%
	% 'next ready' has macro arguments, but the macro \pgfretval
	% contains the lowlevel path as result (i.e. you can write
	% \pgfsetpath\pgfretval to activate it).
	/pgf/fill between/result stream/next ready/.code={
		\pgfaddpathandBB{\pgfretval}%
	},%
	%
	% 'end' has no arguments.
	/pgf/fill between/result stream/end/.code=,%
}%

% \pgfpathfillbetween[<options>]{<first path>}{<second path>}
%
% Generates a new path consisting of the "fill between" of the two arguments.
% #1: optional arguments with /pgf/fill between prefix
% #2: a macro containing the first path. More precisely, it is supposed to be a return value of \pgfgetpath.
% #3: a macro containing the second path (in a format understood by \pgfsetpath). It is supposed to be a return value of \pgfgetpath.
\def\pgfpathfillbetween{\pgfutil@ifnextchar[{\pgfpathfillbetween@opt}{\pgfpathfillbetween@opt[]}}%
\def\pgfpathfillbetween@opt[#1]#2#3{%
	\begingroup
	\pgfqkeys{/pgf/fill between}{#1}%
	%
	% remove any special round-corner-tokens:
	\pgfprocessround{#2}{#2}%
	\pgfprocessround{#3}{#3}%
	%
	\if1\pgfpathfillbetween@inner@moveto
		% inner moveto=connect:
		\pgfpathfillbetween@connect@inner@movetos#2%
		\pgfpathfillbetween@connect@inner@movetos#3%
	\fi
	%
	\if2\pgfpathfillbetween@reverse@mode
		% reverse=auto
		\expandafter\pgfpathfillbetween@heuristics@get@direction#2\pgf@stop
		\let\pgfpath@filled@dir@first=\pgfretval
		\expandafter\pgfpathfillbetween@heuristics@get@direction#3\pgf@stop
		\let\pgfpath@filled@dir@second=\pgfretval
		%
		\ifx\pgfpath@filled@dir@first\pgfpath@filled@dir@second
			% Ok, they (seem to) have the same direction. Reverse one of them:
			\def\pgfpathfillbetween@reverse@mode{1}%
		\else
			\def\pgfpathfillbetween@reverse@mode{0}%
		\fi
	\fi
	%
	% softclip, if configured (no-op otherwise):
	\pgfpathcomputesoftclippath{#2}{\pgfpathfillbetween@softclip@A}\let#2=\pgfretval%
	\pgfpathcomputesoftclippath{#3}{\pgfpathfillbetween@softclip@B}\let#3=\pgfretval%
	%
	\ifx#2\pgfutil@empty
		\pgfpathfillbetween@warning{first}%
	\else
		\ifx#3\pgfutil@empty
			\pgfpathfillbetween@warning{second}%
		\else
			%
			\ifpgfpathfillbetween@split
				\pgfpathfillbetween@compute@splitted{#2}{#3}%
			\else
				\pgfkeys{/pgf/fill between/result stream/begin=1}%
				\pgfpathfillbetween@compute{#2}{#3}%
				\pgfpathfillbetween@invoke{result stream/next ready}%
				\pgfpathfillbetween@invoke{result stream/end}%
			\fi
		\fi
	\fi
	%
	%
	\endgroup
}%

\def\pgfpathfillbetween@warning#1{%
	\pgfwarning{fill between skipped: the #1 input path is empty.}%
}%

% Replaces all 'moveto' operations inside of the soft path '#1' by
% 'lineto'. This excludes the first moveto.
%
% The motivation is that fillbetween should ignore inner movetos.
%
% UPDATE: it turned out that replacing inner movetos is necessary, but
% not sufficient. Now, this macro does more:
% - it replaces isolated inner movetos by lineto
% - if two successive inner movetos occur, it throws away the first
%   one replaces the second by lineto
% - if one or more trailing movetos occur in a path, these will be
%   thrown away.
\def\pgfpathfillbetween@connect@inner@movetos#1{%
	\expandafter\pgfpathfillbetween@connect@inner@movetos@#1\pgf@stop%
	\let#1=\pgfretval
}
\def\pgfpathfillbetween@connect@inner@movetos@#1#2\pgf@stop{%
	\ifx#1\pgfsyssoftpath@movetotoken
		\pgfpathfillbetween@connect@inner@movetos@@{#2}%
		\expandafter\def\expandafter\pgfretval\expandafter{\expandafter\pgfsyssoftpath@movetotoken\pgfretval}%
	\else
		\pgfpathfillbetween@connect@inner@movetos@@{#1#2}%
	\fi
}%

% Substitute all movetotokens by linetotokens.
%
% In addition, it should *deduplicate* movetos, i.e.
% "moveto{<x>}{<y}moveto{<x2>}{<y2>}"
% -> "moveto{<x2>}{<y2>}"
%
% and: trailing movetos should be discarded.
\def\pgfpathfillbetween@connect@inner@movetos@@#1{%
	% this implementation is derived from \pgfutilstrreplace - it does
	% almost the same as
	% s/\pgfsyssoftpath@movetotoken/pgfsyssoftpath@linetotoken/g
	% -> but with the extra additions of deduplication and trailing
	%  moveto removal.
	\def\pgfretval{}%
	\pgfpathfillbetween@search@and@replace@loop{#1}%
}
\def\pgfpathfillbetween@connect@inner@moveto@foundit@#1\pgfsyssoftpath@movetotoken#2#3#4{%
	\ifx#4\pgf@EOI
		% ah - a trailing moveto.
		% In this case, we remember all until the moveto, but we omit
		% the trailing moveto and its arguments.
		\expandafter\def\expandafter\pgfretval\expandafter{\pgfretval #1}%
		%
		% ... and stop searching.
		\let\pgf@loc@TMPa\relax
	\else
		\ifx#4\pgfsyssoftpath@movetotoken
			% DEDUPLICATE: we have at least two successive movetos.
			% silently skip the first moveto and its arguments and go on
			% with the second moveto.
			\def\pgf@loc@TMPa{\pgfpathfillbetween@connect@inner@moveto@foundit@#1\pgfsyssoftpath@movetotoken}%
		\else
			% substitute it by a lineto.
			\expandafter\def\expandafter\pgfretval\expandafter{\pgfretval #1\pgfsyssoftpath@linetotoken{#2}{#3}}%
			%
			% ... continue the standard loop which skips over paths
			% until the next moveto. Remember to re-insert '#4':
			\def\pgf@loc@TMPa{\pgfpathfillbetween@connect@inner@moveto@foundit@@ #4}%
		\fi
	\fi
	\pgf@loc@TMPa
}%
\def\pgfpathfillbetween@connect@inner@moveto@foundit@@#1\pgf@EOI{%
	\pgfpathfillbetween@search@and@replace@loop{#1}%
}%

\def\pgfpathfillbetween@search@and@replace@loop#1{%
	\pgfutil@in@{\pgfsyssoftpath@movetotoken}{#1}%
	\ifpgfutil@in@
		\def\pgf@loc@TMPa{\pgfpathfillbetween@connect@inner@moveto@foundit@ #1\pgf@EOI}%
	\else
		\expandafter\def\expandafter\pgfretval\expandafter{\pgfretval #1}%
		\let\pgf@loc@TMPa=\relax
	\fi
	\pgf@loc@TMPa
}%

\def\pgfpathfillbetween@invoke#1{\pgfkeysvalueof{/pgf/fill between/#1/.@cmd}\pgfeov}

\def\pgfpathfillbetween@replace@first@moveto#1#2\pgf@stop{%
	\ifx#1\pgfsyssoftpath@movetotoken
		\def\pgfretval{\pgfsyssoftpath@linetotoken #2}%
	\else
		\def\pgfretval{#1#2}%
	\fi
}%

\def\pgfpathfillbetween@compute@splitted#1#2{%
	% 0. normalize path sequences.
	%  ATTENTION : there are implicit assumptions on the INTERNAL ORDER of the two paths!
    %    This implementation needs to loop over them synchronously, i.e. it processes
	%       the 0.th segment of a and the 0th of b, 
	%       the 1.th segment of a and the 1th of b, 
	%    and so on. Here, "i th segment" implies a sort order in ascending x direction.
	%    This is, however, a weakness of \pgfintersectionofpaths - it does not really support this kind of sorting.
	%    
	%   I work around this by restricting the implementation to the "common use-cases", i.e. to two plots of functions which do not intersect themselves (i.e. to "functions" in the original sense). This will probably (almost surely) fail for parametric functions or circles.
    %  
	\if0\pgfpathfillbetween@reverse@mode
		% reverse=false
		%
		% This means one plot is in direction '+' and one in '-', i.e.
		% a:  x ---> x ---> x
		% b:  x <--- x <--- x
		%
		% However, we have the implicit assumption that both paths can be processed synchronously, i.e. that they have the SAME direction.
		% To this end, we have to reverse one of them here (since \pgfintersectionofpaths does not automatically sort results in a suitable way):
		%
		\pgf@reverse@path{#2}%
		\let#2=\pgfretval
		%
		% However, we need to re-reverse the individual segments later-on...
		% So: set 'reverse=true'. Will be respected when assembling the splitted segments...
		\def\pgfpathfillbetween@reverse@mode{1}%
	\fi
	%
	% 1. compute intersection points:
	\pgf@intersect@sort@by@second@pathfalse
	%
	% FIXME : do we want to sort by time!? That might be needed for curvetos ... ?
	\pgf@intersect@sortfalse
	\pgfintersectionofpaths%
		{%
			\pgfsetpath#1%
		}%
		{%
			\pgfsetpath#2%
		}%
	%
	% FIXME : computing the intersections is fine... but it would be
	% even finer to report the resulting points back to tikz!
	% -> call the *tikz* intersection lib through some sort of callback!?
	%
	% 2.  split the first involved path into the
	% segments induced by the intersection points:
	\pgfcomputeintersectionsegments{1}%
	\let\pgfpathfilled@a@segments=\pgfretval
%
	% 2. split the second involved path into the
	% segments induced by the intersection points:
	\pgfcomputeintersectionsegments{2}%
	\let\pgfpathfilled@b@segments=\pgfretval
	%
	\ifnum\pgfpathfilled@a@segments=\pgfpathfilled@b@segments\relax
	\else
		\pgferror{Illegal internal state encountered: the number segments induced by the intersection points of the two paths DIFFER between the first and the second path: first path has \pgfpathfilled@a@segments\space whereas the second has \pgfpathfilled@b@segments.}%
	\fi
	%
	\pgfkeys{/pgf/fill between/result stream/begin=\pgfpathfilled@a@segments}%
	% Recombine the pairs of segments (a_i, b_i), i = 0,..., N-1 in a
	% filled way:
	\def\c@pgfpathfilled@counter{0}%
	\pgfmathloop
	\ifnum\c@pgfpathfilled@counter<\pgfpathfilled@a@segments\relax
		\expandafter\let\expandafter\pgf@loc@path@a\csname pgf@intersect@path@split@a@\c@pgfpathfilled@counter\endcsname
		\expandafter\let\expandafter\pgf@loc@path@b\csname pgf@intersect@path@split@b@\c@pgfpathfilled@counter\endcsname
		%
		\pgfpathfillbetween@compute{\pgf@loc@path@a}{\pgf@loc@path@b}%
		% report to the result stream. It knows how to deal with it:
		\pgfpathfillbetween@invoke{result stream/next ready}%
		%
		\pgfutil@advancestringcounter\c@pgfpathfilled@counter
	\repeatpgfmathloop
	\pgfpathfillbetween@invoke{result stream/end}%
}

\def\pgfpathfillbetween@compute#1#2{%
%\message{Combination of ^^J  \meaning#1\space and ^^J \meaning#2...^^J}%
	%
	\if1\pgfpathfillbetween@reverse@mode
		% reverse=true
		%
		% Ok, then reverse one of the paths. We choose the second one as that is easier to debug.
		% FIXME : might make sense to determine which one is shorter...
		\pgf@reverse@path{#2}%
		\let#2=\pgfretval
	\fi
	%
	% FIXME: what should I do if I have closed paths!? What is the
	% expected behavior!? I know that the combination of two closed
	% paths should probably be used as is, perhaps with even-odd-rule.
	% This here should do the job.
	%
	% NOTE: I believe the 'split' fails to work with closed paths.
	\pgfpathfillbetween@contains@closepathtoken{#1}%
	\let\b@pgfpathfillbetween@contains@close@a=\pgfretval
	\pgfpathfillbetween@contains@closepathtoken{#2}%
	\let\b@pgfpathfillbetween@contains@close@b=\pgfretval
	%
	\def\b@pgfpathfillbetween@contains@close{0}%
	\if1\b@pgfpathfillbetween@contains@close@b
		\def\b@pgfpathfillbetween@contains@close{1}%
	\fi
	\if1\b@pgfpathfillbetween@contains@close@a
		\def\b@pgfpathfillbetween@contains@close{1}%
	\fi
	%
	\if0\b@pgfpathfillbetween@contains@close@b
		\expandafter\pgfpathfillbetween@replace@first@moveto#2\pgf@stop
		\let#2=\pgfretval
	\fi
	%
	\t@pgf@toka=\expandafter{#1}%
	\t@pgf@tokb=\expandafter{#2}%
	%
	\if0\b@pgfpathfillbetween@contains@close
		% we need to close the resulting combined path, otherwise decorations will look strange:
		\expandafter\pgfpathfillbetween@get@first@coord#1\pgf@stop
		\t@pgf@tokc=\expandafter{\expandafter\pgfsyssoftpath@closepathtoken\pgfretval}%
	\else
		\t@pgf@tokc={}%
	\fi
	%
	\edef\pgfretval{\the\t@pgf@toka\the\t@pgf@tokb\the\t@pgf@tokc}%
	%
%\message{^^J   = \meaning\pgfretval^^J}%
	% that's it.
}

% #1 a macro containing a softpath
% OUTPUT:
%   \pgfretval = 1 if the path contains \pgfsyssoftpath@closepathtoken
%   and 0 otherwise.
\def\pgfpathfillbetween@contains@closepathtoken#1{%
	\expandafter\pgfutil@in@\expandafter\pgfsyssoftpath@closepathtoken\expandafter{#1}%
	\ifpgfutil@in@
		\def\pgfretval{1}%
	\else
		\def\pgfretval{0}%
	\fi
}

\def\pgfpathfillbetween@get@first@coord#1#2#3#4\pgf@stop{%
	\def\pgfretval{{#2}{#3}}%
}%

% A utility function like \pgfsetpath which calls \pgfsetpath *and* protocols
% the size of each path segment (i.e. compute the bounding box).
%
% #1 a macro containing a softpath (i.e. something returned by
% \pgfgetpath)
%
% SIDE--EFFECT: defines \pgfpointlastofsetpath  to be the last point of path #1
\def\pgfsetpathandBB#1{%
	\let\pgfpointlastofsetpath=\pgfutil@empty
	\expandafter\pgfsetpath@loop#1\pgf@stop
	%
	\pgfsetpath{#1}%
}%

% Like \pgfsetpathandBB, but this here *appends* to the existing
% softpath.
%
% #1 a macro containing a softpath (i.e. something returned by
% \pgfgetpath)
% SIDE--EFFECT: defines \pgfpointlastofsetpath  to be the last point of path #1
\def\pgfaddpathandBB#1{%
	\let\pgfpointlastofsetpath=\pgfutil@empty
	\expandafter\pgfsetpath@loop#1\pgf@stop
	\pgfaddpath#1%
}

% Like \pgfsetpath, but this here *appends* to the existing
% softpath.
%
% #1 a macro containing a softpath (i.e. something returned by
% \pgfgetpath)
\def\pgfaddpath#1{%
	% append to any previous path elements:
	\pgfgetpath\pgf@temp
	\t@pgf@tokc=\expandafter{\pgf@temp}%
	\t@pgf@toka=\expandafter{#1}%
	\edef\pgfretval{\the\t@pgf@tokc\the\t@pgf@toka}%
	\pgfsetpath{\pgfretval}%
}

% Takes a softpath on input, replaces its first moveto by a lineto,
% and returns it as softpath.
% #1: a macro containing a softpath (i.e. the result of \pgfgetpath)
% 
% On output, \pgfretval contains a modified path.
\def\pgfpathreplacefirstmoveto#1{%
	\ifx#1\pgfutil@empty
		\let\pgfretval=#1%
	\else
		\expandafter\pgfpathfillbetween@replace@first@moveto#1\pgf@stop
	\fi
}

% Defines \pgfretval to be '+' if the path's direction is "ascending"
% and "-" otherwise.
%
% Here, "ascending" means that its first two coordinates have
% ascending X coordinates. If the X coordinates are equal, the Y
% coordinates are used instead.
\def\pgfpathfillbetween@heuristics@get@direction#1#2#3{%
	\pgfutil@ifnextchar\pgf@stop{%
		% wow. it has just one path element... we can do nothing.
		\def\pgfretval{+}%
		\pgfutil@gobble
	}{%
		\pgfpathfillbetween@heuristics@get@direction@{#1}{#2}{#3}%
	}%
}%

% example: \pgfsyssoftpath@movetotoken{#2}{#3}\pgfsyssoftpath@linetotoken{#5}{#6}#7\pgf@stop
% example: 
%	\pgfsyssoftpath@movetotoken{#2}{#3}
%	\pgfsyssoftpath@curvetosupportatoken{<x>}{<y>}
%	\pgfsyssoftpath@curvetosupportbtoken{<x>}{<y>}
%	\pgfsyssoftpath@curvetotoken{<x>}{<y>}\pgf@stop
\def\pgfpathfillbetween@heuristics@get@direction@#1#2#3#4#5#6#7\pgf@stop{%
	\def\pgf@temp{#4}%
	\def\pgf@tempb{\pgfsyssoftpath@curvetosupportatoken}%
	\ifx\pgf@temp\pgf@tempb
		% Ah - a curveto! Use the end-point for the heuristics.
		\pgfpathfillbetween@heuristics@get@direction@curveto #1{#2}{#3}#4{#5}{#6}#7\pgf@stop
	\else
		% Ok, assume it is line to (or its variants):
		\pgfpathfillbetween@heuristics@get@direction@@{#2}{#3}{#5}{#6}%
	\fi
}%

\def\pgfpathfillbetween@heuristics@get@direction@curveto#1#2#3\pgfsyssoftpath@curvetosupportatoken#4\pgfsyssoftpath@curvetotoken#5#6#7\pgf@stop{%
	\pgfpathfillbetween@heuristics@get@direction@@{#2}{#3}{#5}{#6}%
}%

% #1: x1
% #2: y1
% #3: x2
% #4: y2
\def\pgfpathfillbetween@heuristics@get@direction@@#1#2#3#4{%
	\edef\pgfretval{%
		\ifdim #1<#3\space
			+%
		\else 
			\ifdim #1=#3\space
				\ifdim #2<#4\space
					+%
				\else
					-%
				\fi
			\else
				-%
			\fi
		\fi
	}%
}

% Accumulates the path's bounding box, the last moveto, and the last
% coord.
\def\pgfsetpath@loop#1{%
	\ifx#1\pgf@stop%
		\let\pgfsetpathBB@protocolsizesnext=\relax%
	\else%
		\ifx#1\pgfsyssoftpath@movetotoken%
			\let\pgfsetpathBB@protocolsizesnext=\pgfsetpathBB@protocolsizestoken@moveto%
		\else%
			\ifx#1\pgfsyssoftpath@linetotoken%
				\let\pgfsetpathBB@protocolsizesnext=\pgfsetpathBB@protocolsizestoken@simple%
			\else%
				\ifx#1\pgfsyssoftpath@closepathtoken%
					\let\pgfsetpathBB@protocolsizesnext=\pgfsetpathBB@protocolsizestoken@simple%
				\else%
					\ifx#1\pgfsyssoftpath@curvetosupportatoken%
						\let\pgfsetpathBB@protocolsizesnext=\pgfsetpathBB@protocolsizestoken@curveto%
					\else%
						\ifx#1\pgfsyssoftpath@rectcornertoken%
							\let\pgfsetpathBB@protocolsizesnext=\pgfsetpathBB@protocolsizestoken@rect%
						\fi%
					\fi%
				\fi%
			\fi%
		\fi%
	\fi%
	\pgfsetpathBB@protocolsizesnext}

\def\pgfsetpathBB@protocol@lastmoveto#1#2{%
	\gdef\pgfsyssoftpath@lastmoveto{{#1}{#2}}%
}

\def\pgfsetpathBB@protocolsizestoken@moveto#1#2{%
	% required for --cycle, among others:
	\pgfsetpathBB@protocol@lastmoveto{#1}{#2}%
	\pgfsetpathBB@protocolsizestoken@simple{#1}{#2}%
}
\def\pgfsetpathBB@protocolsizestoken@simple#1#2{%
	\def\pgfpointlastofsetpath{\pgfqpoint{#1}{#2}}%
	\pgf@protocolsizes{#1}{#2}%
	\pgfsetpath@loop%
}

\def\pgfsetpathBB@protocolsizestoken@curveto#1#2\pgfsyssoftpath@curvetosupportbtoken#3#4\pgfsyssoftpath@curvetotoken#5#6{%
	\def\pgfpointlastofsetpath{\pgfqpoint{#5}{#6}}%
	\pgf@protocolsizes{#1}{#2}%
	\pgf@protocolsizes{#3}{#4}%
	\pgf@protocolsizes{#5}{#6}%
	\pgfsetpath@loop
}

\def\pgfsetpathBB@protocolsizestoken@rect#1#2\pgfsyssoftpath@rectsizetoken#3#4{%
	\pgf@protocolsizes{#1}{#2}%
	\pgf@xa=#1\relax%
	\advance\pgf@xa by#3\relax%
	\pgf@ya=#2\relax%
	\advance\pgf@ya by#4\relax%
	\pgf@protocolsizes{\pgf@xa}{\pgf@ya}%
	\pgfsetpath@loop
}%

% Defines \pgfretval to be the reversed path of #1.
%
% #1 is supposed to be a macro containing a path without rounding specials (i.e. a result
% of \pgfprocessround)
\def\pgfcomputereversepath#1{%
	% unfortunately, this is already used by internal macros...
	\pgf@reverse@path#1%
}%
\def\pgf@reverse@path#1{%
	% ATTENTION: this here is a special implementation which
	% operates directly on softpaths. It does not make use of \pgf@decorate@inputsegmentobjects@reverse (reverse path decoration)
	% because (a) decorations require their own special format and (b)
	% this implementation is faster (both with respect to runtime asymptotics and runtime constant).
	\def\pgf@reverse@first@type{}%
	\def\pgf@reverse@last@pt{}%
	\def\b@pgf@reversepath@last@is@close{0}%
	\pgfprependlistnewempty{pgfretval}%
	\let\pgfreverse@iterate=\pgfreverse@checkfirst@then
	\expandafter\pgf@reverse@loop#1\pgf@stop
	%
	\if 0\b@pgf@reversepath@last@is@close%
		\expandafter\pgfreverse@prepend@last\expandafter{\pgf@reverse@first@type}{x}{x}%
	\else
		% as soon as a closepathtoken is encountered, the associated
		% moveto is processed right away.
		%
		% FIXME : I doubt that the implementation works if more than
		% one closepathtoken is in here ...
	\fi
	\pgfprependlistlet\pgfretval={pgfretval}%
	%
}%

\def\pgf@reverse@loop#1{%
	\ifx#1\pgf@stop%
		\let\pgfreverse@next=\relax%
	\else%
		\def\b@pgf@reversepath@last@is@close{0}%
		\ifx#1\pgfsyssoftpath@movetotoken%
			\let\pgfreverse@next=\pgfreverse@token@moveto%
		\else%
			\ifx#1\pgfsyssoftpath@linetotoken%
				\let\pgfreverse@next=\pgfreverse@token@lineto%
			\else%
				\ifx#1\pgfsyssoftpath@closepathtoken%
					\let\pgfreverse@next=\pgfreverse@token@close%
				\else%
					\ifx#1\pgfsyssoftpath@curvetosupportatoken%
						\let\pgfreverse@next=\pgfreverse@token@curveto%
					\else%
						\ifx#1\pgfsyssoftpath@rectcornertoken%
							\let\pgfreverse@next=\pgfreverse@token@rect%
						\fi%
					\fi%
				\fi%
			\fi%
		\fi%
	\fi%
	\pgfreverse@next}

\def\pgfreverse@checkfirst@then#1{%
	\def\pgf@reverse@first@type{#1}%
	\let\pgfreverse@iterate=\pgfutil@gobble
}%

\def\pgfreverse@prepend@last#1#2#3{%
	\ifx\pgf@reverse@last@pt\pgfutil@empty
	\else
		\t@pgf@toka={#1}%
		\t@pgf@tokb=\expandafter{\pgf@reverse@last@pt}%
		\edef\pgf@marshal{\the\t@pgf@toka\the\t@pgf@tokb}%
		\expandafter\pgfprependlistpushfront\pgf@marshal\to{pgfretval}%
	\fi
	\def\pgf@reverse@last@pt{{#2}{#3}}%
}%

\def\pgfreverse@token@moveto#1#2{%
	\pgfreverse@iterate{\pgfsyssoftpath@movetotoken}%
	\pgfreverse@prepend@last\pgfsyssoftpath@movetotoken{#1}{#2}%
	\pgf@reverse@loop%
}

\def\pgfreverse@token@lineto#1#2{%
	\pgfreverse@iterate{\pgfsyssoftpath@linetotoken}%
	\pgfreverse@prepend@last\pgfsyssoftpath@linetotoken{#1}{#2}%
	\pgf@reverse@loop
}
\def\pgfreverse@token@close#1#2{%
	% close tokens are complicated: they always correspond to the most
	% recent moveto token.
	%
	% First: remember that the last encountered token was 'close': if
	% this is the lastmost token, we must not insert a final moveto.
	\def\b@pgf@reversepath@last@is@close{1}%
	%
	% Second: *append*
	% \pgfsyssoftpath@closepathtoken{<lastx>}{<lasty>}.
	%
	% Appending is unsupported by the prepend-list, so we have to
	% terminate it, append, and reinitialize it with the result:
	\pgfprependlistlet\pgfretval={pgfretval}%
	\t@pgf@toka=\expandafter{\pgfretval}%
	\t@pgf@tokb={\pgfsyssoftpath@closepathtoken}%
	\t@pgf@tokc=\expandafter{\pgf@reverse@last@pt}%
	\edef\pgf@marshal{\the\t@pgf@toka\the\t@pgf@tokb\the\t@pgf@tokc}%
	%
	% ... create a new list with the result:
	\pgfprependlistnewempty{pgfretval}%
	\expandafter\pgfprependlistpushfront\pgf@marshal\to{pgfretval}%
	%
	% and prepend a moveto.
	\pgfreverse@prepend@last\pgfsyssoftpath@movetotoken{#1}{#2}%
	%
	\pgf@reverse@loop
}

\def\pgfreverse@token@curveto#1#2\pgfsyssoftpath@curvetosupportbtoken#3#4\pgfsyssoftpath@curvetotoken#5#6{%
	\pgfreverse@iterate{\pgfsyssoftpath@curvetosupportatoken{#1}{#2}\pgfsyssoftpath@curvetosupportbtoken{#3}{#4}\pgfsyssoftpath@curvetotoken}%
	\pgfreverse@prepend@last{\pgfsyssoftpath@curvetosupportatoken{#3}{#4}\pgfsyssoftpath@curvetosupportbtoken{#1}{#2}\pgfsyssoftpath@curvetotoken}{#5}{#6}%
	\pgf@reverse@loop
}

\def\pgfreverse@token@rect#1#2\pgfsyssoftpath@rectsizetoken#3#4{%
	% FIXME: UNTESTED
	\pgf@xa=#1\relax%
	\advance\pgf@xa by#3\relax%
	\pgf@ya=#2\relax%
	\advance\pgf@ya by#4\relax%
	\edef\pgf@marshal{%
		\noexpand\pgfsyssoftpath@movetotoken
		{%
			{#1}{#2}%
			\noexpand\pgfsyssoftpath@linetotoken{\the\pgf@xa}{#2}%
			\noexpand\pgfsyssoftpath@linetotoken{\the\pgf@xa}{\the\pgf@ya}%
			\noexpand\pgfsyssoftpath@linetotoken{#1}{\the\pgf@ya}%
			\noexpand\pgfsyssoftpath@closepathtoken{#1}{#2}%
		}%
	}%
	\pgfreverse@iterate\pgfsyssoftpath@movetotoken
	\edef\pgf@reverse@last@pt{{#1}{#2}}%
	\expandafter\pgf@reverse@loop\pgf@marshal%
}

% ----------------------------------------
% Given that some intersections have been computed already (and are in
% the current scope), this command computes the intersection segments
% for one of the input arguments.
%
% On output, both \pgfretval and \pgfintersectionsegments contain the number of computed segments. The
% segments as such can be accessed via \pgfgetintersectionsegmentpath.
%
% #1 : should be '1' if the FIRST argument of
% \pgfintersectionofpaths should be used and '2' the SECOND
% argument of \pgfintersectionofpaths should be used on input.
%
% EXAMPLE:
%
%   	\def\inputValue{%
%   		\pgfsyssoftpath@movetotoken {56.90549pt}{0.0pt}%
%   		\pgfsyssoftpath@linetotoken {85.35823pt}{28.45274pt}%
%   		\pgfsyssoftpath@linetotoken {113.81097pt}{0.0pt}%
%   		\pgfsyssoftpath@linetotoken {142.26372pt}{28.45274pt}%
%   		\pgfsyssoftpath@linetotoken {170.71646pt}{0.0pt}%
%   	}
%
%   	\pgfpointintersectionsolution{1}%
%   	\pgfplotsassertequalstok{\the\pgf@x, \the\pgf@y}{71.13918pt, 14.2278pt}{solution 1}
%   	\pgfpointintersectionsolution{2}%
%   	\pgfplotsassertequalstok{\the\pgf@x, \the\pgf@y}{99.59497pt, 14.2278pt}{solution 2}
%   	\pgfpointintersectionsolution{3}%
%   	\pgfplotsassertequalstok{\the\pgf@x, \the\pgf@y}{128.05057pt, 14.2278pt}{solution 3}
%   	\pgfpointintersectionsolution{4}%
%   	\pgfplotsassertequalstok{\the\pgf@x, \the\pgf@y}{156.50636pt, 14.2278pt}{solution 4}
%   	
%   
%   	\pgfcomputeintersectionsegments{1}%
%   
%   	\message{OUTPUT: \meaning\pgfretval^^J}%
%   	\expandafter\def\csname expected@a@0\endcsname{%
%   		\pgfsyssoftpath@movetotoken {56.90549pt}{0.0pt}%
%   \pgfsyssoftpath@linetotoken{71.13918pt}{14.2278pt}%
%   	}
%   	\expandafter\def\csname expected@a@1\endcsname{%
%   		\pgfsyssoftpath@movetotoken{71.13918pt}{14.2278pt}%
%   		\pgfsyssoftpath@linetotoken {85.35823pt}{28.45274pt}%
%   \pgfsyssoftpath@linetotoken{99.59497pt}{14.2278pt}%
%   	}
%   	\expandafter\def\csname expected@a@2\endcsname{%
%   		\pgfsyssoftpath@movetotoken{99.59497pt}{14.2278pt}%
%   		\pgfsyssoftpath@linetotoken {113.81097pt}{0.0pt}%
%   \pgfsyssoftpath@linetotoken{128.05057pt}{14.2278pt}%
%   	}
%   	\expandafter\def\csname expected@a@3\endcsname{%
%   		\pgfsyssoftpath@movetotoken{128.05057pt}{14.2278pt}%
%   		\pgfsyssoftpath@linetotoken {142.26372pt}{28.45274pt}%
%   \pgfsyssoftpath@linetotoken{156.50636pt}{14.2278pt}%
%   	}
%   	\expandafter\def\csname expected@a@4\endcsname{%
%   		\pgfsyssoftpath@movetotoken{156.50636pt}{14.2278pt}%
%   		\pgfsyssoftpath@linetotoken {170.71646pt}{0.0pt}%
%   	}
%   % 
\def\pgfcomputeintersectionsegments#1{%
	\pgfcomputeintersectionsegments@set@src{#1}%
	\ifnum\pgfintersectionsolutions=0 %
		\pgfutil@namelet{pgf@intersect@path@split@\pgf@insert@intersections@src @0}{pgf@intersect@path@\pgf@insert@intersections@src}%
		\def\pgfretval{0}%
	\else
		%
		% This algorithm *relies* on an increasing sort order. Sort
		% them:
		\pgfintersectionsolutionsortbytime@@%
		%
		%
		\pgfapplistnewempty{pgfretval@tmp}%
		\def\pgf@insert@cursolution{1}%
		\def\c@pgf@path@result{0}%
		\let\c@pgf@path@segment=\c@pgf@countd
		\let\c@pgf@path@segment@trg=\c@pgf@countc
		\c@pgf@path@segment=0 %
		\pgf@fillbetween@get@time@off{\pgf@insert@intersections@src}{\pgf@insert@cursolution}%
		\c@pgf@path@segment@trg=\pgfretval\relax
		%
		\pgfutil@namelet{pgf@loc@TMPa}{pgf@intersect@path@\pgf@insert@intersections@src}%
		\expandafter\pgf@insert@intersections@loop\pgf@loc@TMPa\pgf@stop
		%
		\pgfapplistlet\pgf@loc@TMPa={pgfretval@tmp}%
		\expandafter\let\csname pgf@intersect@path@split@\pgf@insert@intersections@src @\c@pgf@path@result\endcsname=\pgf@loc@TMPa%
		\pgfutil@advancestringcounter\c@pgf@path@result%
		\let\pgfretval=\c@pgf@path@result%
	\fi
	\let\pgfintersectionsegments=\pgfretval
}%

% Defines \pgfretval to contain the desired path segment as softpath.
%
% @see \pgfsetpath
% @see \pgfsetpathandBB
% @see \pgfaddpathandBB
%
% #1: the value '1' if results for the FIRST argument of
% \pgfintersectionofpaths are requested or '2' if results for the
% SECOND path are requested (compare \pgfcomputeintersectionsegments).
% #2: the segment index (a number 0<= #2 < numbersegments).
%  The number of segments is \pgfintersectionsegments
\def\pgfgetintersectionsegmentpath#1#2{%
	\pgfcomputeintersectionsegments@set@src{#1}%
	\pgfmathparse{#2}%
	\afterassignment\pgfcomputeintersectionsegments@set@src@gobble
	\c@pgf@countc=\pgfmathresult\relax%
	\ifnum\c@pgf@countc<0
		\advance\c@pgf@countc by \pgfintersectionsegments\relax
	\fi
	\expandafter\let\expandafter\pgfretval\csname pgf@intersect@path@split@\pgf@insert@intersections@src @\the\c@pgf@countc\endcsname
	\ifx\pgfretval\relax
		\pgferror{There is no intersection segment '#2' in path '#1'}%
	\fi
}%
\def\pgfcomputeintersectionsegments@set@src@gobble#1\relax{}

\def\pgfcomputeintersectionsegments@set@src#1{%
	\ifcase#1\relax
		% 0
		\pgferror{illegal argument supplied.}
	\or
		\def\pgf@insert@intersections@src{a}%
	\or
		\def\pgf@insert@intersections@src{b}%
	\else
		\pgferror{illegal argument supplied.}
	\fi
}%

\def\pgfintersectionsolutionsortbytime@@{%
	% this is an O(n^2) sort method. It might suffice provided that
	% the number of intersections is small... and it is the same
	% runtime as that of the intersection lib as such (which is, in
	% fact, worse).
	%
	% Note that this bubble-sort-approach has the benefit that if the
	% input sequence *is* actually sorted, that it will have no effect
	% at all (linear time).
	\pgf@intersect@solutions@sortfinishtrue%
	\pgfmathloop%
		\ifnum\pgfmathcounter<\pgfintersectionsolutions\relax%
			\pgfutil@tempcnta=\pgfmathcounter%
			\advance\pgfutil@tempcnta by1\relax%
			%
			% acquire the sort keys...
			\pgfintersectiongetsolutiontimes{\pgfmathcounter}{\pgf@loc@tmp@A@a}{\pgf@loc@tmp@A@b}%
			\pgfintersectiongetsolutiontimes{\the\pgfutil@tempcnta}{\pgf@loc@tmp@B@a}{\pgf@loc@tmp@B@b}%
			%
			\ifdim\csname pgf@loc@tmp@A@\pgf@insert@intersections@src\endcsname pt>%
				\csname pgf@loc@tmp@B@\pgf@insert@intersections@src\endcsname pt\relax%
				\pgf@intersect@solutions@sortfinishfalse%
				%
				\pgfintersectionsolutionsortbytime@swap{pgfpoint@intersect@solution@\pgfmathcounter}%
					{pgfpoint@intersect@solution@\the\pgfutil@tempcnta}%
				%
				\pgfintersectionsolutionsortbytime@swap{pgf@intersect@solution@props@\pgfmathcounter}%
					{pgf@intersect@solution@props@\the\pgfutil@tempcnta}%
			\fi%
	\repeatpgfmathloop%
	\ifpgf@intersect@solutions@sortfinish%
	\else%
		\expandafter\pgfintersectionsolutionsortbytime@@%
	\fi%
}


% #1: either 'a' or 'b', depending on the required part
% #2: the solution index (starting with 1)
% Defines \pgfretval to contain the result.
\def\pgf@fillbetween@get@time@off#1#2{%
	\pgfintersectiongetsolutionsegmentindices{#2}{\pgf@temp@a}{\pgf@temp@b}%
	\edef\pgfretval{\csname pgf@temp@#1\endcsname}%
}%

% ----------------------------------------------------------------------------------


% Splits a Bezier curve at a designated time 't'
% using decasteljau
%--------------------------------------------------
% Point lerp(float t, Point A, Point B) {
% return A*(1-t) + B*t; // + and * overloaded for Points
% }
% 
% void split(t, Point P[4], Point L[4], Point R[4]) {
% 	Point P01 = lerp(t, P[0], P[1]);
% 	Point P12 = lerp(t, P[1], P[2]);
% 	Point P23 = lerp(t, P[2], P[3]);
% 	Point P012 = lerp(t, P01, P12);
% 	Point P123 = lerp(t, P12, P13);
% 	Point Q = lerp(t, P012, P123);
% 	L[0] = P[0]; L[1] = P01; L[2] = P012; L[3] = Q;
% 	R[0] = Q;
% 	R[1] = P123; R[2] = P23; R[3] = P[3];
% }
%-------------------------------------------------- 
% INPUT:
%  #1: a value in the range [0,1] which determines the split point
%  #2,#3,#4,#5: the points of the curve, each of the form {<x>}{<y>}
% 
% OUTPUT:
%  \pgfretval@L{{<A>}{<B>}{<C>}{<D>}}
%  \pgfretval@R{{<A>}{<B>}{<C>}{<D>}}
%
% @see \pgf@split@curveto@softpaths
\def\pgf@split@curveto#1#2#3#4#5{%
	\begingroup
	\pgf@xa=-#1pt %
	\advance\pgf@xa by1pt %
	\edef\pgf@split@one@m@t{\pgf@sys@tonumber\pgf@xa}%
	%
	\pgf@split@curveto@lerp{#1}{\pgf@split@one@m@t}{#2}{#3}%
	\pgf@split@curveto@tomacro\pgf@split@curveto@p@AB
	%
	\pgf@split@curveto@lerp{#1}{\pgf@split@one@m@t}{#3}{#4}%
	\pgf@split@curveto@tomacro\pgf@split@curveto@p@BC
	%
	\pgf@split@curveto@lerp{#1}{\pgf@split@one@m@t}{#4}{#5}%
	\pgf@split@curveto@tomacro\pgf@split@curveto@p@CD
	%
	\pgf@split@curveto@lerp{#1}{\pgf@split@one@m@t}{\pgf@split@curveto@p@AB}{\pgf@split@curveto@p@BC}%
	\pgf@split@curveto@tomacro\pgf@split@curveto@p@ABC
	%
	\pgf@split@curveto@lerp{#1}{\pgf@split@one@m@t}{\pgf@split@curveto@p@BC}{\pgf@split@curveto@p@CD}%
	\pgf@split@curveto@tomacro\pgf@split@curveto@p@BCD
	%
	\pgf@split@curveto@lerp{#1}{\pgf@split@one@m@t}{\pgf@split@curveto@p@ABC}{\pgf@split@curveto@p@BCD}%
	\pgf@split@curveto@tomacro\pgf@split@curveto@p@Q
	%
	\xdef\pgf@marshal{%
		\edef\noexpand\pgfretval@L{{#2}{\pgf@split@curveto@p@AB}{\pgf@split@curveto@p@ABC}{\pgf@split@curveto@p@Q}}%
		\edef\noexpand\pgfretval@R{{\pgf@split@curveto@p@Q}{\pgf@split@curveto@p@BCD}{\pgf@split@curveto@p@CD}{#5}}%
	}%
	\endgroup
	\pgf@marshal
}

% Splits a Bezier curve at a designated time 't'
%
% This variants takes a part of a softpath as input:
%
% #1: a curveto- a macro containing a softpath of the form 
%   <x><y>\pgfsyssoftpath@curvetosupportatoken<x><y>\pgfsyssoftpath@curvetosupportbtoken<x><y>\pgfsyssoftpath@curvetotoken<x><y>
% #2: t in [0,1]
%
% OUTPUT: \pgfretval@L contains the LEFT segment (in the same softpath format) and \pgfretval@R contains the RIGHT segment (in the softpath format), \pgfretval contains the intersection point (i.e. the point evaluated at 't')
\def\pgf@split@curveto@softpaths#1#2{%
	\expandafter\pgf@split@curveto@softpaths@#1{#2}%
}

\def\pgf@split@curveto@softpaths@#1#2\pgfsyssoftpath@curvetosupportatoken#3#4\pgfsyssoftpath@curvetosupportbtoken#5#6\pgfsyssoftpath@curvetotoken#7#8#9{%
	\pgf@split@curveto{#9}%
		{{#1}{#2}}%
		{{#3}{#4}}%
		{{#5}{#6}}%
		{{#7}{#8}}%
	\expandafter\pgf@split@curveto@softpaths@@\pgfretval@L\pgfretval@L
	\expandafter\pgf@split@curveto@softpaths@@\pgfretval@R\pgfretval@R
}%

\def\pgf@split@curveto@softpaths@@#1#2#3#4#5{%
	% we can silently omit the moveto component.
	\def#5{\pgfsyssoftpath@curvetosupportatoken#2\pgfsyssoftpath@curvetosupportbtoken#3\pgfsyssoftpath@curvetotoken#4}%
	\def\pgfretval{#1}%
}%

% ----------------------------------------------------------------------------------

% defines \pgf@x, \pgf@y to be A*(1-t) + B*t
% #1: the scalar value 't' in [0,1]
% #2: the scalar value '1-t' in [0,1]
% #3: a 2d point 'A' of the form {<x>}{<y>}
% #4: a 2d point 'B' of the form {<x>}{<y>}
\def\pgf@split@curveto@lerp#1#2#3#4{%
	\pgfpointadd
		{\pgfqpointscale{#2}{\expandafter\pgfqpoint#3}}%
		{\pgfqpointscale{#1}{\expandafter\pgfqpoint#4}}%
}%

\def\pgf@split@curveto@tomacro#1{%
	\edef#1{{\the\pgf@x}{\the\pgf@y}}%
}


\def\pgfcomputeintersectionsegments@@{%
%\message{processing segment \the\c@pgf@path@segment\space (current solution \pgf@insert@cursolution/\pgfintersectionsolutions; target segment \the\c@pgf@path@segment@trg, currentxy \pgfinsert@intersect@tok@currentxy, lastxy \pgfinsert@intersect@tok@lastxy)^^J}%
	\pgfmathloop
	% we need to loop: it is fully acceptable if more than one
	% solution is on the same segment.
	\ifnum\c@pgf@path@segment=\c@pgf@path@segment@trg
		%
		\pgf@insert@intersections@split@segment
		\expandafter\pgfapplistpushback\pgfretval\to{pgfretval@tmp}%
		%
		%
		% report the current result segment!
		\pgfapplistlet\pgf@loc@TMPa={pgfretval@tmp}%
		\expandafter\let\csname pgf@intersect@path@split@\pgf@insert@intersections@src @\c@pgf@path@result\endcsname=\pgf@loc@TMPa%
		\pgfutil@advancestringcounter\c@pgf@path@result%
		% ... and start a new result segment. Keep in mind that it
		% should start with a moveto:
		\pgfapplistnewempty{pgfretval@tmp}%
		\csname pgfpoint@intersect@solution@\pgf@insert@cursolution\endcsname%
		\edef\pgf@loc@TMPa{\noexpand\pgfsyssoftpath@movetotoken{\the\pgf@x}{\the\pgf@y}}%
		\expandafter\pgfapplistpushback\pgf@loc@TMPa\to{pgfretval@tmp}%
		%
		%
		% OK, iterate:
		\ifnum\pgf@insert@cursolution=\pgfintersectionsolutions\relax
			% collect all remaining ones:
			\c@pgf@path@segment@trg=10000000 %
		\else
			\pgfutil@advancestringcounter\pgf@insert@cursolution
			\pgf@fillbetween@get@time@off{\pgf@insert@intersections@src}{\pgf@insert@cursolution}%
			\c@pgf@path@segment@trg=\pgfretval\relax
		\fi
	\repeatpgfmathloop
	\expandafter\pgfapplistpushback\pgfinsert@intersect@tok\to{pgfretval@tmp}%
	\let\pgfinsert@intersect@tok@lastxy=\pgfinsert@intersect@tok@currentxy
	\advance\c@pgf@path@segment by1 %
}%

% INPUT:
%  - \pgfinsert@intersect@tok@type is the current type (one of \pgfsyssoftpath@linetotoken or \pgfsyssoftpath@curvetotoken)
%  - \pgf@insert@cursolution is the current intersection index
%  - \pgfinsert@intersect@tok is the current path segment. On output, it is the *remaining* path segment.
%  - \pgfinsert@intersect@tok@lastxy the (x,y) coordinates of the last seen coordinate.
%
% OUTPUT:
%  - \pgfretval the segment which has been splitted off. It will be appended to the result.
%  - \pgfinsert@intersect@tok the remaining path segment which is to be processed
%  - \pgfinsert@intersect@tok@lastxy the (x,y) coordinates of the last seen coordinate which is to be processed.
\def\pgf@insert@intersections@split@segment{%
	\ifx\pgfinsert@intersect@tok@type\pgfsyssoftpath@linetotoken
		\csname pgfpoint@intersect@solution@\pgf@insert@cursolution\endcsname%
		\edef\pgfretval{\noexpand\pgfsyssoftpath@linetotoken{\the\pgf@x}{\the\pgf@y}}%
		% ... and keep \pgfinsert@intersect@tok at its current value (it is \pgfsyssoftpath@linetotoken{<next x>}{<next y>})
	\else
		\ifx\pgfinsert@intersect@tok@type\pgfsyssoftpath@curvetotoken
			% Ah; a curveto. That's more involved!
			% First, get the time offset of the current intersection:
			%
			% Get the global time:
			\pgfintersectiongetsolutiontimes{\pgf@insert@cursolution}{\pgf@split@it@time@a}{\pgf@split@it@time@b}%
			% Get time at the beginning of the current solution segment:
			\pgfintersectiongetsolutionsegmentindices{\pgf@insert@cursolution}{\pgf@split@it@timeoff@a}{\pgf@split@it@timeoff@b}%
			% compute local time within the current solution segment:
			\pgf@xa=\csname pgf@split@it@time@\pgf@insert@intersections@src\endcsname pt %
			\advance\pgf@xa by-\csname pgf@split@it@timeoff@\pgf@insert@intersections@src\endcsname pt %
			\edef\pgf@split@it@time{\pgf@sys@tonumber\pgf@xa}%
			%
			\let\pgf@split@it@start=\pgfinsert@intersect@tok@lastxy
			% we have to insert the last XY coordinates:
			\t@pgf@toka=\expandafter{\pgf@split@it@start}%
			\t@pgf@tokb=\expandafter{\pgfinsert@intersect@tok}%
			\edef\pgf@temp{\the\t@pgf@toka\the\t@pgf@tokb}%
			% Split into TWO curveto operations!
			\pgf@split@curveto@softpaths{\pgf@temp}{\pgf@split@it@time}%
			% ok, the first returned sub-curveto is the result of this method...
			\let\pgfretval=\pgfretval@L
			% ... and the second is the "remainder" which is still to be processed.
			\let\pgfinsert@intersect@tok=\pgfretval@R
		\else
			\pgferror{Unsupported path type \meaning\pgfinsert@intersect@tok@type. Cannot process these paths.}%
		\fi
	\fi
	%
	\csname pgfpoint@intersect@solution@\pgf@insert@cursolution\endcsname%
	\edef\pgfinsert@intersect@tok@lastxy{{\the\pgf@x}{\the\pgf@y}}%
}%

\def\pgf@insert@intersections@loop#1{%
	\ifx#1\pgf@stop%
		\let\pgfinsert@intersect@tok\pgfutil@empty%
		\let\pgfinsert@intersect@tok@type\pgfutil@empty
		\pgfcomputeintersectionsegments@@%
		\let\pgfinsert@intersect@next=\relax%
	\else%
		\ifx#1\pgfsyssoftpath@movetotoken%
			\let\pgfinsert@intersect@next=\pgfinsert@intersect@token@moveto%
		\else%
			\ifx#1\pgfsyssoftpath@linetotoken%
				\let\pgfinsert@intersect@next=\pgfinsert@intersect@token@lineto%
			\else%
				\ifx#1\pgfsyssoftpath@closepathtoken%
					\let\pgfinsert@intersect@next=\pgfinsert@intersect@token@close%
				\else%
					\ifx#1\pgfsyssoftpath@curvetosupportatoken%
						\let\pgfinsert@intersect@next=\pgfinsert@intersect@token@curveto%
					\else%
						\ifx#1\pgfsyssoftpath@rectcornertoken%
							\let\pgfinsert@intersect@next=\pgfinsert@intersect@token@rect%
						\fi%
					\fi%
				\fi%
			\fi%
		\fi%
	\fi%
	\pgfinsert@intersect@next}

\def\pgfinsert@intersect@token@moveto#1#2{%
	\def\pgfinsert@intersect@tok{\pgfsyssoftpath@movetotoken{#1}{#2}}%
	\let\pgfinsert@intersect@tok@type\pgfsyssoftpath@movetotoken
	\def\pgfinsert@intersect@tok@lastxy{{#1}{#2}}%
	\expandafter\pgfapplistpushback\pgfinsert@intersect@tok\to{pgfretval@tmp}%
	\pgf@insert@intersections@loop%
}

\def\pgfinsert@intersect@token@lineto#1#2{%
	\def\pgfinsert@intersect@tok{\pgfsyssoftpath@linetotoken{#1}{#2}}%
	\let\pgfinsert@intersect@tok@type\pgfsyssoftpath@linetotoken
	\def\pgfinsert@intersect@tok@currentxy{{#1}{#2}}%
	\pgfcomputeintersectionsegments@@%
	\pgf@insert@intersections@loop
}
\def\pgfinsert@intersect@token@close#1#2{%
	\def\pgfinsert@intersect@tok{\pgfsyssoftpath@closepathtoken{#1}{#2}}%
	\let\pgfinsert@intersect@tok@type\pgfsyssoftpath@linetotoken
	\def\pgfinsert@intersect@tok@currentxy{{#1}{#2}}%
	\pgfcomputeintersectionsegments@@%
	\pgf@insert@intersections@loop
}

\def\pgfinsert@intersect@token@curveto#1#2\pgfsyssoftpath@curvetosupportbtoken#3#4\pgfsyssoftpath@curvetotoken#5#6{%
	\def\pgfinsert@intersect@tok{\pgfsyssoftpath@curvetosupportatoken{#1}{#2}\pgfsyssoftpath@curvetosupportbtoken{#3}{#4}\pgfsyssoftpath@curvetotoken{#5}{#6}}%
	\let\pgfinsert@intersect@tok@type\pgfsyssoftpath@curvetotoken
	\def\pgfinsert@intersect@tok@currentxy{{#5}{#6}}%
	\pgfcomputeintersectionsegments@@%
	\pgf@insert@intersections@loop
}

\def\pgfinsert@intersect@token@rect#1#2\pgfsyssoftpath@rectsizetoken#3#4{%
	\pgf@xa=#1\relax%
	\advance\pgf@xa by#3\relax%
	\pgf@ya=#2\relax%
	\advance\pgf@ya by#4\relax%
	\edef\pgf@marshal{%
		\noexpand\pgfsyssoftpath@movetotoken{#1}{#2}%
		\noexpand\pgfsyssoftpath@linetotoken{#1}{\the\pgf@ya}%
		\noexpand\pgfsyssoftpath@linetotoken{\the\pgf@xa}{\the\pgf@ya}%
		\noexpand\pgfsyssoftpath@linetotoken{\the\pgf@xa}{#2}%
		\noexpand\pgfsyssoftpath@closepathtoken{#1}{#2}%
	}%
	\expandafter\pgf@insert@intersections@loop\pgf@marshal%
}


% #1: a macro containing the clip path. More precisely, it is supposed to be a return value of \pgfgetpath.
\def\pgffillbetweensetsoftclippathfirst#1{%
	\let\pgfpathfillbetween@softclip@A=#1%
}%

% #1: a macro containing the clip path. More precisely, it is supposed to be a return value of \pgfgetpath.
\def\pgffillbetweensetsoftclippathsecond#1{%
	\let\pgfpathfillbetween@softclip@B=#1%
}%

% #1: a macro containing the clip path. More precisely, it is supposed to be a return value of \pgfgetpath.
\def\pgffillbetweensetsoftclippath#1{%
	\pgffillbetweensetsoftclippathfirst{#1}%
	\pgffillbetweensetsoftclippathsecond{#1}%
}

% Default: no clip paths
\pgffillbetweensetsoftclippathfirst{\pgfutil@empty}
\pgffillbetweensetsoftclippathsecond{\pgfutil@empty}
\endinput

pgflibraryfpu.code.tex
% Copyright 2008/2009 by Christian Feuersaenger
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU General Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\newif\ifpgfmathfloatparseactive
\newif\ifpgfmathfloat@scaleactive

% public macro which invokes '#1' if the fpu is installed and ready and '#2'
% otherwise.
\def\pgflibraryfpuifactive#1#2{%
	\ifpgfmathfloatparseactive
		#1%
	\else
		#2%
	\fi
}%

\pgfqkeys{/pgf}{
	% enable the FPU parser if it is not yet active
	%
	% It will be deactivated after the current TeX group
	fpu/.is choice,
	fpu/true/.code={%
		\ifpgfmathfloatparseactive
		\else
			\pgfutil@ifundefined{pgfmathdeclarefunction}{%
				% Ohoh - we are running on a TeX distribution with 
				% PGF 2.00 which doesn't have the new math engine.
				% I can provide special treatment here, provided that
				% all float commands are still able to run (that means
				% more information needs to be copied from the pgf cvs
				% to pgf 2.00 - for example pgfmathfloat.code.tex).
				% 
				% I employ this to work with pgfplots and pgf 2.00
				% using all new features.
				\pgfmathfloat@parser@install@pgf@two@null@null%
			}{%
				\pgfmathfloat@parser@install%
			}%
			\pgfmathfloatparseactivetrue
			% improve compatibility with Marks FP library:
			\pgfkeysalso{/pgf/fixed point arithmetic/.prefix style={/pgf/fpu=false}}%
		\fi
	},%
	fpu/false/.code={%
		\ifpgfmathfloatparseactive
			\pgfmathfloat@uninstall%
			\pgfmathfloatparseactivefalse
		\fi
	},%
	fpu/.default=true,
	% Use this to introduce a result scaling.
	% Every expression in which the prefix '*' occurs
	% will be multiplied with the result and converted to fixed point
	% representation.
	fpu/scale results/.code={%
		\ifpgfmathfloatparseactive
			\pgfmathparse{#1}%
		\else
			\pgfmathfloatparsenumber{#1}%
		\fi
		\let\pgfmathfloatscale=\pgfmathresult%
	},%		
	% determines the output format of each complete expression parsing
	% process. If 'scale results' is active, 'fixed' is assumed
	% automatically.
	fpu/output format/.is choice,
	fpu/output format/float/.code=	{\let\pgfmathfloatparse@output=\relax},
	fpu/output format/sci/.code=	{\def\pgfmathfloatparse@output{\pgfmathfloattosci@{\pgfmathresult}}},
	fpu/output format/fixed/.code=	{\def\pgfmathfloatparse@output{\pgfmathfloattofixed@{\pgfmathresult}}},
	fpu/output format/float,
	fpu/rel thresh/.code={%
		\pgfmathfloatparsenumber{#1}%
		\let\pgfmathfloat@relthresh=\pgfmathresult
	},
	fpu/rel thresh=1e-4,
}

\pgfmathfloatcreate{1}{1.0}{0}\let\pgfmathfloatscale=\pgfmathresult

% This is the replacement parser invocation.
% It does two things which are different to \pgfmathparse:
% 1. it disables any dimension dependand scalings,
% 2. it implements the 'scale results' feature.
\def\pgfmathfloatparse{%
	\begingroup%
		% disable any dimension-dependant scalings:
		\let\pgfmathpostparse=\relax%
		\pgfmath@catcodes%
		\pgfmath@quickparsefalse%
		\pgfmathfloatparse@}

% for pgf 2.00 :
\def\pgfmathfloatparse@pgf@two@null@null{%
	\pgfmath@quickparsefalse%
	\pgfmathfloatparse@}

\def\pgfmathfloatparse@#1{%
	\edef\pgfmathfloat@expression{#1}%
	\expandafter\pgfmathfloatparse@@\pgfmathfloat@expression\pgfmathfloat@
	\ifpgfmathfloat@scaleactive
		\expandafter\pgfmathfloatmultiply@\expandafter{\pgfmathresult}{\pgfmathfloatscale}
		\pgfmathfloattofixed{\pgfmathresult}%
	\else
		\pgfmathfloatparse@output
	\fi
}

\def\pgfmathfloat@char@asterisk{*}
\def\pgfmathfloatparse@@#1#2\pgfmathfloat@{%
	\def\pgfmathfloat@test{#1}%
	\ifx\pgfmathfloat@test\pgfmathfloat@char@asterisk%
		\def\pgfmathfloat@expression{#2}%
		\pgfmathfloat@scaleactivetrue
	\fi%
	\expandafter\pgfmathparse@\expandafter{\pgfmathfloat@expression}%
	% \endgroup provided by \pgfpathmarse@end
}

% Crude handling of file plots
%
\pgfkeys{/pgf/fpu/.cd,
  scale file plot x/.code=\pgfmathfloatparse{#1}\edef\pgfmathfloatplotscalex{\pgfmathresult*},
  scale file plot y/.code=\pgfmathfloatparse{#1}\edef\pgfmathfloatplotscaley{\pgfmathresult*},
  scale file plot z/.code=\pgfmathfloatparse{#1}\edef\pgfmathfloatplotscalez{\pgfmathresult*}
}

\def\pgfmathfloat@uninstall@appendcmd#1{%
	\expandafter\gdef\expandafter\pgfmathfloat@uninstall\expandafter{\pgfmathfloat@uninstall #1}%
}%

% If the uninstall command is already assembled, it will skip the
% uninstall assemblation.
\def\pgfmathfloat@plots@checkuninstallcmd{%
	\pgfutil@ifundefined{pgfmathfloat@uninstall}{%
		\global\let\pgfmathfloat@uninstall=\pgfutil@empty
	}{%
		% We already HAVE an uninstall command (prepared globally).
		% So: don't waste time assembling one!
		\def\pgfmathfloat@uninstall@appendcmd##1{}%
		\def\pgfmathfloat@prepareuninstallcmd##1{}%
	}%
}%

% This assembles an uninstall command globally ON FIRST USAGE.
% See \pgfmathfloat@plots@checkuninstallcmd
\def\pgfmathfloat@prepareuninstallcmd#1{%
	% and store backup information (globally - I don't want to do that
	% all the time when the FPU is used!):
	\expandafter\global\expandafter\let\csname pgfmathfloat@backup@\string#1\endcsname=#1%
	\expandafter\gdef\expandafter\pgfmathfloat@uninstall\expandafter{\pgfmathfloat@uninstall
		\expandafter\let\expandafter#1\csname pgfmathfloat@backup@\string#1\endcsname%
	}%
}
\def\pgfmathfloat@prepareuninstallcmd@csname#1{%
	% and store backup information (globally - I don't want to do that
	% all the time when the FPU is used!):
	{%
		\globaldefs=1
		\pgfutil@namelet{pgfmathfloat@backup@#1}{#1}%
		\expandafter\gdef\expandafter\pgfmathfloat@uninstall\expandafter{\pgfmathfloat@uninstall
			\pgfutil@namelet{#1}{pgfmathfloat@backup@#1}%
		}%
	}%
}

\def\pgfmathfloat@install#1=#2{%
	\pgfmathfloat@prepareuninstallcmd{#1}%
	\let#1=#2%
}
\def\pgfmathfloat@install@csname#1#2{%
	\pgfmathfloat@prepareuninstallcmd@csname{#1}%
	\pgfutil@namelet{#1}{#2}%
}
\def\pgfmathfloat@install@unimplemented#1{%
	\expandafter\pgfmathfloat@prepareuninstallcmd\csname pgfmath@#1@\endcsname%
	\expandafter\def\csname pgfmath#1@\endcsname##1{\pgfmathfloat@notimplemented{#1}}%
}
\def\pgfmathfloat@plots@install{%
	\let\pgfmathfloatplotscalex=\pgfutil@empty
	\let\pgfmathfloatplotscaley=\pgfutil@empty
	\let\pgfmathfloatplotscalez=\pgfutil@empty
	\pgfmathfloat@install\pgf@parsexyline=\pgfmathfloat@parsexyline%
	\pgfmathfloat@install\pgf@parsexyzline=\pgfmathfloat@parsexyzline%
}
\def\pgfmathfloat@parsexyline#1 #2 #3\pgf@stop{%
	\edef\pgfmathfloat@marshal{%
		\noexpand\pgfplotstreampoint{\noexpand\pgfpointxy{\pgfmathfloatplotscalex#1}{\pgfmathfloatplotscaley#2}}%
	}%
	\pgfmathfloat@marshal%
}
\def\pgfmathfloat@parsexyzline#1 #2 #3 #4\pgf@stop{%
  \edef\pgfmathfloat@marshal{%
		\noexpand\pgfplotstreampoint{%
			\noexpand\pgfpointxyz{\pgfmathfloatplotscalex#1}{\pgfmathfloatplotscaley#2}{\pgfmathfloatplotscalez#3}%
		}%
	}%
	\pgfmathfloat@marshal%
}

% 
\def\pgfmathfloat@parser@install@functions{%
	% Install float commands...
	%
	\pgfmathfloat@install\pgfmathadd@=\pgfmathfloatadd@%
	\pgfmathfloat@install\pgfmathsubtract@=\pgfmathfloatsubtract@%
	\pgfmathfloat@install\pgfmathneg@=\pgfmathfloatneg@%
	\pgfmathfloat@install\pgfmathmultiply@=\pgfmathfloatmultiply@%
	\pgfmathfloat@install\pgfmathdivide@=\pgfmathfloatdivide@%
	\pgfmathfloat@install\pgfmathabs@=\pgfmathfloatabs@%
	\pgfmathfloat@install\pgfmathround@=\pgfmathfloatround@%
	\pgfmathfloat@install\pgfmathfloor@=\pgfmathfloatfloor@%
	\pgfmathfloat@install\pgfmathmod@=\pgfmathfloatmod@%
	\pgfmathfloat@install\pgfmathmax@=\pgfmathfloatmax@%
	\pgfmathfloat@install\pgfmathmin@=\pgfmathfloatmin@%
	\pgfmathfloat@install\pgfmathsin@=\pgfmathfloatsin@%
	\pgfmathfloat@install\pgfmathcos@=\pgfmathfloatcos@%
	\pgfmathfloat@install\pgfmathtan@=\pgfmathfloattan@%
	\pgfmathfloat@install\pgfmathdeg@=\pgfmathfloatdeg@%
	\pgfmathfloat@install\pgfmathrad@=\pgfmathfloatrad@%
	\pgfmathfloat@install\pgfmathatan@=\pgfmathfloatatan@%
	\pgfmathfloat@install\pgfmathasin@=\pgfmathfloatasin@%
	\pgfmathfloat@install\pgfmathacos@=\pgfmathfloatacos@%
	\pgfmathfloat@install\pgfmathcot@=\pgfmathfloatcot@%
	\pgfmathfloat@install\pgfmathsec@=\pgfmathfloatsec@%
	\pgfmathfloat@install\pgfmathcosec@=\pgfmathfloatcosec@%
	\pgfmathfloat@install\pgfmathexp@=\pgfmathfloatexp@%
	\pgfmathfloat@install\pgfmathln@=\pgfmathfloatln@%
	\pgfmathfloat@install@csname{pgfmathlog10@}{pgfmathfloatlog10@}%
	\pgfmathfloat@install@csname{pgfmathlog2@}{pgfmathfloatlog2@}%
	\pgfmathfloat@install\pgfmathsqrt@=\pgfmathfloatsqrt@%
	\pgfmathfloat@install\pgfmath@pi=\pgfmathfloatpi@%
	\pgfmathfloat@install\pgfmathpi=\pgfmathfloatpi@%
	\pgfmathfloat@install\pgfmathe@=\pgfmathfloate@%
	\pgfmathfloat@install\pgfmathe=\pgfmathfloate@%
	\pgfmathfloat@install\pgfmathlessthan@=\pgfmathfloatlessthan@%
	\pgfmathfloat@install\pgfmathnotless@=\pgfmathfloatnotless@%
	\pgfmathfloat@install\pgfmathnotgreater@=\pgfmathfloatnotgreater@%
	\pgfmathfloat@install\pgfmathless@=\pgfmathfloatlessthan@%
	\pgfmathfloat@install\pgfmathgreaterthan@=\pgfmathfloatgreaterthan@%
	\pgfmathfloat@install\pgfmathgreater@=\pgfmathfloatgreaterthan@%
	\pgfmathfloat@install\pgfmathifthenelse@=\pgfmathfloatifthenelse@%
	\pgfmathfloat@install\pgfmathequal@=\pgfmathfloatequal@%
	\pgfmathfloat@install\pgfmathequalto@=\pgfmathfloatequal@%
	\pgfmathfloat@install\pgfmathnotequal@=\pgfmathfloatnotequal@%
	\pgfmathfloat@install\pgfmathnotequalto@=\pgfmathfloatnotequal@%
	\pgfmathfloat@install\pgfmathpow@=\pgfmathfloatpow@
	\pgfmathfloat@install\pgfmathrand@=\pgfmathfloatrand@
	\pgfmathfloat@install\pgfmathrand=\pgfmathfloatrand@
	\pgfmathfloat@install\pgfmathrnd@=\pgfmathfloatrnd@
	\pgfmathfloat@install\pgfmathrnd=\pgfmathfloatrnd@
	\pgfmathfloat@install\pgfmathtrue@=\pgfmathfloattrue@
	\pgfmathfloat@install\pgfmathfalse@=\pgfmathfloatfalse@
	\pgfmathfloat@install\pgfmathnot@=\pgfmathfloatnot@
	\pgfmathfloat@install\pgfmathhex@=\pgfmathfloathex@
	\pgfmathfloat@install\pgfmathHex@=\pgfmathfloatHex@
	\pgfmathfloat@install\pgfmathoct@=\pgfmathfloatoct@
	\pgfmathfloat@install\pgfmathbin@=\pgfmathfloatbin@
	\pgfmathfloat@install\pgfmathand@=\pgfmathfloatand@
	\pgfmathfloat@install\pgfmathor@=\pgfmathfloator@
	\pgfmathfloat@install\pgfmathfactorial@=\pgfmathfloatfactorial@
	\pgfmathfloat@install\pgfmathveclen@=\pgfmathfloatveclen@
	\pgfmathfloat@install\pgfmathcosh@=\pgfmathfloatcosh@
	\pgfmathfloat@install\pgfmathsinh@=\pgfmathfloatsinh@
	\pgfmathfloat@install\pgfmathtanh@=\pgfmathfloattanh@
	\pgfmathfloat@install@unimplemented{ceil}%
	\pgfmathfloat@install@unimplemented{frac}%
	\pgfmathfloat@install@unimplemented{random}%
	\pgfmathfloat@install@unimplemented{setseed}%
	\pgfmathfloat@install@unimplemented{Mod}%
	\pgfmathfloat@install@unimplemented{real}%
%	\pgfmathfloat@install@unimplemented{atan2}%
%	\pgfmathfloat@install@unimplemented{height}%
	%
	%
	\pgfmathfloat@install\pgfmathscientific=\pgfmathfloatscientific%
}

\def\pgfmathfloat@parser@install{%
	\pgfmathfloat@plots@checkuninstallcmd
	\pgfmathfloat@plots@install%
	\pgfmathfloat@parser@install@functions
	%
	%
	%
	% The following methods actually enable the parser to work with
	% the internal floating point number representation.
	%
	% The idea is as follows:
	% 1. Every operand must be given in internal float representation.
	% 2. The internal float repr can be distinguished by a normal
	% number. This is accomplished by introducing a new "exponent"
	% token.
	% 3. The stack-push-operation checks whether the argument is a
	% float. If not, it is parsed properly before pushing it.
	\pgfmath@tokens@make{exponent}{\pgfmathfloat@POSTFLAGSCHAR}%
	\pgfmathfloat@uninstall@appendcmd{%
		\expandafter\let\csname pgfmath@token@exponent@\pgfmathfloat@POSTFLAGSCHAR\endcsname=\relax
	}%
	\let\pgfmath@basic@parse@exponent=\pgfmath@parse@exponent%
	\let\pgfmath@basic@stack@push@operand=\pgfmath@stack@push@operand
	\pgfmathfloat@install\pgfmath@stack@push@operand=\pgfmathfloat@stack@push@operand
	\pgfmathfloat@install\pgfmath@parse@exponent=\pgfmathfloat@parse@float@or@exponent
	%
	\pgfmathfloat@install\pgfmathparse=\pgfmathfloatparse%
}%

\def\pgfmathfloat@defineadapter@for@pgf@two@null@null@ONEARG#1{%
	\edef\pgfmathfloat@loc@TMPa{%
		\noexpand\def\expandafter\noexpand\csname pgfmath@parsefunction@#1\endcsname{%
			\noexpand\let\noexpand\pgfmath@parsepostgroup\expandafter\noexpand\csname pgfmath@parsefunction@#1@\endcsname%
			\noexpand\expandafter\noexpand\pgfmath@parse@}%
		\noexpand\def\expandafter\noexpand\csname pgfmath@parsefunction@#1@\endcsname{%	
			\noexpand\expandafter\expandafter\noexpand\csname pgfmath#1@\endcsname\noexpand\expandafter{\noexpand\pgfmathresult}%
			\noexpand\pgfmath@postfunction%
		}%
	}%
	\pgfmathfloat@loc@TMPa
}%
\def\pgfmathfloat@parser@install@pgf@two@null@null{%
	\pgfmathfloat@plots@checkuninstallcmd
	\pgfmathfloat@plots@install%
	\pgfmathfloat@parser@install@functions
	\let\pgfmathrand@=\pgfmath@basic@rand@
	\let\pgfmathrnd@=\pgfmath@basic@rnd@
	\pgfmathfloat@install\pgfmathmax@=\pgfmathfloatmaxtwo%
	\pgfmathfloat@install\pgfmathmin@=\pgfmathfloatmintwo%
	\pgfmathfloat@defineadapter@for@pgf@two@null@null@ONEARG{factorial}%
	\pgfmathfloat@defineadapter@for@pgf@two@null@null@ONEARG{hex}%
	\pgfmathfloat@defineadapter@for@pgf@two@null@null@ONEARG{bin}%
	\pgfmathfloat@defineadapter@for@pgf@two@null@null@ONEARG{oct}%
	\pgfmathfloat@defineadapter@for@pgf@two@null@null@ONEARG{tanh}%
	\pgfmathfloat@defineadapter@for@pgf@two@null@null@ONEARG{sinh}%
	\pgfmathfloat@defineadapter@for@pgf@two@null@null@ONEARG{cosh}%
	%
	% The following methods actually enable the parser to work with
	% the internal floating point number representation.
	%
	% The idea is as follows:
	% 1. Every operand must be given in internal float representation.
	% 2. The internal float repr can be distinguished by a normal
	% number. This is accomplished by introducing a new "exponent"
	% token.
	% 3. The stack-push-operation checks whether the argument is a
	% float. If not, it is parsed properly before pushing it.
	\let\pgfmath@basic@parsedecimalpoint=\pgfmath@parsedecimalpoint%
	\let\pgfmath@basic@stack@push@operand=\pgfmath@stackpushoperand
	\pgfmathfloat@install\pgfmath@stackpushoperand=\pgfmathfloat@stack@push@operand
	\pgfmathfloat@install\pgfmath@parsedecimalpoint=\pgfmathfloat@parsedecimalpoint@pgf@two@null@null
	\pgfmathfloat@install\pgfmath@endparse=\pgfmathfloat@endparse@pgf@two@null@null
	\pgfmathfloat@install\pgfmath@endparsegroup=\pgfmathfloat@endparsegroup@pgf@two@null@null
	\pgfmathfloat@install\pgfmath@postfunction=\pgfmathfloat@postfunction@pgf@two@null@null
	\pgfmathfloat@install\pgfmath@@parseoperandgroup=\pgfmathfloat@@parseoperandgroup
	%
	\pgfmathfloat@install\pgfmathparse=\pgfmathfloatparse@pgf@two@null@null%
}%

\pgfutil@ifundefined{pgfmathdeclarefunction}{%
	% BACKWARDS COMPATIBILITY: We have PGF 2.00 :
	\def\pgfmathdeclarepseudoconstant#1#2{%
		\begingroup
		\toks0=\expandafter{\csname pgfmath#1@\endcsname}%
		\toks1={\pgfmath@postfunction}%
		\xdef\pgfmathfloat@glob@TMP{\the\toks0 \the\toks1 }%
		\xdef\pgfmathfloat@glob@TMPb{\the\toks0 }%
		\endgroup
		\expandafter\let\csname pgfmath@parsefunction@#1\endcsname=\pgfmathfloat@glob@TMP
		\expandafter\let\csname pgfmath#1\endcsname=\pgfmathfloat@glob@TMPb
		\expandafter\def\csname pgfmath#1@\endcsname{#2}%
	}%
	\let\pgfmathredeclarepseudoconstant=\pgfmathdeclarepseudoconstant
}{%
	\pgfutil@ifundefined{pgfmathdeclarepseudoconstant}{%
		\def\pgfmathdeclarepseudoconstant#1#2{\pgfmathdeclarefunction*{#1}{0}{#2}}
	}{}%
}%

\pgfmathdeclarepseudoconstant{inf}{\def\pgfmathresult{inf}}
\pgfmathdeclarepseudoconstant{infty}{\def\pgfmathresult{inf}}
\pgfmathdeclarepseudoconstant{nan}{\def\pgfmathresult{nan}}
\pgfmathdeclarepseudoconstant{NaN}{\def\pgfmathresult{nan}}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Hacks to the basic level pgf math engine:
%
% WARNING: These methods rely heavily on the internal float representation!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% for pgf2.00 :
\def\pgfmathfloat@parsedecimalpoint@pgf@two@null@null#1{%
	\expandafter\ifx\pgfmathfloat@POSTFLAGSCHAR#1% check whether it is a float
		\let\pgfmath@next=\pgfmathfloat@return@float@pgf@two@null@null%
	\else
		\def\pgfmath@next{\pgfmath@basic@parsedecimalpoint#1}%
	\fi
	\pgfmath@next
}
% for pgf2.00:
\def\pgfmathfloat@return@float@pgf@two@null@null#1]{%
	\edef\pgfmathresult{\the\c@pgfmath@parsecounta\pgfmathfloat@POSTFLAGSCHAR#1]}%
	\let\pgfmath@resulttemp=\pgfmathresult
	\pgfmath@parseoperator%
}%
% for pgf2.00:
\def\pgfmathfloat@endparse@pgf@two@null@null#1\pgfmath@empty{%
    \pgfmath@processalloperations%
    \pgfmath@stackpop{\pgfmathresult}%
	% delete the final unit scalings
    \pgfmath@smuggleone{\pgfmathresult}%
  \endgroup%
  \ignorespaces%
}
% for pgf2.00:
\def\pgfmathfloat@endparsegroup@pgf@two@null@null{%
		\pgfmath@processalloperations%
		\pgfmath@stackpop{\pgfmathresult}%
		% eliminated register usage here...
		\pgfmath@smuggleone{\pgfmathresult}%
	\endgroup%
	\pgfmath@parsepostgroup%
}
% for pgf2.00:
\def\pgfmathfloat@postfunction@pgf@two@null@null{%
	\let\pgfmath@parsepostgroup\pgfmath@parseoperator%
	\ifnum\pgfmath@sign1<0
		\pgfmathfloatneg@{\pgfmathresult}%
		\let\pgfmath@sign\pgfutil@empty
	\fi
	\pgfmath@parseoperator}
% for pgf2.00:
\def\pgfmathfloat@@parseoperandgroup{%
	\let\pgfmath@postparsegroup\pgfmath@parseoperator%
	\ifnum\pgfmath@sign1<0
		\pgfmathfloatneg@{\pgfmathresult}%
		\let\pgfmath@sign\pgfutil@empty
	\fi
	\pgfmath@parseoperator%
}






% PRECONDITION:
% either
% 	<number>e
% 	        ^
% 	-> read the exponent.
% or
%   <sign>\pgfmathfloat@POSTFLAGSCHAR
%         ^
%   -> we have a parsed floating point number -> read it.
\def\pgfmathfloat@parse@float@or@exponent{%
	\if\pgfmath@token \pgfmathfloat@POSTFLAGSCHAR%
		% Ok, we actually HAVE a pre-parsed floating point number!
		% Return it.
		\expandafter\pgfmathfloat@return@float\expandafter\pgfmath@token@next
	\else
		% We have a standard number in scientific format. Parse it.
		\expandafter\pgfmath@basic@parse@exponent
	\fi
}%
\def\pgfmathfloat@return@float#1]{%
	\edef\pgfmathresult{\pgfmath@number \pgfmathfloat@POSTFLAGSCHAR#1]}%
	\expandafter\pgfmath@basic@stack@push@operand\expandafter{\pgfmathresult}%
	\pgfmath@parse@@operator%
}%

% This extends the functionality of the basic level operand stack: it
% assures every element on the stack is a float.
\def\pgfmathfloat@stack@push@operand#1{%
	\pgfutil@ifnextchar\bgroup{%
		\let\pgfmathfloat@stack@push@operand@list@=\pgfutil@empty
		\pgfmathfloat@stack@push@operand@list
	}{%
		\pgfmathfloat@stack@push@operand@single
	}%
	#1\relax
}%
\def\pgfmathfloat@stack@push@operand@single#1\relax{%
	\expandafter\pgfutil@in@\pgfmathfloat@POSTFLAGSCHAR{#1}%
	\ifpgfutil@in@
		\pgfmath@basic@stack@push@operand{#1}%
	\else
		\pgfmathfloatparsenumber{#1}%
		\expandafter\pgfmath@basic@stack@push@operand\expandafter{\pgfmathresult}%
	\fi
}%
\def\pgfmathfloat@stack@push@operand@GOBBLE#1\relax{}%
\def\pgfmathfloat@stack@push@operand@list#1{%
	\expandafter\pgfutil@in@ \pgfmathfloat@POSTFLAGSCHAR{#1}%
	\ifpgfutil@in@
		\expandafter\def\expandafter\pgfmathfloat@stack@push@operand@list@\expandafter{%
			\pgfmathfloat@stack@push@operand@list@{#1}%
		}%
	\else
		\pgfmathfloatparsenumber{#1}%
		\begingroup
		\toks0=\expandafter{\pgfmathfloat@stack@push@operand@list@}%
		\toks1=\expandafter{\pgfmathresult}%
		\xdef\pgfmathfloat@glob@TMP{\the\toks0 {\the\toks1}}%
		\endgroup
		\let\pgfmathfloat@stack@push@operand@list@=\pgfmathfloat@glob@TMP
	\fi
	\pgfutil@ifnextchar\relax{%
		\expandafter\pgfmath@basic@stack@push@operand\expandafter{\pgfmathfloat@stack@push@operand@list@}%
		\pgfmathfloat@stack@push@operand@GOBBLE
	}{%
		\pgfmathfloat@stack@push@operand@list
	}%
}%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% --- END --- Hacks to the basic level pgf math engine
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Here starts the implementation of the floating point
% routines.
%
% They can be used even if the FPU parser is not active.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Remember the basic math commands. They will be invoked as subroutines in floating point routines.
\let\pgfmath@basic@add@=\pgfmathadd@
\let\pgfmath@basic@subtract@=\pgfmathsubtract@
\let\pgfmath@basic@multiply@=\pgfmathmultiply@
\let\pgfmath@basic@divide@=\pgfmathdivide@
\let\pgfmath@basic@reciprocal@=\pgfmathreciprocal@
\let\pgfmath@basic@abs@=\pgfmathabs@
\let\pgfmath@basic@round@=\pgfmathround@
\let\pgfmath@basic@rand@=\pgfmathrand@
\let\pgfmath@basic@rnd@=\pgfmathrnd@
\let\pgfmath@basic@setseed@=\pgfmathsetseed@
\let\pgfmath@basic@random@=\pgfmathrandom@
\let\pgfmath@basic@floor@=\pgfmathfloor@
\let\pgfmath@basic@ceil@=\pgfmathceil@
\let\pgfmath@basic@mod@=\pgfmathmod@
\let\pgfmath@basic@max@=\pgfmathmax@
\let\pgfmath@basic@min@=\pgfmathmin@
\let\pgfmath@basic@sin@=\pgfmathsin@
\let\pgfmath@basic@cos@=\pgfmathcos@
\let\pgfmath@basic@tan@=\pgfmathtan@
\let\pgfmath@basic@deg@=\pgfmathdeg@
\let\pgfmath@basic@rad@=\pgfmathrad@
\let\pgfmath@basic@atan@=\pgfmathatan@
\let\pgfmath@basic@asin@=\pgfmathasin@
\let\pgfmath@basic@acos@=\pgfmathacos@
\let\pgfmath@basic@cot@=\pgfmathcot@
\let\pgfmath@basic@sec@=\pgfmathsec@
\let\pgfmath@basic@cosec@=\pgfmathcosec@
\let\pgfmath@basic@pow@=\pgfmathpow@
\let\pgfmath@basic@exp@=\pgfmathexp@
\let\pgfmath@basic@ln@=\pgfmathln@
\let\pgfmath@basic@sqrt@=\pgfmathsqrt@
\let\pgfmath@basic@@pi=\pgfmath@pi
\let\pgfmath@basic@veclen@=\pgfmathveclen@
\let\pgfmath@basic@e@=\pgfmathe@
\let\pgfmath@basic@lessthan@=\pgfmathlessthan@
\let\pgfmath@basic@greaterthan@=\pgfmathgreaterthan@
\let\pgfmath@basic@equalto@=\pgfmathequalto@
\let\pgfmath@basic@equal@=\pgfmathequal@
\let\pgfmath@basic@true@=\pgfmathtrue@
\let\pgfmath@basic@false@=\pgfmathfalse@

\def\pgfmathfloatscientific#1#2{%
	\edef\pgfmathresult{#1e#2}%
	\expandafter\pgfmathfloatparsenumber\expandafter{\pgfmathresult}%
}
% Compares #1 with #2 and sets \pgfmathresult either to 1.0 or 0.0.
% 
% It also sets the boolean \ifpgfmathfloatcomparison (globally).
\def\pgfmathfloatlessthan@#1#2{%
%\def\pgfmathfloatlessthan#1#2#3\and#4#5#6{%
	\global\pgfmathfloatcomparisonfalse
	\begingroup
	\edef\pgfmathfloat@loc@TMPa{#1}%
	\edef\pgfmathfloat@loc@TMPb{#2}%
	\expandafter\pgfmathfloat@decompose\pgfmathfloat@loc@TMPa\relax\pgfmathfloat@a@S\pgfmathfloat@a@M\pgfmathfloat@a@E
	\expandafter\pgfmathfloat@decompose\pgfmathfloat@loc@TMPb\relax\pgfmathfloat@b@S\pgfmathfloat@b@M\pgfmathfloat@b@E
	\ifcase\pgfmathfloat@a@S
		% x = 0 -> (x<y <=> y >0)
		\ifcase\pgfmathfloat@b@S
			% y = 0
		\or% y > 0
			\global\pgfmathfloatcomparisontrue
		\or% y < 0
		\or% y = nan
		\or% y = + infty
			\global\pgfmathfloatcomparisontrue
		\or% y = -infty
		\fi
	\or
		% x > 0 -> (x<y <=> ( y > 0 && |x| < |y|) )
		\ifcase\pgfmathfloat@b@S
			% y = 0
		\or% y>0:
			\pgfmathfloatlessthan@positive
		\or% y < 0
		\or% y = nan
		\or% y = + infty
			\global\pgfmathfloatcomparisontrue
		\or% y = -infty
		\fi
	\or
		% x < 0 -> (x<y <=> (y >= 0 ||   |x| > |y|) )
		\ifcase\pgfmathfloat@b@S
			% y = 0
			\global\pgfmathfloatcomparisontrue
		\or%y > 0
			\global\pgfmathfloatcomparisontrue
		\or% 'y<0':
			\pgfmathfloatgreaterthan@positive
		\or% y = nan
		\or% y = + infty
			\global\pgfmathfloatcomparisontrue
		\or% y = -infty
		\fi
	\or
		% x = nan.
	\or
		% x = +infty
	\or
		% x = -infty
		\ifnum\pgfmathfloat@b@S=3
		\else
			\global\pgfmathfloatcomparisontrue
		\fi
	\fi
	\endgroup
	\ifpgfmathfloatcomparison
		\def\pgfmathresult{1.0}%
	\else
		\def\pgfmathresult{0.0}%
	\fi
}
\let\pgfmathfloatlessthan=\pgfmathfloatlessthan@
\let\pgfmathfloatless@=\pgfmathfloatlessthan@

% ! (#1 < #2)  <=>  (#1 >= #2) 
\def\pgfmathfloatnotless@#1#2{%
	\pgfmathfloatless@{#1}{#2}%
	\ifpgfmathfloatcomparison
		\def\pgfmathresult{0.0}%
	\else
		\def\pgfmathresult{1.0}%
	\fi
}%
% ! (#1 > #2)  <=>  (#1 <= #2) 
\def\pgfmathfloatnotgreater@#1#2{%
	\pgfmathfloatless@{#2}{#1}%
	\ifpgfmathfloatcomparison
		\def\pgfmathresult{0.0}%
	\else
		\def\pgfmathresult{1.0}%
	\fi
}%

% compares \pgfmathfloat@a@[SME] < \pgfmathfloat@b@[SME]
\def\pgfmathfloatlessthan@positive{%
	\ifnum\pgfmathfloat@a@E<\pgfmathfloat@b@E
		\global\pgfmathfloatcomparisontrue
	\else
		\ifnum\pgfmathfloat@a@E=\pgfmathfloat@b@E
			\ifdim\pgfmathfloat@a@M<\pgfmathfloat@b@M
				\global\pgfmathfloatcomparisontrue
			\fi
		\fi
	\fi
}

% compares \pgfmathfloat@a@[SME] > \pgfmathfloat@b@[SME]
\def\pgfmathfloatgreaterthan@positive{%
	\ifnum\pgfmathfloat@a@E>\pgfmathfloat@b@E
		\global\pgfmathfloatcomparisontrue
	\else
		\ifnum\pgfmathfloat@a@E=\pgfmathfloat@b@E
			\ifdim\pgfmathfloat@a@M>\pgfmathfloat@b@M
				\global\pgfmathfloatcomparisontrue
			\fi
		\fi
	\fi
}


\def\pgfmathfloatgreaterthan@#1#2{\pgfmathfloatlessthan@{#2}{#1}}
\let\pgfmathfloatgreaterthan=\pgfmathfloatgreaterthan@
\let\pgfmathfloatgreater@=\pgfmathfloatgreaterthan@

\def\pgfmathfloatmax@#1{%
	\begingroup
		\pgfmathfloatcreate{2}{1.0}{2147483644}%
		\let\pgfmathmaxsofar=\pgfmathresult
		\pgfmathfloatmax@@#1{}%
}%
\def\pgfmathfloatmax@@#1{%
	\def\pgfmath@temp{#1}%
	\ifx\pgfmath@temp\pgfmath@empty%
		\expandafter\pgfmathfloatmax@@@%
	\else%
		\pgfmathfloatlessthan{\pgfmathmaxsofar}{#1}%
		\ifpgfmathfloatcomparison
			\edef\pgfmathmaxsofar{#1}%
		\fi
		\expandafter\pgfmathfloatmax@@%
	\fi%
}%
\def\pgfmathfloatmax@@@{%
	\let\pgfmathresult=\pgfmathmaxsofar
	\pgfmath@smuggleone{\pgfmathresult}%
	\endgroup
}%
\def\pgfmathfloatmin@#1{%
	\begingroup
		\pgfmathfloatcreate{1}{1.0}{2147483644}%
		\let\pgfmathminsofar=\pgfmathresult
		\pgfmathfloatmin@@#1{}%
}%
\def\pgfmathfloatmin@@#1{%
	\def\pgfmath@temp{#1}%
	\ifx\pgfmath@temp\pgfmath@empty%
		\expandafter\pgfmathfloatmin@@@%
	\else%
		\pgfmathfloatlessthan{#1}{\pgfmathminsofar}%
		\ifpgfmathfloatcomparison
			\edef\pgfmathminsofar{#1}%
		\fi
		\expandafter\pgfmathfloatmin@@%
	\fi%
}%
\def\pgfmathfloatmin@@@{%
	\let\pgfmathresult=\pgfmathminsofar
	\pgfmath@smuggleone{\pgfmathresult}%
	\endgroup
}%

\def\pgfmathfloatmaxtwo#1#2{%
	\pgfmathfloatlessthan{#1}{#2}%
	\ifpgfmathfloatcomparison
		\edef\pgfmathresult{#2}%
	\else
		\edef\pgfmathresult{#1}%
	\fi
}
\let\pgfmathfloatmax=\pgfmathfloatmaxtwo

\def\pgfmathfloatmintwo#1#2{%
	\pgfmathfloatlessthan{#1}{#2}%
	\ifpgfmathfloatcomparison
		\edef\pgfmathresult{#1}%
	\else
		\edef\pgfmathresult{#2}%
	\fi
}
\let\pgfmathfloatmin=\pgfmathfloatmintwo

% Renormalizes #1 to extended precision mantisse, meaning
% 100 <= m < 1000
% instead of 1 <= m < 10.
% 
% The 'extended precision' means we have higher accuracy when we apply pgfmath operations to mantissas.
%
% The input argument is expected to be a normalized floating point number; the output argument is a non-normalized floating point number (well, normalized to extended precision).
%
% The operation is supposed to be very fast.
%
% @see \pgfmathfloatsetextprecision
%
% There is a routine for internal usage,
% \pgfmathfloattoextentedprecision@a. It also provides exponent and
% sign of #1 in output arguments and may be used to increase speed.
\def\pgfmathfloattoextentedprecision#1{%
	\begingroup
	\pgfmathfloattoextentedprecision@a{#1}%
	\pgfmathfloatcreate{\pgfmathfloat@a@S}{\pgfmathresult}{\pgfmathfloat@a@E}%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%

\def\pgfmathfloattoextentedprecision@@zero#1\pgfmathfloat@EOI{%
	\edef\pgfmathresult{#1}%
}%
\def\pgfmathfloattoextentedprecision@@one#1.#2#3\pgfmathfloat@EOI{%
	\edef\pgfmathresult{#1#2.#3}%
}%
\def\pgfmathfloattoextentedprecision@@two#1.#2#3#4\pgfmathfloat@EOI{%
	\edef\pgfmathresult{#1#2#3.#4}%
}%
\def\pgfmathfloattoextentedprecision@@three#1.#2#3#4#5\pgfmathfloat@EOI{%
	\edef\pgfmathresult{#1#2#3#4.#5}%
}%

% Sets extended precision to 10^#1.
%
% The different choices are
% 
% - 0:  normalization      0 <= m < 1 (disable extended precision)
% - 1:  normalization     10 <= m < 100
% - 2:  normalization    100 <= m < 1000  (default)
% - 3:  normalization   1000 <= m < 10000
%
% #1 is the exponent, #1 = 0,1,2 or 3.
%
% This setting applies to \pgfmathfloattoextentedprecision and friends.
\def\pgfmathfloatsetextprecision#1{%
	\ifcase#1\relax
		\let\pgfmathfloattoextentedprecision@@=\pgfmathfloattoextentedprecision@@zero
		\def\pgfmathfloatextprec@shift{0}%
	\or
		\let\pgfmathfloattoextentedprecision@@=\pgfmathfloattoextentedprecision@@one
		\def\pgfmathfloatextprec@shift{1}%
	\or
		\let\pgfmathfloattoextentedprecision@@=\pgfmathfloattoextentedprecision@@two
		\def\pgfmathfloatextprec@shift{2}%
	\else
		\let\pgfmathfloattoextentedprecision@@=\pgfmathfloattoextentedprecision@@three
		\def\pgfmathfloatextprec@shift{3}%
	\fi
}%
\pgfmathfloatsetextprecision{2}%

% Does the "hard" work for \pgfmathfloattoextentedprecision. It
% provides additional outputs.
%
% INPUT:
% #1  normalized floating point number. Maybe a macro (it will be expanded ONCE)
% 
% OUTPUT:
% - \pgfmathresult : the mantisse in extended precision
% - \pgfmathfloat@a@S : the sign of #1
% - \pgfmathfloat@a@E : the exponent of #1, adjusted for extended precision
% - \pgfmathfloat@a@Mtok : undefined (its contents will be destroyed.
%
\def\pgfmathfloattoextentedprecision@a#1{%
	\edef\pgfmathresult{#1}%
	\expandafter\pgfmathfloat@decompose@tok\pgfmathresult\relax\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
	\ifnum\pgfmathfloat@a@S<3
		\advance\pgfmathfloat@a@E by-\pgfmathfloatextprec@shift\relax% compensate for shift
		\expandafter\pgfmathfloattoextentedprecision@@\the\pgfmathfloat@a@Mtok 000\pgfmathfloat@EOI
	\fi
}%


% Similar to \pgfmathfloattoextentedprecision@a, this one here fills the '@b' registers.
\def\pgfmathfloattoextentedprecision@b#1{%
	\edef\pgfmathresult{#1}%
	\expandafter\pgfmathfloat@decompose@tok\pgfmathresult\relax\pgfmathfloat@b@S\pgfmathfloat@a@Mtok\pgfmathfloat@b@E
	\ifnum\pgfmathfloat@b@S<3
		\advance\pgfmathfloat@b@E by-\pgfmathfloatextprec@shift\relax
		\expandafter\pgfmathfloattoextentedprecision@@\the\pgfmathfloat@a@Mtok 00\pgfmathfloat@EOI
	\fi
}%

% Addition of two floating point numbers using 8 significant digits.
\def\pgfmathfloatadd@#1#2{%
	\begingroup
	%
	% renormalize argument to 100 <= m < 1000 for extended accuracy:
	\pgfmathfloattoextentedprecision@a{#1}%
	\let\pgfmathfloat@arga=\pgfmathresult
	%
	\pgfmathfloattoextentedprecision@b{#2}%
	\let\pgfmathfloat@argb=\pgfmathresult
	%
	\pgfmathfloatcomparisontrue% re-use this boolean here to handle special cases.
	\ifcase\pgfmathfloat@a@S
		\edef\pgfmathresult{#2}%
		\pgfmathfloatcomparisonfalse
	\or
	\or
		\edef\pgfmathfloat@arga{-\pgfmathfloat@arga}%
	\else
		\pgfmathfloatcomparisonfalse
		\pgfmathfloatcreate{\the\pgfmathfloat@a@S}{0.0}{0}%
	\fi
	\ifcase\pgfmathfloat@b@S
		\edef\pgfmathresult{#1}%
		\pgfmathfloatcomparisonfalse
	\or
	\or
		\edef\pgfmathfloat@argb{-\pgfmathfloat@argb}%
	\else
		\pgfmathfloatcomparisonfalse
		\pgfmathfloatcreate{\the\pgfmathfloat@b@S}{0.0}{0}%
	\fi
	\ifpgfmathfloatcomparison
		% Shift lesser mantisse to fit the larger one:
		\ifnum\pgfmathfloat@a@E<\pgfmathfloat@b@E
			\pgfmathfloatadd@shift{\pgfmathfloat@arga}{\pgfmathfloat@a@E}{\pgfmathfloat@b@E}%
		\else
			\pgfmathfloatadd@shift{\pgfmathfloat@argb}{\pgfmathfloat@b@E}{\pgfmathfloat@a@E}%
		\fi
		% add them!
		\pgfmath@basic@add@{\pgfmathfloat@arga}{\pgfmathfloat@argb}%
		% renormalize sum. This is the only part were an expensive routine comes into play:
		\edef\pgfmathresult{\pgfmathresult e\the\pgfmathfloat@a@E}%
		\expandafter\pgfmathfloatqparsenumber\expandafter{\pgfmathresult}%
	\fi
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%

% #1= floating point number
% #2= TeX code to execute if #1 == 0
% #3= TeX code to execute if #1 != 0
\def\pgfmathfloatifzero#1#2#3{%
	\pgfmathfloatgetflagstomacro{#1}\pgfmathfloat@loc@TMPa
	\if\pgfmathfloat@loc@TMPa0 #2\else#3\fi
}%

\def\pgfmathfloatiffinite#1#2#3{%
	\pgfmathfloatgetflagstomacro{#1}\pgfmathfloatiffinite@
	\ifnum\pgfmathfloatiffinite@>2 #3\else #2\fi
}%

\def\pgfmathfloatifthenelse@#1#2#3{%
	\pgfmathfloatifflags{#1}{0}{%
		\edef\pgfmathresult{#3}%%
	}{%
		\edef\pgfmathresult{#2}%
	}%
}
\def\pgfmathfloatequal@#1#2{%
	\pgfmathfloatifapproxequalrel{#1}{#2}{%
		\def\pgfmathresult{1}%
		\pgfmathfloatcomparisontrue
	}{%
		\def\pgfmathresult{0}%
		\pgfmathfloatcomparisonfalse
	}%
}
\let\pgfmathfloatequalto@=\pgfmathfloatequal@

\def\pgfmathfloatnotequal@#1#2{%
	\pgfmathfloatifapproxequalrel{#1}{#2}{%
		\def\pgfmathresult{0}%
		\pgfmathfloatcomparisonfalse
	}{%
		\def\pgfmathresult{1}%
		\pgfmathfloatcomparisontrue
	}%
}
\let\pgfmathfloatnotequalto@=\pgfmathfloatnotequal@

% Computes the relative error between #1 and #2 (assuming #2 != 0) and
% invokes #3 if the relative error is below `/pgf/fpu/rel thresh' and
% #4 if that is not the case.
\long\def\pgfmathfloatifapproxequalrel#1#2#3#4{%
	\begingroup
	\pgfmathfloatparsenumber{#1}%
	\let\pgfmathfloatarga=\pgfmathresult
	\pgfmathfloatparsenumber{#2}%
	\let\pgfmathfloatargb=\pgfmathresult
	\pgfmathfloatrelerror@\pgfmathfloatarga\pgfmathfloatargb
	\let\pgfmathfloatarga=\pgfmathresult
	\pgfmathfloatlessthan@\pgfmathfloatarga\pgfmathfloat@relthresh
	\ifpgfmathfloatcomparison
		\def\pgfmathfloat@loc@TMPa{#3}%
	\else
		\def\pgfmathfloat@loc@TMPa{#4}%
	\fi
	\expandafter\endgroup
	\pgfmathfloat@loc@TMPa
}%

% Invokes code '#3' if the flags of the floating point number '#1'
% match the flag provided in '#2'.
%
% \pgfmathfloatcreate{1}{1.0}{2}
% \pgfmathfloatifflags{\pgfmathresult}{0}{It's zero!}{It's not zero!}%
% \pgfmathfloatifflags{\pgfmathresult}{1}{It's positive!}{It's not positive!}%
% \pgfmathfloatifflags{\pgfmathresult}{2}{It's negative!}{It's not negative!}%
% or, equivalently
% \pgfmathfloatifflags{\pgfmathresult}{+}{It's positive!}{It's not positive!}%
% \pgfmathfloatifflags{\pgfmathresult}{-}{It's negative!}{It's not negative!}%
% it also supports #2=u which means 'unbounded'
\def\pgfmathfloatifflags#1#2#3#4{%
	\if#2-%
		\pgfmathfloatifflags{#1}{2}{#3}{#4}%
	\else
		\if#2+%
			\pgfmathfloatifflags{#1}{1}{#3}{#4}%
		\else
			\pgfmathfloatgetflagstomacro#1\pgfmathfloat@loc@TMPa
			\if#2u%
				\ifnum\pgfmathfloat@loc@TMPa>2
					#3\relax
				\else
					#4\relax
				\fi
			\else
				\if\pgfmathfloat@loc@TMPa#2%
					#3\relax
				\else
					#4\relax
				\fi
			\fi
		\fi
	\fi
}%

% #1=mantisse which needs to be shifted (with smaller exponent)
% #2=smaller exponent
% #3=larger exponent
% 
% ATTENTION: this helper method DESTROYS contents of \pgfmathfloat@a@S.
\def\pgfmathfloatadd@shift#1#2#3{%
	\pgf@xa=#1 pt%
	\pgfmathfloat@a@S=#3\relax
	\advance\pgfmathfloat@a@S by-#2\relax
	\ifcase\pgfmathfloat@a@S
	\or
		\divide\pgf@xa by10\relax
	\or
		\divide\pgf@xa by100\relax
	\or
		\divide\pgf@xa by1000\relax
	\or
		\divide\pgf@xa by10000\relax
	\or
		\divide\pgf@xa by10000\relax
		\divide\pgf@xa by10\relax
	\or
		\divide\pgf@xa by10000\relax
		\divide\pgf@xa by100\relax
	\or
		\divide\pgf@xa by10000\relax
		\divide\pgf@xa by1000\relax
	\or
		\divide\pgf@xa by10000\relax
		\divide\pgf@xa by10000\relax
	\else
		\pgf@xa=0pt%
	\fi
	#2=#3\relax
	\edef#1{\pgf@sys@tonumber\pgf@xa}%
}

\let\pgfmathfloatadd=\pgfmathfloatadd@


% Subtracts two floating point numbers.
\def\pgfmathfloatsubtract@#1#2{%
	\begingroup
	\edef\pgfmathresult{#2}%
	\expandafter\pgfmathfloat@decompose@tok\pgfmathresult\relax\pgfmathfloat@b@S\pgfmathfloat@a@Mtok\pgfmathfloat@b@E
	\ifcase\pgfmathfloat@b@S
		\edef\pgfmathresult{#1}%
	\or
		\pgfmathfloatcreate{2}{\the\pgfmathfloat@a@Mtok}{\the\pgfmathfloat@b@E}%
		\let\pgfmathfloatsub@arg=\pgfmathresult
		\pgfmathfloatadd@{#1}{\pgfmathfloatsub@arg}%
	\or
		\pgfmathfloatcreate{1}{\the\pgfmathfloat@a@Mtok}{\the\pgfmathfloat@b@E}%
		\let\pgfmathfloatsub@arg=\pgfmathresult
		\pgfmathfloatadd@{#1}{\pgfmathfloatsub@arg}%
	\else
		\pgfmathfloatcreate{\the\pgfmathfloat@b@S}{0.0}{0}%
	\fi
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%

\let\pgfmathfloatsubtract=\pgfmathfloatsubtract@

% Scales a floating point number #1 with a fixed point number #2 using pgfmathmultiply.
% 
% Use this method if #2 is small number.
\def\pgfmathfloatmultiplyfixed@#1#2{%
	\begingroup
	%
	% renormalize argument to 100 <= m < 1000 for extended accuracy:
	\pgfmathfloattoextentedprecision@a{#1}%
	\let\pgfmathfloat@arga=\pgfmathresult
	%
	\pgfmathfloatcomparisontrue% re-use this boolean here to handle special cases.
	\ifcase\pgfmathfloat@a@S
		\edef\pgfmathresult{#1}%
		\pgfmathfloatcomparisonfalse
	\or
	\or
		\edef\pgfmathfloat@arga{-\pgfmathfloat@arga}%
	\else
		\pgfmathfloatcomparisonfalse
		\pgfmathfloatcreate{\the\pgfmathfloat@a@S}{0.0}{0}%
	\fi
	\ifpgfmathfloatcomparison
		\pgfmath@basic@multiply@{\pgfmathfloat@arga}{#2}%
		% renormalize product. This is the only part were an expensive routine comes into play:
		\edef\pgfmathresult{\pgfmathresult e\the\pgfmathfloat@a@E}%
		\expandafter\pgfmathfloatqparsenumber\expandafter{\pgfmathresult}%
	\fi
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%

\let\pgfmathfloatmultiplyfixed=\pgfmathfloatmultiplyfixed@


\def\pgfmathfloatmultiply@#1#2{%
	\begingroup
	\pgfmathfloatsetextprecision{1}%
	\pgfmathfloattoextentedprecision@a{#1}%
	\let\pgfmathfloat@arga=\pgfmathresult
	%
	\pgfmathfloattoextentedprecision@b{#2}%
	\let\pgfmathfloat@argb=\pgfmathresult
	%
	\pgfmathfloatcomparisontrue% re-use this boolean here to handle special cases.
	\ifcase\pgfmathfloat@a@S
	% 0
		\pgfmathfloatcreate{0}{0.0}{0}%
		\pgfmathfloatcomparisonfalse
	\or% +
		\ifcase\pgfmathfloat@b@S
			\pgfmathfloatcreate{0}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\def\pgfmathresult@S{1}%
		\or
			\def\pgfmathresult@S{2}%
		\else
			\expandafter\pgfmathfloatcreate\the\pgfmathfloat@b@S{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\fi
	\or% -
		\ifcase\pgfmathfloat@b@S
			\pgfmathfloatcreate{0}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\def\pgfmathresult@S{2}%
		\or
			\def\pgfmathresult@S{1}%
		\or
			\pgfmathfloatcreate{3}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{5}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{4}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\fi
	\or% nan
		\pgfmathfloatcreate{3}{0.0}{0}%
		\pgfmathfloatcomparisonfalse
	\or% +infty
		\ifcase\pgfmathfloat@b@S
			\pgfmathfloatcreate{0}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{4}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{5}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{3}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{4}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{5}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\fi
	\or% -infty
		\ifcase\pgfmathfloat@b@S
			\pgfmathfloatcreate{0}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{5}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{4}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{3}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{5}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{4}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\fi
	\fi
	\ifpgfmathfloatcomparison
		\pgfmath@basic@multiply@{\pgfmathfloat@arga}{\pgfmathfloat@argb}%
		\advance\pgfmathfloat@a@E by\pgfmathfloat@b@E
		% renormalize sum. This is the only part were an expensive routine comes into play:
		\edef\pgfmathresult{\pgfmathresult e\the\pgfmathfloat@a@E}%
		\expandafter\pgfmathfloatqparsenumber\expandafter{\pgfmathresult}%
		\expandafter\pgfmathfloat@decompose@tok\pgfmathresult\relax\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
		\pgfmathfloatcreate{\pgfmathresult@S}{\the\pgfmathfloat@a@Mtok}{\the\pgfmathfloat@a@E}%
	\fi
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%
\let\pgfmathfloatmultiply=\pgfmathfloatmultiply@

% Defines \pgfmathresult to be #1 / #2 for two floating point numbers.
%
% It employs the basic math engine internally to divide mantissas.
\def\pgfmathfloatdivide@#1#2{%
	\begingroup
	\pgfmathfloatsetextprecision{1}% is not too important, I think. After all, 0.1 <= #1/#2 < 10 or so due to normalization (no matter, which)
	\edef\pgfmathfloat@arga{#1}%
	\pgfmathfloattoextentedprecision@a{\pgfmathfloat@arga}%
	\let\pgfmathfloat@arga=\pgfmathresult
	%
	\edef\pgfmathfloat@argb{#2}%
	\pgfmathfloattoextentedprecision@b{\pgfmathfloat@argb}%
	\let\pgfmathfloat@argb=\pgfmathresult
	%
	\pgfmathfloatcomparisontrue% re-use this boolean here to handle special cases.
	\ifcase\pgfmathfloat@a@S
	% 0
		\pgfmathfloatcreate{0}{0.0}{0}%
		\pgfmathfloatcomparisonfalse
	\or% +
		\ifcase\pgfmathfloat@b@S
			\pgfmathfloatcreate{4}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\def\pgfmathresult@S{1}%
		\or
			\def\pgfmathresult@S{2}%
		\or
			\pgfmathfloatcreate{3}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\else
			\pgfmathfloatcreate{0}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\fi
	\or% -
		\ifcase\pgfmathfloat@b@S
			\pgfmathfloatcreate{5}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\def\pgfmathresult@S{2}%
		\or
			\def\pgfmathresult@S{1}%
		\or
			\pgfmathfloatcreate{3}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\else
			\pgfmathfloatcreate{0}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\fi
	\or% nan
		\pgfmathfloatcreate{3}{0.0}{0}%
		\pgfmathfloatcomparisonfalse
	\or% +infty
		\ifcase\pgfmathfloat@b@S
			\pgfmathfloatcreate{4}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{4}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{5}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{3}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{4}{0.0}{0}% what is inf/inf ?
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{5}{0.0}{0}% or inf/-inf ?
			\pgfmathfloatcomparisonfalse
		\fi
	\or% -infty
		\ifcase\pgfmathfloat@b@S
			\pgfmathfloatcreate{5}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{5}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{4}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{3}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{5}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\or
			\pgfmathfloatcreate{4}{0.0}{0}%
			\pgfmathfloatcomparisonfalse
		\fi
	\fi
	\ifpgfmathfloatcomparison
		\pgfmath@basic@divide@{\pgfmathfloat@arga}{\pgfmathfloat@argb}%
		\advance\pgfmathfloat@a@E by-\pgfmathfloat@b@E
		% renormalize. This is the only part were an expensive float routine comes into play:
		\edef\pgfmathresult{\pgfmathresult e\the\pgfmathfloat@a@E}%
		\expandafter\pgfmathfloatqparsenumber\expandafter{\pgfmathresult}%
		% And re-insert the proper sign:
		\expandafter\pgfmathfloat@decompose@tok\pgfmathresult\relax\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
		\pgfmathfloatcreate{\pgfmathresult@S}{\the\pgfmathfloat@a@Mtok}{\the\pgfmathfloat@a@E}%
	\fi
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%
\let\pgfmathfloatdivide=\pgfmathfloatdivide@

\def\pgfmathfloatreciprocal@#1{%
	\begingroup
	% FIXME optimize
	\edef\pgfmathfloat@loc@TMPa{#1}%
	\pgfmathfloatcreate{1}{1.0}{0}%
	\pgfmathfloatdivide@{\pgfmathresult}{\pgfmathfloat@loc@TMPa}%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%

% Computes sqrt(#1) in floating point arithmetics.
%
% It employs sqrt( m * 10^e ) = sqrt(m) * sqrt(10^e).
\def\pgfmathfloatsqrt@#1{%
	\begingroup
	\pgfmathfloatsetextprecision{3}%
	\edef\pgfmathfloat@arga{#1}%
	\pgfmathfloattoextentedprecision@a{\pgfmathfloat@arga}%
	\let\pgfmathfloat@arga=\pgfmathresult
	%
	\ifcase\pgfmathfloat@a@S
	% 0
		\pgfmathfloatcreate{0}{0.0}{0}%
	\or% +
		\pgfmath@basic@sqrt@{\pgfmathfloat@arga}%
		\ifodd\pgfmathfloat@a@E
			\ifnum\pgfmathfloat@a@E>0
				\expandafter\pgfmath@basic@multiply@\expandafter{\pgfmathresult}{3.16227766}% * sqrt(10)
			\else
				\expandafter\pgfmath@basic@multiply@\expandafter{\pgfmathresult}{0.316227766}% * sqrt(0.1)
			\fi
		\fi
		\divide\pgfmathfloat@a@E by2 % sqrt(10^e) = 10^{e/2} (see above for odd e)
		% renormalize sum. This is the only part were an expensive routine comes into play:
		\edef\pgfmathfloat@arga{\pgfmathresult e\the\pgfmathfloat@a@E}%
		\pgfmathfloatqparsenumber{\pgfmathfloat@arga}%
	\or% -
		\pgfmathfloatcreate{3}{0.0}{0}%
	\or% nan
		\pgfmathfloatcreate{3}{0.0}{0}%
	\or% +infty
		\pgfmathfloatcreate{4}{0.0}{0}%
	\or% -infty
		\pgfmathfloatcreate{3}{0.0}{0}%
	\fi
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%
\let\pgfmathfloatsqrt=\pgfmathfloatsqrt@

% Returns the integer part of the floating point number #1.
%
% The result is returned as floating point as well. 
%
% This operation is not limited to TeX's range of count registers (it
% works symbolly)
%
% @see \pgfmathfloattoint
\def\pgfmathfloatint@#1{%
	\begingroup
	\edef\pgfmathresult{#1}%
	\expandafter\pgfmathfloat@decompose@tok\pgfmathresult\relax\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
	\ifcase\pgfmathfloat@a@S
		% 0: nothing to do.
	\or% +
		\expandafter\pgfmathfloatint@@\the\pgfmathfloat@a@Mtok\pgfmathfloat@EOI
		\pgfmathfloatcreate{\the\pgfmathfloat@a@S}{\the\pgfmathfloat@a@Mtok}{\the\pgfmathfloat@a@E}%
	\or% -
		\expandafter\pgfmathfloatint@@\the\pgfmathfloat@a@Mtok\pgfmathfloat@EOI
		\pgfmathfloatcreate{\the\pgfmathfloat@a@S}{\the\pgfmathfloat@a@Mtok}{\the\pgfmathfloat@a@E}%
	\else
		% nothing to do
	\fi
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%
\def\pgfmathfloatint@@#1.{%
	\ifnum\pgfmathfloat@a@E<0
		\pgfmathfloat@a@S=0
		\pgfmathfloat@a@Mtok={0.0}%
		\pgfmathfloat@a@E=0
		\expandafter\pgfmathfloatint@@loop@gobble
	\else
		\pgfmathfloat@a@Mtok={#1.}%
		\pgfmathfloat@b@E=\pgfmathfloat@a@E
		\expandafter\pgfmathfloatint@@loop
	\fi
}%
\def\pgfmathfloatint@@loop#1{%
	\def\pgfmathfloatint@@loop@{#1}%
	\ifx\pgfmathfloatint@@loop@\pgfmathfloat@EOI
		\let\pgfmathfloatint@@loop@next=\relax
	\else
		\ifnum\pgfmathfloat@b@E=0
			\let\pgfmathfloatint@@loop@next=\pgfmathfloatint@@loop@gobble
		\else
			\pgfmathfloat@a@Mtok=\expandafter{\the\pgfmathfloat@a@Mtok#1}%
			\advance\pgfmathfloat@b@E by-1
			\let\pgfmathfloatint@@loop@next=\pgfmathfloatint@@loop
		\fi
	\fi
	\pgfmathfloatint@@loop@next
}%
\def\pgfmathfloatint@@loop@gobble#1\pgfmathfloat@EOI{}%
\let\pgfmathfloatint=\pgfmathfloatint@
\let\pgfmathfloatfloor=\pgfmathfloatint
\let\pgfmathfloatfloor@=\pgfmathfloatint@

\def\pgfmathfloat@notimplemented#1{%
	\pgfmath@error{Sorry, the operation '#1' has not yet been implemented in the floating point unit :-(}{}%
	\pgfmathfloatcreate{0}{0.0}{0}%
}%

% Divides or multiplies the input number by 10^#4 using an arithmetic
% left/right shift.
%
% Input:
% #1 a normalised floating point number.
% #2 a positive or negative integer number denoting the shift.
%
% Example:
% \pgfmathfloatshift{11e3}{4}%
% -> pgfmathresult = 11e7
\def\pgfmathfloatshift@#1#2{%
	\begingroup
	\expandafter\pgfmathfloat@decompose@tok#1\relax\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
	\advance\pgfmathfloat@a@E by#2\relax
	\pgfmathfloatcreate{\the\pgfmathfloat@a@S}{\the\pgfmathfloat@a@Mtok}{\the\pgfmathfloat@a@E}%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}
\let\pgfmathfloatshift=\pgfmathfloatshift@

% Defines \pgfmathresult to be |#1|, the absolute value of the
% normalized floating point number #1.
\def\pgfmathfloatabs@#1{%
	\begingroup
	\expandafter\pgfmathfloat@decompose@tok#1\relax\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
	\ifcase\pgfmathfloat@a@S
		% 0: do nothing.
	\or
		% +: ok, is positive.
	\or
		% -: multiply with -1:
		\pgfmathfloat@a@S=1
	\or
		% nan: do nothing.
	\or
		% +infty: ok.
	\or
		% -infty: multiply with -1:
		\pgfmathfloat@a@S=4
	\fi
	\pgfmathfloatcreate{\the\pgfmathfloat@a@S}{\the\pgfmathfloat@a@Mtok}{\the\pgfmathfloat@a@E}%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%
\let\pgfmathfloatabs=\pgfmathfloatabs@

% Computes the absolute error |#1 - #2| into \pgfmathresult.
\def\pgfmathfloatabserror@#1#2{%
	\pgfmathfloatsubtract@{#1}{#2}%
	\pgfmathfloatabs@{\pgfmathresult}%
}%
\let\pgfmathfloatabserror=\pgfmathfloatabserror@

% Computes the relative error |#1 - #2|/|#2| into \pgfmathresult,
% assuming #2 != 0.
\def\pgfmathfloatrelerror@#1#2{%
	\pgfmathfloatsubtract@{#1}{#2}%
	\let\pgfmathfloat@subtract=\pgfmathresult
	\pgfmathfloatifflags{#2}{0}{%
		\let\pgfmathresult=\pgfmathfloat@subtract
	}{%
		\pgfmathfloatdivide@{\pgfmathfloat@subtract}{#2}%
		\pgfmathfloatabs@{\pgfmathresult}%
	}%
}%
\let\pgfmathfloatrelerror=\pgfmathfloatrelerror@

% Computes \pgfmathresult = #1 mod #2 using truncated division.
%
\def\pgfmathfloatmod@#1#2{%
	\begingroup
	\pgfmathfloatdivide@{#1}{#2}%
	\pgfmathfloatint@{\pgfmathresult}%
	\let\pgfmathfloat@loc@TMPa=\pgfmathresult
	\pgfmathfloatmultiply@{\pgfmathfloat@loc@TMPa}{#2}%
	\let\pgfmathfloat@loc@TMPb=\pgfmathresult
	\pgfmathfloatsubtract@{#1}{\pgfmathfloat@loc@TMPb}%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}
\let\pgfmathfloatmod=\pgfmathfloatmod@


% A modification of \pgfmathfloatmod@ where #3 = 1/#2 is already
% known. This may be faster.
\def\pgfmathfloatmodknowsinverse@#1#2#3{%
	\begingroup
	\pgfmathfloatmultiply@{#1}{#3}%
	\pgfmathfloatint@{\pgfmathresult}%
	\let\pgfmathfloat@loc@TMPa=\pgfmathresult
	\pgfmathfloatmultiply@{\pgfmathfloat@loc@TMPa}{#2}%
	\let\pgfmathfloat@loc@TMPb=\pgfmathresult
	\pgfmathfloatsubtract@{#1}{\pgfmathfloat@loc@TMPb}%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}
\let\pgfmathfloatmodknowsinverse=\pgfmathfloatmodknowsinverse@

\def\pgfmathfloatpi@{%
	\pgfmathfloatcreate{1}{3.14159265358979}{0}%
}%
\let\pgfmathfloatpi=\pgfmathfloatpi@

\def\pgfmathfloate@{%
	\pgfmathfloatcreate{1}{2.71828182845905}{0}%
}
\let\pgfmathfloate=\pgfmathfloate@

% Converts #1 from radians to degrees.
\def\pgfmathfloatdeg@#1{%
	\expandafter\ifx\csname pgfmfltdeg@factor\endcsname\relax
		% Lazy evaluation:
		\pgfmathfloatcreate{1}{5.72957795130823}{1}%
		\global\let\pgfmfltdeg@factor=\pgfmathresult
	\fi
	\pgfmathfloatmultiply@{#1}\pgfmfltdeg@factor%
}
\let\pgfmathfloatdeg=\pgfmathfloatdeg@

% Converts #1 from degree to radians.
\def\pgfmathfloatrad@#1{%
	\expandafter\ifx\csname pgfmfltrad@factor\endcsname\relax
		% Lazy evaluation:
		\pgfmathfloatcreate{1}{1.74532925199433}{-2}%
		\global\let\pgfmfltrad@factor=\pgfmathresult
	\fi
	\pgfmathfloatmultiply@{#1}\pgfmfltrad@factor%
}
\let\pgfmathfloatrad=\pgfmathfloatrad@

% Computes #1(#2) where #1 is a trigonometric function, i.e.
% #1(#2) = #1( #2 + r*360 )
%
% #1 is a one-argument macro which assigns \pgfmathresult.
\def\pgfmathfloatTRIG@#1#2{%
	\expandafter\ifx\csname pgfmathfloatTRIG@NUM\endcsname\relax%
		% Lazy evaluation:
		\pgfmathfloatcreate{1}{3.6}{2}%
		\global\let\pgfmathfloatTRIG@NUM=\pgfmathresult
		\pgfmathfloatcreate{1}{2.77777777777778}{-3}%
		\global\let\pgfmathfloatTRIG@NUM@INV=\pgfmathresult
	\fi
	\pgfmathfloatmodknowsinverse@{#2}{\pgfmathfloatTRIG@NUM}{\pgfmathfloatTRIG@NUM@INV}%
	\pgfmathfloattofixed@{\pgfmathresult}%
	\expandafter#1\expandafter{\pgfmathresult}%
	\pgfmathfloatparsenumber{\pgfmathresult}%
}%

\def\pgfmathfloatsin@#1{\pgfmathfloatTRIG@\pgfmath@basic@sin@{#1}}
\let\pgfmathfloatsin=\pgfmathfloatsin@
\def\pgfmathfloatcos@#1{\pgfmathfloatTRIG@\pgfmath@basic@cos@{#1}}
\let\pgfmathfloatcos=\pgfmathfloatcos@
\def\pgfmathfloattan@#1{%
	% compute sin(#1) / cos(#1)
	\begingroup
	\pgfmathfloatcos@{#1}%
	\let\pgfmathfloat@loc@TMPa=\pgfmathresult
	\pgfmathfloatsin@{#1}%
	\expandafter\pgfmathfloatdivide@\expandafter{\pgfmathresult}{\pgfmathfloat@loc@TMPa}%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}
\let\pgfmathfloattan=\pgfmathfloattan@

\def\pgfmathfloatcot@#1{%
	% compute cos(#1) / sin(#1)
	\begingroup
	\pgfmathfloatsin@{#1}%
	\let\pgfmathfloat@loc@TMPa=\pgfmathresult
	\pgfmathfloatcos@{#1}%
	\expandafter\pgfmathfloatdivide@\expandafter{\pgfmathresult}{\pgfmathfloat@loc@TMPa}%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%
\let\pgfmathfloatcot=\pgfmathfloatcot@

\def\pgfmathfloatatan@#1{%
	\begingroup
	\expandafter\ifx\csname pgfmathfloatatan@TMP\endcsname\relax% 
		\pgfmathfloatcreate{1}{1.6}{4}%
		\global\let\pgfmathfloatatan@TMP=\pgfmathresult
		\pgfmathfloatcreate{2}{1.6}{4}%
		\global\let\pgfmathfloatatan@TMPB=\pgfmathresult
	\fi
	\pgfmathfloatgreaterthan@{#1}{\pgfmathfloatatan@TMP}%
	\ifpgfmathfloatcomparison
		\pgfmathfloatcreate{1}{9.0}{1}%
	\else
		\pgfmathfloatlessthan{#1}{\pgfmathfloatatan@TMPB}%
		\ifpgfmathfloatcomparison
			\pgfmathfloatcreate{2}{9.0}{1}%
		\else
			\pgfmathfloattofixed@{#1}%
			\expandafter\pgfmath@basic@atan@\expandafter{\pgfmathresult}%
			\pgfmathfloatparsenumber{\pgfmathresult}%
		\fi
	\fi
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%
\let\pgfmathfloatatan=\pgfmathfloatatan@

\def\pgfmathfloatsec@#1{\pgfmathfloatTRIG@\pgfmath@basic@cos@{#1}\pgfmathfloatreciprocal@{\pgfmathresult}}
\let\pgfmathfloatsec=\pgfmathfloatsec@
\def\pgfmathfloatcosec@#1{\pgfmathfloatTRIG@\pgfmath@basic@sin@{#1}\pgfmathfloatreciprocal@{\pgfmathresult}}
\let\pgfmathfloatcosec=\pgfmathfloatcosec@

% Expands #2 using \edef and invokes #1 with the resulting string.
%
% DEPRECATED
% Example:
%   \pgfmath@y=7.9pt
%   \pgfmathlog@invoke@expanded\pgfmathexp@{{\pgf@sys@tonumber{\pgfmath@y}}}%
% will invoke
%   \pgfmathexp@{7.9}
\def\pgfmathlog@invoke@expanded#1#2{%
	\edef\pgfmath@resulttemp{#2}%
	\expandafter#1\pgfmath@resulttemp
}

\def\pgfmathfloatln@#1{%
	\pgfmathlog@float{#1}%
	\ifx\pgfmathresult\pgfutil@empty
		\pgfmathfloatcreate{3}{0.0}{0}%
	\else
		\pgfmathfloatparsenumber{\pgfmathresult}%
	\fi
}
\let\pgfmathfloatln=\pgfmathfloatln@

\expandafter\def\csname pgfmathfloatlog10@\endcsname#1{%
	\pgfmathfloatln@{#1}%
	\let\pgfmathfloat@log@ten=\pgfmathresult
	\pgfmathfloatcreate{1}{4.34294481903252}{-1}% 1/ln(10)
	\pgfmathfloatmultiply@{\pgfmathresult}{\pgfmathfloat@log@ten}%
}%
\expandafter\def\csname pgfmathfloatlog2@\endcsname#1{%
	\pgfmathfloatln@{#1}%
	\let\pgfmathfloat@log@two=\pgfmathresult
	\pgfmathfloatcreate{1}{1.44269504088896}{0}% 1/ln(2)
	\pgfmathfloatmultiply@{\pgfmathresult}{\pgfmathfloat@log@two}%
}%

% Computes log(x) into \pgfmathresult.
%
% This allows numbers such at 10000000 or 5.23e-10 to be represented
% properly, although TeX-registers would produce overflow/underflow
% errors in these cases. 
%
% The natural logarithm is computed using log(X*10^Y) = log(X) + log(10)*Y
%
% FIXME This routine is only kept for backwards compatibility!
% It does not work as expected because
% 1. it calls \pgfmathfloatparsenumber
% 2. it returns the result as fixed point number
% Use \pgfmathln@ instead!
\def\pgfmathlog@#1{%
	\pgfmathfloatparsenumber{#1}%
	\pgfmathlog@float{\pgfmathresult}%
}
\let\pgfmathlog=\pgfmathlog@
\def\pgfmathlog@float#1{%
	\begingroup%
		% compute #1 = M*10^E with normalised mantisse M = [+-]*[1-9].XXXXX
		\expandafter\pgfmathfloat@decompose@tok#1\relax\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
		\ifnum\pgfmathfloat@a@S=1
			% Now, compute log(#1) = log(M) + E*log(10)
			\expandafter\pgfmath@basic@ln@\expandafter{\the\pgfmathfloat@a@Mtok}%
			\pgfmathfloat@b@M=\pgfmathresult pt%
			\pgfmathfloat@a@M=2.302585pt% = log(10)
			\multiply\pgfmathfloat@a@M by\pgfmathfloat@a@E\relax
			\advance\pgfmathfloat@b@M by\pgfmathfloat@a@M
			\edef\pgfmathresult{\pgf@sys@tonumber{\pgfmathfloat@b@M}}%
		\else
			\let\pgfmathresult=\pgfutil@empty%
		\fi
	\pgfmath@smuggleone\pgfmathresult
	\endgroup%
}


% Computes exp(#1) in floating point.
%
% The algorithm employs the identity 
%  exp(x) = exp(x - log(10^k) + log(10^k)
%         = 10^k exp( x - k*log 10 )
% with k choosen such that exp( x - k*log10) can be computed with the
% basic level math engine.
%
% The precision (relative error) is between 10^{-4} and 10^{-6}. For
% #1 = 700, it is even 10^{-3}. I will need to improve that someday.
\def\pgfmathfloatexp@#1{%
	\begingroup
		\expandafter\pgfmathfloat@decompose@tok#1\relax\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
		\ifcase\pgfmathfloat@a@S
		% #1 = 0:
			\pgfmathfloatcreate{1}{1.0}{0}%
		\or% #1 > 0
			\pgfmathfloatexp@@{#1}%
		\or% #1 < 0
			\pgfmathfloatexp@@{#1}%
		\else
			\edef\pgfmathresult{#1}%
		\fi
		\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%
\def\pgfmathfloatexp@@#1{%
	% Employ the identity
	% exp(x) = exp(x - log(10^k) + log(10^k)) = 10^k exp( x - k *log(10))
	%
	% I'd like to have x - k*log(10) <= 1
	% => compute k := int( (x - 1) * 1/log(10) )
	% that should suffice since \pgfmathexp@ should be
	% accurate enough for those numbers.
	%
	% please note that we can do all this in TeX registers.
	% exp(700) is almost the maximum of double precision
	% anyway, and exp(16000) is certainly the largest we will
	% ever need.
	\pgfmathfloattofixed@{#1}%
	\pgf@xa=\pgfmathresult pt
	\pgf@xa=0.434294481\pgf@xa\relax
	\edef\pgfmathfloat@loc@TMPa{\pgf@sys@tonumber{\pgf@xa}}%
	\expandafter\pgfmathfloatexp@@toint\pgfmathfloat@loc@TMPa\relax
	\pgf@xa=2.302585092pt
	\multiply\pgf@xa by-\pgfmathfloat@k\relax
	\advance\pgf@xa by\pgfmathresult pt
	\edef\pgfmathfloat@loc@TMPa{\pgf@sys@tonumber{\pgf@xa}}%
%\message{computing exp(\pgfmathresult) = 10^\pgfmathfloat@k * exp(\pgfmathfloat@loc@TMPa)...}%
	\pgfmath@basic@exp@{\pgfmathfloat@loc@TMPa}%
	\let\pgfmathfloat@loc@TMPa=\pgfmathresult
	\pgfmathfloatparsenumber{\pgfmathfloat@loc@TMPa}%
	\let\pgfmathfloat@loc@TMPa=\pgfmathresult
	\pgfmathfloatshift@{\pgfmathfloat@loc@TMPa}{\pgfmathfloat@k}%
}
% determine 'k'. This is a heuristics. The exponential series
% converges best for |x| <= 1. However, the fixed point arithmetics
% for tex results in best results for large |x|. Well, I'll need to
% tune this here.
\def\pgfmathfloatexp@@toint#1.#2\relax{%
	\c@pgf@counta=#1\relax
	\ifnum\c@pgf@counta<0
\advance\c@pgf@counta by-1 % FIXME . this is a test for optimizations.
		\c@pgf@countb=#2\relax
		\ifnum\c@pgf@countb>0
			\advance\c@pgf@counta by-1
		\fi
	\fi
	\edef\pgfmathfloat@k{\the\c@pgf@counta}%
}%
\let\pgfmathfloatexp=\pgfmathfloatexp@

\def\pgfmathfloatround@#1{%
	\begingroup
	\pgfkeysvalueof{/pgf/number format/precision/.@cmd}0\pgfeov
	\pgfmathfloattofixed{#1}%
	\pgfmathroundto{\pgfmathresult}%
	\pgfmathfloatparsenumber{\pgfmathresult}%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%


\def\pgfmathfloatneg@#1{%
	\begingroup
	\expandafter\pgfmathfloat@decompose@tok#1\relax\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
	\ifcase\pgfmathfloat@a@S\relax
		% 0:
		\edef\pgfmathresult{#1}%
	\or
		% +:
		\pgfmathfloatcreate{2}{\the\pgfmathfloat@a@Mtok}{\the\pgfmathfloat@a@E}%
	\or
		% -:
		\pgfmathfloatcreate{1}{\the\pgfmathfloat@a@Mtok}{\the\pgfmathfloat@a@E}%
	\or
		% nan:
		\edef\pgfmathresult{#1}%
	\or
		% +infty:
		\pgfmathfloatcreate{5}{\the\pgfmathfloat@a@Mtok}{\the\pgfmathfloat@a@E}%
	\or
		% -infty:
		\pgfmathfloatcreate{4}{\the\pgfmathfloat@a@Mtok}{\the\pgfmathfloat@a@E}%
	\fi
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%


\def\pgfmathfloatpow@#1#2{%
	\begingroup%
	\expandafter\pgfmathfloat@decompose@tok#2\relax\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
	\ifcase\pgfmathfloat@a@S\relax
		% #1 ^ 0 = 1
		\pgfmathfloatcreate{1}{1.0}{0}%
	\or
		% #2 > 0
		\pgfmathfloatpow@@{#1}{#2}%
	\or
		% #2 < 0
		\pgfmathfloatpow@@{#1}{#2}%
	\or
		% #2 = nan
		\edef\pgfmathresult{#2}%
	\or
		% #2 = inf
		\edef\pgfmathresult{#2}%
	\or
		% #2 = -inf
		\pgfmathfloatcreate{0}{0.0}{0}%
	\fi
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%

% computes #1^#2
% PRECONDITIONS
% - #2 is positive.
\def\pgfmathfloatpow@@#1#2{%
	\pgfmathfloattofixed@{#2}%
	\afterassignment\pgfmath@x%
	\expandafter\c@pgfmath@counta\pgfmathresult pt\relax%
	\ifdim\pgfmath@x=0pt %
		% loop "manually"; we have an integer exponent!
		\ifnum\c@pgfmath@counta<0
			\pgfmathfloatreciprocal@{#1}%
			\let\pgfmathfloat@loc@TMPa=\pgfmathresult
			\c@pgfmath@counta=-\c@pgfmath@counta
		\else
			\edef\pgfmathfloat@loc@TMPa{#1}%
		\fi
		\pgfmathfloatcreate{1}{1.0}{0}%
		\let\pgfmathfloat@loc@TMPb=\pgfmathresult
		\pgfmathloop
			\ifnum\c@pgfmath@counta>0\relax%
				\ifodd\c@pgfmath@counta%
					\pgfmathfloatmultiply@{\pgfmathfloat@loc@TMPb}{\pgfmathfloat@loc@TMPa}%
					\let\pgfmathfloat@loc@TMPb=\pgfmathresult
				\fi
				\ifnum\c@pgfmath@counta>1\relax%
					\pgfmathfloatmultiply@{\pgfmathfloat@loc@TMPa}{\pgfmathfloat@loc@TMPa}%
					\let\pgfmathfloat@loc@TMPa=\pgfmathresult
				\fi%
				\divide\c@pgfmath@counta by2\relax%
		\repeatpgfmathloop%
	\else
		\pgfmathfloatgetflags{#1}\c@pgfmath@counta
		\ifnum0=\c@pgfmath@counta
			% ah: 0^x 
			\pgfmathfloatgetflags{#2}\c@pgfmath@counta
			\ifnum0=\c@pgfmath@counta
				% ah: 0^0
				\pgfmathfloatcreate{1}{1.0}{0}%
			\else	
				% ah: 0^x with x!=0:
				\pgfmathfloatcreate{0}{0.0}{0}%
			\fi
		\else
			% employ #1^#2 = exp( #2 * ln(#1) )
			\pgfmathfloatln@{#1}%
			\let\pgfmathfloat@loc@TMPa=\pgfmathresult
			\edef\pgfmathfloat@loc@TMPb{#2}%
			\pgfmathfloatmultiply@{\pgfmathfloat@loc@TMPa}{\pgfmathfloat@loc@TMPb}%
			\pgfmathfloatexp@{\pgfmathresult}%
		\fi
	\fi
}

\def\pgfmathfloat@definemethodfrombasic@NOARG#1{%
	\pgfutil@ifundefined{pgfmath@basic@#1@}{%
		\pgfutil@namelet{pgfmath@basic@#1@}{pgfmath#1@}%
	}{}%
	\edef\pgfmathfloat@glob@TMP{%
		\expandafter\noexpand\csname pgfmath@basic@#1@\endcsname
		\noexpand\pgfmathfloatparsenumber{\noexpand\pgfmathresult}%
	}%
	\expandafter\let\csname pgfmathfloat#1@\endcsname=\pgfmathfloat@glob@TMP%
	\expandafter\let\csname pgfmathfloat#1\endcsname=\pgfmathfloat@glob@TMP%
}%
\def\pgfmathfloat@definemethodfrombasic@ONEARG#1{%
	\pgfutil@ifundefined{pgfmath@basic@#1@}{%
		\pgfutil@namelet{pgfmath@basic@#1@}{pgfmath#1@}%
	}{}%
	\edef\pgfmathfloat@glob@TMP##1{%
		\noexpand\pgfmathfloattofixed{##1}%
		\noexpand\expandafter
		\expandafter\noexpand\csname pgfmath@basic@#1@\endcsname\noexpand\expandafter%
			{\noexpand\pgfmathresult}%
		\noexpand\pgfmathfloatparsenumber{\noexpand\pgfmathresult}%
	}%
	\expandafter\let\csname pgfmathfloat#1@\endcsname=\pgfmathfloat@glob@TMP%
	\expandafter\let\csname pgfmathfloat#1\endcsname=\pgfmathfloat@glob@TMP%
}%
\def\pgfmathfloat@definemethodfrombasic@TWOARGS#1{%
	\pgfutil@ifundefined{pgfmath@basic@#1@}{%
		\pgfutil@namelet{pgfmath@basic@#1@}{pgfmath#1@}%
	}{}%
	\edef\pgfmathfloat@glob@TMP##1##2{%
		\noexpand\pgfmathfloattofixed{##2}%
		\noexpand\let\noexpand\pgfmathfloat@loc@TMPa=\noexpand\pgfmathresult
		\noexpand\pgfmathfloattofixed{##1}%
		\noexpand\expandafter
		\expandafter\noexpand\csname pgfmath@basic@#1@\endcsname\noexpand\expandafter%
			{\noexpand\pgfmathresult}{\noexpand\pgfmathfloat@loc@TMPa}%
		\noexpand\pgfmathfloatparsenumber{\noexpand\pgfmathresult}%
	}%
	\expandafter\let\csname pgfmathfloat#1@\endcsname=\pgfmathfloat@glob@TMP%
	\expandafter\let\csname pgfmathfloat#1\endcsname=\pgfmathfloat@glob@TMP%
}%
\pgfmathfloat@definemethodfrombasic@NOARG{rand}
\pgfmathfloat@definemethodfrombasic@NOARG{rnd}
\pgfmathfloat@definemethodfrombasic@NOARG{false}
\pgfmathfloat@definemethodfrombasic@NOARG{true}
% arcsin, arccos 
\pgfmathfloat@definemethodfrombasic@ONEARG{asin}
\pgfmathfloat@definemethodfrombasic@ONEARG{acos}
\pgfmathfloat@definemethodfrombasic@ONEARG{not}
\pgfmathfloat@definemethodfrombasic@ONEARG{hex}
\pgfmathfloat@definemethodfrombasic@ONEARG{Hex}
\pgfmathfloat@definemethodfrombasic@ONEARG{oct}
\pgfmathfloat@definemethodfrombasic@ONEARG{bin}
\pgfmathfloat@definemethodfrombasic@TWOARGS{and}
\pgfmathfloat@definemethodfrombasic@TWOARGS{or}

\pgfutil@ifundefined{pgfmathdeclarefunction}{%
	% special treatment: \pgfmathrand@ was not properly defined for pgf 2.00:
	\let\pgfmath@basic@rand=\pgfmathrand
	\let\pgfmath@basic@rand@=\pgfmathrand@
	\def\pgfmathfloatrand@{%
		\pgfmath@basic@rand
		\pgfmathfloatparsenumber{\pgfmathresult}%
	}%
	\let\pgfmathfloatrand=\pgfmathfloatrand@%
	%
	% special treatment: \pgfmathrnd@ was not properly defined for pgf 2.00:
	\let\pgfmath@basic@rnd=\pgfmathrnd
	\let\pgfmath@basic@rnd@=\pgfmathrnd@
	\def\pgfmathfloatrnd@{%
		\pgfmath@basic@rnd
		\pgfmathfloatparsenumber{\pgfmathresult}%
	}%
	\let\pgfmathfloatrnd=\pgfmathfloatrnd@%
}{}

% Implements the factorial of '#1'.
% This does only work if '#1 < 2^32'.
\def\pgfmathfloatfactorial@#1{%
	\begingroup
	\pgfmathfloattofixed{#1}%
	% collect integer part into a 32 bit register:
	\afterassignment\pgfmath@gobbletilpgfmath@%
	\expandafter\c@pgfmath@counta\pgfmathresult\relax\pgfmath@%
	\pgfmathfloatcreate{1}{1.0}{0}%
	\let\pgfmathfloat@loc@TMPa=\pgfmathresult
	\pgfmathloop
	\ifnum\c@pgfmath@counta<2 %
	\else
		\expandafter\pgfmathfloatparsenumber\expandafter{\the\c@pgfmath@counta}%
		\expandafter\pgfmathfloatmultiply@\expandafter{\pgfmathresult}{\pgfmathfloat@loc@TMPa}%
		\let\pgfmathfloat@loc@TMPa=\pgfmathresult
		\advance\c@pgfmath@counta by-1\relax%
	\repeatpgfmathloop
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%

% Implements the vector length of a 2D vector.
%
% ATTENTION: this does NOT use the improved code of the basic layer!
% It simply computed sqrt( #1^2 + #2^2 )!
\def\pgfmathfloatveclen@#1#2{%
	\begingroup
	\edef\pgfmathfloat@@a{#1}%
	\pgfmathfloatmultiply@{\pgfmathfloat@@a}{\pgfmathfloat@@a}%
	\let\pgfmathfloat@@a=\pgfmathresult
	%
	\edef\pgfmathfloat@@b{#2}%
	\pgfmathfloatmultiply@{\pgfmathfloat@@b}{\pgfmathfloat@@b}%
	\let\pgfmathfloat@@b=\pgfmathresult
	%
	\pgfmathfloatadd@{\pgfmathfloat@@a}{\pgfmathfloat@@b}%
	\pgfmathfloatsqrt@{\pgfmathresult}%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%

\def\pgfmathfloatcosh@#1{%
	\begingroup
	\pgfmathfloatexp@{#1}%
	\let\pgfmathfloat@@a=\pgfmathresult
	%
	\pgfmathfloatneg@{#1}%
	\pgfmathfloatexp@{\pgfmathresult}%
	%
	\pgfmathfloatadd@{\pgfmathresult}{\pgfmathfloat@@a}%
	\expandafter\pgfmathfloatmultiplyfixed@\expandafter{\pgfmathresult}{0.5}%
	%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%
\def\pgfmathfloatsinh@#1{%
	\begingroup
	\pgfmathfloatexp@{#1}%
	\let\pgfmathfloat@@a=\pgfmathresult
	%
	\pgfmathfloatneg@{#1}%
	\pgfmathfloatexp@{\pgfmathresult}%
	%
	\pgfmathfloatsubtract@{\pgfmathfloat@@a}{\pgfmathresult}%
	\expandafter\pgfmathfloatmultiplyfixed@\expandafter{\pgfmathresult}{0.5}%
	%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%
\def\pgfmathfloattanh@#1{%
	\begingroup
	\pgfmathfloatsinh@{#1}%
	\let\pgfmathfloat@@a=\pgfmathresult
	%
	\pgfmathfloatcosh@{#1}%
	\let\pgfmathfloat@@b=\pgfmathresult
	%
	\pgfmathfloatdivide@{\pgfmathfloat@@a}{\pgfmathfloat@@b}%
	%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%
\endinput

pgflibraryintersections.code.tex
% Copyright 2008 by Mark Wibrow
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Free Documentation License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

% Note: at the time of this writing, the library has quadratic runtime.
%   Experimentally, it performed well while computing ~12 intersections of two
%   plots, each with 600 samples. It failed when the number of samples exceeded 700.

\newcount\pgf@intersect@solutions

\newif\ifpgf@intersect@sort
\newif\ifpgf@intersect@sort@by@second@path

\def\pgfintersectionsortbyfirstpath{%
	\pgf@intersect@sorttrue%
	\pgf@intersect@sort@by@second@pathfalse%
}

\def\pgfintersectionsortbysecondpath{%
	\pgf@intersect@sorttrue%
	\pgf@intersect@sort@by@second@pathtrue%
}

% #1: the index. It starts at 1 and ends with \pgfintersectionsolutions (inclusive).
% Invalid values will implicitly result in the origin.
\def\pgfpointintersectionsolution#1{%
	\ifnum#1<1\relax%
		\pgfpoint@intersect@solution@orgin%
	\else%
		\ifnum#1>\pgfintersectionsolutions\relax%
			\pgfpoint@intersect@solution@orgin%
		\else%
			\csname pgfpoint@intersect@solution@#1\endcsname%
		\fi%
	\fi%
}

% Gets the segment indices of solution #1.
%
% #1: the solution index (i.e. the same argument as in \pgfpointintersectionsolution)
% #2: [output] a macro name which will contain the segment index of the first path which contains the solution
% #3: [output] a macro name which will contain the segment index of the second path which contains the solution
%
% Example: \pgfintersectiongetsolutionsegmentindices{0}{\first}{\second}
%
% -> \first may be 0 if point #0 is in the 0'th segment
% -> \second may be 42 if point #0 is in the 42'th segment 
\def\pgfintersectiongetsolutionsegmentindices#1#2#3{%
	\ifnum#1<1\relax%
		\let#2=\pgfutil@empty
		\let#3=\pgfutil@empty
	\else%
		\ifnum#1>\pgfintersectionsolutions\relax%
			\let#2=\pgfutil@empty
			\let#3=\pgfutil@empty
		\else%
			\edef#2{\csname pgf@intersect@solution@segment@a@#1\endcsname}%
			\edef#3{\csname pgf@intersect@solution@segment@b@#1\endcsname}%
		\fi%
	\fi%
}%

\def\pgfpoint@intersect@solution@orgin{%
	\begingroup%
		\pgftransforminvert%
		\pgfpointorigin%
		\pgf@pos@transform{\pgf@x}{\pgf@y}%
		\global\pgf@x=\pgf@x%
		\global\pgf@y=\pgf@y%
	\endgroup%
}

% #1 code which assigns the first path using \pgfsetpath.
% #2 code which assigns the second path using \pgfsetpath.
%
% On output, the points, their properties, and the number of points are set.
% Use \pgfintersectionsolutions which expands to the number of intersections
\long\def\pgfintersectionofpaths#1#2{%
	\begingroup%
		\pgfinterruptpath%
		#1% 
		\pgfgetpath\pgf@intersect@path@a%
		\global\let\pgf@intersect@path@temp=\pgf@intersect@path@a%
		\endpgfinterruptpath%
	\endgroup%
	\let\pgf@intersect@path@a=\pgf@intersect@path@temp%
	%
	\begingroup%
		\pgfinterruptpath%
		#2% 
		\pgfgetpath\pgf@intersect@path@b%
		\global\let\pgf@intersect@path@temp=\pgf@intersect@path@b%
		\endpgfinterruptpath%
	\endgroup%
	\let\pgf@intersect@path@b=\pgf@intersect@path@temp%
	%
	\pgf@intersect@solutions=0\relax%
	\def\pgf@intersect@time@offset{0}%
	%
	\ifpgf@intersect@sort@by@second@path%
		\let\pgf@intersect@temp=\pgf@intersect@path@a%
		\let\pgf@intersect@path@a=\pgf@intersect@path@b%
		\let\pgf@intersect@path@b=\pgf@intersect@temp%
	\fi%
	%
	\pgfprocessround\pgf@intersect@path@a\pgf@intersect@path@a%
	\pgfprocessround\pgf@intersect@path@b\pgf@intersect@path@b%
	%
	\let\pgf@intersect@token@after=\pgf@intersect@path@process@a%
	\expandafter\pgf@intersectionofpaths\pgf@intersect@path@a\pgf@stop%
	\edef\pgfintersectionsolutions{\the\pgf@intersect@solutions}%
	\pgfmathloop%
		\ifnum\pgfmathcounter>\pgfintersectionsolutions\relax%
		\else%
			\pgfutil@namelet{pgfpoint@intersect@solution@\pgfmathcounter}%
				{pgfpoint@g@intersect@solution@\pgfmathcounter}%
			\edef\pgf@marshal{\noexpand\pgf@intersection@set@properties\csname pgfpoint@g@intersect@solution@\pgfmathcounter @props\endcsname}%
			\pgf@marshal
			\ifpgf@intersect@sort%
				\pgfutil@namelet{pgf@intersect@solution@\pgfmathcounter @time@a}%
					{pgf@g@intersect@solution@\pgfmathcounter @time@a}%
			\fi%
	\repeatpgfmathloop%
	\ifpgf@intersect@sort%
		\pgfintersectionsolutionsortbytime%
	\fi%
}

\def\pgf@intersection@set@properties#1#2{%
	\pgfutil@namedef{pgf@intersect@solution@segment@a@\pgfmathcounter}{#1}%
	\pgfutil@namedef{pgf@intersect@solution@segment@b@\pgfmathcounter}{#2}%
}%

% #1 a global name prefix to store properties.
\def\pgf@intersection@store@properties#1{%
	% we store the time offsets as well and make them available programmatically:
	\expandafter\xdef\csname #1@props\endcsname{{\pgf@intersect@time@offset}{\pgf@intersect@time@offset@b}}%
}

\def\pgf@intersectionofpaths#1{%
	\ifx#1\pgf@stop%
		\let\pgf@intersect@next=\relax%
	\else%
		\ifx#1\pgfsyssoftpath@movetotoken%
			\let\pgf@intersect@next=\pgf@intersect@token@moveto%
		\else%
			\ifx#1\pgfsyssoftpath@linetotoken%
				\let\pgf@intersect@next=\pgf@intersect@token@lineto%
			\else%
				\ifx#1\pgfsyssoftpath@closepathtoken%
					\let\pgf@intersect@next=\pgf@intersect@token@lineto%
				\else%
					\ifx#1\pgfsyssoftpath@curvetosupportatoken%
						\let\pgf@intersect@next=\pgf@intersect@token@curveto%
					\else%
						\ifx#1\pgfsyssoftpath@rectcornertoken%
							\let\pgf@intersect@next=\pgf@intersect@token@rect%
						\fi%
					\fi%
				\fi%
			\fi%
		\fi%
	\fi%
	\pgf@intersect@next}

\def\pgf@intersect@token@moveto#1#2{%
	\def\pgfpoint@intersect@start{\pgfqpoint{#1}{#2}}%
	\pgf@intersectionofpaths%
}

\def\pgf@intersect@token@lineto#1#2{%
	\def\pgfpoint@intersect@end{\pgfqpoint{#1}{#2}}%
	\def\pgf@intersect@type{line}%
	\pgf@intersect@token@after%
}
\def\pgf@intersect@token@curveto#1#2\pgfsyssoftpath@curvetosupportbtoken#3#4\pgfsyssoftpath@curvetotoken#5#6{%
	\def\pgfpoint@intersect@firstsupport{\pgfqpoint{#1}{#2}}%
	\def\pgfpoint@intersect@secondsupport{\pgfqpoint{#3}{#4}}%
	\def\pgfpoint@intersect@end{\pgfqpoint{#5}{#6}}%
	\def\pgf@intersect@type{curve}%
	\pgf@intersect@token@after%
}

\def\pgf@intersect@token@rect#1#2\pgfsyssoftpath@rectsizetoken#3#4{%
	\pgf@xa=#1\relax%
	\advance\pgf@xa by#3\relax%
	\pgf@ya=#2\relax%
	\advance\pgf@ya by#4\relax%
	\edef\pgf@marshal{%
		\noexpand\pgfsyssoftpath@movetotoken{#1}{#2}%
		\noexpand\pgfsyssoftpath@linetotoken{#1}{\the\pgf@ya}%
		\noexpand\pgfsyssoftpath@linetotoken{\the\pgf@xa}{\the\pgf@ya}%
		\noexpand\pgfsyssoftpath@linetotoken{\the\pgf@xa}{#2}%
		\noexpand\pgfsyssoftpath@closepathtoken{#1}{#2}%
	}%
	\expandafter\pgf@intersectionofpaths\pgf@marshal%
}

\def\pgf@intersect@path@process@a{%
	\pgf@intersect@path@getpoints@a%
	\let\pgf@intersect@token@after=\pgf@intersect@path@process@b%
	\def\pgf@intersect@time@offset@b{0}%
	\expandafter\pgf@intersectionofpaths\pgf@intersect@path@b\pgf@stop%
	\let\pgfpoint@intersect@start=\pgfpoint@intersect@end@a%
	\let\pgf@intersect@token@after=\pgf@intersect@path@process@a%
	\c@pgf@counta=\pgf@intersect@time@offset\relax%
	\advance\c@pgf@counta by1\relax%
	\edef\pgf@intersect@time@offset{\the\c@pgf@counta}%
	\pgf@intersectionofpaths%
}

\def\pgf@intersect@path@getpoints@a{%
	\let\pgfpoint@intersect@start@a=\pgfpoint@intersect@start%
	\let\pgfpoint@intersect@end@a=\pgfpoint@intersect@end%
	\let\pgfpoint@intersect@firstsupport@a=\pgfpoint@intersect@firstsupport%
	\let\pgfpoint@intersect@secondsupport@a=\pgfpoint@intersect@secondsupport%
	\let\pgf@intersect@type@a=\pgf@intersect@type%
}

\def\pgf@intersect@path@process@b{%
	\pgf@intersect@path@getpoints@b%
	\csname pgf@intersect@\pgf@intersect@type@a @and@\pgf@intersect@type@b\endcsname%
	\let\pgfpoint@intersect@start=\pgfpoint@intersect@end@b%
	\c@pgf@counta=\pgf@intersect@time@offset@b\relax%
	\advance\c@pgf@counta by1\relax%
	\edef\pgf@intersect@time@offset@b{\the\c@pgf@counta}%
	\pgf@intersectionofpaths}

\def\pgf@intersect@path@getpoints@b{%
	\let\pgfpoint@intersect@start@b=\pgfpoint@intersect@start%
	\let\pgfpoint@intersect@end@b=\pgfpoint@intersect@end%
	\let\pgfpoint@intersect@firstsupport@b=\pgfpoint@intersect@firstsupport%
	\let\pgfpoint@intersect@secondsupport@b=\pgfpoint@intersect@secondsupport%
	\let\pgf@intersect@type@b=\pgf@intersect@type%
}

\def\pgf@intersect@line@and@line{%
	\pgf@intersectionoflines{\pgfpoint@intersect@start@a}{\pgfpoint@intersect@end@a}%
		{\pgfpoint@intersect@start@b}{\pgfpoint@intersect@end@b}%
}%

\def\pgf@intersect@line@and@curve{%
	\pgf@intersectionoflineandcurve%
		{\pgf@process{\pgfpoint@intersect@start@a}}{\pgf@process{\pgfpoint@intersect@end@a}}%
		{\pgf@process{\pgfpoint@intersect@start@b}}{\pgf@process{\pgfpoint@intersect@firstsupport@b}}%
		{\pgf@process{\pgfpoint@intersect@secondsupport@b}}{\pgf@process{\pgfpoint@intersect@end@b}}%
}

\def\pgf@intersect@curve@and@line{%
	\pgf@intersectionofcurveandline%
		{\pgf@process{\pgfpoint@intersect@start@a}}{\pgf@process{\pgfpoint@intersect@firstsupport@a}}%
		{\pgf@process{\pgfpoint@intersect@secondsupport@a}}{\pgf@process{\pgfpoint@intersect@end@a}}%
		{\pgf@process{\pgfpoint@intersect@start@b}}{\pgf@process{\pgfpoint@intersect@end@b}}%
}

\def\pgf@intersect@curve@and@curve{%
	\pgf@intersectionofcurves%
		{\pgf@process{\pgfpoint@intersect@start@a}}{\pgf@process{\pgfpoint@intersect@firstsupport@a}}%
		{\pgf@process{\pgfpoint@intersect@secondsupport@a}}{\pgf@process{\pgfpoint@intersect@end@a}}%
		{\pgf@process{\pgfpoint@intersect@start@b}}{\pgf@process{\pgfpoint@intersect@firstsupport@b}}%
		{\pgf@process{\pgfpoint@intersect@secondsupport@b}}{\pgf@process{\pgfpoint@intersect@end@b}}%
}


\def\pgfintersectionoflines#1#2#3#4{%
	\pgf@intersect@solutions=0\relax%
	\pgf@intersectionoflines{#1}{#2}{#3}{#4}%
}

\def\pgf@intersectionoflines#1#2#3#4{%
	\pgf@iflinesintersect{#1}{#2}{#3}{#4}%
	{%
		\global\advance\pgf@intersect@solutions by1\relax%
		\expandafter\pgfextract@process\csname pgfpoint@g@intersect@solution@\the\pgf@intersect@solutions\endcsname{%
			\pgfpointintersectionoflines{\pgfpoint@intersect@start@a}{\pgfpoint@intersect@end@a}%
				{\pgfpoint@intersect@start@b}{\pgfpoint@intersect@end@b}%
		}%
		\pgf@intersection@store@properties{pgfpoint@g@intersect@solution@\the\pgf@intersect@solutions}%
		%
		\ifpgf@intersect@sort%
			\pgf@xc=\pgf@x%
			\pgf@yc=\pgf@y%
			\pgf@process{\pgfpointdiff{\pgfpoint@intersect@start@a}{\pgfpoint@intersect@end@a}}%
			\edef\pgf@marshal{%
				\noexpand\pgfmathveclen@{\pgfmath@tonumber{\pgf@xa}}{\pgfmath@tonumber{\pgf@ya}}%
			}%
			\pgf@marshal%
			\let\pgf@intersect@length@a=\pgfmathresult%
			\pgf@process{\pgfpointdiff{\pgfpoint@intersect@start@a}{\pgfqpoint{\pgf@xc}{\pgf@yc}}}%
			\edef\pgf@marshal{%
				\noexpand\pgfmathveclen@{\pgfmath@tonumber{\pgf@x}}{\pgfmath@tonumber{\pgf@y}}%
			}%
			\pgf@marshal%
			\pgfmathdivide@{\pgfmathresult}{\pgf@intersect@length@a}%
			\pgf@x=\pgfmathresult pt\relax%
			\advance\pgf@x by\pgf@intersect@time@offset pt\relax%		
			\expandafter\xdef\csname pgf@g@intersect@solution@\the\pgf@intersect@solutions @time@a\endcsname%
				{\pgfmath@tonumber{\pgf@x}}%
		\fi%
	}{}%		
}

% Test if two lines L1 and L2 intersect.
%
% #1 - first point P1 on L1.
% #2 - second point P2 on L1.
% #3 - first point P3 on L2.
% #2 - second point P4 on L2.
% #5 - code executed if intersection occurs.
% #6 - code executed if intersection does no occur.
%
% Let L1 be represented by P1+(P2-P1)s where 0<=s<=1
% Let L2 be represented by P3+(P4-P3)t where 0<=t<=1
%
% Then L1 and L2 intersect at
%
% s = |x2-x1  x3-x1| / |x4-x3  x2-x1|
%     |y2-y1  y3-y1|   |y4-y3  y2-y1|
%
% t = |x4-x3  x3-x1| / |x4-x3  x2-x1|
%     |y4-y3  y3-y1|   |y4-y3  y2-y1|
% 
% with 0<=s,t<=1
%		
% s and t do not need to be calculated:
%
% Let s = A / C and t = B / C
% 
% Then 0<=s<=1 if !(C=0) && ((A=0) || ((A>0) && !(C<A)) || ((A<0) && !(C>A)))
%      0<=t<=1 if !(C=0) && ((B=0) || ((B>0) && !(C<B)) || ((B<0) && !(C>B)))
% 
\newif\ifpgf@s
\newif\ifpgf@t
\def\pgfiflinesintersect#1#2#3#4{%
	\begingroup%
		\pgf@iflinesintersect{\pgf@process{#1}}{\pgf@process{#2}}{\pgf@process{#3}}{\pgf@process{#4}}%
			{\aftergroup\pgfutil@firstoftwo}{\aftergroup\pgfutil@secondoftwo}%
	\endgroup%
}

\def\pgf@iflinesintersect#1#2#3#4{%
	#4\relax%
	\pgf@xc=\pgf@x%
	\pgf@yc=\pgf@y%
	#3\relax%
	\advance\pgf@xc by-\pgf@x%
	\advance\pgf@yc by-\pgf@y%
	\pgf@xb=\pgf@x%
	\pgf@yb=\pgf@y%
	#2\relax%
	\pgf@xa=\pgf@x%
	\pgf@ya=\pgf@y%
	#1\relax%
	\advance\pgf@xa by-\pgf@x%
	\advance\pgf@ya by-\pgf@y%
	\advance\pgf@xb by-\pgf@x%
	\advance\pgf@yb by-\pgf@y%
	%
	% xc = x4-x3; yc=y4-y3;
	% xb = x3-x1; yb=y3-y1;
	% xa = x2-x1; ya=y2-y1;
	%
	%
	% Normalise a little. 16384 may not be a robust choice.
	%
	\c@pgf@counta=\pgf@xa\divide\c@pgf@counta by16384\relax% 
	\c@pgf@countb=\pgf@xb\divide\c@pgf@countb by16384\relax%
	\c@pgf@countc=\pgf@ya\divide\c@pgf@countc by16384\relax%
	\c@pgf@countd=\pgf@yb\divide\c@pgf@countd by16384\relax%
	\multiply\c@pgf@counta by\c@pgf@countd%
	\multiply\c@pgf@countc by\c@pgf@countb%
	\advance\c@pgf@counta by-\c@pgf@countc%
	\pgfutil@tempcnta=\c@pgf@counta%
	%
	\c@pgf@counta=\pgf@xc\divide\c@pgf@counta by16384\relax%
	\c@pgf@countc=\pgf@yc\divide\c@pgf@countc by16384\relax%
	\multiply\c@pgf@countd by\c@pgf@counta%
	\multiply\c@pgf@countb by\c@pgf@countc%
	\advance\c@pgf@countd by-\c@pgf@countb%
	\pgfutil@tempcntb=\c@pgf@countd%
	%
	\c@pgf@countb=\pgf@xa\divide\c@pgf@countb by16384\relax%
	\c@pgf@countd=\pgf@ya\divide\c@pgf@countd by16384\relax%
	\multiply\c@pgf@counta by\c@pgf@countd%
	\multiply\c@pgf@countc by\c@pgf@countb%
	\advance\c@pgf@counta by-\c@pgf@countc%
	%
	\pgf@sfalse%
	\pgf@tfalse%
	\ifnum\c@pgf@counta=0\relax%
	\else%
		\ifnum\pgfutil@tempcnta=0\relax%
			\pgf@strue%
		\else%
			\ifnum\pgfutil@tempcnta>0\relax%
				\ifnum\c@pgf@counta<\pgfutil@tempcnta%
				\else%
					\pgf@strue%
				\fi%
			\else%
				\ifnum\c@pgf@counta>\pgfutil@tempcnta%
				\else%
					\pgf@strue%
				\fi%
			\fi%
		\fi%
		\ifnum\pgfutil@tempcntb=0\relax%
			\pgf@ttrue%
		\else%
			\ifnum\pgfutil@tempcntb>0\relax%
				\ifnum\c@pgf@counta<\pgfutil@tempcntb%
				\else%
					\pgf@ttrue%
				\fi%
			\else%
				\ifnum\c@pgf@counta>\pgfutil@tempcntb%
				\else%
					\pgf@ttrue%
				\fi%
			\fi%
		\fi%
	\fi%
	\let\pgf@intersect@next=\pgfutil@secondoftwo%
	\ifpgf@s%
		\ifpgf@t%
			\let\pgf@intersect@next=\pgfutil@firstoftwo%
		\fi%
	\fi%
	\pgf@intersect@next%
}




\def\pgfintersectionoflineandcurve#1#2#3#4#5#6{%
	\pgf@intersect@solutions=0\relax%
	\pgf@intersectionoflineandcurve{#1}{#2}{#3}{#4}{#5}{#6}%
}

\def\pgf@intersectionoflineandcurve#1#2#3#4#5#6{%
	\pgf@intersectionofcurves%
		{\pgf@process{#1}}%
		{%
			\pgf@process{%
				\pgfpointadd{#1\relax\pgf@x=0.666666\pgf@x\pgf@y=0.666666\pgf@y}%
					{#2\relax\pgf@x=0.333333\pgf@x\pgf@y=0.333333\pgf@y}%
			}%
		}%
		{%
			\pgf@process{%
				\pgfpointadd{#1\relax\pgf@x=0.333333\pgf@x\pgf@y=0.333333\pgf@y}%
					{#2\relax\pgf@x=0.666666\pgf@x\pgf@y=0.666666\pgf@y}%
			}%
		}%
		{\pgf@process{#2}}%
		{\pgf@process{#3}}%
		{\pgf@process{#4}}%
		{\pgf@process{#5}}%
		{\pgf@process{#6}}%
}%

\def\pgf@intersectionofcurveandline#1#2#3#4#5#6{%
	\pgf@intersectionofcurves%
		{\pgf@process{#1}}%
		{\pgf@process{#2}}%
		{\pgf@process{#3}}%
		{\pgf@process{#4}}%
		{\pgf@process{#5}}%
		{%
			\pgf@process{%
				\pgfpointadd{#5\relax\pgf@x=0.666666\pgf@x\pgf@y=0.666666\pgf@y}%
					{#6\relax\pgf@x=0.333333\pgf@x\pgf@y=0.333333\pgf@y}%
			}%
		}%
		{%
			\pgf@process{%
				\pgfpointadd{#5\relax\pgf@x=0.333333\pgf@x\pgf@y=0.333333\pgf@y}%
					{#6\relax\pgf@x=0.666666\pgf@x\pgf@y=0.666666\pgf@y}%
			}%
		}%
		{\pgf@process{#6}}%
}%




\def\pgfintersectiontolerance{0.1pt}
\def\pgfintersectiontolerancefactor{0.1}



% Find the intersections of two bezier curves.
% 
% #1 - #4 = curve 1.
% #5 - #8 = curve 2.
% #9      = the solution number.
%
% There is no guarantee of ordering of solutions. If there are 
% no solutions, the origin is returned.
%
\def\pgfpointintersectionofcurves#1#2#3#4#5#6#7#8#9{%
	\pgf@intersect@solutions=0\relax%
	\pgf@intersectionofcurves%
		{\pgf@process{#1}}{\pgf@process{#2}}{\pgf@process{#3}}{\pgf@process{#4}}%
		{\pgf@process{#5}}{\pgf@process{#6}}{\pgf@process{#7}}{\pgf@process{#8}}%
	\pgfpointintersectionsolution{#9}%
}

% Return any intersection points of two curves C1 and C2.
% No order can be guaranteed for the solutions.
%
% #1, #2, #3, #4 - the points on C1 
% #5, #6, #7, #8 - the points on C2
%
% Returns:
%
% \pgf@intersect@solutions          - the number of solutions.
%	\pgfpointintersectionsolution{<S>} - the point for soultion S.
%
% (Sort of) use:
%
%	intersection(C1,C2)
%		S = {};
%	  intersection'(C1,C2);
%		return S;
%		
%	intersection'(C1,C2)
%		B1 = boundingbox(C1);
%		B2 = boundingbox(C2);
%		if intersect(B1,B2)
%			if (B1.width < q) and (B1.height < q) and
%        (B2.width < q) and (B2.height < q)
%				S = S + {average_of_all_points(B1,B2)}; \\ is there a better choice?
%			else
%				Q = subdivideLeft(C1);
%				R = subdivideRight(C1);
%				intersection'(C2,Q);
%				intersection'(C2,R);
%
% where q is a small value (tolerance).
%
\def\pgfintersectionofcurves#1#2#3#4#5#6#7#8{%
	\pgf@intersect@solutions=0\relax%
	\pgf@intersectionofcurves%
		{\pgf@process{#1}}{\pgf@process{#2}}{\pgf@process{#3}}{\pgf@process{#4}}%
		{\pgf@process{#5}}{\pgf@process{#6}}{\pgf@process{#7}}{\pgf@process{#8}}%
}%
\def\pgf@intersectionofcurves#1#2#3#4#5#6#7#8{%
	\begingroup%
		\dimendef\pgf@time@a=2\relax%
		\dimendef\pgf@time@aa=4\relax%
		\dimendef\pgf@time@b=6\relax%
		\dimendef\pgf@time@bb=8\relax%
		\pgf@time@a=0pt\relax%
		\pgf@time@aa=1pt\relax%
		\pgf@time@b=0pt\relax%
		\pgf@time@bb=1pt\relax%
		\let\pgf@intersect@subdivide@curve=\pgf@intersect@subdivide@curve@b%
		\let\pgf@curve@subdivde@after=\pgf@@intersectionofcurves%
		\pgf@@intersectionofcurves{#1}{#2}{#3}{#4}{#5}{#6}{#7}{#8}%
	\endgroup%
}

\def\pgf@@intersectionofcurves#1#2#3#4#5#6#7#8{%
	\pgf@intersect@boundingbox@reset%
	\pgf@intersect@boundingbox@update{#1}%
	\pgf@intersect@boundingbox@update{#2}%
	\pgf@intersect@boundingbox@update{#3}%
	\pgf@intersect@boundingbox@update{#4}%
	\edef\pgf@intersect@boundingbox@b{%
		\noexpand\pgf@x=\the\pgf@xa% 
		\noexpand\pgf@y=\the\pgf@ya%
		\noexpand\pgf@xa=\the\pgf@xb%
		\noexpand\pgf@ya=\the\pgf@yb%
	}%
	\pgf@intersect@boundingbox@reset%
	\pgf@intersect@boundingbox@update{#5}%
	\pgf@intersect@boundingbox@update{#6}%
	\pgf@intersect@boundingbox@update{#7}%
	\pgf@intersect@boundingbox@update{#8}%
	\edef\pgf@intersect@boundingbox@a{%
		\noexpand\pgf@xb=\the\pgf@xa%
		\noexpand\pgf@yb=\the\pgf@ya%
		\noexpand\pgf@xc=\the\pgf@xb%
		\noexpand\pgf@yc=\the\pgf@yb%
	}%	
	\pgf@intersect@boundingbox@a%
	\pgf@intersect@boundingbox@b%
	\ifdim\pgf@xa<\pgf@xb%
	\else%
		\ifdim\pgf@x>\pgf@xc%
		\else%
			\ifdim\pgf@ya<\pgf@yb%
			\else%
				\ifdim\pgf@y>\pgf@yc%
				\else%
					\advance\pgf@xc by-\pgf@xb%
					\advance\pgf@yc by-\pgf@yb%
					\advance\pgf@xa by-\pgf@x%
					\advance\pgf@ya by-\pgf@y%
					\let\pgf@intersect@subdivde=\relax%
					\ifdim\pgf@xc<\pgfintersectiontolerance\relax%
						\ifdim\pgf@xa<\pgfintersectiontolerance\relax%
							\ifdim\pgf@yc<\pgfintersectiontolerance\relax%
								\ifdim\pgf@ya<\pgfintersectiontolerance\relax%
									\pgfextract@process\pgf@intersect@solution@candidate{%
										\pgf@intersect@boundingbox@a%
										\pgf@intersect@boundingbox@b%
										\pgf@x=0.25\pgf@x%
										\advance\pgf@x by0.25\pgf@xa%
										\advance\pgf@x by0.25\pgf@xb%
										\advance\pgf@x by0.25\pgf@xc%
										\pgf@y=0.25\pgf@y%
										\advance\pgf@y by0.25\pgf@ya%
										\advance\pgf@y by0.25\pgf@yb%
										\advance\pgf@y by0.25\pgf@yc%
									}%
									% We must avoid duplicate solutions.
									\let\pgf@intersect@subdivde=\pgf@stop%
									\pgf@ifsolution@duplicate\pgf@intersect@solution@candidate{}%
									{%
										\global\advance\pgf@intersect@solutions by1\relax%
										\pgf@intersection@store@properties{pgfpoint@g@intersect@solution@\the\pgf@intersect@solutions}%
										\expandafter\global\expandafter\let%
											\csname pgfpoint@g@intersect@solution@\the\pgf@intersect@solutions\endcsname=%
												\pgf@intersect@solution@candidate%
										{%
											\ifpgf@intersect@sort%
												\advance\pgf@time@a by\pgf@time@aa%
												\divide\pgf@time@a by2\relax%
												\advance\pgf@time@a by\pgf@intersect@time@offset pt\relax%
												\expandafter\xdef%
												\csname pgf@g@intersect@solution@\the\pgf@intersect@solutions @time@a\endcsname%	
													{\pgfmath@tonumber{\pgf@time@a}}%						
											\fi%
										}%		
									}%
								\fi%
							\fi%
						\fi%
					\fi%
					\ifx\pgf@intersect@subdivde\pgf@stop%
					\else%
						\pgf@intersect@subdivide@curve{#1}{#2}{#3}{#4}{#5}{#6}{#7}{#8}%
					\fi%
				\fi%
			\fi%
		\fi%
	\fi%
}

\def\pgf@intersect@subdivide@curve@b#1#2#3#4#5#6#7#8{%
	\begingroup%
		\advance\pgf@time@bb by\pgf@time@b\relax%
		\divide\pgf@time@bb by2\relax%
		\let\pgf@intersect@subdivide@curve=\pgf@intersect@subdivide@curve@a%
		\pgf@curve@subdivide@left{#5}{#6}{#7}{#8}{#1}{#2}{#3}{#4}%
	\endgroup%
	\begingroup%
		\advance\pgf@time@b by\pgf@time@bb\relax%
		\divide\pgf@time@b by2\relax%
		\let\pgf@intersect@subdivide@curve=\pgf@intersect@subdivide@curve@a%
		\pgf@curve@subdivide@right{#5}{#6}{#7}{#8}{#1}{#2}{#3}{#4}%
	\endgroup%
}

\def\pgf@intersect@subdivide@curve@a#1#2#3#4#5#6#7#8{%
	\begingroup%
		\advance\pgf@time@aa by\pgf@time@a\relax%
		\divide\pgf@time@aa by2\relax%
		\let\pgf@intersect@subdivide@curve=\pgf@intersect@subdivide@curve@b%
		\pgf@curve@subdivide@left{#5}{#6}{#7}{#8}{#1}{#2}{#3}{#4}%
	\endgroup%
	\begingroup%
		\advance\pgf@time@a by\pgf@time@aa\relax%
		\divide\pgf@time@a by2\relax%
		\let\pgf@intersect@subdivide@curve=\pgf@intersect@subdivide@curve@b%
		\pgf@curve@subdivide@right{#5}{#6}{#7}{#8}{#1}{#2}{#3}{#4}%
	\endgroup%
}

\def\pgf@intersect@boundingbox@reset{%
	\pgf@xa=16000pt\relax%
	\pgf@ya=16000pt\relax%
	\pgf@xb=-16000pt\relax%
	\pgf@yb=-16000pt\relax%
}

\def\pgf@intersect@boundingbox@update#1{%
	#1\relax%
	\ifdim\pgf@x<\pgf@xa\pgf@xa=\pgf@x\fi%
	\ifdim\pgf@y<\pgf@ya\pgf@ya=\pgf@y\fi%
	\ifdim\pgf@x>\pgf@xb\pgf@xb=\pgf@x\fi%
	\ifdim\pgf@y>\pgf@yb\pgf@yb=\pgf@y\fi%
}


\def\pgf@curve@subdivide@left#1#2#3#4{%
	%
	% The left curve (from t=0 to t=.5) 
	%
	#1\relax%
	\pgfutil@tempdima=\pgf@x%
	\pgfutil@tempdimb=\pgf@y%
	\pgf@xa=.5\pgf@x\pgf@ya=.5\pgf@y%
	\pgf@xb=.25\pgf@x\pgf@yb=.25\pgf@y%
	\pgf@xc=.125\pgf@x\pgf@yc=.125\pgf@y%
	#2\relax%
	\advance\pgf@xa by.5\pgf@x\advance\pgf@ya by.5\pgf@y%
	\advance\pgf@xb by.5\pgf@x\advance\pgf@yb by.5\pgf@y%
	\advance\pgf@xc by.375\pgf@x\advance\pgf@yc by.375\pgf@y%
	#3\relax%
	\advance\pgf@xb by.25\pgf@x\advance\pgf@yb by.25\pgf@y%
	\advance\pgf@xc by.375\pgf@x\advance\pgf@yc by.375\pgf@y%
	#4\relax%
	\advance\pgf@xc by.125\pgf@x\advance\pgf@yc by.125\pgf@y%
	\edef\pgf@marshal{%
		\noexpand\pgf@curve@subdivde@after%
			{\noexpand\pgf@x=\the\pgfutil@tempdima\noexpand\pgf@y=\the\pgfutil@tempdimb}%
			{\noexpand\pgf@x=\the\pgf@xa\noexpand\pgf@y\the\pgf@ya}%
			{\noexpand\pgf@x=\the\pgf@xb\noexpand\pgf@y=\the\pgf@yb}
			{\noexpand\pgf@x=\the\pgf@xc\noexpand\pgf@y=\the\pgf@yc}%
	}%
	\pgf@marshal%
}

\def\pgf@curve@subdivide@right#1#2#3#4{%
	%
	% The right curve (from t=0.5 to t=1) 
	%
	#1\relax%
	\pgfutil@tempdima=.125\pgf@x\pgfutil@tempdimb=.125\pgf@y%
	#2\relax%
	\advance\pgfutil@tempdima by.375\pgf@x\advance\pgfutil@tempdimb by.375\pgf@y%
	\pgf@xa=.25\pgf@x\pgf@ya=.25\pgf@y%
	#3\relax%
	\advance\pgfutil@tempdima by.375\pgf@x\advance\pgfutil@tempdimb by.375\pgf@y%
	\advance\pgf@xa by.5\pgf@x\advance\pgf@ya by.5\pgf@y%
	\pgf@xb=.5\pgf@x\pgf@yb=.5\pgf@y%
	#4\relax%
	\advance\pgfutil@tempdima by.125\pgf@x\advance\pgfutil@tempdimb by.125\pgf@y%
	\advance\pgf@xa by.25\pgf@x\advance\pgf@ya by.25\pgf@y%
	\advance\pgf@xb by.5\pgf@x\advance\pgf@yb by.5\pgf@y%
	\pgf@xc=\pgf@x\pgf@yc=\pgf@y%
	\edef\pgf@marshal{%
		\noexpand\pgf@curve@subdivde@after%
			{\pgf@x\the\pgfutil@tempdima\pgf@y\the\pgfutil@tempdimb}%
			{\pgf@x\the\pgf@xa\pgf@y\the\pgf@ya}{\pgf@x\the\pgf@xb\pgf@y\the\pgf@yb}
				{\pgf@x\the\pgf@xc\pgf@y\the\pgf@yc}%
	}%
	\pgf@marshal%
}


% A solution S1 is considered a duplicate of S2, if
% 
% |x1 - x2|f < q and |y1 - y2|f < q
%
% where q is a small value (tolerance).
%
% #1 - the solution.
%
\def\pgf@ifsolution@duplicate#1{%
	#1%
	\pgf@xa=\pgf@x%
	\pgf@ya=\pgf@y%
	\let\pgf@intersect@next=\pgfutil@secondoftwo%
	\pgfmathloop%
		\ifnum\pgfmathcounter>\pgf@intersect@solutions\relax%
		\else%			
			\pgf@process{\csname pgfpoint@g@intersect@solution@\pgfmathcounter\endcsname}%
			\advance\pgf@x by-\pgf@xa%
			\advance\pgf@y by-\pgf@ya%
			\ifdim\pgf@x<0pt\relax\pgf@x=-\pgf@x\fi%
			\ifdim\pgf@y<0pt\relax\pgf@y=-\pgf@y\fi%
			%
			\pgf@x=\pgfintersectiontolerancefactor\pgf@x%
			\pgf@y=\pgfintersectiontolerancefactor\pgf@y%
			\ifdim\pgf@x<\pgfintersectiontolerance\relax%
				\ifdim\pgf@y<\pgfintersectiontolerance\relax%
					\let\pgf@intersect@next=\pgfutil@firstoftwo%
				\fi%
			\fi%
	\repeatpgfmathloop%
	\pgf@intersect@next%
}


\newif\ifpgf@intersect@solutions@sortfinish

% Sort solutions according to their time index.
%
\def\pgfintersectionsolutionsortbytime{%
	\pgf@intersect@solutions@sortfinishtrue%
	\pgfmathloop%
		\ifnum\pgfmathcounter=\pgfintersectionsolutions\relax%
		\else%
			\pgfutil@tempcnta=\pgfmathcounter%
			\advance\pgfutil@tempcnta by1\relax%
			\ifdim\csname pgf@intersect@solution@\pgfmathcounter @time@a\endcsname pt>%
				\csname pgf@intersect@solution@\the\pgfutil@tempcnta @time@a\endcsname pt\relax%
				\pgf@intersect@solutions@sortfinishfalse%
				%
				\pgfintersectionsolutionsortbytime@swap{pgfpoint@intersect@solution@\pgfmathcounter}%
					{pgfpoint@intersect@solution@\the\pgfutil@tempcnta}%
				%
				\pgfintersectionsolutionsortbytime@swap{pgf@intersect@solution@\pgfmathcounter @time@a}%
					{pgf@intersect@solution@\the\pgfutil@tempcnta @time@a}%
				%
				\pgfintersectionsolutionsortbytime@swap{pgf@intersect@solution@segment@a@\pgfmathcounter}%
					{pgf@intersect@solution@segment@a@\the\pgfutil@tempcnta}%
				\pgfintersectionsolutionsortbytime@swap{pgf@intersect@solution@segment@b@\pgfmathcounter}%
					{pgf@intersect@solution@segment@b@\the\pgfutil@tempcnta}%
			\fi%
	\repeatpgfmathloop%
	\ifpgf@intersect@solutions@sortfinish%
	\else%
		\expandafter\pgfintersectionsolutionsortbytime%
	\fi%
}

\def\pgfintersectionsolutionsortbytime@swap#1#2{%
	\pgfutil@namelet{pgf@intersect@temp}{#1}%
	\pgfutil@namelet{#1}{#2}%
	\pgfutil@namelet{#2}{pgf@intersect@temp}%
}%

\endinput

pgflibrarypgfplots.surfshading.code.tex
%--------------------------------------------
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2007-2012 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------

%--------------------------------------------------
% \pgfqkeys{/pgfplots/surf shading}{
% 	cols=3,
% %	test colormap 1,
% }
% \pgfplotslibrarysurfstreamstart
% \pgfplotslibrarysurfstreamcoord{\pgfqpoint{0pt}{10pt}}{0}
% \pgfplotslibrarysurfstreamcoord{\pgfqpoint{100pt}{10pt}}{100}
% \pgfplotslibrarysurfstreamcoord{\pgfqpoint{180pt}{10pt}}{30}
% %
% \pgfplotslibrarysurfstreamcoord{\pgfqpoint{0pt}{100pt}}{300}
% \pgfplotslibrarysurfstreamcoord{\pgfqpoint{110pt}{90pt}}{1000}
% \pgfplotslibrarysurfstreamcoord{\pgfqpoint{190pt}{110pt}}{600}
% %
% \pgfplotslibrarysurfstreamcoord{\pgfqpoint{0pt}{200pt}}{0}
% \pgfplotslibrarysurfstreamcoord{\pgfqpoint{110pt}{200pt}}{100}
% \pgfplotslibrarysurfstreamcoord{\pgfqpoint{190pt}{200pt}}{60}
% \pgfplotslibrarysurfstreamend
% \fbox{%
% 	\pgfplotslibrarysurfdraw
% }%
%-------------------------------------------------- 


\newif\ifpgfplotslibrarysurf@updatebb
\newif\ifpgfplotslibrarysurf@usecolormap
\pgfplotslibrarysurf@updatebbtrue

\pgfkeys{%
	/pgfplots/surf shading/anchor/.initial=\pgfpointorigin,%
	/pgfplots/surf shading/shading type/.initial=5,% triangles in form of lattice
	%
	% If this is true, the embedding picture's bounding box will be updated using
	% the shading's bounding box.
	% This bounding box may be (highly!) inaccurate for coons shadings and tensor product shadings.
	% The 'patch' plot handler disables it and takes control over it explicitly (using interpolation
	% points rather than bezier control points).
	/pgfplots/surf shading/update BB/.is if=pgfplotslibrarysurf@updatebb,
	% 
	% can only have values '' (empty) for binary encoding or
	% ASCIIHexEncode for base 16 encoding. Use this if some driver
	% cannot produce binary encoding. This is undocumented; for use in
	% emergency only.
	/pgfplots/surf shading/pdf stream filter/.initial=,%
	%
	/pgfplots/surf shading/precision/.is choice,
	/pgfplots/surf shading/precision/pdf/.code={%
		% Lossless coordinate output.
		\def\pgfplotslibrarysurf@bitspercoordinate{32}%
		\def\pgfplotslibrarysurf@bytespercoordinate{4}%
		\def\pgfplotslibrarysurf@filter@encode{}% raw binary.
		\def\pgfplotslibrarysurf@filter@decode{}%
	},%
	/pgfplots/surf shading/precision/ps/.code={%
		% quantized coordinate output (introduces quantization error).
		\def\pgfplotslibrarysurf@bitspercoordinate{24}%
		\def\pgfplotslibrarysurf@bytespercoordinate{3}%
		% doesn't improve behavior of pdf2ps:
		%\def\pgfplotslibrarysurf@filter@encode{ASCIIHexEncode}%
		%\def\pgfplotslibrarysurf@filter@decode{ASCIIHexDecode}%
		\def\pgfplotslibrarysurf@filter@encode{}% raw binary.
		\def\pgfplotslibrarysurf@filter@decode{}%
	},%
	/pgfplots/surf shading/precision/postscript/.style={%
		/pgfplots/surf shading/precision/ps},%
	/pgfplots/surf shading/precision/ps,% 
	% columns:
	/pgfplots/surf shading/cols/.initial=,%
	/pgfplots/surf shading/colorspace/.initial=rgb,% rgb or cmyk or gray
	%
	% the colormap. If this key is empty, we assume that individual
	% color components are provided for EVERY vertex for which cdata
	% is expected.
	/pgfplots/surf shading/colormap/.initial={%
		<<
			/FunctionType 2 
			/Domain [0 1] 
			/C0 [0 0 1] /C1 [1 0 0] /N 1 
		>>
	},%
	/pgfplots/surf shading/test colormap 1/.style={%
		/pgfplots/surf shading/colormap={
			<< 
				/FunctionType 3 
				/Domain [0 1] 
				/Functions [ 
					<< 
						/FunctionType 2 
						/Domain [0 1] 
						/C0 [0 0 1] /C1 [1 1 0] /N 1 
					>>  
					<< 
						/FunctionType 2 
						/Domain [0 1] 
						/C0 [1 1 0] /C1 [1 0.5 0] /N 1 
					>>  
					<< 
						/FunctionType 2 
						/Domain [0 1] 
						/C0 [1 0.5 0] /C1 [1 0 0] /N 1 
					>>
				]
				/Bounds [ 0.3 0.6 ] 
				/Encode [0 1  0 1 0 1] 
				%/Range [0 1 0 1 0 1] INCOMPATIBLE WITH ACROBAT 6.0
			>> 
		}%
	},%
	/pgfplots/surf shading/debug text/.initial=\the\c@pgfplotslibrarysurf@no,
	/pgfplots/surf shading/every debug coord/.style={
		circle,
		draw,
		fill=yellow,
	},
	/pgfplots/surf shading/debug/.is choice,
	/pgfplots/surf shading/debug/false/.code={%
		\let\pgfplotslibrarysurfprocesscoordinate=\pgfplotslibrarysurfprocesscoordinate@orig
		\let\pgfplotslibrarysurfusepath=\pgfplotslibrarysurfusepath@orig
	},
	/pgfplots/surf shading/debug/true/.code={%
		\let\pgfplotslibrarysurfprocesscoordinate=\pgfplotslibrarysurfprocesscoordinate@debug
		\def\pgfplotslibrarysurfusepath{\pgfusepath{stroke,fill}}
	},
	/pgfplots/surf shading/debug/.default=true,
}%

\def\pgfplotslibrarysurf@corner@sw{\pgfplots@error{This is unavailable until \string\pgfplotslibrarysurfstreamend}}
\let\pgfplotslibrarysurf@corner@ne\pgfplotslibrarysurf@corner@sw

% parametric colors (colormap) are always in [0,1000]. I
% 2 bytes suffice for that range.
\def\pgfplotslibrarysurf@bytespercomponent{2}%
\def\pgfplotslibrarysurf@bitspercomponent{16}%

\def\pgfplotslibrarysurf@decode{%
	-16383.999992 16384 % see the docs of \pgfplotsbinaryencodedimenmaplinearly
	-16383.999992 16384 %
	\pgfplotslibrarysurf@decode@colors
}%
\def\pgfplotslibrarysurf@decode@colors@colormap{%
	0 \pgfplotscolormappdfmax % map [0,2^BitsPerComponent-1] linearly to [0 1] for parametric color data
}%
\def\pgfplotslibrarysurf@decode@colors@explicit@one@component{%
	% this is just one component for explicit color data.
	% it will be replicated for every color component.
	0 1 % the target value for color component values.
}%

\def\pgfplotslibrarysurf@count{0}%
\newcount\c@pgfplotslibrarysurf@no

% driver specific:
\def\pgfplotslibrarysurf@initstream{%
	\edef\pgfplots@loc@TMPa{\pgfkeysvalueof{/pgfplots/surf shading/pdf stream filter}}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
	\else
		\let\pgfplotslibrarysurf@filter@encode=\pgfplots@loc@TMPa
		\let\pgfplotslibrarysurf@filter@decode=\pgfplotslibrarysurf@filter@encode
	\fi
}

\def\pgfplotslibrarysurf@advancestreamlen#1{}%

\def\pgfplotslibrarysurfstreamstart{%
	\pgfplotslibrarysurfstreamstart@init@colors
	\pgfkeysgetvalue{/pgfplots/surf shading/shading type}\pgfplotslibrarysurf@type
	\pgfplotsapplistXglobalnewempty\pgfplotslibrarysurf@binarystream@accum
	\pgfplotslibrarysurf@initstream
	\ifx\pgfplotslibrarysurf@filter@encode\pgfutil@empty
		\def\pgfplotslibrarysurf@filter@encode{binary encoding}%
	\fi
	\pgfkeysalso{/pgfplots/bin/\pgfplotslibrarysurf@filter@encode}%
	%
	\pgfplotsbinarysetbytes1%
	\pgfplotsbinaryencodeunsigned{0}% use this method - it respects any special encodings.
	\let\pgfplots@loc@TMPa=\pgfplotsbinaryresult
	\ifcase\pgfplotslibrarysurf@type\relax
		% 0
		\pgfplotslibrarysurf@initstream@wrongtype
	\or% 1
		\pgfplotslibrarysurf@initstream@wrongtype
	\or% 2
		\pgfplotslibrarysurf@initstream@wrongtype
	\or% 3
	\or% 4
		% ok, triangle meshes.
		\let\pgfplotslibrarysurf@edgeflag=\pgfplots@loc@TMPa
	\or% 5 triangles in lattice form. disable edge flag:
		\let\pgfplotslibrarysurf@edgeflag=\pgfutil@empty
	\or% 6 coons patches:
		\global\let\pgfplotslibrarysurf@cubicpatch@cdata=\pgfutil@empty
		\global\c@pgfplotslibrarysurf@no=0
		\def\pgfplotslibrarysurf@cubicpatch@numverts{12}%
		\let\pgfplotslibrarysurfstreamcoord=\pgfplotslibrarysurfstreamcoord@cubicpatch
		\let\pgfplotslibrarysurf@edgeflag=\pgfplots@loc@TMPa
	\or% 7 full tensor product cubic bezier patches:
		\global\let\pgfplotslibrarysurf@cubicpatch@cdata=\pgfutil@empty
		\global\c@pgfplotslibrarysurf@no=0
		\def\pgfplotslibrarysurf@cubicpatch@numverts{16}%
		\let\pgfplotslibrarysurfstreamcoord=\pgfplotslibrarysurfstreamcoord@cubicpatch
		\let\pgfplotslibrarysurf@edgeflag=\pgfplots@loc@TMPa
	\else
		\pgfplotslibrarysurf@initstream@wrongtype
	\fi
	%
	%
	% we want to establish a bounding box for THIS shading only! Otherwise the pdf XFORM might have a larger bounding box than we want. Is that ok here? Or does it hurt somewhere? 
	\pgf@getpathsizes{\pgfplots@loc@TMPa}%
	\global\let\pgfplotslibrarysurf@pathsizes@before=\pgfplots@loc@TMPa
}%


\def\pgfplotslibrarysurfstreamstart@init@colors{%
	%
	\pgfkeysgetvalue{/pgfplots/surf shading/colormap}\pgfplots@loc@TMPa
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\pgfplotslibrarysurf@usecolormapfalse
	\else
		\pgfplotslibrarysurf@usecolormaptrue
	\fi
	%
	\ifpgfplotslibrarysurf@usecolormap
		\let\pgfplotslibrarysurf@decode@colors=\pgfplotslibrarysurf@decode@colors@colormap
	\else
		\pgfplotscolorspacegetcomponents{\pgfkeysvalueof{/pgfplots/surf shading/colorspace}}%
		\c@pgf@counta=0 %
		\c@pgf@countb=\pgfplotsretval\relax
		%
		\def\pgfplotslibrarysurf@decode@colors{}%
		\pgfplotslibrarysurf@decode@colors@loop
	\fi
	%
	\pgfplotslibrarysurf@translate@colorspace
	\let\pgfplotslibrarysurf@colorspace=\pgfplotsretval
}%

\def\pgfplotslibrarysurf@decode@colors@loop{%
	\ifnum\c@pgf@counta<\c@pgf@countb
		%
		\edef\pgfplotslibrarysurf@decode@colors{%
			\pgfplotslibrarysurf@decode@colors
			\pgfplotslibrarysurf@decode@colors@explicit@one@component
		}%
		\advance\c@pgf@counta by1 %
		%
		\expandafter\pgfplotslibrarysurf@decode@colors@loop
	\fi
}%

\def\pgfplotslibrarysurf@initstream@wrongtype{%
	\pgfplots@error{CRITICAL: shader=interp: got unsupported pdf shading type '\pgfplotslibrarysurf@type'. This may corrupt your pdf!}%
}%
\def\pgfplotslibrarysurfstreamend{%
	\pgfplotsapplistXgloballet\pgfplotslibrarysurf@binarystream=\pgfplotslibrarysurf@binarystream@accum
	\pgfplotsapplistXglobalnewempty\pgfplotslibrarysurf@binarystream@accum
	%
	\pgfplotslibrarysurfstreamend@set@BB
}

\def\pgfplotslibrarysurfstreamend@set@BB{%
	\xdef\pgfplotslibrarysurf@corner@sw{%
		\global\pgf@x=\the\pgf@pathminx\space
		\global\pgf@y=\the\pgf@pathminy\space
	}%
	\xdef\pgfplotslibrarysurf@corner@ne{%
		\global\pgf@x=\the\pgf@pathmaxx\space
		\global\pgf@y=\the\pgf@pathmaxy\space
	}%
	\pgf@setpathsizes\pgfplotslibrarysurf@pathsizes@before
}%

% ATTENTION: see also \pgfplotslibrarysurfstreamcoord@cubicpatch
% #1: a pgf point.
% #2: a color coordinate in the range [0,1000]
\def\pgfplotslibrarysurfstreamcoord#1#2{%
	\pgfplotsbinarysetbytes\pgfplotslibrarysurf@bytespercoordinate%
	\pgfplotslibrarysurf@advancestreamlen{\pgfplotslibrarysurf@bytespercoordinate}%
	\pgfplotslibrarysurf@advancestreamlen{\pgfplotslibrarysurf@bytespercoordinate}%
	%\pgf@process{#1}% this here causes `{retaining \pgf@x}' messages and pollutes the save stack! Avoid it. See \tracingrestores=2
	\pgfplotslibrarysurfprocesscoordinate{#1}%
	% The idea is to map 
	% the low-level point coordinates LINEARLY into [0,2^{8*<bytes>}].
	%
	% This is what the pdf standard expects for surface shadings.
	%
	% To do that, we simply map
	% [-16384,16384] linearly into [0,2^{32}]
	% and write the resulting integer in big endian binary format to
	% the pdf low level stream.
	%
	% The decode procedure tells the pdf viewer how to invert that
	% stuff.
	%
	\pgf@xa=\pgf@x
	\pgf@sys@bp@correct\pgf@xa%
	\pgfplotsbinaryencodedimenmaplinearly\pgf@xa
%\message{POINT \the\c@pgfplots@scanlineindex: ENCODING(x=\the\pgf@x)=\pgfplotsbinaryresult.}\advance\c@pgfplots@scanlineindex by1
	\t@pgfplots@toka=\expandafter{\pgfplotsbinaryresult}%
	\pgf@ya=\pgf@y
	\pgf@sys@bp@correct\pgf@ya%
	\pgfplotsbinaryencodedimenmaplinearly\pgf@ya
%\message{ENCODING(y=\the\pgf@y)=\pgfplotsbinaryresult.}%
	\t@pgfplots@tokb=\expandafter{\pgfplotsbinaryresult}%
	%
	\pgfplotslibrarysurf@encode@cdata{#2}%
%\message{\pgfplotsbinaryresult.}%
	\t@pgfplots@tokc=\expandafter{\pgfplotsbinaryresult}%
	\ifx\pgfplotslibrarysurf@edgeflag\pgfutil@empty
	\else
		% for shading type 4, the edge flag is given for EVERY
		% coordinate (unlike all other shading types).
		\pgfplotslibrarysurf@advancestreamlen{1}%
	\fi
	\edef\pgfplots@loc@TMPa{\pgfplotslibrarysurf@edgeflag\the\t@pgfplots@toka\the\t@pgfplots@tokb\the\t@pgfplots@tokc}%
	\expandafter\pgfplotsapplistXglobalpushback\pgfplots@loc@TMPa\to\pgfplotslibrarysurf@binarystream@accum
}

% defines \pgfplotsbinaryresult to contain the result of a CDATA
% entry and advances the stream counters.
\def\pgfplotslibrarysurf@encode@cdata#1{%
	\ifpgfplotslibrarysurf@usecolormap
		\pgfplotslibrarysurf@map@to@FFF@colormap{#1}%
	\else
		% oh. No cdata. Ok, then encode stuff individually!
		% We expect data of the form
		% {<comma-separated-components>}
		\edef\pgfplots@loc@TMPa{#1}%
		\def\pgfplotsretval{}%
		\expandafter\pgfplotslibrarysurf@encode@cdata@loop\pgfplots@loc@TMPa,,%
		\let\pgfplotsbinaryresult=\pgfplotsretval
	\fi
}

\def\pgfplotslibrarysurf@encode@cdata@loop#1,{%
	\def\pgfplots@loc@TMPa{#1}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
	\else
		%
		%
		\pgfplotslibrarysurf@map@to@FFF@component{#1}%
		\edef\pgfplotsretval{\pgfplotsretval\pgfplotsbinaryresult}%
		%
		%
		% continue loop:
		\expandafter\pgfplotslibrarysurf@encode@cdata@loop
	\fi
}%

% Defines \pgfplotsbinaryresult
\def\pgfplotslibrarysurf@map@to@FFF@colormap#1{%
	\begingroup
		% read fixed point input (in the range [0,1000]).
		\pgf@xa=#1pt %
		% convert to integer (= *65536):
		\c@pgf@counta=\pgf@xa
		% provide map [0,1000] -> [0,2^16-1]
		\divide\c@pgf@counta by1000
		% now, we have \c@pgf@counta in [0,2^16]. Simply strip it into
		% the required range, that's ok.
		\ifnum\c@pgf@counta<0
			\c@pgf@counta=0
		\else
			\ifnum\c@pgf@counta>65535
				\c@pgf@counta=65535
			\fi
		\fi
		% Now, we have CDATA in the range [0,65535] 
		\xdef\pgfplots@glob@TMPa{\the\c@pgf@counta}%
%\message{ENCODING(C=\pgfplots@glob@TMPa\space for \the\pgf@xa)=}%
	\endgroup
	\pgfplotsbinarysetbytes\pgfplotslibrarysurf@bytespercomponent%
	\pgfplotsbinaryencodeunsigned\pgfplots@glob@TMPa
	\pgfplotslibrarysurf@advancestreamlen{\pgfplotslibrarysurf@bytespercomponent}%
}

% Defines \pgfplotsbinaryresult
\def\pgfplotslibrarysurf@map@to@FFF@component#1{%
	\begingroup
		% read fixed point input (in the range [0,1]).
		\pgf@xa=#1pt %
		% convert to integer (= *65536):
		\c@pgf@counta=\pgf@xa
		% provide map [0,1] -> [0,2^16-1]
		% well, there is nothing to do! it was in [0,1], we multiplied by 65536 implicitly... that's it.
		%
		% now, we have \c@pgf@counta in [0,2^16]. Simply strip it into
		% the required range, that's ok.
		\ifnum\c@pgf@counta<0
			\c@pgf@counta=0
		\else
			\ifnum\c@pgf@counta>65535
				\c@pgf@counta=65535
			\fi
		\fi
		% Now, we have CDATA in the range [0,65535] 
		\xdef\pgfplots@glob@TMPa{\the\c@pgf@counta}%
%\message{ENCODING(C=\pgfplots@glob@TMPa\space for \the\pgf@xa)=}%
	\endgroup
	\pgfplotsbinarysetbytes\pgfplotslibrarysurf@bytespercomponent%
	\pgfplotsbinaryencodeunsigned\pgfplots@glob@TMPa
	\pgfplotslibrarysurf@advancestreamlen{\pgfplotslibrarysurf@bytespercomponent}%
}

\def\pgfplotslibrarysurf@translate@colorspace{%
	\pgfkeysgetvalue{/pgfplots/surf shading/colorspace}\pgfplots@loc@TMPd
	\edef\pgfplots@loc@TMPd{\pgfplots@loc@TMPd}%
	\def\pgfplots@loc@TMPa{rgb}%
	\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPd
		\def\pgfplotsretval{RGB}%
	\else
		\def\pgfplots@loc@TMPa{cmyk}%
		\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPd
			\def\pgfplotsretval{CMYK}%
		\else
			\def\pgfplots@loc@TMPa{cmy}%
			\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPd
				\def\pgfplotsretval{CMY}%
			\else
				\def\pgfplots@loc@TMPa{gray}%
				\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPd
					\def\pgfplotsretval{Gray}%
				\else
					\pgfplots@error{Sorry, the 'surfshading' lib failed to recognise the choice '/pgfplots/surf shading/colorspace=\pgfplots@loc@TMPd'... maybe you misspelled it?}%
					\def\pgfplotsretval{RGB}%
				\fi
			\fi
		\fi
	\fi
}%

\def\pgfplotslibrarysurfusepath{\pgfusepath{fill}}
\let\pgfplotslibrarysurfusepath@orig=\pgfplotslibrarysurfusepath

% We DO want to protocol the size of the shading. In fact, we NEED a
% bounding box which contains the whole shading, otherwise it will be
% clipped. More precisely, it will be packed into a pdf XForm object
% and that appears to need a correct bounding box.
%
% But we do NOT want to update the picture's bounding box, only that
% of the pdf XForm. The picture's bounding box will be updated as soon
% as we *use* the shading anyway (in
% \pgfplotslibrarysurfdrawinpicture). This here takes care of that detail:
\def\pgfplotslibrarysurf@protocolsizes@#1#2{%
	\ifpgf@relevantforpicturesize
		\pgfplots@loc@tmptrue
	\else
		\pgfplots@loc@tmpfalse
	\fi
	\pgf@relevantforpicturesizefalse
	\pgf@protocolsizes{#1}{#2}%
	\ifpgfplots@loc@tmp
		\pgf@relevantforpicturesizetrue
	\fi
}%

\def\pgfplotslibrarysurfprocesscoordinate#1{%
	#1\relax%
	\pgfplotslibrarysurf@protocolsizes@{\pgf@x}{\pgf@y}%
}%
\let\pgfplotslibrarysurfprocesscoordinate@orig=\pgfplotslibrarysurfprocesscoordinate%

\def\pgfplotslibrarysurfprocesscoordinate@debug#1{%
	\pgfinterruptpath
	\scope
	\pgftransformshift{#1}%
	\node[/pgfplots/surf shading/every debug coord] at (0pt,0pt) {\pgfkeysvalueof{/pgfplots/surf shading/debug text}};%
	\endscope
	\endpgfinterruptpath
	#1\relax%
	\pgfplotslibrarysurf@protocolsizes@{\pgf@x}{\pgf@y}%
}%

% ATTENTION: see also \pgfplotslibrarysurfstreamcoord
% special routine for coons type patches and cubic tensor product type
% patches. It has FIRST all vertices,
% THEN the cdata. Furthermore, it only has 4 CDATA points, but a total
% of 12 vertices.
%
% #1: a pgf point.
% #2: a color coordinate in the range [0,1000]
\def\pgfplotslibrarysurfstreamcoord@cubicpatch#1#2{%
	\pgfplotsbinarysetbytes\pgfplotslibrarysurf@bytespercoordinate%
	\pgfplotslibrarysurf@advancestreamlen{\pgfplotslibrarysurf@bytespercoordinate}%
	\pgfplotslibrarysurf@advancestreamlen{\pgfplotslibrarysurf@bytespercoordinate}%
	%\pgf@process{#1}% this here causes `{retaining \pgf@x}' messages and pollutes the save stack! Avoid it. See \tracingrestores=2
	\pgfplotslibrarysurfprocesscoordinate{#1}%
	% The idea is to map 
	% the low-level point coordinates LINEARLY into [0,2^{8*<bytes>}].
	%
	% This is what the pdf standard expects for surface shadings.
	%
	% To do that, we simply map
	% [-16384,16384] linearly into [0,2^{32}]
	% and write the resulting integer in big endian binary format to
	% the pdf low level stream.
	%
	% The decode procedure tells the pdf viewer how to invert that
	% stuff.
	%
	\pgf@xa=\pgf@x
	\pgf@sys@bp@correct\pgf@xa%
	\pgfplotsbinaryencodedimenmaplinearly\pgf@xa
%\message{POINT \the\c@pgfplots@scanlineindex: ENCODING(x=\the\pgf@x)=\pgfplotsbinaryresult.}\advance\c@pgfplots@scanlineindex by1
	\t@pgfplots@toka=\expandafter{\pgfplotsbinaryresult}%
	\pgf@ya=\pgf@y
	\pgf@sys@bp@correct\pgf@ya%
	\pgfplotsbinaryencodedimenmaplinearly\pgf@ya
%\message{ENCODING(y=\the\pgf@y)=\pgfplotsbinaryresult.}%
	\t@pgfplots@tokb=\expandafter{\pgfplotsbinaryresult}%
	\def\pgfplotslibrarysurf@cubicpatch@hascdata{0}%
	\ifnum\c@pgfplotslibrarysurf@no=0
		\def\pgfplotslibrarysurf@cubicpatch@hascdata{1}%
		% prepend edge flag. it is a new patch.
		\t@pgfplots@toka=\expandafter{\expandafter\pgfplotslibrarysurf@edgeflag\the\t@pgfplots@toka}%
		\pgfplotslibrarysurf@advancestreamlen{1}%
	\else
		\ifnum\c@pgfplotslibrarysurf@no=3
			\def\pgfplotslibrarysurf@cubicpatch@hascdata{1}%
		\else
			\ifnum\c@pgfplotslibrarysurf@no=6
				\def\pgfplotslibrarysurf@cubicpatch@hascdata{1}%
			\else
				\ifnum\c@pgfplotslibrarysurf@no=9
					\def\pgfplotslibrarysurf@cubicpatch@hascdata{1}%
				\fi
			\fi
		\fi
	\fi
	\if1\pgfplotslibrarysurf@cubicpatch@hascdata
		%
		\pgfplotslibrarysurf@encode@cdata{#2}%
	%\message{\pgfplotsbinaryresult.}%
		\t@pgfplots@tokc=\expandafter{\pgfplotslibrarysurf@cubicpatch@cdata}%
		\xdef\pgfplotslibrarysurf@cubicpatch@cdata{%
			\the\t@pgfplots@tokc
			\pgfplotsbinaryresult
		}%
	\fi
	\global\advance\c@pgfplotslibrarysurf@no by1
	%
	\ifnum\pgfplotslibrarysurf@cubicpatch@numverts=\c@pgfplotslibrarysurf@no %finalize patch.
		\t@pgfplots@tokc=\expandafter{\pgfplotslibrarysurf@cubicpatch@cdata}%
		\global\let\pgfplotslibrarysurf@cubicpatch@cdata=\pgfutil@empty
		\global\c@pgfplotslibrarysurf@no=0
	\else
		\t@pgfplots@tokc={}%
	\fi
	% edge flag is already in \t@pgfplots@toka (if this is the first
	% vertex)
	\edef\pgfplots@loc@TMPa{\the\t@pgfplots@toka\the\t@pgfplots@tokb\the\t@pgfplots@tokc}%
	\expandafter\pgfplotsapplistXglobalpushback\pgfplots@loc@TMPa\to\pgfplotslibrarysurf@binarystream@accum
}

\def\pgfplotslibrarysurfactivateshadefill{%
	\pgfplotssys@do@surfshading@fillpaths\pgfplots@loc@TMPa%
	\expandafter\pgfutil@addpdfresource@patterns\expandafter{\pgfplots@loc@TMPa}%%
}

%--------------------------------------------------
% \def\pgfplotslibrarysurfdraw{%
% %	\pgftext[at=\pgfqpoint{0pt}{0pt}]%
% 		{\pgfplotssys@do@surfshading}%
% }%
%-------------------------------------------------- 

\def\pgfplotslibrarysurfdrawinpicture{%
	\begingroup
	% this statement will modify both the picture's BB and the path's BB
	% unless we take control.
	%
	% Note that the path's BB will eventually be updated into the
	% picture's BB as well (meaning that 'overlay' is of no use inside
	% of this group).
	%
	% Implement the 'surf shading/update BB' functionality here:
	\let\pgfplots@@protocolsizes=\pgf@protocolsizes
	\ifpgfplotslibrarysurf@updatebb
	\else
		% NO update to any BB. this implies 'overlay' 
		% *and* disables updates to the path's BB.
		\def\pgf@protocolsizes##1##2{\relax}%
	\fi
	\pgftext[at=\pgfplotslibrarysurf@corner@sw,left,bottom] {%
		\begingroup
		% inside of this box, we *always* need bounding boxes.
		% restore functionality.
		\let\pgf@protocolsizes=\pgfplots@@protocolsizes
		\pgfplotslibrarysurfdraw
		\endgroup
% this does NOT work because I can't undo the box' shift:
%\pgfplotssys@do@surfshading
	}%
	\endgroup
}

\pgfplotsiffileexists{pgflibrarypgfplots.surfshading.\pgfsysdriver}{%
	\input pgflibrarypgfplots.surfshading.\pgfsysdriver\relax
	\def\pgflibrarysurfshadingifactive#1#2{#1}%
}{%
	\def\pgfplotslibrarysurfdraw{%
		\pgfplots@error{Sorry, surfshading (shader=interp) is NOT available for the selected driver `\pgfsysdriver'.}%
	}%
	\def\pgflibrarysurfshadingifactive#1#2{#2}%
}
\endinput

pgflibraryplothandlers.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/libraries/pgflibraryplothandlers.code.tex,v 1.20 2013/08/31 13:02:59 ludewich Exp $


% This handler converts each plot stream command into a curveto
% command, except for the first, which is converted to the previously
% specified action.
%
% Example:
%
% \pgfpathmoveto{\pgfpointorigin}
% \pgfsetlinetofirstplotpoint
% \pgfplothandlercurveto
% \pgfplotxyfile{mytable}

\pgfdeclareplothandler{\pgfplothandlercurveto}{}{%
  point macro=\pgf@plot@curveto@handler@initial,
  jump macro=\pgf@plot@smooth@next@moveto,
  end macro=\pgf@plot@curveto@handler@finish
}

\def\pgf@plot@smooth@next@moveto{%
  \pgf@plot@curveto@handler@finish%
  \global\pgf@plot@startedfalse%
  \global\let\pgf@plotstreampoint\pgf@plot@curveto@handler@initial%
}

\def\pgf@plot@curveto@handler@initial#1{%
  \pgf@process{#1}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \pgf@plot@first@action{\pgfqpoint{\pgf@xa}{\pgf@ya}}%
  \xdef\pgf@plot@curveto@first{\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}%
  \global\let\pgf@plot@curveto@first@support=\pgf@plot@curveto@first%
  \global\let\pgf@plotstreampoint=\pgf@plot@curveto@handler@second%
}

\def\pgf@plot@curveto@handler@second#1{%
  \pgf@process{#1}%
  \xdef\pgf@plot@curveto@second{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
  \global\let\pgf@plotstreampoint=\pgf@plot@curveto@handler@third%
  \global\pgf@plot@startedtrue%
}

\def\pgf@plot@curveto@handler@third#1{%
  \pgf@process{#1}%
  \xdef\pgf@plot@curveto@current{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
  % compute difference vector:
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \pgf@process{\pgf@plot@curveto@first}
  \advance\pgf@xa by-\pgf@x%
  \advance\pgf@ya by-\pgf@y%
  % compute support directions:
  \pgf@xa=\pgf@plottension\pgf@xa%
  \pgf@ya=\pgf@plottension\pgf@ya%
  % first marshal:
  \pgf@process{\pgf@plot@curveto@second}%
  \pgf@xb=\pgf@x%
  \pgf@yb=\pgf@y%
  \pgf@xc=\pgf@x%
  \pgf@yc=\pgf@y%
  \advance\pgf@xb by-\pgf@xa%
  \advance\pgf@yb by-\pgf@ya%
  \advance\pgf@xc by\pgf@xa%
  \advance\pgf@yc by\pgf@ya%
  \edef\pgf@marshal{\noexpand\pgfpathcurveto{\noexpand\pgf@plot@curveto@first@support}%
    {\noexpand\pgfqpoint{\the\pgf@xb}{\the\pgf@yb}}{\noexpand\pgf@plot@curveto@second}}%
  {\pgf@marshal}%
  % Prepare next:
  \global\let\pgf@plot@curveto@first=\pgf@plot@curveto@second%
  \global\let\pgf@plot@curveto@second=\pgf@plot@curveto@current%
  \xdef\pgf@plot@curveto@first@support{\noexpand\pgfqpoint{\the\pgf@xc}{\the\pgf@yc}}%
}

\def\pgf@plot@curveto@handler@finish{%
  \ifpgf@plot@started%
    \pgfpathcurveto{\pgf@plot@curveto@first@support}{\pgf@plot@curveto@second}{\pgf@plot@curveto@second}%
  \fi%
}


% This commands sets the tension for smoothing of plots.
%
% #1 = tension of curves. A value of 1 will yield a circle when the
%      control points are at quarters of a circle. A smaller value
%      will result in a tighter curve. Default is 0.5. 
%
% Example:
%
% \pgfsetplottension{0.2}

\def\pgfsetplottension#1{%
  \pgf@x=#1pt\relax%
  \pgf@x=0.2775\pgf@x\relax%
  \edef\pgf@plottension{\pgf@sys@tonumber\pgf@x}}
\pgfsetplottension{0.5}


% This handler converts the plot stream command into a curveto
% command that is closed using a closepath.
%
% Example:
%
% \pgfpathmoveto{\pgfpointorigin}
% \pgfplothandlerclosedcurve
% \pgfplotxyfile{mytable}

\pgfdeclareplothandler{\pgfplothandlerclosedcurve}{}{%
  point macro=\pgf@plot@closedcurve@handler@initial,
  end macro=\pgf@plot@closedcurve@handler@finish,
  jump macro=\pgf@plot@closedsmooth@next@moveto
}

\def\pgf@plot@closedsmooth@next@moveto{%
  \pgf@plot@closedcurve@handler@finish%
  \global\pgf@plot@startedfalse%
  \global\let\pgf@plotstreampoint\pgf@plot@closedcurve@handler@initial%
}

\def\pgf@plot@closedcurve@handler@initial#1{%
  \pgf@process{#1}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \xdef\pgf@plot@closedcurve@initial{\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}%
  \global\let\pgf@plotstreampoint=\pgf@plot@closedcurve@handler@second%
  \global\pgf@plot@startedfalse%
}

\def\pgf@plot@closedcurve@handler@second#1{%
  \pgf@process{#1}%
  \xdef\pgf@plot@closedcurve@after@initial{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
  {\pgfpathmoveto{}}%
  \global\let\pgf@plotstreampoint=\pgf@plot@closedcurve@handler@third%
}

\def\pgf@plot@closedcurve@handler@third#1{%
  \global\pgf@plot@startedtrue%
  \pgf@process{#1}%
  \xdef\pgf@plot@closedcurve@current{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
  % compute difference vector:
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \pgf@process{\pgf@plot@closedcurve@initial}
  \advance\pgf@xa by-\pgf@x%
  \advance\pgf@ya by-\pgf@y%
  % compute support directions:
  \pgf@xa=\pgf@plottension\pgf@xa%
  \pgf@ya=\pgf@plottension\pgf@ya%
  % first marshal:
  \pgf@process{\pgf@plot@closedcurve@after@initial}%
  \pgf@xb=\pgf@x%
  \pgf@yb=\pgf@y%
  \pgf@xc=\pgf@x%
  \pgf@yc=\pgf@y%
  \advance\pgf@xb by-\pgf@xa%
  \advance\pgf@yb by-\pgf@ya%
  \advance\pgf@xc by\pgf@xa%
  \advance\pgf@yc by\pgf@ya%
  \global\let\pgf@plot@closedcurve@first=\pgf@plot@closedcurve@after@initial%
  \global\let\pgf@plot@closedcurve@second=\pgf@plot@closedcurve@current%
  \xdef\pgf@plot@closedcurve@after@initial@presupport{\noexpand\pgfqpoint{\the\pgf@xb}{\the\pgf@yb}}%
  \xdef\pgf@plot@closedcurve@first@support{\noexpand\pgfqpoint{\the\pgf@xc}{\the\pgf@yc}}%
  \global\let\pgf@plotstreampoint=\pgf@plot@closedcurve@handler@fourth%
}

\def\pgf@plot@closedcurve@handler@fourth#1{%
  \pgf@process{#1}%
  \xdef\pgf@plot@closedcurve@current{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
  % compute difference vector:
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \pgf@process{\pgf@plot@closedcurve@first}
  \advance\pgf@xa by-\pgf@x%
  \advance\pgf@ya by-\pgf@y%
  % compute support directions:
  \pgf@xa=\pgf@plottension\pgf@xa%
  \pgf@ya=\pgf@plottension\pgf@ya%
  % first marshal:
  \pgf@process{\pgf@plot@closedcurve@second}%
  \pgf@xb=\pgf@x%
  \pgf@yb=\pgf@y%
  \pgf@xc=\pgf@x%
  \pgf@yc=\pgf@y%
  \advance\pgf@xb by-\pgf@xa%
  \advance\pgf@yb by-\pgf@ya%
  \advance\pgf@xc by\pgf@xa%
  \advance\pgf@yc by\pgf@ya%
  \edef\pgf@marshal{\noexpand\pgfpathcurveto{\noexpand\pgf@plot@closedcurve@first@support}%
    {\noexpand\pgfqpoint{\the\pgf@xb}{\the\pgf@yb}}{\noexpand\pgf@plot@closedcurve@second}}%
  {\pgf@marshal}%
  % Prepare next:
  \global\let\pgf@plot@closedcurve@first=\pgf@plot@closedcurve@second%
  \global\let\pgf@plot@closedcurve@second=\pgf@plot@closedcurve@current%
  \xdef\pgf@plot@closedcurve@first@support{\noexpand\pgfqpoint{\the\pgf@xc}{\the\pgf@yc}}%
}

\def\pgf@plot@closedcurve@handler@finish{%
  \ifpgf@plot@started
    %
    % first, draw line from 2nd last to last:
    %
    \pgf@process{\pgf@plot@closedcurve@initial}%
    % compute difference vector:
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgf@process{\pgf@plot@closedcurve@first}%
    \advance\pgf@xa by-\pgf@x%
    \advance\pgf@ya by-\pgf@y%
    % compute support directions:
    \pgf@xa=\pgf@plottension\pgf@xa%
    \pgf@ya=\pgf@plottension\pgf@ya%
    % first marshal:
    \pgf@process{\pgf@plot@closedcurve@second}%
    \pgf@xb=\pgf@x%
    \pgf@yb=\pgf@y%
    \pgf@xc=\pgf@x%
    \pgf@yc=\pgf@y%
    \advance\pgf@xb by-\pgf@xa%
    \advance\pgf@yb by-\pgf@ya%
    \advance\pgf@xc by\pgf@xa%
    \advance\pgf@yc by\pgf@ya%
    \edef\pgf@marshal{\noexpand\pgfpathcurveto{\noexpand\pgf@plot@closedcurve@first@support}%
      {\noexpand\pgfqpoint{\the\pgf@xb}{\the\pgf@yb}}{\noexpand\pgf@plot@closedcurve@second}}%
    {\pgf@marshal}%
    \xdef\pgf@plot@closedcurve@first@support{\noexpand\pgfqpoint{\the\pgf@xc}{\the\pgf@yc}}%
    %
    % second, draw line from last point to start:
    %
    \pgf@process{\pgf@plot@closedcurve@after@initial}%
    % compute difference vector:
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgf@process{\pgf@plot@closedcurve@second}%
    \advance\pgf@xa by-\pgf@x%
    \advance\pgf@ya by-\pgf@y%
    % compute support directions:
    \pgf@xa=\pgf@plottension\pgf@xa%
    \pgf@ya=\pgf@plottension\pgf@ya%
    % first marshal:
    \pgf@process{\pgf@plot@closedcurve@initial}%
    \pgf@xb=\pgf@x%
    \pgf@yb=\pgf@y%
    \pgf@xc=\pgf@x%
    \pgf@yc=\pgf@y%
    \advance\pgf@xb by-\pgf@xa%
    \advance\pgf@yb by-\pgf@ya%
    \advance\pgf@xc by\pgf@xa%
    \advance\pgf@yc by\pgf@ya%
    \edef\pgf@marshal{\noexpand\pgfpathcurveto{\noexpand\pgf@plot@closedcurve@first@support}%
      {\noexpand\pgfqpoint{\the\pgf@xb}{\the\pgf@yb}}{\noexpand\pgf@plot@closedcurve@initial}}%
    {\pgf@marshal}%
    %
    % third, draw line from first to second point:
    %
    \edef\pgf@marshal{\noexpand\pgfpathcurveto{\noexpand\pgfqpoint{\the\pgf@xc}{\the\pgf@yc}}%
      {\noexpand\pgf@plot@closedcurve@after@initial@presupport}{\noexpand\pgf@plot@closedcurve@after@initial}}%
    {\pgf@marshal}%
    \pgfpathclose%
  \fi%
}





% This handler converts each point in a stream into a line from the
% $y$-axis to the given points coordinate, resulting in a
% ``comb.'' 
%
% Example:
%
% \pgfplothandlerxcomb
% \pgfplotxyfile{mytable}

\pgfdeclareplothandler{\pgfplothandlerxcomb}{}{%
  start macro=\pgfplotxzerolevelstreamstart,
  point macro=\pgf@plot@xcomb@handler,
  end macro=\pgfplotxzerolevelstreamend,
}

\def\pgf@plot@xcomb@handler#1{%
  \pgf@process{#1}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \begingroup
  \pgfplotxzerolevelstreamnext
  \endgroup
  \pgf@yb=\pgf@x
  \pgfpathmoveto{\pgfqpoint{\pgf@yb}{\pgf@ya}}%
  \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@ya}}%
}


% This handler converts each point in a stream into a line from the
% $x$-axis straight up to the given points coordinate, resulting in a
% ``comb.'' 
%
% Example:
%
% \pgfplothandlerycomb
% \pgfplotxyfile{mytable}

\pgfdeclareplothandler{\pgfplothandlerycomb}{}{%
  start macro=\pgfplotyzerolevelstreamstart,
  point macro=\pgf@plot@ycomb@handler,
  end macro=\pgfplotyzerolevelstreamend
}

\def\pgf@plot@ycomb@handler#1{%
  \pgf@process{#1}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \begingroup
  \pgfplotyzerolevelstreamnext
  \endgroup
  \pgf@yb=\pgf@x
  \pgfpathmoveto{\pgfqpoint{\pgf@xa}{\pgf@yb}}%
  \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@ya}}%
}

% PGF Bar or comb plots usually draw something from zero to the current plot's coordinate.
% 
% The 'zero' offset can be changed using an input stream.
%
% There are two such streams which can be configured independently.
% The first one returns "zeros" for coordinate x, the second one
% returns "zeros" for coordinate y.
% 
% \pgfplotxzerolevelstreamstart
% \pgfplotxzerolevelstreamnext % assigns \pgf@x globally
% \pgfplotxzerolevelstreamnext
% \pgfplotxzerolevelstreamnext
% \pgfplotxzerolevelstreamend
%
% and 
% \pgfplotyzerolevelstreamstart
% \pgfplotyzerolevelstreamnext % assigns \pgf@x globally
% \pgfplotyzerolevelstreamend
%
\def\pgfplotxzerolevelstreamstart{\pgf@plotxzerolevelstreamstart}%
\def\pgfplotxzerolevelstreamend{\pgf@plotxzerolevelstreamend}%
\def\pgfplotxzerolevelstreamnext{\pgf@plotxzerolevelstreamnext}
\def\pgfplotyzerolevelstreamstart{\pgf@plotyzerolevelstreamstart}%
\def\pgfplotyzerolevelstreamend{\pgf@plotyzerolevelstreamend}%
\def\pgfplotyzerolevelstreamnext{\pgf@plotyzerolevelstreamnext}

% This zero level stream always returns '#1' (a dimension).
\def\pgfplotxzerolevelstreamconstant#1{%
	\edef\pgfplotxzerolevelstreamconstant@val{#1}%
	\def\pgf@plotxzerolevelstreamstart{%
		\global\let\pgf@plotxzerolevelstreamend=\relax
		\gdef\pgf@plotxzerolevelstreamnext{\global\pgf@x=\pgfplotxzerolevelstreamconstant@val\relax}%
	}%
}%
\pgfplotxzerolevelstreamconstant{0pt}%

% This zero level stream always returns '#1'.
\def\pgfplotyzerolevelstreamconstant#1{%
	\edef\pgfplotyzerolevelstreamconstant@val{#1}%
	\def\pgf@plotyzerolevelstreamstart{%
		\global\let\pgf@plotyzerolevelstreamend=\relax
		\gdef\pgf@plotyzerolevelstreamnext{\global\pgf@x=\pgfplotyzerolevelstreamconstant@val\relax}%
	}%
}%
\pgfplotyzerolevelstreamconstant{0pt}%

\def\pgfplotbarwidth{\pgfkeysvalueof{/pgf/bar width}}
\def\pgfplotbarshift{\pgfkeysvalueof{/pgf/bar shift}}

\pgfqkeys{/pgf}{%
	bar width/.initial=10pt,
	bar shift/.initial=0pt,
	bar interval width/.initial=1,
	bar interval shift/.initial=0.5,
	%
	% hook which is executed right before a new bar is begun.
	at begin bar/.initial=,
	% hook which is executed right after a bar path has been finished.
	% In this context, the bar's path has not been used.
	at end bar/.initial=,
}

% This handler places a rectangle at each point in the plot stream, a
% rectangle which touches the x-axis at one end and the current point
% at the other end:
%    --(X)--
%    |     |
%    |     |
%    |     |
%    --(0)--
% Example:
%
% \pgfplothandlerybar
% \pgfplotxyfile{mytable}

\pgfdeclareplothandler{\pgfplothandlerybar}{}{%
  start={
    \pgfmathparse{\pgfplotbarwidth}%
    \xdef\pgfplotbarwidth@{\pgfmathresult pt}%
    \pgfmathparse{\pgfplotbarshift}%
    \xdef\pgfplotbarshift@{\pgfmathresult pt}%
    \pgfplotyzerolevelstreamstart
  },
  end macro=\pgfplotyzerolevelstreamend,
  point macro=\pgf@plot@ybar@handler
}

\def\pgf@plot@ybar@handler#1{%
  \pgfkeysvalueof{/pgf/at begin bar}%
  \pgf@process{#1}%
  \pgf@ya=\pgf@y
  \expandafter\pgf@xb\pgfplotbarwidth@\relax
  \pgf@xc=\pgf@x
  \advance\pgf@xc by-.5\pgf@xb
  \advance\pgf@xc by\pgfplotbarshift@\relax
  \begingroup
  \pgfplotyzerolevelstreamnext
  \endgroup
  \pgf@yb=\pgf@x
  \advance\pgf@ya by-\pgf@yb
  \pgfpathrectangle
	{\pgfqpoint{\pgf@xc}{\pgf@yb}}%
	{\pgfqpoint{\pgf@xb}{\pgf@ya}}%
  \pgfkeysvalueof{/pgf/at end bar}%
}

% This handler places a rectangle at each point in the plot stream, a
% rectangle which touches the y-axis at one end and the current point
% at the other end:
%    ---------
%    |       |
%   (0)     (X)
%    |       |
%    ---------
% Example:
%
% \pgfplothandlerxbar
% \pgfplotxyfile{mytable}
\pgfdeclareplothandler{\pgfplothandlerxbar}{}{%
  start={
    \pgfmathparse{\pgfplotbarwidth}%
    \xdef\pgfplotbarwidth@{\pgfmathresult pt}%
    \pgfmathparse{\pgfplotbarshift}%
    \xdef\pgfplotbarshift@{\pgfmathresult pt}%
    \pgfplotxzerolevelstreamstart
  },
  end macro=\pgfplotxzerolevelstreamend,
  point macro=\pgf@plot@xbar@handler
}

\def\pgf@plot@xbar@handler#1{%
  \pgfkeysvalueof{/pgf/at begin bar}%
  \pgf@process{#1}%
  \pgf@ya=\pgf@x
  \expandafter\pgf@xb\pgfplotbarwidth@\relax
  \pgf@xc=\pgf@y
  \advance\pgf@xc by-.5\pgf@xb
  \advance\pgf@xc by\pgfplotbarshift@\relax
  \begingroup
  \pgfplotxzerolevelstreamnext
  \endgroup
  \pgf@yb=\pgf@x
  \advance\pgf@ya by-\pgf@yb
  \pgfpathrectangle
	{\pgfqpoint{\pgf@yb}{\pgf@xc}}%
	{\pgfqpoint{\pgf@ya}{\pgf@xb}}%
  \pgfkeysvalueof{/pgf/at end bar}%
}

% This handler is a variant of \pgfplothandlerybar which works with
% intervals instead of points.
% 
% Bars are drawn between successive input coordinates and the width is
% determined relatively to the interval length.
%
% It looks like this:
%
%    |---|      |-----| 
%    |   |      |     |    
%    |   |      |     |     
%    |   |      |     |       
% (X)------(X)-----------(X)
%
% where (X) denotes the x-axis offsets of input coordinates.
%
% In more detail, if (x_i,y_i) and (x_{i+1},y_{i+1}) denote successive
% input coordinates, the bar will be placed above the
% interval [x_i,x_{i+1}], centered at
%
%    x_i + \pgfkeysvalueof{/pgf/bar interval shift} * (x_{i+1} - x_i)
%
% with width
%
%    \pgfkeysvalueof{/pgf/bar interval width} * (x_{i+1} - x_i).
%
% If you have N+1 input points, you will get N bars (one for each
% interval). The y_i value of the last bar will be ignored.
%
% Example:
%
% \pgfplothandlerybarinterval
% \pgfplotxyfile{mytable}
\pgfdeclareplothandler{\pgfplothandlerybarinterval}{}{%
  start={
    \pgfmathparse{\pgfkeysvalueof{/pgf/bar interval width}}%
    \xdef\pgfplotbarintervalwidth@{\pgfmathresult}%
    \pgfmathparse{\pgfkeysvalueof{/pgf/bar interval shift}}%
    \xdef\pgfplotbarintervalshift@{\pgfmathresult}%
    \pgfplotyzerolevelstreamstart
  },
  end macro=\pgfplotyzerolevelstreamend,
  point macro=\pgf@plot@ybarinterval@handler@first
}

\def\pgf@plot@ybarinterval@handler@first#1{%
  \pgf@process{#1}%
  \xdef\pgf@plot@barinterval@intervalstart{\the\pgf@x}%
  \xdef\pgf@plot@barinterval@bar{\the\pgf@y}%
  \global\let\pgf@plotstreampoint=\pgf@plot@ybarinterval@handler%
}
\def\pgf@plot@ybarinterval@handler#1{%
  \pgfkeysvalueof{/pgf/at begin bar}%
  \pgf@process{#1}%
  \pgf@ya=\pgf@plot@barinterval@bar
  \xdef\pgf@plot@barinterval@bar{\the\pgf@y}%
  \pgf@xc=\pgf@plot@barinterval@intervalstart\relax
  \xdef\pgf@plot@barinterval@intervalstart{\the\pgf@x}%
  \pgf@xb=\pgf@x
  \advance\pgf@xb by-\pgf@xc
  \advance\pgf@xc by\pgfplotbarintervalshift@\pgf@xb
  \pgf@xb=\pgfplotbarintervalwidth@\pgf@xb
  \advance\pgf@xc by-.5\pgf@xb% center
  \begingroup
  \pgfplotyzerolevelstreamnext
  \endgroup
  \pgf@yb=\pgf@x
  \advance\pgf@ya by-\pgf@yb
  \pgfpathrectangle
	{\pgfqpoint{\pgf@xc}{\pgf@yb}}%
	{\pgfqpoint{\pgf@xb}{\pgf@ya}}%
  \pgfkeysvalueof{/pgf/at end bar}%
}

% Like \pgfplothandlerybarinterval but for xbar.
\pgfdeclareplothandler{\pgfplothandlerxbarinterval}{}{%
  start={
    \pgfmathparse{\pgfkeysvalueof{/pgf/bar interval width}}%
    \xdef\pgfplotbarintervalwidth@{\pgfmathresult}%
    \pgfmathparse{\pgfkeysvalueof{/pgf/bar interval shift}}%
    \xdef\pgfplotbarintervalshift@{\pgfmathresult}%
    \pgfplotxzerolevelstreamstart
  },
  end macro=\pgfplotxzerolevelstreamend,
  point macro=\pgf@plot@xbarinterval@handler@first
}

\def\pgf@plot@xbarinterval@handler@first#1{%
  \pgf@process{#1}%
  \xdef\pgf@plot@barinterval@intervalstart{\the\pgf@y}%
  \xdef\pgf@plot@barinterval@bar{\the\pgf@x}%
  \global\let\pgf@plotstreampoint=\pgf@plot@xbarinterval@handler%
}
\def\pgf@plot@xbarinterval@handler#1{%
  \pgfkeysvalueof{/pgf/at begin bar}%
  \pgf@process{#1}%
  \pgf@ya=\pgf@plot@barinterval@bar
  \xdef\pgf@plot@barinterval@bar{\the\pgf@x}%
  \pgf@xc=\pgf@plot@barinterval@intervalstart\relax
  \xdef\pgf@plot@barinterval@intervalstart{\the\pgf@y}%
  \pgf@xb=\pgf@y
  \advance\pgf@xb by-\pgf@xc
  \advance\pgf@xc by\pgfplotbarintervalshift@\pgf@xb
  \pgf@xb=\pgfplotbarintervalwidth@\pgf@xb
  \advance\pgf@xc by-.5\pgf@xb% center
  \begingroup
  \pgfplotxzerolevelstreamnext
  \endgroup
  \pgf@yb=\pgf@x
  \advance\pgf@ya by-\pgf@yb
  \pgfpathrectangle
	{\pgfqpoint{\pgf@yb}{\pgf@xc}}%
	{\pgfqpoint{\pgf@ya}{\pgf@xb}}%
  \pgfkeysvalueof{/pgf/at end bar}%
}


% This handler is very similar to \pgfplothandlerlineto, but it
% produces CONSTANT connected pieces of the form
%
%          x
%          |
%   x---   |
%   |  x----
% x-|
%
% Example:
%
% \pgfplothandlerconstantlineto
% \pgfplotxyfile{mytable}

\pgfdeclareplothandler{\pgfplothandlerconstantlineto}{}{%
  point macro=\pgf@plot@const@line@handler
}

\def\pgf@plot@const@line@handler#1{%
  \pgf@process{#1}%
  \xdef\pgf@plot@const@line@handler@last{\the\pgf@y}%
  \pgf@plot@first@action{}%
  \global\let\pgf@plotstreampoint=\pgf@plot@const@line@handler@@%
}
\def\pgf@plot@const@line@handler@@#1{%
  \pgf@process{#1}%
  \pgf@xa=\pgf@x
  \pgf@ya=\pgf@y
  \pgf@yb\pgf@plot@const@line@handler@last\relax
  \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@yb}}%
  \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@ya}}%
  \xdef\pgf@plot@const@line@handler@last{\the\pgf@ya}%
}

% A variant of \pgfplothandlerconstantlineto which places its mark on
% the right line ends.
% 
%       |---x
% ---x  |
%    |--x
% x
%
% Example:
%
% \pgfplothandlerconstantlinetomarkright
% \pgfplotxyfile{mytable}

\pgfdeclareplothandler{\pgfplothandlerconstantlinetomarkright}{}{%
  point macro=\pgf@plot@const@line@mark@right@handler
}

\def\pgf@plot@const@line@mark@right@handler#1{%
  \pgf@process{#1}%
  \xdef\pgf@plot@const@line@handler@last{\the\pgf@x}%
  \pgf@plot@first@action{}%
  \global\let\pgf@plotstreampoint=\pgf@plot@const@line@mark@right@handler@@%
}
\def\pgf@plot@const@line@mark@right@handler@@#1{%
  \pgf@process{#1}%
  \pgf@xa=\pgf@x
  \pgf@ya=\pgf@y
  \pgf@yb\pgf@plot@const@line@handler@last\relax
  \pgfpathlineto{\pgfqpoint{\pgf@yb}{\pgf@ya}}%
  \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@ya}}%
  \xdef\pgf@plot@const@line@handler@last{\the\pgf@xa}%
}

% A variant of \pgfplothandlerconstantlineto which places its mark on
% the middle of the line segment.
%
%               ----x
%               |
%   --x---      |
%   |    |--x----
% x--
%
% Example:
%
% \pgfplothandlerconstantlinetomarkmid
% \pgfplotxyfile{mytable}

\pgfdeclareplothandler{\pgfplothandlerconstantlinetomarkmid}{}{%
  point macro=\pgf@plot@const@line@mark@mid@handler
}

\def\pgf@plot@const@line@mark@mid@handler#1{%
  \pgf@process{#1}%
  \xdef\pgf@plot@const@line@handler@last{\global\pgf@x=\the\pgf@x\space\global\pgf@y=\the\pgf@y\space}%
  \pgf@plot@first@action{}%
  \global\let\pgf@plotstreampoint=\pgf@plot@const@line@mark@mid@handler@@%
}
\def\pgf@plot@const@line@mark@mid@handler@@#1{%
  \pgf@process{#1}%
  \pgf@xa=\pgf@x
  \pgf@ya=\pgf@y
  \pgf@plot@const@line@handler@last
  \pgf@xc=.5\pgf@xa
  \advance\pgf@xc by.5\pgf@x
  \pgfpathlineto{\pgfqpoint{\pgf@xc}{\pgf@y}}%
  \pgfpathlineto{\pgfqpoint{\pgf@xc}{\pgf@ya}}%
  \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@ya}}%
  \xdef\pgf@plot@const@line@handler@last{\global\pgf@x=\the\pgf@x\space\global\pgf@y=\the\pgf@y\space}%
}

% This handler is in fact a variant of \pgfplothandlerconstantlineto,
% but it does not draw vertical lines. It produces a sequence of
% line-to and move-to operations such that plot marks are placed at
% each right end:
%
%          ---x
%   ---x   
%       ---x
% --x
%
% Example:
%
% \pgfplothandlerjumpmarkright
% \pgfplotxyfile{mytable}

\pgfdeclareplothandler{\pgfplothandlerjumpmarkright}{}{%
  point macro=\pgf@plot@jumpmarkright@handler
}

\def\pgf@plot@jumpmarkright@handler#1{%
  \pgf@process{#1}%
  \xdef\pgf@plot@const@line@handler@last{\the\pgf@x}%
  \pgf@plot@first@action{}%
  \global\let\pgf@plotstreampoint=\pgf@plot@jumpmarkright@handler@@%
}
\def\pgf@plot@jumpmarkright@handler@@#1{%
  \pgf@process{#1}%
  \pgf@xa=\pgf@x
  \pgf@ya=\pgf@y
  \pgf@yb\pgf@plot@const@line@handler@last\relax
  \pgfpathmoveto{\pgfqpoint{\pgf@yb}{\pgf@ya}}%
  \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@ya}}%
  \xdef\pgf@plot@const@line@handler@last{\the\pgf@xa}%
}

% This handler is in fact a variant of \pgfplothandlerconstantlineto,
% but it does not draw vertical lines. It produces a sequence of
% line-to and move-to operations such that plot marks are placed at
% each left end:
%
%          x---
%   x---   
%       x---
% x--
%
% Example:
%
% \pgfplothandlerjumpmarkleft
% \pgfplotxyfile{mytable}

\pgfdeclareplothandler{\pgfplothandlerjumpmarkleft}{}{%
  point macro=\pgf@plot@jumpmarkleft@handler
}
\def\pgf@plot@jumpmarkleft@handler#1{%
  \pgf@process{#1}%
  \xdef\pgf@plot@const@line@handler@last{\the\pgf@y}%
  \pgf@plot@first@action{}%
  \global\let\pgf@plotstreampoint=\pgf@plot@jumpmarkleft@handler@@%
}
\def\pgf@plot@jumpmarkleft@handler@@#1{%
  \pgf@process{#1}%
  \pgf@xa=\pgf@x
  \pgf@ya=\pgf@y
  \pgf@yb\pgf@plot@const@line@handler@last\relax
  \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@yb}}%
  \pgfpathmoveto{\pgfqpoint{\pgf@xa}{\pgf@ya}}%
  \xdef\pgf@plot@const@line@handler@last{\the\pgf@ya}%
}

% This handler is in fact a variant of
% \pgfplothandlerconstantlinetomarkmid,
% but it does not draw vertical lines. It produces a sequence of
% line-to and move-to operations such that plot marks are placed like
%
%             ----x
%             
%   --x--     
%       --x----
% x--
%
% Example:
%
% \pgfplothandlerjumpmarkmid
% \pgfplotxyfile{mytable}

\pgfdeclareplothandler{\pgfplothandlerjumpmarkmid}{}{%
  point macro=\pgf@plot@jump@mark@mid@handler
}

\def\pgf@plot@jump@mark@mid@handler#1{%
  \pgf@process{#1}%
  \xdef\pgf@plot@const@line@handler@last{\global\pgf@x=\the\pgf@x\space\global\pgf@y=\the\pgf@y\space}%
  \pgf@plot@first@action{}%
  \global\let\pgf@plotstreampoint=\pgf@plot@jump@mark@mid@handler@@%
}
\def\pgf@plot@jump@mark@mid@handler@@#1{%
  \pgf@process{#1}%
  \pgf@xa=\pgf@x
  \pgf@ya=\pgf@y
  \pgf@plot@const@line@handler@last
  \pgf@xc=.5\pgf@xa
  \advance\pgf@xc by.5\pgf@x
  \pgfpathlineto{\pgfqpoint{\pgf@xc}{\pgf@y}}%
  \pgfpathmoveto{\pgfqpoint{\pgf@xc}{\pgf@ya}}%
  \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@ya}}%
  \xdef\pgf@plot@const@line@handler@last{\global\pgf@x=\the\pgf@x\space\global\pgf@y=\the\pgf@y\space}%
}


% This handler converts each point in a stream into a line from the
% origin to the point's coordinate, resulting in a ``star''.
%
% Example:
%
% \pgfplothandlerpolarcomb
% \pgfplotxyfile{mytable}

\pgfdeclareplothandler{\pgfplothandlerpolarcomb}{}{%
  point macro=\pgf@plot@polarcomb@handler
}

\def\pgf@plot@polarcomb@handler#1{%
  \pgf@process{#1}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \pgfpathmoveto{\pgfpointorigin}%
  \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@ya}}%
}




% This handler draws a given mark at each point. 
%
% #1 = some code to be executed at each point (with the coordinate
%      system translated to that point).
%      Typically, this code will be \pgfuseplotmark{whatever}.
%
% Example:
%
% \pgfplothandlermark{\pgfuseplotmark{*}}
% \pgfplotxyfile{mytable}

\pgfdeclareplothandler{\pgfplothandlermark}{#1}{%
  start={
    \def\pgf@plot@mark{%
      \ifnum\pgf@plot@mark@count<\pgf@plot@mark@repeat\relax%
      \else%
        \global\pgf@plot@mark@count=0\relax%
        #1%
      \fi%
    }%
    \global\pgf@plot@mark@count=\pgf@plot@mark@repeat\relax%
    \global\advance\pgf@plot@mark@count by-\pgf@plot@mark@phase\relax%
  },
  point macro=\pgf@plot@mark@handler
}

\newcount\pgf@plot@mark@count
\def\pgf@plot@mark@phase{0}

\def\pgf@plot@mark@handler#1{%
  \global\advance\pgf@plot@mark@count by1\relax%
  {\pgftransformshift{#1}\pgf@plot@mark}%
}


% Set the repeat count for marks. For example, if 3 is given as a
% value, only every third point will get a mark.
%
% #1 = repeat count
%
% Example:
%
% \pgfsetplotmarkrepeat{2}

\def\pgfsetplotmarkrepeat#1{\def\pgf@plot@mark@repeat{#1}}
\pgfsetplotmarkrepeat{1}


% Set the phase for marks. For example, if 3 is the repeat and 3 is 
% the phase, already the first point will be marked. 
%
% #1 = the index of the first point that should be marked.
%
% Example:
%
% \pgfsetplotmarkphase{3}

\def\pgfsetplotmarkphase#1{\def\pgf@plot@mark@phase{#1}}
\pgfsetplotmarkphase{1}



% This handler draws a given mark at those points whose number is
% given in the (pgffor-like) list.
%
% #1 = some code to be executed at each point (with the coordinate
%      system translated to that point).
%      Typically, this code will be \pgfuseplotmark{whatever}.
% #2 = list of positions like "1,2,4,...,9,10"
%
% Example:
%
% \pgfplothandlermarklisted{\pgfuseplotmark{*}}{1,2,4,...,9}
% \pgfplotxyfile{mytable}

\pgfdeclareplothandler{\pgfplothandlermarklisted}{#1#2}{%
  start={
    \let\pgf@plot@mark@list=\pgfutil@empty%
    \edef\pgf@marshal{\noexpand\foreach\noexpand\pgf@temp in{#2}}
    \pgf@marshal{\xdef\pgf@plot@mark@list{\pgf@plot@mark@list(\pgf@temp)}}%
    \def\pgf@plot@mark{%
      \edef\pgf@marshal{\noexpand\pgfutil@in@{(\the\pgf@plot@mark@count)}{\pgf@plot@mark@list}}%
      \pgf@marshal%
      \ifpgfutil@in@#1\fi%
    }%
    \global\pgf@plot@mark@count=\pgf@plot@mark@repeat\relax%
    \global\advance\pgf@plot@mark@count by-\pgf@plot@mark@phase\relax%
  },
  point macro=\pgf@plot@mark@handler
}

% \def\pgfplothandlermarklisted#1#2{%
%   \let\pgf@plot@mark@list=\pgfutil@empty%
%   \edef\pgf@marshal{\noexpand\foreach\noexpand\pgf@temp in{#2}}
%   \pgf@marshal{\xdef\pgf@plot@mark@list{\pgf@plot@mark@list(\pgf@temp)}}%
%   \pgf@plothandlermark{%
%     \edef\pgf@marshal{\noexpand\pgfutil@in@{(\the\pgf@plot@mark@count)}{\pgf@plot@mark@list}}%
%     \pgf@marshal%
%     \ifpgfutil@in@#1\fi}%
% }


% Define a new plot mark for use with \pgfplotmark.
%
% #1 = a plot mark mnemonic
% #2 = code for drawing the mark
%
% Example:
%
% \pgfdeclareplotmark{*}{\pgfpathcircle{\pgfpointorigin}{2pt}\pgfusepathqfill}

\def\pgfdeclareplotmark#1#2{\expandafter\def\csname pgf@plot@mark@#1\endcsname{#2}}


% Set the size of plot marks. For circles, this will be the radius,
% for other shapes it should be about half the width/height.
%
% Example:
%
% \pgfsetplotmarksize{1pt}

\def\pgfsetplotmarksize#1{\pgfmathsetlength\pgfplotmarksize{#1}}

\newdimen\pgfplotmarksize
\pgfplotmarksize=2pt


% Insert a plot mark's code at the origin.
%
% #1 = plot mark mnemonic
%
% Example:
%
% \pgfuseplotmark{*}

\def\pgfuseplotmark#1{\csname pgf@plot@mark@#1\endcsname}


% A stroke-filled circle mark

\pgfdeclareplotmark{*}
{%
  \pgfpathellipse{\pgfpointorigin}{\pgfqpoint{\pgfplotmarksize}{0sp}}{\pgfqpoint{0sp}{\pgfplotmarksize}}%
  \pgfusepathqfillstroke
}


% A plus-sign like mark

\pgfdeclareplotmark{+}
{%
  \pgfpathmoveto{\pgfqpoint{-\pgfplotmarksize}{0pt}}
  \pgfpathlineto{\pgfqpoint{\pgfplotmarksize}{0pt}}
  \pgfpathmoveto{\pgfqpoint{0pt}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpoint{0pt}{-\pgfplotmarksize}}
  \pgfusepathqstroke
}


% An x-shaped mark

\pgfdeclareplotmark{x}
{%
  \pgfpathmoveto{\pgfqpoint{-.70710678\pgfplotmarksize}{-.70710678\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpoint{.70710678\pgfplotmarksize}{.70710678\pgfplotmarksize}}
  \pgfpathmoveto{\pgfqpoint{-.70710678\pgfplotmarksize}{.70710678\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpoint{.70710678\pgfplotmarksize}{-.70710678\pgfplotmarksize}}
  \pgfusepathqstroke
}

% See pgflibraryplotmarks for more plot marks




% This handler turns creates a series of straight line segements
% between consecutive points, but leaving /pgf/gap around stream point
% space.
%
% Example:
%
% \pgfplothandlergaplineto
% \pgfplotxyfile{mytable}

\pgfkeys{/pgf/gap around stream point/.initial=1.5pt}

\pgfdeclareplothandler{\pgfplothandlergaplineto}{}{%
  point macro=\pgf@plot@gap@lineto@handler@initial,
  jump macro=\pgf@plot@gap@next@moveto
}

\def\pgf@plot@gap@next@moveto{%
  \global\let\pgf@plotstreampoint=\pgf@plot@gap@lineto@handler@initial%
}

\def\pgf@plot@gap@lineto@handler@initial#1{%
  \pgf@process{#1}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \xdef\pgf@plot@gap@lineto@last{\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}%
  \global\let\pgf@plotstreampoint=\pgf@plot@gap@lineto@handler%
}

\def\pgf@plot@gap@lineto@handler#1{%
  % Ok, compute normalized line vector
  \pgf@process{#1}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \xdef\pgf@plot@gap@lineto@next{\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}%
  \pgf@process{\pgfpointnormalised{\pgfpointdiff{\pgf@plot@gap@lineto@last}{\pgf@plot@gap@lineto@next}}}%
  \pgf@xc=\pgf@x%
  \pgf@yc=\pgf@y%
  \pgfpathmoveto{\pgfpointadd{\pgfpointscale{\pgfkeysvalueof{/pgf/gap
          around stream point}}{\pgfqpoint{\pgf@xc}{\pgf@yc}}}{\pgf@plot@gap@lineto@last}}%
  \pgfpathlineto{\pgfpointadd{\pgfpointscale{\pgfkeysvalueof{/pgf/gap
          around stream point}}{\pgfqpoint{-\pgf@xc}{-\pgf@yc}}}{\pgf@plot@gap@lineto@next}}%
  \global\let\pgf@plot@gap@lineto@last=\pgf@plot@gap@lineto@next%
}




% This handler works like \pgfplothandlergaplineto, only the last
% point is connected to the first point, creating a closed curve
% space.
%
% Example:
%
% \pgfplothandlergapcycle
% \pgfplotxyfile{mytable}

\pgfdeclareplothandler{\pgfplothandlergapcycle}{}{%
  point macro=\pgf@plot@gap@cycle@handler@initial,
  jump macro=\pgf@plot@gapcycle@next@moveto,
  end macro=\pgf@plot@gap@cycle@handler@finish,
  start={\global\let\pgf@plot@gap@cycle@first\relax}
}

\def\pgf@plot@gapcycle@next@moveto{%
  \pgf@plot@gap@cycle@handler@finish%
  \global\let\pgf@plot@gap@cycle@first=\relax%
  \global\let\pgf@plotstreampoint=\pgf@plot@gap@cycle@handler@initial%
}

\def\pgf@plot@gap@cycle@handler@initial#1{%
  \pgf@process{#1}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \xdef\pgf@plot@gap@cycle@last{\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}%
  \global\let\pgf@plot@gap@cycle@first=\pgf@plot@gap@cycle@last%
  \global\let\pgf@plotstreampoint=\pgf@plot@gap@cycle@handler%
}

\def\pgf@plot@gap@cycle@handler#1{%
  % Ok, compute normalized line vector
  \pgf@process{#1}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \xdef\pgf@plot@gap@cycle@next{\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}%
  \pgf@process{\pgfpointnormalised{\pgfpointdiff{\pgf@plot@gap@cycle@last}{\pgf@plot@gap@cycle@next}}}%
  \pgf@xc=\pgf@x%
  \pgf@yc=\pgf@y%
  \pgfpathmoveto{\pgfpointadd{\pgfpointscale{\pgfkeysvalueof{/pgf/gap
          around stream point}}{\pgfqpoint{\pgf@xc}{\pgf@yc}}}{\pgf@plot@gap@cycle@last}}%
  \pgfpathlineto{\pgfpointadd{\pgfpointscale{\pgfkeysvalueof{/pgf/gap
          around stream point}}{\pgfqpoint{-\pgf@xc}{-\pgf@yc}}}{\pgf@plot@gap@cycle@next}}%
  \global\let\pgf@plot@gap@cycle@last=\pgf@plot@gap@cycle@next%
}

\def\pgf@plot@gap@cycle@handler@finish{%
  \ifx\pgf@plot@gap@cycle@first\relax%
  \else
    \pgf@plot@gap@cycle@handler{\pgf@plot@gap@cycle@first}%
  \fi
}



\endinput

% Local Variables:
% tab-width: 2
% End:

pgflibraryplotmarks.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/libraries/pgflibraryplotmarks.code.tex,v 1.13 2013/07/20 13:56:18 ludewich Exp $


% A stroked circle mark

\pgfdeclareplotmark{o}
{%
  \pgfpathellipse{\pgfpointorigin}{\pgfqpoint{\pgfplotmarksize}{0sp}}{\pgfqpoint{0sp}{\pgfplotmarksize}}%
  \pgfusepathqstroke
}


% A Mercedes-line star

\pgfdeclareplotmark{Mercedes star}
{%
  \pgfpathmoveto{\pgfqpointpolar{90}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfpointorigin}
  \pgfpathmoveto{\pgfqpointpolar{-30}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfpointorigin}
  \pgfpathmoveto{\pgfqpointpolar{-150}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfpointorigin}
  \pgfusepathqstroke
}

\pgfdeclareplotmark{Mercedes star flipped}
{%
  \pgfpathmoveto{\pgfqpointpolar{-90}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfpointorigin}
  \pgfpathmoveto{\pgfqpointpolar{30}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfpointorigin}
  \pgfpathmoveto{\pgfqpointpolar{150}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfpointorigin}
  \pgfusepathqstroke
}




% A six-pointed star mark

\pgfdeclareplotmark{asterisk}
{%
  \pgfpathmoveto{\pgfqpoint{0pt}{-\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpoint{0pt}{\pgfplotmarksize}}
  \pgfpathmoveto{\pgfqpointpolar{30}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpointpolar{210}{\pgfplotmarksize}}
  \pgfpathmoveto{\pgfqpointpolar{-30}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpointpolar{-210}{\pgfplotmarksize}}
  \pgfusepathqstroke
}


% A five-pointed star mark

\pgfdeclareplotmark{star}
{%
  \pgfpathmoveto{\pgfpointorigin}\pgfpathlineto{\pgfqpoint{0pt}{\pgfplotmarksize}}
  \pgfpathmoveto{\pgfpointorigin}\pgfpathlineto{\pgfqpointpolar{18}{\pgfplotmarksize}}
  \pgfpathmoveto{\pgfpointorigin}\pgfpathlineto{\pgfqpointpolar{-54}{\pgfplotmarksize}}
  \pgfpathmoveto{\pgfpointorigin}\pgfpathlineto{\pgfqpointpolar{234}{\pgfplotmarksize}}
  \pgfpathmoveto{\pgfpointorigin}\pgfpathlineto{\pgfqpointpolar{162}{\pgfplotmarksize}}
  \pgfusepathqstroke
}


% An 10-pointed star mark

\pgfdeclareplotmark{10-pointed star}
{%
  \pgfpathmoveto{\pgfqpoint{0pt}{-\pgfplotmarksize}}\pgfpathlineto{\pgfqpoint{0pt}{\pgfplotmarksize}}
  \pgfpathmoveto{\pgfqpointpolar{18}{-\pgfplotmarksize}}\pgfpathlineto{\pgfqpointpolar{18}{\pgfplotmarksize}}
  \pgfpathmoveto{\pgfqpointpolar{-54}{-\pgfplotmarksize}}\pgfpathlineto{\pgfqpointpolar{-54}{\pgfplotmarksize}}
  \pgfpathmoveto{\pgfqpointpolar{234}{-\pgfplotmarksize}}\pgfpathlineto{\pgfqpointpolar{234}{\pgfplotmarksize}}
  \pgfpathmoveto{\pgfqpointpolar{162}{-\pgfplotmarksize}}\pgfpathlineto{\pgfqpointpolar{162}{\pgfplotmarksize}}
  \pgfusepathqstroke
}


% An \oplus mark

\pgfdeclareplotmark{oplus}
{%
  \pgfpathcircle{\pgfpointorigin}{\pgfplotmarksize}
  \pgfpathmoveto{\pgfqpoint{-\pgfplotmarksize}{0pt}}
  \pgfpathlineto{\pgfqpoint{\pgfplotmarksize}{0pt}}
  \pgfpathmoveto{\pgfqpoint{0pt}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpoint{0pt}{-\pgfplotmarksize}}
  \pgfusepathqstroke
}

\pgfdeclareplotmark{oplus*}
{%
  \pgfpathcircle{\pgfpointorigin}{\pgfplotmarksize}
  \pgfpathmoveto{\pgfqpoint{-\pgfplotmarksize}{0pt}}
  \pgfpathlineto{\pgfqpoint{\pgfplotmarksize}{0pt}}
  \pgfpathmoveto{\pgfqpoint{0pt}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpoint{0pt}{-\pgfplotmarksize}}
  \pgfusepathqfillstroke
}


% An \otimes mark

\pgfdeclareplotmark{otimes}
{%
  \pgfpathcircle{\pgfpointorigin}{\pgfplotmarksize}
  \pgfpathmoveto{\pgfqpoint{-.70710678\pgfplotmarksize}{-.70710678\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpoint{.70710678\pgfplotmarksize}{.70710678\pgfplotmarksize}}
  \pgfpathmoveto{\pgfqpoint{-.70710678\pgfplotmarksize}{.70710678\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpoint{.70710678\pgfplotmarksize}{-.70710678\pgfplotmarksize}}
  \pgfusepathqstroke
}

\pgfdeclareplotmark{otimes*}
{%
  \pgfpathcircle{\pgfpointorigin}{\pgfplotmarksize}
  \pgfpathmoveto{\pgfqpoint{-.70710678\pgfplotmarksize}{-.70710678\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpoint{.70710678\pgfplotmarksize}{.70710678\pgfplotmarksize}}
  \pgfpathmoveto{\pgfqpoint{-.70710678\pgfplotmarksize}{.70710678\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpoint{.70710678\pgfplotmarksize}{-.70710678\pgfplotmarksize}}
  \pgfusepathqfillstroke
}


% A vertical bar mark

\pgfdeclareplotmark{|}
{%
  \pgfpathmoveto{\pgfqpoint{0pt}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpoint{0pt}{-\pgfplotmarksize}}
  \pgfusepathqstroke
}



% A horizontal bar mark

\pgfdeclareplotmark{-}
{%
  \pgfpathmoveto{\pgfqpoint{\pgfplotmarksize}{0pt}}
  \pgfpathlineto{\pgfqpoint{-\pgfplotmarksize}{0pt}}
  \pgfusepathqstroke
}


% A square stroked mark

\pgfdeclareplotmark{square}
{%
  \pgfpathrectangle{\pgfqpoint{-\pgfplotmarksize}{-\pgfplotmarksize}}{\pgfqpoint{2\pgfplotmarksize}{2\pgfplotmarksize}}%
  \pgfusepathqstroke
}

% A square stroked-filled mark

\pgfdeclareplotmark{square*}
{%
  \pgfpathrectangle{\pgfqpoint{-\pgfplotmarksize}{-\pgfplotmarksize}}{\pgfqpoint{2\pgfplotmarksize}{2\pgfplotmarksize}}%
  \pgfusepathqfillstroke
}


% A triangle mark

\pgfdeclareplotmark{triangle}
{%
  \pgfpathmoveto{\pgfqpoint{0pt}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpointpolar{-30}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpointpolar{-150}{\pgfplotmarksize}}
  \pgfpathclose
  \pgfusepathqstroke
}


% A stroke-filled triangle mark

\pgfdeclareplotmark{triangle*}
{%
  \pgfpathmoveto{\pgfqpoint{0pt}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpointpolar{-30}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpointpolar{-150}{\pgfplotmarksize}}
  \pgfpathclose
  \pgfusepathqfillstroke
}



% A diamond-shaped mark

\pgfdeclareplotmark{diamond}
{%
  \pgfpathmoveto{\pgfqpoint{0pt}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpoint{.75\pgfplotmarksize}{0pt}}
  \pgfpathlineto{\pgfqpoint{0pt}{-\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpoint{-.75\pgfplotmarksize}{0pt}}
  \pgfpathclose
  \pgfusepathqstroke
}


% A stroke-filled diamond-shaped mark

\pgfdeclareplotmark{diamond*}
{%
  \pgfpathmoveto{\pgfqpoint{0pt}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpoint{.75\pgfplotmarksize}{0pt}}
  \pgfpathlineto{\pgfqpoint{0pt}{-\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpoint{-.75\pgfplotmarksize}{0pt}}
  \pgfpathclose
  \pgfusepathqfillstroke
}



% A pentagon-shaped mark

\pgfdeclareplotmark{pentagon}
{%
  \pgfpathmoveto{\pgfqpoint{0pt}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpointpolar{18}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpointpolar{-54}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpointpolar{234}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpointpolar{162}{\pgfplotmarksize}}
  \pgfpathclose
  \pgfusepathqstroke
}

% A stroke-filled pentagon-shaped mark

\pgfdeclareplotmark{pentagon*}
{%
  \pgfpathmoveto{\pgfqpoint{0pt}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpointpolar{18}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpointpolar{-54}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpointpolar{234}{\pgfplotmarksize}}
  \pgfpathlineto{\pgfqpointpolar{162}{\pgfplotmarksize}}
  \pgfpathclose
  \pgfusepathqfillstroke
}

\newif\ifpgfmarktext@usetikznode
\pgfkeys{
  /pgf/text mark/.initial=p,
  /pgf/text mark style/.initial=,
  /pgf/text mark as node/.is if=pgfmarktext@usetikznode,
  /pgf/text mark as node/.default=true,
  % 
  % backw. compat: the extra search path confuses the '.unknown'
  % handlers, so this here is deprecated:
  /pgf/text mark/style/.style={/pgf/text mark style={#1}},%
  /pgf/text mark/as node/.style={/pgf/text mark as node=#1},%
}%

\pgfdeclareplotmark{text}
{
  \pgfkeysgetvalue{/pgf/text mark style}\pgfmarktext@style
  \pgfkeysgetvalue{/pgf/text mark}\pgfmarktext@
  \ifpgfmarktext@usetikznode
    \expandafter\node\expandafter[\pgfmarktext@style]{\pgfmarktext@};
  \else
    \expandafter\pgftext\expandafter[\pgfmarktext@style]{\pgfmarktext@}%
  \fi
}

\pgfkeysdef{/pgf/mark color}{\def\pgf@mark@color{#1}}
\let\pgf@mark@color\pgfutil@empty

\def\pgf@set@mark@color{%
	\ifx\pgf@mark@color\pgfutil@empty
		\pgfsys@color@rgb@fill{1}{1}{1}%
	\else
		\pgfsetfillcolor{\pgf@mark@color}%
	\fi
}%
\def\pgf@mark@color@none{none}%

% A half-down-filled and half-up-filled-white diamond-shaped mark
% (the shape can be rotated by "mark options = {rotate = 90}")
% created by Tomek

\pgfdeclareplotmark{halfcircle}{%
	\ifx\pgf@mark@color@none\pgf@mark@color
	\else
		\pgfscope
		\pgf@set@mark@color
		\pgfpathmoveto
			{\pgfqpoint{-\pgfplotmarksize}{0pt}}%
		\pgfpatharc{180}{360}{\pgfplotmarksize}%
		\pgfusepathqfill
		\endpgfscope%
	\fi
	\pgfpathmoveto
		{\pgfqpoint{-\pgfplotmarksize}{0pt}}%
	\pgfpathlineto
		{\pgfqpoint{\pgfplotmarksize}{0pt}}%
	\pgfpathcircle{\pgfpointorigin}%
		{\pgfplotmarksize}%
	\pgfusepathqstroke
}
\pgfdeclareplotmark{halfcircle*}{%
    \pgfpathmoveto
        {\pgfqpoint{\pgfplotmarksize}{0pt}}%
    \pgfpatharc{0}{180}{\pgfplotmarksize}%
    \pgfpathclose
    \pgfusepathqfill
	\ifx\pgf@mark@color@none\pgf@mark@color
	\else
		\pgfscope
			\pgf@set@mark@color
			\pgfpathmoveto
				{\pgfqpoint{-\pgfplotmarksize}{0pt}}%
			\pgfpatharc{180}{360}{\pgfplotmarksize}%
			\pgfusepathqfill
		\endpgfscope%
	\fi
	\pgfpathcircle{\pgfpointorigin}%
		{\pgfplotmarksize}%
	\pgfusepathqstroke
}

% A half-down-filled and half-up-filled-white diamond-shaped mark
% created by Magnus Tewes

\pgfdeclareplotmark{halfdiamond*}{%
  \pgfpathmoveto{\pgfqpoint{-.75\pgfplotmarksize}{0pt}}%
  \pgfpathlineto{\pgfqpoint{0pt}{-\pgfplotmarksize}}%
  \pgfpathlineto{\pgfqpoint{.75\pgfplotmarksize}{0pt}}%
  \pgfusepathqfill
  \ifx\pgf@mark@color@none\pgf@mark@color
  \else
	  \pgfscope
	  \pgf@set@mark@color
	  \pgfpathmoveto{\pgfqpoint{.75\pgfplotmarksize}{0pt}}%
	  \pgfpathlineto{\pgfqpoint{0pt}{\pgfplotmarksize}}%
	  \pgfpathlineto{\pgfqpoint{-.75\pgfplotmarksize}{0pt}}%
	  \pgfusepathqfill
	  \endpgfscope
  \fi
  \pgfpathmoveto{\pgfqpoint{.75\pgfplotmarksize}{0pt}}%
  \pgfpathlineto{\pgfqpoint{0pt}{\pgfplotmarksize}}%
  \pgfpathlineto{\pgfqpoint{-.75\pgfplotmarksize}{0pt}}%
  \pgfpathlineto{\pgfqpoint{0pt}{-\pgfplotmarksize}}%
  \pgfpathclose
  \pgfusepathqstroke
}

% A half-down-filled and half-up-filled-white tilted-squared-shaped mark
% created by Magnus Tewes

\pgfdeclareplotmark{halfsquare*}{%
  \pgfpathmoveto{\pgfqpoint{-\pgfplotmarksize}{0pt}}%
  \pgfpathlineto{\pgfqpoint{0pt}{-\pgfplotmarksize}}%
  \pgfpathlineto{\pgfqpoint{\pgfplotmarksize}{0pt}}%
  \pgfusepathqfill
  \ifx\pgf@mark@color@none\pgf@mark@color
  \else
	  \pgfscope
		  \pgf@set@mark@color
		  \pgfpathmoveto{\pgfqpoint{\pgfplotmarksize}{0pt}}%
		  \pgfpathlineto{\pgfqpoint{0pt}{\pgfplotmarksize}}%
		  \pgfpathlineto{\pgfqpoint{-\pgfplotmarksize}{0pt}}%
		  \pgfusepathqfill
	  \endpgfscope
  \fi
  \pgfpathmoveto{\pgfqpoint{\pgfplotmarksize}{0pt}}%
  \pgfpathlineto{\pgfqpoint{0pt}{\pgfplotmarksize}}%
  \pgfpathlineto{\pgfqpoint{-\pgfplotmarksize}{0pt}}%
  \pgfpathlineto{\pgfqpoint{0pt}{-\pgfplotmarksize}}%
  \pgfpathclose
  \pgfusepathqstroke
}

% A half-right-filled and half-up-filled-white tilted-squared-shaped mark
% created by Magnus Tewes

\pgfdeclareplotmark{halfsquare right*}{%
  \pgfpathmoveto{\pgfqpoint{0pt}{-\pgfplotmarksize}}%
  \pgfpathlineto{\pgfqpoint{\pgfplotmarksize}{0pt}}%
  \pgfpathlineto{\pgfqpoint{0pt}{\pgfplotmarksize}}%
  \pgfusepathqfill
  \ifx\pgf@mark@color@none\pgf@mark@color
  \else
	  \pgfscope
		  \pgf@set@mark@color
		  \pgfpathmoveto{\pgfqpoint{0pt}{-\pgfplotmarksize}}%
		  \pgfpathlineto{\pgfqpoint{-\pgfplotmarksize}{0pt}}%
		  \pgfpathlineto{\pgfqpoint{0pt}{\pgfplotmarksize}}%
		  \pgfusepathqfill
	  \endpgfscope
  \fi
  \pgfpathmoveto{\pgfqpoint{\pgfplotmarksize}{0pt}}%
  \pgfpathlineto{\pgfqpoint{0pt}{\pgfplotmarksize}}%
  \pgfpathlineto{\pgfqpoint{-\pgfplotmarksize}{0pt}}%
  \pgfpathlineto{\pgfqpoint{0pt}{-\pgfplotmarksize}}%
  \pgfpathclose
  \pgfusepathqstroke
}

% A half-left-filled and half-up-filled-white tilted-squared-shaped mark
% created by Magnus Tewes

\pgfdeclareplotmark{halfsquare left*}{%
  \pgfpathmoveto{\pgfqpoint{0pt}{-\pgfplotmarksize}}%
  \pgfpathlineto{\pgfqpoint{-\pgfplotmarksize}{0pt}}%
  \pgfpathlineto{\pgfqpoint{0pt}{\pgfplotmarksize}}%
  \pgfusepathqfill
  \ifx\pgf@mark@color@none\pgf@mark@color
  \else
	  \pgfscope
		  \pgf@set@mark@color
		  \pgfpathmoveto{\pgfqpoint{0pt}{-\pgfplotmarksize}}%
		  \pgfpathlineto{\pgfqpoint{\pgfplotmarksize}{0pt}}%
		  \pgfpathlineto{\pgfqpoint{0pt}{\pgfplotmarksize}}%
		  \pgfusepathqfill
	  \endpgfscope
  \fi
  \pgfpathmoveto{\pgfqpoint{\pgfplotmarksize}{0pt}}%
  \pgfpathlineto{\pgfqpoint{0pt}{\pgfplotmarksize}}%
  \pgfpathlineto{\pgfqpoint{-\pgfplotmarksize}{0pt}}%
  \pgfpathlineto{\pgfqpoint{0pt}{-\pgfplotmarksize}}%
  \pgfpathclose
  \pgfusepathqstroke
}


% A stroke-filled heart-shaped mark
% created by Magnus Tewes
\pgfdeclareplotmark{heart}{%
  \pgfpathmoveto{\pgfqpoint{0pt}{-1.75\pgfplotmarksize}}
  \pgfpathcurveto{\pgfqpoint{0pt}{-1.75\pgfplotmarksize}}{\pgfqpoint{0pt}{-1.66\pgfplotmarksize}}{\pgfqpoint{-.5\pgfplotmarksize}{-1.165\pgfplotmarksize}}
  \pgfpathcurveto{\pgfqpoint{-.5\pgfplotmarksize}{-1.165\pgfplotmarksize}}{\pgfqpoint{-\pgfplotmarksize}{-.75\pgfplotmarksize}}{\pgfqpoint{-\pgfplotmarksize}{0pt}}
  \pgfpathcurveto{\pgfqpoint{-\pgfplotmarksize}{0pt}}{\pgfqpoint{-\pgfplotmarksize}{.5825\pgfplotmarksize}}{\pgfqpoint{-.5825\pgfplotmarksize}{.5825\pgfplotmarksize}}
  \pgfpathcurveto{\pgfqpoint{-.5825\pgfplotmarksize}{.5825\pgfplotmarksize}}{\pgfqpoint{0pt}{.5825\pgfplotmarksize}}{\pgfqpoint{0pt}{0pt}}
  \pgfpathcurveto{\pgfqpoint{0pt}{0pt}}{\pgfqpoint{0pt}{.5825\pgfplotmarksize}}{\pgfqpoint{.5825\pgfplotmarksize}{.5825\pgfplotmarksize}}
  \pgfpathcurveto{\pgfqpoint{.5825\pgfplotmarksize}{.5825\pgfplotmarksize}}{\pgfqpoint{\pgfplotmarksize}{.5825\pgfplotmarksize}}{\pgfqpoint{\pgfplotmarksize}{0pt}}
  \pgfpathcurveto{\pgfqpoint{\pgfplotmarksize}{0pt}}{\pgfqpoint{\pgfplotmarksize}{-.75\pgfplotmarksize}}{\pgfqpoint{.5\pgfplotmarksize}{-1.165\pgfplotmarksize}}
  \pgfpathcurveto{\pgfqpoint{.5\pgfplotmarksize}{-1.165\pgfplotmarksize}}{\pgfqpoint{0pt}{-1.66\pgfplotmarksize}}{\pgfqpoint{0pt}{-1.75\pgfplotmarksize}}
  \pgfpathclose
  \pgfusepathqfillstroke
}


\endinput

pgfmathcalc.code.tex
% Copyright 2007 by Mark Wibrow
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

% This file loads all the parsing, functions and operator stuff
%
% Version 1.414213 29/9/2007

\input pgfmathutil.code.tex
\input pgfmathparser.code.tex
\input pgfmathfunctions.code.tex
%\input pgfmathbase.code.tex

% \pgfmathsetlength, \pgfmathaddtolength
%
% #1 = dimension register
% #2 = expression
%
% Description:
%
% These functions work similar to \setlength and \addtolength. Only,
% they allow #2 to contain an expression, which is evaluated before
% assignment. Furthermore, the font is setup before the assignment is
% done, so that dimensions like 1em are evaluated correctly.
%
% If #2 starts with "+", then a simple assignment is done (but the
% font is still setup). This is orders of magnitude faster than a
% parsed assignment.

\def\pgfmathsetlength#1#2{%
  \expandafter\pgfmath@onquick#2\pgfmath@%
  {%
    % Ok, quick version:
    \begingroup%
      \pgfmath@selectfont%
      #1#2\unskip%
    \expandafter\endgroup%
    \expandafter#1\the#1\relax%  
  }%
  {%
    \pgfmathparse{#2}%
    \ifpgfmathmathunitsdeclared%
      #1\pgfmathresult mu\relax%
    \else%
      #1\pgfmathresult pt\relax%
    \fi%
  }%
  \ignorespaces%
}

% \pgfmathaddtolength
%
% Add to #1 the result of evaluating #2.
%
% #1 - a dimension register
% #2 - an expression
%
\def\pgfmathaddtolength#1#2{%
  \expandafter\pgfmath@onquick#2\pgfmath@%
  {%
    \begingroup%
      \pgfmath@selectfont%
      \advance#1#2\unskip%
      \expandafter%
    \endgroup%
    \expandafter#1\the#1\relax%  
  }%
  {%
    \pgfmathparse{#2}%
    \ifpgfmathmathunitsdeclared%
      \advance#1\pgfmathresult mu\relax%
    \else%
      \advance#1\pgfmathresult pt\relax%
    \fi%
  }%
  \ignorespaces%
}

% \pgfmathsetcount
%
% Assign #1 the truncated evaluation of #2.
%
% #1 - a count register
% #2 - an expression
%
\def\pgfmathsetcount#1#2{%
  \expandafter\pgfmath@onquick#2\pgfmath@%
  {%
    \afterassignment\pgfmath@gobbletilpgfmath@%
    #1#2\relax\pgfmath@%
  }%
  {%
    \pgfmathparse{#2}%
    \afterassignment\pgfmath@gobbletilpgfmath@%
    #1\pgfmathresult\relax\pgfmath@%
  }%
  \ignorespaces%
}

% \pgfmathaddtocount
%
% Add to #1 the truncated evaluation of #2.
%
% #1 - a count register
% #2 - an expression
%
\def\pgfmathaddtocount#1#2{%
  \expandafter\pgfmath@onquick#2\pgfmath@%
  {%
    \edef\pgfmath@addtocounttemp{\the#1}%
    \afterassignment\pgfmath@gobbletilpgfmath@%
    #1#2\relax\pgfmath@%
    \advance#1\pgfmath@addtocounttemp\relax%
  }%
  {%
    \edef\pgfmath@addtocounttemp{\the#1}%
    \pgfmathparse{#2}%
    \afterassignment\pgfmath@gobbletilpgfmath@%
    #1\pgfmathresult\relax\pgfmath@%
    \advance#1\pgfmath@addtocounttemp\relax%
  }%
  \ignorespaces%
}

% \pgfmathnewcounter
%
% LaTeX style counter which also works in plain TeX. Defines
% \c@<name> as a count register and also defines \the<name>.
%
% #1 the name of the counter.
%
% Example:
%
% \pgfmathnewcounter{counter}
% \pgfmathsetcounter{counter}{12}
% \thecounter  (same as \the\c@counter)
%
\def\pgfmathnewcounter#1{%
  \expandafter\ifx\csname c@#1\endcsname\relax%
    \def\pgfmath@marshal{\csname newcount\endcsname}% Ha! Who cares about \outer?
    \expandafter\pgfmath@marshal\csname c@#1\endcsname%
    \expandafter\def\csname the#1\endcsname{\expandafter\the\csname c@#1\endcsname}%
  \fi%
}

% \pgfmathsetcounter
%
% Set the counter #1 to the evaluation of #2.
%
% #1 - a counter name
% #2 - an expression
%
\def\pgfmathsetcounter#1#2{%
   \expandafter\pgfmathsetcount\csname c@#1\endcsname{#2}%
}

% \pgfmathaddtocounter
%
% Add the counter #1 to the evaluation of #2.
%
% #1 - a counter name
% #2 - an expression
%
\def\pgfmathaddtocounter#1#2{%
  \expandafter\pgfmathaddtocount\csname c@#1\endcsname{#2}%
}

% \pgfmathmakecounterglobal
%
% Make the current value of a counter globally defined.
%
% #1 - a (valid) counter name.
%
\def\pgfmath@pgftext{pgf}
\def\pgfmath@tikztext{tikz}
\def\pgfmathmakecounterglobal#1{%
  \pgfmath@ifundefined{c@#1}{}{%
    \expandafter\pgfmath@in@\expandafter{\pgfmath@pgftext}{#1}%
    \ifpgfmath@in@%
    \else%
      \expandafter\pgfmath@in@\expandafter{\pgfmath@tikztext}{#1}%
      \ifpgfmath@in@%
      \else%
        \expandafter\global\csname c@#1\endcsname\csname c@#1\endcsname\relax%
      \fi%
    \fi%
  }%
}

% \pgfmathsetmacro
%
% \edef#1 as the result of evaluating #2.
%
% #1 - a macro
% #2 - an expression
%
\def\pgfmathsetmacro#1#2{%
  \begingroup%
    \pgfmathparse{#2}%
	\let#1=\pgfmathresult
    \pgfmath@smuggleone{#1}%
  \endgroup%
}

% \pgfmathsetlengthmacro
%
% \edef#1 as the result of evaluating #2 with pt.
%
% #1 - a macro
% #2 - an expression
%
\def\pgfmathsetlengthmacro#1#2{%
  \begingroup%
    \pgfmathsetlength\pgfmath@x{#2}%
    \edef#1{\the\pgfmath@x}%
    \pgfmath@smuggleone{#1}%
  \endgroup%
}

% \pgfmathtruncatemacro
%
% \edef#1 as the truncated result of evaluating #2.
%
% #1 - a macro
% #2 - an expression
%
\def\pgfmathtruncatemacro#1#2{%
  \begingroup%
    \pgfmathsetcount\c@pgfmath@counta{#2}%
    \edef#1{\the\c@pgfmath@counta}%
    \pgfmath@smuggleone{#1}%
  \endgroup%
}

% Check whether a given parameter starts with quick.
%
% The command should be followed by nonempty text, ending with
% \pgfmath@ as a stop-token. Then should follow
%
% #1 - code to execute if text starts with +
% #2 - code to execute if text does not
%
% Example:
%
% \pgfmath@onquick+0pt\pgfmath@{is quick}{is slow}

\def\pgfmath@onquick{%
  \futurelet\pgfmath@next%
  \pgfmath@@onquick}
\def\pgfmath@@onquick#1\pgfmath@{%
  \ifx\pgfmath@next+%
    \let\pgfmath@next=\pgfmath@firstoftwo%
  \else%
    \let\pgfmath@next=\pgfmath@secondoftwo%
  \fi%
  \pgfmath@next%
}

% *** The following commands DO NOT WORK without the rest of PGF ***
%
% (a dumping ground for stuff that doesn't really belong anywhere else)
  
% \pgfmathanglebetweenpoints
%
% Define \pgfmathresult as the angle between points #1 and #2
% Should get the quadrants right as well.
%
\def\pgfmathanglebetweenpoints#1#2{%
  \begingroup%
    \pgf@process{\pgfpointdiff{#1}{#2}}%
    \edef\pgf@marshall{\expandafter\noexpand\csname pgfmathatan2@\endcsname{\expandafter\Pgf@geT\the\pgf@y}{\expandafter\Pgf@geT\the\pgf@x}}%
    \pgf@marshall%
    \ifdim\pgfmathresult pt<0pt%
      \pgfmathparse{\pgfmathresult+360}%
    \fi%
    \expandafter%
  \endgroup\expandafter\def\expandafter\pgfmathresult\expandafter{\pgfmathresult}%
}

%
% \pgfmathrotatepointaround
%
% Rotate point #1 about point #2 by #3 degrees.
%
\def\pgfmathrotatepointaround#1#2#3{%
  \pgf@process{%
    \pgf@process{#1}%
    \pgf@xc=\pgf@x%
    \pgf@yc=\pgf@y%
    \pgf@process{#2}%
    \pgf@xa\pgf@x%
    \pgf@ya\pgf@y%
    \pgf@xb\pgf@x%
    \pgf@yb\pgf@y%
    \pgf@x=\pgf@xc%
    \pgf@y=\pgf@yc%
    \advance\pgf@x-\pgf@xa%
    \advance\pgf@y-\pgf@ya%
    \pgfmathsetmacro\angle{#3}%
    \pgfmathsin@{\angle}%
    \let\sineangle\pgfmathresult%
    \pgfmathcos@{\angle}%
    \let\cosineangle\pgfmathresult%
    \pgf@xa\cosineangle\pgf@x%
    \advance\pgf@xa-\sineangle\pgf@y%
    \pgf@ya\sineangle\pgf@x%
    \advance\pgf@ya\cosineangle\pgf@y%
    \pgf@x\pgf@xb%
    \pgf@y\pgf@yb%
    \advance\pgf@x\pgf@xa%
    \advance\pgf@y\pgf@ya%
  }%
}

% \pgfmathanglebetweenlines
%
% Calculate the clockwise angle between a line from point #1
% to point #2 and a line from #3 to point #4.
%
\def\pgfmathanglebetweenlines#1#2#3#4{%
  \begingroup%
    \pgfmathanglebetweenpoints{#1}{#2}%
    \let\firstangle\pgfmathresult%
    \pgfmathanglebetweenpoints{#3}{#4}%
    \let\secondangle\pgfmathresult%
    \ifdim\firstangle pt>\secondangle pt\relax%
      \pgfmathadd@{\secondangle}{360}%
      \let\secondangle\pgfmathresult%
    \fi%
    \pgfmathsubtract@{\secondangle}{\firstangle}%
    \pgfmath@smuggleone\pgfmathresult%
  \endgroup%
}

% \pgfmathpointreflectalongaxis
%
% Reflects point #2 around an axis centered on #2 at an angle #3.
%
\def\pgfmathreflectpointalongaxis#1#2#3{%
  \pgf@process{%
    \pgfmathanglebetweenpoints{#2}{#1}%
    \pgfmath@tempdima\pgfmathresult pt\relax%
    \pgfmathparse{#3}%
    \advance\pgfmath@tempdima-\pgfmathresult pt\relax%
    \pgfmath@tempdima-2.0\pgfmath@tempdima%
    \pgfmathrotatepointaround{#1}{#2}{\pgfmath@tonumber{\pgfmath@tempdima}}%
  }%
}



% \pgfmathpointintersectionoflineandarc 
%
% A bit experimental at the moment:
%
% Locates the point where a line crosses an eliptical arc. If the line
% does not cross the arc, a meaningless point will result.
%
% #1 the point of the line on the "convex" side of the arc.
% #2 the point of the line on the "concave" side of the arc.
% #3 the center of the eliptical arc.
% #4 start angle of the arc.
% #5 end angle of the arc.
% #6 radii of the arc.
%
\def\pgfmathpointintersectionoflineandarc#1#2#3#4#5#6{%
  \pgf@process{%
    %
    % Get the required angle.
    %
    \pgfmathanglebetweenpoints{#2}{#1}%
    \let\x\pgfmathresult%
    %
    % Get the radii of the arc.
    %
    \pgfmath@in@{and }{#6}%
    \ifpgfmath@in@%
      \pgf@polar@#6\@@%
    \else%
      \pgf@polar@#6 and #6\@@%
    \fi%
    \edef\xarcradius{\the\pgf@x}%
    \edef\yarcradius{\the\pgf@y}% 
     %
    % Get the start and end angles of the arc...
    % 
    \pgfmathsetmacro\s{#4}%
    \pgfmathsetmacro\e{#5}%
    %
    % ...and also with rounding.
    %
    \pgfmathmod@{\s}{360}%
    \ifdim\pgfmathresult pt<0pt\relax%
      \pgfmathadd@{\pgfmathresult}{360}%
    \fi%
    \let\ss\pgfmathresult%
    \pgfmathmod@{\e}{360}%
    \ifdim\pgfmathresult pt<0pt\relax%
      \pgfmathadd@{\pgfmathresult}{360}%
    \fi%
    \let\ee\pgfmathresult%
    %
    % Hackery for when arc straddles zero.
    %
    \ifdim\ee pt<\ss pt\relax%
      \pgfmathadd@{\x}{180}%
      \pgfmathmod@{\pgfmathresult}{360}%
      \let\x\pgfmathresult%
    \fi%
    \def\m{360}% Measure of nearness.
    \pgfmathadd@{\s}{\e}%
    \pgfmathdivide@{\pgfmathresult}{2}%
    \let\n\pgfmathresult% The best estimate (default to middle of arc).
    \pgfmathloop%
      \pgfmathadd@{\s}{\e}%
      \pgfmathdivide@{\pgfmathresult}{2}%
      \let\p\pgfmathresult%
      \ifdim\p pt=\s pt\relax% 
      \else%
        \pgfmathanglebetweenpoints{#2}{%
          \pgfpointadd{#3}{%
            \pgf@x\xarcradius\relax%
            \pgfmathcos@{\p}%
            \pgf@x\pgfmathresult\pgf@x%
            \pgf@y\yarcradius\relax%
            \pgfmathsin@{\p}%
            \pgf@y\pgfmathresult\pgf@y%
          }%
        }%
        %
        % Hackery for when arc straddles zero.
        %
        \ifdim\ee pt<\ss pt\relax%
          \pgfmathadd@{\pgfmathresult}{180}%
          \pgfmathmod@{\pgfmathresult}{360}%
        \fi%
        \let\q\pgfmathresult%
        %
        % More hackery...
        %
        \ifdim\x pt>335pt\relax%
          \ifdim\q pt<45pt\relax%
            \pgfmathadd@{\q}{360}%
            \let\q\pgfmathresult%
          \fi%
        \fi%
        \ifdim\x pt=\q pt% Found it!
            \pgfmathbreakloop% Breaks after current iteration is complete.
          \else
            \ifdim\x pt<\q pt\relax%
              \let\e\p%
            \else%
              \let\s\p%
            \fi%
          \fi%
          \pgfmathsubtract@{\x}{\q}%
          \pgfmathabs@{\pgfmathresult}%
          %
          % Save the estimate if it is better than any previous estimate.
          %
          \ifdim\pgfmathresult pt<\m pt\relax%
            \let\m\pgfmathresult%
            \let\n\p%
          \fi%        
    \repeatpgfmathloop%
    \pgfpointadd{#3}{\pgfpointpolar{\n}{\xarcradius and \yarcradius}}%
  }%
}

% \pgfmathangleonellipse
% 
% Find the angle corresponding to a point on the border of an ellispe.
%
% #1 - the point on the border.
% #2 - the radii of the ellipse.
%
\def\pgfmathangleonellipse#1#2{%
  \begingroup%
    \pgfmath@in@{and }{#2}%
    \ifpgfmath@in@%
      \pgf@polar@#2\@@%
    \else%
      \pgf@polar@#2 and #2\@@%
    \fi%
    \pgf@xa\pgf@x%
    \pgf@ya\pgf@y%
    \pgf@process{#1}% 
    \ifdim\pgf@x=0pt\relax%
      \pgfutil@tempdima1pt\relax%
    \else%
      \pgfutil@tempdima\pgf@x%
      \pgfmathdivide@{\pgfmath@tonumber{\pgf@xa}}{\pgfmath@tonumber{\pgfutil@tempdima}}%
      \pgfutil@tempdima\pgfmathresult pt\relax%
    \fi%
    \ifdim\pgf@y=0pt\relax%
      \pgfutil@tempdima1pt\relax%
    \else%
      \pgfmathdivide@{\pgfmath@tonumber{\pgf@y}}{\pgfmath@tonumber{\pgf@ya}}%
      \pgfutil@tempdima\pgfmathresult\pgfutil@tempdima%
      \pgfmathatan@{\pgfmath@tonumber{\pgfutil@tempdima}}%
    \fi%
    %
    \pgfutil@tempdima\pgfmathresult pt\relax%
    \ifdim\pgfutil@tempdima<0pt\relax%
      \advance\pgfutil@tempdima360pt\relax%
    \fi%
    \ifdim\pgf@x<0pt\relax%
      \ifdim\pgf@y=0pt\relax%
        \pgfutil@tempdima180pt\relax%
      \else%
        \ifdim\pgf@y<0pt\relax%
          \advance\pgfutil@tempdima180pt\relax%
        \else%
          \advance\pgfutil@tempdima-180pt\relax%
        \fi%
      \fi%
    \else%
      \ifdim\pgf@x=0pt\relax%
        \ifdim\pgf@y<0pt\relax%
          \pgfutil@tempdima270pt\relax%
        \else%
          \pgfutil@tempdima90pt\relax%
        \fi%
      \else%
        \ifdim\pgf@y=0pt\relax%
          \pgfutil@tempdima0pt\relax%
        \fi%
      \fi%        
    \fi%
    \pgfmath@returnone\pgfutil@tempdima%
  \endgroup%
}


% Local Variables:
% tab-width: 2
% End:

pgfmath.code.tex
% Copyright 2007 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ifx\pgfmathsetlength\undefined
\else
  \expandafter\endinput
\fi

\input pgfmathcalc.code.tex

\ifx\pgfkeysloaded\undefined
  \let\pgfkeysloaded=\relax
\else
  \expandafter\input pgfmathfloat.code.tex
\fi

\endinput
pgfmathfloat.code.tex
% Copyright 2008 by Christian Feuersaenger
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.
%
% This file contains methods for basic floating point arithmetics, rounding
% to arbitrary precision and number pretty printing.
%


\pgfkeys{
	% The bug 3430171 (wrong minus sign spacing in pgfmathprintnumber)
	% has been fixed in 2.10 CVS. Since it changes the spacing, its
	% effects can be undone with this compatibility switch.
	/pgf/compat/number printer/.is choice,
	/pgf/compat/number printer/2.10/.code={%
		\def\pgfmathprintnumber@begingroup{\bgroup}%
		\def\pgfmathprintnumber@endgroup{\egroup}%
	},
	% I do not know the version number of the next release at this
	% time. Please be so kind and KEEP THIS NAME INTACT. Add an alias
	% if needed.
	/pgf/compat/number printer/next after 2.10/.code={%
		\def\pgfmathprintnumber@begingroup{\begingroup}%
		\def\pgfmathprintnumber@endgroup{\endgroup}%
	},
	% activate the fix by default.
	/pgf/compat/number printer/next after 2.10,%
}


\global\newif\ifpgfmathfloatcomparison
\newif\ifpgfmathfloatroundhasperiod
\newif\ifpgfmathprintnumberskipzeroperiod


% used internally in grouped macros:
\toksdef\pgfmathfloat@tmptoks=1
\newif\ifpgfmathfloat@fixed@digits@after@period
\newif\ifpgfmathfloatroundmayneedrenormalize
\toksdef\pgfmathfloat@a@Mtok=0

%% WARNING: avoid conflicting register names!
\let\pgfmathfloat@a@S=\c@pgf@counta
\let\pgfmathfloat@a@M=\pgf@xa
\let\pgfmathfloat@a@E=\c@pgf@countb
\let\pgfmathfloat@b@S=\c@pgf@countc
\let\pgfmathfloat@b@M=\pgf@xb
\let\pgfmathfloat@b@E=\c@pgf@countd

% can be changed with options.
\def\pgfmathfloat@round@precision{2}

% I introduced this to acces the "original" precision in case a
% formatted changes it locally... in this case, the formatter may
% overwrite \pgfmathfloat@round@precision@orig to provide the original
% one.
% The default implementation here does nothing:
\def\pgfmathfloat@round@precision@orig{\pgfmathfloat@round@precision}%

\gdef\pgfmathfloat@glob@TMP{}


% Computes a normalised floating point representation for #1 of the
% form
%   [FLAGS] MANTISSE EXPONENT
% meaning
%   [+-]X.XXXXXXX*10^C
% where 
%   X.XXXXXX is a mantissa with first number != 0, C is an integer and
% FLAGS contains the sign and some other special cases.
%
% This method does NOT use TeX Registers to represent the numbers! The
% computation is COMPLETELY STRING BASED.
% This allows numbers such at 10000000 or 5.23e-10 to be represented
% properly, although TeX-registers would produce overflow/underflow
% errors in these cases. 
%
% It is to be used to compute logs, because log(X*10^Y) = log(X) + log(10)*Y
%
% Arguments:
% #1:  an arbitrary number which shall be parsed. Maybe a macro.
%     Examples:
%     [+-]XXXXX.XXXXXX
%     [+-]XXXXX.XXXXXXeXXXX
%     [+-]0.0000XXXXXX
%     [+-]0.0000XXXXXXeXXXX
%     [+-]inf
%     nan
%    Maybe a macro containing such a number.
%
% Return value:
% \pgfmathresult will be \def'ed to
%  FLAGS MANTISSE 'e' EXPONENT
% where
% FLAGS is a number in [0-5] where
% 		0 == '0' (the number is +- 0.0),
% 		1 == '+', 
% 		2 == '-',
% 		3 == 'not a number'
% 		4 == '+ infinity'
% 		5 == '- infinity'
%
% MANTISSE is a normalised number 1 <= M < 10. It always contains a
% period and at least one digit after the period.
%
% EXPONENT is an integer value.
%
% Example:
% \pgfmathfloatparsenumber{1}
% -> \pgfmathresult = 11.0e0
% \pgfmathfloatparsenumber{141.212}
% -> \pgfmathresult = 11.41212e2
\def\pgfmathfloatparsenumber#1{%
	\begingroup
	\edef\pgfmathresult{#1}%
	\expandafter\pgfflt@impl\pgfmathresult\pgfflt@EOI
	\ifpgfmathfloatparsenumberpendingperiod
		\pgfmathfloat@a@Mtok=\expandafter{\the\pgfmathfloat@a@Mtok.0}%
	\fi
	\pgfmathfloatcreate{\the\pgfmathfloat@a@S}{\the\pgfmathfloat@a@Mtok}{\the\pgfmathfloat@a@E}%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}

% The same as \pgfmathfloatparsenumber, but does not perform sanity checking.
% FIXME: there is no longer any difference here.
\let\pgfmathfloatqparsenumber=\pgfmathfloatparsenumber

% Takes a floating point number #1 as input and writes flags to count
% register #2, mantissa to dimen register #3 and exponent to count
% register #4.
\def\pgfmathfloattoregisters#1#2#3#4{%
	\expandafter\pgfmathfloat@decompose#1\relax{#2}{#3}{#4}%
}

% the same, but writes the mantissa into a token register.
\def\pgfmathfloattoregisterstok#1#2#3#4{%
	\expandafter\pgfmathfloat@decompose@tok#1\relax{#2}{#3}{#4}%
}

% Extracts the flags of #1 into the count register #2.
\def\pgfmathfloatgetflags#1#2{%
	\expandafter\pgfmathfloat@decompose@F#1\relax{#2}%
}
% Extracts the flags of #1 into the macro #2.
\def\pgfmathfloatgetflagstomacro#1#2{%
	\expandafter\pgfmathfloat@decompose@Fmacro#1\relax{#2}%
}%

% Extracts the mantissa of #1 into the dimen register #2.
\def\pgfmathfloatgetmantissa#1#2{%
	\expandafter\pgfmathfloat@decompose@M#1\relax{#2}%
}
\let\pgfmathfloatgetmantisse=\pgfmathfloatgetmantissa
% Extracts the mantissa of #1 into the token register #2.
\def\pgfmathfloatgetmantissatok#1#2{%
	\expandafter\pgfmathfloat@decompose@Mtok#1\relax{#2}%
}
\let\pgfmathfloatgetmantissetok=\pgfmathfloatgetmantissatok
% Extracts the exponent of #1 into the count register #2.
\def\pgfmathfloatgetexponent#1#2{%
	\expandafter\pgfmathfloat@decompose@E#1\relax{#2}%
}


% Assigns \pgfmathresult to be a float encoded as
% <FLAGS><MANTISSE>e<EXPONENT>
%
% example:
% \pgfmathfloatcreate{1}{2.0}{10}
% \pgfmathfloat@to@FMeE@style\pgfmathresult
% ->
% \pgfmathresult is now '12.0e10' regardless of the internal float
% format.
\def\pgfmathfloat@to@FMeE@style#1{\expandafter\pgfmathfloat@to@FMeE@style@#1\relax\relax}%
\def\pgfmathfloat@to@FMeE@style@#1#2{%
	\ifx#2Y%
		\expandafter\pgfmathfloat@to@FMeE@style@@%
	\else
		\expandafter\pgfmathfloat@to@FMeE@style@error%
	\fi
	#1#2%
}%
\def\pgfmathfloat@to@FMeE@style@@#1Y#2e#3]\relax\relax{\def\pgfmathresult{#1#2e#3}}%
\def\pgfmathfloat@to@FMeE@style@error#1\relax\relax{%
	\begingroup
	\pgfmathfloatparsenumber@handleerror{wrong lowlevel format}{#1}{#1}%
	\xdef\pgfmathfloat@decompose@TMP{%
		\noexpand\pgfmathfloatcreate{\the\pgfmathfloat@a@S}{\the\pgfmathfloat@a@Mtok}{\the\pgfmathfloat@a@E}%
	}%
	\endgroup
	\pgfmathfloat@decompose@TMP
}%


% decomposes a lowlevel floating point representation into flags,
% mantissa and exponent.
%
% #4: integer register for the flags.
% #5: dimen registers for the mantissa.
% #6: integer register for the exponent.
%
% \expandafter\pgfmathfloat@decompose\pgfmathresult\relax\pgfmathfloat@a@S\pgfmathfloat@a@M\pgfmathfloat@a@E
% -> the three temp registers contain flags, mantissa and exponent
\def\pgfmathfloat@decompose#1#2{% sanitize!
	\ifx#2Y%
		\expandafter\pgfmathfloat@decompose@%
	\else
		\expandafter\pgfmathfloat@decompose@error%
	\fi
	#1#2%
}
\def\pgfmathfloat@decompose@#1Y#2e#3]\relax#4#5#6{%
   #4=#1\relax
   #5=#2pt % keep space here.
   #6=#3\relax%
}

% overloaded, #5 needs to be a token register for the mantissa.
% @see also \pgfmathfloatvalueof  which does also employ the load
% level repr.
% \expandafter\pgfmathfloat@decompose@tok\pgfmathresult\relax\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
% -> the three temp registers contain flags, mantissa and exponent
\def\pgfmathfloat@decompose@tok#1#2{%
	\ifx#2Y%
		\expandafter\pgfmathfloat@decompose@tok@%
	\else
		\expandafter\pgfmathfloat@decompose@tok@error%
	\fi
	#1#2%
}%
\def\pgfmathfloat@decompose@tok@#1Y#2e#3]\relax#4#5#6{%
   #4=#1\relax
   #5={#2}%
   #6=#3\relax%
}
% overloaded, returns only ONE of the three components into #4:
% \expandafter\pgfmathfloat@decompose@tok\pgfmathresult\relax\pgfmathfloat@a@S
% -> \pgfmathfloat@a@S contains the flags field.
\def\pgfmathfloat@decompose@F#1#2{%
	\ifx#2Y%
		\expandafter\pgfmathfloat@decompose@F@%
	\else
		\expandafter\pgfmathfloat@decompose@F@error%
	\fi
	#1#2%
}%
\def\pgfmathfloat@decompose@Fmacro#1#2{%
	\ifx#2Y%
		\expandafter\pgfmathfloat@decompose@Fmacro@%
	\else
		\expandafter\pgfmathfloat@decompose@F@error%
	\fi
	#1#2%
}%
\def\pgfmathfloat@decompose@M#1#2{%
	\ifx#2Y%
		\expandafter\pgfmathfloat@decompose@M@%
	\else
		\expandafter\pgfmathfloat@decompose@M@error%
	\fi
	#1#2%
}%
\def\pgfmathfloat@decompose@E#1#2{%
	\ifx#2Y%
		\expandafter\pgfmathfloat@decompose@E@%
	\else
		\expandafter\pgfmathfloat@decompose@E@error%
	\fi
	#1#2%
}%
\def\pgfmathfloat@decompose@Mtok#1#2{%
	\ifx#2Y%
		\expandafter\pgfmathfloat@decompose@Mtok@%
	\else
		\expandafter\pgfmathfloat@decompose@Mtok@error%
	\fi
	#1#2%
}%
\def\pgfmathfloat@decompose@F@#1Y#2e#3]\relax#4{#4=#1\relax}%
\def\pgfmathfloat@decompose@Fmacro@#1Y#2e#3]\relax#4{\def#4{#1}}%
\def\pgfmathfloat@decompose@M@#1Y#2e#3]\relax#4{#4=#2pt}%
\def\pgfmathfloat@decompose@Mtok@#1Y#2e#3]\relax#4{#4={#2}}%
\def\pgfmathfloat@decompose@E@#1Y#2e#3]\relax#4{#4=#3\relax}%

\def\pgfmathfloat@decompose@error#1\relax#2#3#4{%
	\begingroup
	\pgfmathfloatparsenumber@handleerror{wrong lowlevel format}{#1}{#1}%
	\xdef\pgfmathfloat@decompose@TMP{%
		\noexpand#2=\the\pgfmathfloat@a@S\space
		\noexpand#3=\the\pgfmathfloat@a@Mtok pt
		\noexpand#4=\the\pgfmathfloat@a@E\space
	}%
	\endgroup
	\pgfmathfloat@decompose@TMP
}%
\def\pgfmathfloat@decompose@tok@error#1\relax#2#3#4{%
	\begingroup
	\pgfmathfloatparsenumber@handleerror{wrong lowlevel format}{#1}{#1}%
	\xdef\pgfmathfloat@decompose@TMP{%
		\noexpand#2=\the\pgfmathfloat@a@S\space
		\noexpand#3={\the\pgfmathfloat@a@Mtok}%
		\noexpand#4=\the\pgfmathfloat@a@E\space
	}%
	\endgroup
	\pgfmathfloat@decompose@TMP
}%
\def\pgfmathfloat@decompose@F@error#1\relax#2{%
	\begingroup
	\pgfmathfloatparsenumber@handleerror{wrong lowlevel format}{#1}{#1}%
	\xdef\pgfmathfloat@decompose@TMP{\noexpand#2=\the\pgfmathfloat@a@S\space}%
	\endgroup
	\pgfmathfloat@decompose@TMP
}%
\def\pgfmathfloat@decompose@M@error#1\relax#2{%
	\begingroup
	\pgfmathfloatparsenumber@handleerror{wrong lowlevel format}{#1}{#1}%
	\xdef\pgfmathfloat@decompose@TMP{\noexpand#2=\the\pgfmathfloat@a@Mtok pt }%
	\endgroup
	\pgfmathfloat@decompose@TMP
}%
\def\pgfmathfloat@decompose@Mtok@error#1\relax#2{%
	\begingroup
	\pgfmathfloatparsenumber@handleerror{wrong lowlevel format}{#1}{#1}%
	\xdef\pgfmathfloat@decompose@TMP{\noexpand#2={\the\pgfmathfloat@a@Mtok}}%
	\endgroup
	\pgfmathfloat@decompose@TMP
}%
\def\pgfmathfloat@decompose@E@error#1\relax#2{%
	\begingroup
	\pgfmathfloatparsenumber@handleerror{wrong lowlevel format}{#1}{#1}%
	\xdef\pgfmathfloat@decompose@TMP{\noexpand#2=\the\pgfmathfloat@a@E\space}%
	\endgroup
	\pgfmathfloat@decompose@TMP
}%
% Takes a floating point number #1 as input and writes flags to macro
% #2, mantissa to macro #3 and exponent to macro #4.
\def\pgfmathfloattomacro#1#2#3#4{%
	\begingroup
	\expandafter\pgfmathfloat@decompose@tok#1\relax\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
	\xdef\pgfmathfloat@glob@TMP{%
		\noexpand\def\noexpand#2{\the\pgfmathfloat@a@S}%
		\noexpand\def\noexpand#3{\the\pgfmathfloat@a@Mtok}%
		\noexpand\def\noexpand#4{\the\pgfmathfloat@a@E}%
	}%
	\endgroup
	\pgfmathfloat@glob@TMP
}


% Defines \pgfmathresult as the floating point number encoded by
% the flags #1, mantissa #2 and exponent #3.
%
% All arguments are characters and will be expanded using '\edef'.
\def\pgfmathfloatcreate#1#2#3{%
	\edef\pgfmathresult{#1Y#2e#3]}%
}%
% This is the character present in any low-level floating point
% number. It is assumed to be the SECOND character of a float (after
% the flags integer).
\def\pgfmathfloat@POSTFLAGSCHAR{Y}



% Converts a composed floating point representation to fixed point.
%
% Example:
% \pgfmathfloattofixed{142e1}
% -> \pgfmathresult = 42.0
\def\pgfmathfloattofixed@#1{%
	\begingroup
	\expandafter\pgfmathfloat@decompose@tok#1\relax\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
	\ifcase\pgfmathfloat@a@S
		\def\pgfmathresult{0.0}%
	\or
		\expandafter\pgfmathfloattofixed@impl\the\pgfmathfloat@a@Mtok\relax
	\or
		\expandafter\pgfmathfloattofixed@impl\the\pgfmathfloat@a@Mtok\relax
		\pgfmathfloat@a@Mtok=\expandafter{\pgfmathresult}%
		\edef\pgfmathresult{-\the\pgfmathfloat@a@Mtok}%
	\or\def\pgfmathresult{nan}%
	\or\def\pgfmathresult{inf}%
	\or\def\pgfmathresult{-inf}%
	\fi
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}
\let\pgfmathfloattofixed=\pgfmathfloattofixed@

% Converts a float to an integer (in integer format).
%
% @see \pgfmathfloatint 
\def\pgfmathfloattoint#1{%
	\pgfmathfloattofixed{#1}%
	\expandafter\pgfmathfloattoint@@\pgfmathresult\relax
}%
\def\pgfmathfloattoint@@#1.#2\relax{%
	\def\pgfmathresult{#1}%
}%

% Converts a floating point number to scientific format 1.234e5.
%
% This operation is very fast.
\def\pgfmathfloattosci@#1{%
	\begingroup
	\expandafter\pgfmathfloat@decompose@tok#1\relax\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
	\ifcase\pgfmathfloat@a@S
		\def\pgfmathresult{0.0e0}%
	\or
		\edef\pgfmathresult{\the\pgfmathfloat@a@Mtok e\the\pgfmathfloat@a@E}%
	\or
		\edef\pgfmathresult{-\the\pgfmathfloat@a@Mtok e\the\pgfmathfloat@a@E}%
	\or\def\pgfmathresult{nan}%
	\or\def\pgfmathresult{inf}%
	\or\def\pgfmathresult{-inf}%
	\fi
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%
\let\pgfmathfloattosci=\pgfmathfloattosci@

% Expands a floating point number to scientific format 1.234e5.
%
% This operation is very fast.
\def\pgfmathfloatvalueof#1{\expandafter\pgfmathfloatvalueof@@#1\relax}%
\def\pgfmathfloatvalueof@@#1Y#2e#3]\relax{%
	\ifcase#1 %
		0.0e0%
	\or
		#2e#3%
	\or
		-#2e#3%
	\or nan%
	\or inf%
	\or -inf%
	\fi
}%


% Rounds a fixed point number #1 to \pgfmathfloat@round@precision digits precision and returns
% the result into \pgfmathresult.
%
% Any trailing zeros after the period are discarded.
% See \pgfmathroundtozerofill if you want trailing zeros and fixed
% width.
%
% This method is PURELY text based and can work with arbirtrary
% precision (well, limited to TeX's stack size and integer size).
%
% Examples:
% \pgfmathroundto{1}
% -> \pgfmathresult = '1'
%
% \pgfmathroundto{19999.9996}
% -> \pgfmathresult = '20000'
%
% Arguments:
% #1 may be either a number or a macro (\pgfmathresult is allowed) expanding to a number.
%
% SIDE EFFECT: the global variable \ifpgfmathfloatroundhasperiod will be set.
\def\pgfmathroundto#1{%
	\pgfmathfloatroundhasperiodtrue
	\begingroup
	\pgfmathfloat@fixed@digits@after@periodfalse
	\pgfmathroundto@impl{#1}%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}


% Overloaded method. 
%
% This variant always uses a FIXED number behind the period and fills
% in zeros if necessary.
% Examples:
% \pgfmathroundtozerofill{1}
% -> \pgfmathresult = '1.00'
%
% \pgfmathroundtozerofill{19999.9996}
% -> \pgfmathresult = '20000.00'
%
% SIDE EFFECT: the global variable \ifpgfmathfloatroundhasperiod will be set.
\def\pgfmathroundtozerofill#1{%
	\pgfmathfloatroundhasperiodtrue
	\begingroup
	\pgfmathfloat@fixed@digits@after@periodtrue
	\pgfmathroundto@impl{#1}%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}

% see \pgfmathprintnumber@fixed@style for docs
\def\pgfmathprintnumber@fixed@styleDEFAULT#1#2#3e#4\relax{%
	\begingroup
	\pgfkeysgetvalue{/pgf/number format/set decimal separator}\pgfmathprintnumber@fixed@styleDEFAULT@DEC@SEP
	\pgfkeysgetvalue{/pgf/number format/@dec sep mark}\pgfmathprintnumber@fixed@styleDEFAULT@DEC@SEP@MARK
	\pgfkeysgetvalue{/pgf/number format/set thousands separator}\pgfmathprintnumber@fixed@styleDEFAULT@THOUSAND@SEP
	\c@pgf@counta=#4\relax % it is the exponent here.
	\ifnum#2=0
		\c@pgf@counta=0
	\fi
	\def\pgfmathresult{}%
	\ifpgfmathfloatroundhasperiod
		\expandafter\pgfmathprintnumber@fixed@styleDEFAULT@impl@period#1\pgfmathfloat@EOI
	\else
		\expandafter\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod#1\pgfmathfloat@EOI\pgfmathfloat@EOI\pgfmathfloat@EOI%
		\begingroup
		\toks0=\expandafter{\pgfmathresult}%
		\toks1=\expandafter{\pgfmathprintnumber@fixed@styleDEFAULT@DEC@SEP@MARK}%
		\xdef\pgfmathfloat@glob@TMP{\the\toks0 \the\toks1 }%
		\endgroup
		\let\pgfmathresult=\pgfmathfloat@glob@TMP
	\fi
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}
\def\pgfmathprintnumber@fixed@styleDEFAULT@impl@period#1.#2\pgfmathfloat@EOI{%
	\ifpgfmathprintnumberskipzeroperiod
		\def\pgfmathfloat@loc@TMPb{#1}%
		\ifx\pgfmathfloatparsenumber@tok@ZERO\pgfmathfloat@loc@TMPb
		\else
			\def\pgfmathfloat@loc@TMPc{-0}%
			\ifx\pgfmathfloat@loc@TMPc\pgfmathfloat@loc@TMPb
				\def\pgfmathresult{-}%
			\else
				\def\pgfmathfloat@loc@TMPc{+0}%
				\ifx\pgfmathfloat@loc@TMPc\pgfmathfloat@loc@TMPb
					\def\pgfmathresult{+}%
				\else
					\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod#1\pgfmathfloat@EOI\pgfmathfloat@EOI\pgfmathfloat@EOI
				\fi
			\fi
		\fi
	\else
		\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod#1\pgfmathfloat@EOI\pgfmathfloat@EOI\pgfmathfloat@EOI
	\fi
	\ifpgfmathprintnumber@thousand@sep@in@fractional
		\let\pgfmathresultfractional\pgfutil@empty%
		\pgfmathprintnumber@thousand@sep@in@fractional#2MMMM\@@
	\else
		\def\pgfmathresultfractional{#2}%
	\fi
	\begingroup
	\toks0=\expandafter{\pgfmathresult}%
	\toks1=\expandafter{\pgfmathprintnumber@fixed@styleDEFAULT@DEC@SEP@MARK}%
	\toks2=\expandafter{\pgfmathprintnumber@fixed@styleDEFAULT@DEC@SEP}%
	\toks3=\expandafter{\pgfmathresultfractional}%
	\xdef\pgfmathfloat@glob@TMP{\the\toks0 \the\toks1 \the\toks2 \the\toks3 }%
	\endgroup
	\let\pgfmathresult=\pgfmathfloat@glob@TMP
}%

% assigns \pgfmathresult such that it contains the formatted result.
% It assumes that none of the following tokens contains a period.
\def\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod{%
	\ifx\pgfmathprintnumber@fixed@styleDEFAULT@THOUSAND@SEP\pgfutil@empty
		\def\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@NEXT{%
			\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@printall}%
	\else
		\ifnum\c@pgf@counta<0\relax % exponent of the number in this context
			\def\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@NEXT{%
				\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@printall}%
		\else
			\ifnum\c@pgf@counta<\pgfkeysvalueof{/pgf/number format/min exponent for 1000 sep}\relax
				\def\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@NEXT{%
					\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@printall}%
			\else
				\advance\c@pgf@counta by1 % counta:= total number of digits, N.
				\c@pgf@countb=\c@pgf@counta
				\divide\c@pgf@countb by3 %  countb := N DIV 3
				\c@pgf@countc=\c@pgf@countb
				\multiply\c@pgf@countc by3
				\advance\c@pgf@counta by-\c@pgf@countc% now counta := N MOD 3
				\def\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@NEXT{%
					\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@printsign
				}%
			\fi
		\fi
	\fi
	\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@NEXT
}
\def\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@printsign#1{%
	\def\pgfmathfloat@loc@TMPb{#1}%
	\ifx\pgfmathfloat@loc@TMPb\pgfmathfloatparsenumber@tok@MINUS
		\expandafter\def\expandafter\pgfmathresult\expandafter{\pgfmathresult #1}%
		\let\pgfmathfloat@loc@TMPb=\pgfutil@empty
	\else
		\ifx\pgfmathfloat@loc@TMPb\pgfmathfloatparsenumber@tok@PLUS
			\expandafter\def\expandafter\pgfmathresult\expandafter{\pgfmathresult #1}%
			\let\pgfmathfloat@loc@TMPb=\pgfutil@empty
		\else
			\ifpgfmathprintnumber@showpositive
				\expandafter\def\expandafter\pgfmathresult\expandafter{\pgfmathresult +}%
			\fi
		\fi
	\fi
	\ifnum\c@pgf@counta>0 % \c@pgf@counta = N MOD 3 in this context
		\def\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@NEXT{%
			\expandafter\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@printtrailingdigits\pgfmathfloat@loc@TMPb
		}%
	\else
		\def\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@NEXT{%
			\expandafter\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@counteverythird\pgfmathfloat@loc@TMPb
		}%
	\fi
	\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@NEXT
}
\def\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@printtrailingdigits#1#2{%
	\ifcase\c@pgf@counta % = N MOD 3 in this context
		% does not happen per construction
	\or
		\expandafter\def\expandafter\pgfmathresult\expandafter{\pgfmathresult #1}%
		\def\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@NEXT{%
			\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@counteverythird#2%
		}%
	\or
		\expandafter\def\expandafter\pgfmathresult\expandafter{\pgfmathresult #1#2}%
		\def\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@NEXT{%
			\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@counteverythird%
		}%
	\fi
	\ifnum\c@pgf@countb>0\relax % \c@pgf@countb = N DIV 3 in this context
		\begingroup
		\toks0=\expandafter{\pgfmathresult}%
		\toks1=\expandafter{\pgfmathprintnumber@fixed@styleDEFAULT@THOUSAND@SEP}%
		\xdef\pgfmathfloat@glob@TMP{\the\toks0 \the\toks1 }%
		\endgroup
		\let\pgfmathresult=\pgfmathfloat@glob@TMP
	\fi
	\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@NEXT
}
\def\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@counteverythird#1#2#3{%
	\ifnum\c@pgf@countb>0\relax
		\expandafter\def\expandafter\pgfmathresult\expandafter{\pgfmathresult #1#2#3}%
		\advance\c@pgf@countb by-1
		\ifnum\c@pgf@countb>0\relax
			\begingroup
			\toks0=\expandafter{\pgfmathresult}%
			\toks1=\expandafter{\pgfmathprintnumber@fixed@styleDEFAULT@THOUSAND@SEP}%
			\xdef\pgfmathfloat@glob@TMP{\the\toks0 \the\toks1 }%
			\endgroup
			\let\pgfmathresult=\pgfmathfloat@glob@TMP
		\fi
		\def\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@NEXT{%
			\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@counteverythird%
		}%
	\else
		% in thise case, #1#2#3 are expected to be
		% \pgfmathfloat@EOI\pgfmathfloat@EOI\pgfmathfloat@EOI
		%--------------------------------------------------
		% \def\pgfmathfloat@loc@TMPb{\pgfmathfloat@EOI\pgfmathfloat@EOI\pgfmathfloat@EOI}%
		% \def\pgfmathfloat@loc@TMPc{#1#2#3}%
		% \ifx\pgfmathfloat@loc@TMPc\pgfmathfloat@loc@TMPb
		% \else
		% 	\pgfmath@error{INTERNAL ERROR in fixed style - The input sequence did not terminate as expected; which indicates a wrong exponent argument provided to \string\pgfmathprintnumber@fixed@style}{}%
		% \fi
		%-------------------------------------------------- 
		\let\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@NEXT=\relax
	\fi
	\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@NEXT
}

% \pgfmathprintnumber@thousand@sep@in@fractional 01234525MMMM\@@
% ->
% 012<sep>345<sep>25
\def\pgfmathprintnumber@thousand@sep@in@fractional#1#2#3#4{%
	\if#4M%
		% Ok, no further separator
		\def\pgfmathprint@next{\pgfmathprintnumber@thousand@sep@in@fractional@finish#1#2#3#4}%
	\else
		\begingroup
		\toks0=\expandafter{\pgfmathresultfractional}%
		\toks1={#1#2#3}%
		\toks2=\expandafter{\pgfmathprintnumber@fixed@styleDEFAULT@THOUSAND@SEP}%
		\xdef\pgfmathfloat@glob@TMP{\the\toks0 \the\toks1 \the\toks2 }%
		\endgroup
		\let\pgfmathresultfractional=\pgfmathfloat@glob@TMP
		\def\pgfmathprint@next{\pgfmathprintnumber@thousand@sep@in@fractional#4}%
	\fi
	\pgfmathprint@next
}%
\def\pgfmathprintnumber@thousand@sep@in@fractional@finish#1M{%
	\expandafter\def\expandafter\pgfmathresultfractional\expandafter{\pgfmathresultfractional #1}%
	\pgfmathprintnumber@thousand@sep@in@fractional@finish@
}%
\def\pgfmathprintnumber@thousand@sep@in@fractional@finish@#1\@@{}%

\def\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@printall#1{%
	\def\pgfmathfloat@loc@TMPb{#1}%
	\let\pgfmathfloat@loc@TMPc=\pgfutil@empty
	\ifx\pgfmathfloat@loc@TMPb\pgfmathfloatparsenumber@tok@MINUS
	\else
		\ifx\pgfmathfloat@loc@TMPb\pgfmathfloatparsenumber@tok@PLUS
		\else
			\ifpgfmathprintnumber@showpositive
				\def\pgfmathfloat@loc@TMPc{+}%
			\fi
		\fi
	\fi
	\expandafter\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@printall@\pgfmathfloat@loc@TMPc#1%
}
\def\pgfmathprintnumber@fixed@styleDEFAULT@impl@noperiod@printall@#1\pgfmathfloat@EOI\pgfmathfloat@EOI\pgfmathfloat@EOI{%
	\expandafter\def\expandafter\pgfmathresult\expandafter{\pgfmathresult #1}%
}%

% @deprecated. It has been replaced by \pgfmathprintnumber@fixed@styleDEFAULT
% #1 maybe a macro
\def\pgfmathprintnumber@fixed@stylePERIOD#1#2#3e#4\relax{%
	\def\pgfmathresult{#1}%
}

% @deprecated. It has been replaced by \pgfmathprintnumber@fixed@styleDEFAULT
% #1 maybe a macro
\def\pgfmathprintnumber@fixed@styleCOMMA#1#2#3e#4\relax{%
	\ifpgfmathfloatroundhasperiod
		\expandafter\pgfmathprintnumber@fixed@styleCOMMA@impl#1\pgfmathfloat@EOI
	\else
		\def\pgfmathresult{#1}%
	\fi
}
\def\pgfmathprintnumber@fixed@styleCOMMA@impl#1.#2\pgfmathfloat@EOI{\def\pgfmathresult{#1{,}#2}}

% The default style to display fixed point numbers.
%
% It does not apply numerics, but it is responsable for typesetting the
% rounded number.
% It can access the \ifpgfmathfloatroundhasperiod boolean.
%
% Arguments:
% #1#2#3e#4\relax

% Input: 
% #1  the fixed point number to be displayed (maybe a macro).
% #2#3e#4:  the (possibly unformatted) floating point representation
%     which belongs to #1. This format is returned (only!) by
%     \pgfmathfloat@to@FMeE@style.
%     It is used to determine sign and exponent.
\let\pgfmathprintnumber@fixed@style=\pgfmathprintnumber@fixed@styleDEFAULT


% Rounds a normalized floating point number to \pgfmathfloat@round@precision 
% digits precision and writes the result to \pgfmathresult.
%
% This method uses \pgfmathroundto for the mantissa.
%
% @see pgfmathfloatroundzerofill
%
% SIDE EFFECT: the global variable \ifpgfmathfloatroundhasperiod will be set to
% whether the final mantissa #5 has a period or not.
\def\pgfmathfloatround#1{%
	\pgfmathfloatroundhasperiodtrue
	\begingroup
	\pgfmathfloat@fixed@digits@after@periodfalse
	\expandafter\pgfmathfloat@decompose@tok#1\relax\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
	\pgfmathfloatround@impl
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}

% Overload.
%
% This method uses a fixed width for the mantissa and fills in zeros
% if necessary.
%
% This method uses \pgfmathroundtozerofill for the mantissa.
%
% SIDE EFFECT: the global variable \ifpgfmathfloatroundhasperiod will be set to
% whether the final mantissa #5 has a period or not.
\def\pgfmathfloatroundzerofill#1{%
	\pgfmathfloatroundhasperiodtrue
	\begingroup
	\pgfmathfloat@fixed@digits@after@periodtrue
	\expandafter\pgfmathfloat@decompose@tok#1\relax\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
	\pgfmathfloatround@impl
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}

\newif\ifpgfmathfloatround@allow@empty@mantissa
\def\pgfmathfloatround@mantissa@ONE{1.0}%

% #1: sign
% #2: mantissa
% #3: exponent
% #4: CODE to display if the mantissa is drawn.
% 	This code will be shown just before the exponent. 
% 	Example: #4=\cdot
% #5: CODE to display if the mantissa is NOT draw. (unused currently)
% 	Might be used to display '10^1' instead of '1*10^1'.
% #6: CODE to display the exponent.
\def\pgfmathfloatrounddisplaystyle@shared@impl#1#2e#3\relax#4#5#6{%
	\pgfkeysgetvalue{/pgf/number format/@sci exponent mark}\pgfmathfloatrounddisplaystyle@e@mark
	\ifcase#1\relax
		\pgfmathprintnumber@fixed@style{#2}#1#2e0\relax%
		\expandafter\pgfmathfloatrounddisplaystyle@shared@impl@\expandafter{\pgfmathresult}{#4#6}%
	\or\pgfmathprintnumber@fixed@style{#2}#1#2e0\relax%
		\expandafter\pgfmathfloatrounddisplaystyle@shared@impl@\expandafter{\pgfmathresult}{#4#6}%
	\or\pgfmathprintnumber@fixed@style{-#2}#1#2e0\relax%
		\expandafter\pgfmathfloatrounddisplaystyle@shared@impl@\expandafter{\pgfmathresult}{#4#6}%
	\or
		\pgfmathfloatrounddisplaystyle@shared@impl@@{\hbox{NaN}}{}%
	\or
		\ifpgfmathprintnumber@showpositive
			\pgfmathfloatrounddisplaystyle@shared@impl@@{+\infty}{}%
		\else
			\pgfmathfloatrounddisplaystyle@shared@impl@@{\infty}{}%
		\fi
	\or
		\pgfmathfloatrounddisplaystyle@shared@impl@@{-\infty}{}%
	\fi
}

% #1: the part before the exponent code
% #2: the part for the exponent code.
\def\pgfmathfloatrounddisplaystyle@shared@impl@#1#2{%
	\pgfmathprintnumber@begingroup
	\toks0={#1}%
	\toks1=\expandafter{\pgfmathfloatrounddisplaystyle@e@mark #2}%
	\xdef\pgfmathfloat@glob@TMP{\the\toks0 \the\toks1 }%
	\pgfmathprintnumber@endgroup
	\let\pgfmathresult=\pgfmathfloat@glob@TMP
}%
% Same as \pgfmathfloatrounddisplaystyle@shared@impl@, but it also
% inserts the '@dec sep mark' at the end.
\def\pgfmathfloatrounddisplaystyle@shared@impl@@#1#2{%
	\pgfmathprintnumber@begingroup
	\toks0={#1}%
	\toks1=\expandafter{\pgfmathfloatrounddisplaystyle@e@mark #2}%
	\pgfkeysgetvalue{/pgf/number format/@dec sep mark}\pgfmathprintnumber@fixed@styleDEFAULT@DEC@SEP@MARK
	\toks2=\expandafter{\pgfmathprintnumber@fixed@styleDEFAULT@DEC@SEP@MARK}%
	\xdef\pgfmathfloat@glob@TMP{\the\toks0 \the\toks1 \the\toks2 }%
	\pgfmathprintnumber@endgroup
	\let\pgfmathresult=\pgfmathfloat@glob@TMP
}

\def\pgfmathfloatrounddisplaystyle@std#1#2e#3\relax{%
	\pgfmathfloatrounddisplaystyle@shared@impl#1#2e#3\relax{\cdot}{}{10^{#3}}%
}
\def\pgfmathfloatrounddisplaystyle@subscript#1#2e#3\relax{%
	\pgfmathfloatrounddisplaystyle@shared@impl#1#2e#3\relax{}{1}{_{#3}}%
}
\def\pgfmathfloatrounddisplaystyle@superscript#1#2e#3\relax{%
	\pgfmathfloatrounddisplaystyle@shared@impl#1#2e#3\relax{}{1}{^{#3}}%
}
\def\pgfmathfloatrounddisplaystyle@e#1#2e#3\relax{%
	\ifnum#3<0\relax
		\pgfmathprintnumber@begingroup
		\count0=#3\relax
		\multiply\count0 by-1
		\xdef\pgfmathfloat@glob@TMP{e{-}\the\count0}%
		\pgfmathprintnumber@endgroup%
		\let\pgfmathresult=\pgfmathfloat@glob@TMP
	\else
		\def\pgfmathresult{e{+}#3}%
	\fi
	\def\pgfmathfloat@loc@TMPb{\pgfmathfloatrounddisplaystyle@shared@impl#1#2e#3\relax{}{1}}%
	\expandafter\pgfmathfloat@loc@TMPb\expandafter{\pgfmathresult}%
}
\def\pgfmathfloatrounddisplaystyle@E#1#2e#3\relax{%
	\ifnum#3<0\relax
		\pgfmathprintnumber@begingroup
		\count0=#3\relax
		\multiply\count0 by-1
		\xdef\pgfmathfloat@glob@TMP{E{-}\the\count0}%
		\pgfmathprintnumber@endgroup%
		\let\pgfmathresult=\pgfmathfloat@glob@TMP
	\else
		\def\pgfmathresult{E{+}#3}%
	\fi
	\def\pgfmathfloat@loc@TMPb{\pgfmathfloatrounddisplaystyle@shared@impl#1#2e#3\relax{}{1}}%
	\expandafter\pgfmathfloat@loc@TMPb\expandafter{\pgfmathresult}%
}

\def\pgfmathfloatrounddisplaystyle@generic#1#2e#3\relax{%
	\begingroup
	\pgfkeysvalueof {/pgf/number format/sci generic/@/.@cmd}{#3}{#1}{#2}\pgfeov
	\pgfkeysgetvalue{/pgf/number format/sci generic/mantissa sep}\pgfmathdisplay@aftermantissa
	\pgfkeysgetvalue{/pgf/number format/sci generic/empty mantissa sep}\pgfmathdisplay@nomantissa
	\pgfkeysgetvalue{/pgf/number format/sci generic/exponent}\pgfmathdisplay@e
	\toks0=\expandafter{\pgfmathdisplay@aftermantissa}%
	\toks1=\expandafter{\pgfmathdisplay@nomantissa}%
	\toks2=\expandafter{\pgfmathdisplay@e}%
	\xdef\pgfmathfloat@glob@TMP{\noexpand\pgfmathfloatrounddisplaystyle@shared@impl#1#2e#3\noexpand\relax{\the\toks0}{\the\toks1}{\the\toks2}}%
	\endgroup
	\pgfmathfloat@glob@TMP
}

% A macro which takes the argument '<SIGN><MANTISSE>e<EXPONENT>' and
% expands to the final TeX-representation for that floating point
% number.
%
% PRECONDITION:
%   the floating point number has already been rounded properly and
%   the mantissa has been rounded correcty.
%
% The argument needs to be in the format returned by
% \pgfmathfloat@to@FMeE@style and terminated by '\relax'.
\let\pgfmathfloatrounddisplaystyle=\pgfmathfloatrounddisplaystyle@std
\newif\ifpgfmathfloat@usezerofill@sci
\newif\ifpgfmathfloat@usezerofill@fixed
\newif\ifpgfmathprintnumber@assumemathmode
\newif\ifpgfmathprintnumber@showpositive
\newif\ifpgfmathprintnumber@frac@warn
\newif\ifpgfmathprintnumber@frac@whole

\long\def\pgfmathfloatfrac@verbatim#1#2{#1/#2}%

\let\pgfmathround@@orig=\pgfmathround@

% 2 = compatible
% 0 = no
% 1 = yes
\def\pgfmathprintnumber@RELATIVE@choice@roundtofixed{2}%

\newif\ifpgfmathprintnumber@thousand@sep@in@fractional
\pgfkeys{%
	/pgf/number format/.is family,
	/pgf/number format,
	fixed/.code=			\pgfmath@set@number@printer{pgfmathprintnumber@FIXED},
	sci/.code=				\pgfmath@set@number@printer{pgfmathprintnumber@SCI},
	std/.code=				{\pgfmath@set@number@printer{pgfmathprintnumber@STD}\pgfmathprintnumber@STD@setparam{#1}},
	std/.default=,%
	relative round mode/.is choice,
	relative round mode/fixed/.code={\def\pgfmathprintnumber@RELATIVE@choice@roundtofixed{1}},
	relative round mode/mantissa/.code={\def\pgfmathprintnumber@RELATIVE@choice@roundtofixed{0}},
	relative round mode/compatible/.code={\def\pgfmathprintnumber@RELATIVE@choice@roundtofixed{2}},
	% relative={<exponent base 10>}
	relative/.code=			{%
		\pgfmath@set@number@printer{pgfmathprintnumber@RELATIVE}%
		\pgfmathround@@orig{#1}%
		\expandafter\pgfmathfloattoint@@\pgfmathresult\relax
		\let\pgfmathprintnumber@RELATIVE@param=\pgfmathresult
	},%
	relative/.value required,
	relative*/.style={/pgf/number format/relative={#1},/pgf/number format/relative round mode=fixed},
	every relative/.style=std,
	relative style/.style={/pgf/number format/every relative/.append style={#1}},
	fixed relative/.code=	\pgfmath@set@number@printer{pgfmathprintnumber@FIXED@RELATIVE},
	int detect/.code=		\pgfmath@set@number@printer{pgfmathprintnumber@INT@DETECT},
	int trunc/.code=		\pgfmath@set@number@printer{pgfmathprintnumber@INT@TRUNC},
	frac/.code=				\pgfmath@set@number@printer{pgfmathprintnumber@frac},%
	frac TeX/.initial=\frac,
	frac whole format/.code={\def\pgfmathresult{#1}},
	frac denom/.initial=,
	frac whole/.is if=pgfmathprintnumber@frac@whole,
	frac whole=true,
	frac shift/.initial=4,
	frac warning/.is if=pgfmathprintnumber@frac@warn,
	frac warning=true,
	assume math mode/.is if=pgfmathprintnumber@assumemathmode,
	assume math mode/.default=true,
	fixed zerofill/.is if=	pgfmathfloat@usezerofill@fixed,
	fixed zerofill/.default=true,
	sci zerofill/.is if=	pgfmathfloat@usezerofill@sci,
	sci zerofill/.default=true,
	zerofill/.style=		{/pgf/number format/fixed zerofill=#1,/pgf/number format/sci zerofill=#1},
	zerofill/.default=		true,
	precision/.store in=	\pgfmathfloat@round@precision,
	sci precision/.code={%
		\edef\pgfmathfloat@loc@TMPa{#1}%
		\ifx\pgfmathfloat@loc@TMPa\pgfutil@empty
			\def\pgfmathprintnumber@sci@precision{\pgfmathfloat@round@precision}%
		\else
			\let\pgfmathprintnumber@sci@precision=\pgfmathfloat@loc@TMPa
		\fi
	},%
	sci precision/.default=,
	sci precision=,
	fixed default/.code=		{\let\pgfmathprintnumber@fixed@style=\pgfmathprintnumber@fixed@styleDEFAULT},
	set decimal separator/.initial=,
	dec sep/.style={/pgf/number format/set decimal separator={#1}},
	@dec sep mark/.initial=,
	@sci exponent mark/.initial=,
	set thousands separator/.initial=,
	1000 sep in fractionals/.is if=pgfmathprintnumber@thousand@sep@in@fractional,
	1000 sep in fractionals/.default=true,
	1000 sep/.style={/pgf/number format/set thousands separator={#1}},
	min exponent for 1000 sep/.initial=0,
	use period/.style=		{/pgf/number format/set decimal separator={.},/pgf/number format/set thousands separator={{{,}}}},
	use comma/.style=		{/pgf/number format/set decimal separator={{{,}}},/pgf/number format/set thousands separator={.}},
	showpos/.is if=pgfmathprintnumber@showpositive,
	showpos/.default=true,
	print sign/.is if=pgfmathprintnumber@showpositive,
	print sign/.default=true,
	skip 0./.is if=pgfmathprintnumberskipzeroperiod,
	skip 0./.default=true,
	skip 0.= false,
	use period,
	sci 10^e/.code=			{\let\pgfmathfloatrounddisplaystyle=\pgfmathfloatrounddisplaystyle@std},
	sci 10e/.code=			{\let\pgfmathfloatrounddisplaystyle=\pgfmathfloatrounddisplaystyle@std},
	sci e/.code=			{\let\pgfmathfloatrounddisplaystyle=\pgfmathfloatrounddisplaystyle@e},
	sci E/.code=			{\let\pgfmathfloatrounddisplaystyle=\pgfmathfloatrounddisplaystyle@E},
	sci subscript/.code=	{\let\pgfmathfloatrounddisplaystyle=\pgfmathfloatrounddisplaystyle@subscript},
	sci superscript/.code=	{\let\pgfmathfloatrounddisplaystyle=\pgfmathfloatrounddisplaystyle@superscript},
	sci generic/.code=		{%
		\let\pgfmathfloatrounddisplaystyle=\pgfmathfloatrounddisplaystyle@generic
		\pgfkeysdefargs{/pgf/number format/sci generic/@}%
			{##1##2##3}%
			{\pgfqkeys{/pgf/number format/sci generic}{#1}}%
	},
	sci generic/mantissa sep/.initial=,%
	sci generic/empty mantissa sep/.initial=,%
	sci generic/mantisse sep/.style={/pgf/number format/sci generic/mantissa sep={#1}},%
	sci generic/empty mantisse sep/.style={/pgf/number format/sci generic/empty mantissa sep={#1}},%
	sci generic/exponent/.initial=,%
	sci generic/.value required,
	verbatim/.code={%
		\pgfqkeys{/pgf/number format}{%
			sci generic={mantissa sep=,exponent={e##1}},
			1000 sep=,
			skip 0.=false,
			print sign=false,
			dec sep=.,
			assume math mode,
			frac TeX=\pgfmathfloatfrac@verbatim,
			frac whole format/.code={\def\pgfmathresult{##1 }},
			@dec sep mark=,
			@sci exponent mark=,
		}%
	},
%	sci may skip mantissa/.is if=pgfmathfloatround@allow@empty@mantissa,
%	sci may skip mantissa/.default=true,
}



\def\pgfmathprintnumber@STD#1{%
	% parse the input:
	\pgfmathfloatparsenumber{#1}%
	\pgfmathfloat@to@FMeE@style\pgfmathresult
	\expandafter\pgfmathprintnumber@STD@issci\pgfmathresult\relax
}

\def\pgfmathprintnumber@STD@setparam#1{%
	\edef\pgfmathfloat@loc@TMPb{#1}%
	\ifx\pgfmathfloat@loc@TMPb\pgfutil@empty
		% DEFAULT for lower and upper bound.
		\def\pgfmathprintnumber@STD@getlowerbound{%
			\c@pgf@counta=\pgfmathfloat@round@precision@orig\relax
			\divide\c@pgf@counta by-2\relax
		}%
		\def\pgfmathprintnumber@STD@upperbound{4}%
	\else
		\expandafter\pgfutil@in@\expandafter:\expandafter{\pgfmathfloat@loc@TMPb}%
		\ifpgfutil@in@
			% we have -4:5 or something like that.
			% parse both values:
			\def\pgfmathfloat@loc@TMPa##1:##2\relax{%
				\edef\pgfmathprintnumber@STD@getlowerbound{%
					\noexpand\c@pgf@counta=##1\space
				}%
				\edef\pgfmathprintnumber@STD@upperbound{##2}%
			}%
			\expandafter\pgfmathfloat@loc@TMPa\pgfmathfloat@loc@TMPb\relax
		\else
			% we have just the lower bound:
			\def\pgfmathprintnumber@STD@upperbound{4}%
			\edef\pgfmathprintnumber@STD@getlowerbound{%
				\noexpand\c@pgf@counta=\pgfmathfloat@loc@TMPb\space
			}%
		\fi
	\fi
}%

\def\pgfmathprintnumber@STD@issci#1#2e#3\relax{%
	\expandafter\ifnum#1<3
		\expandafter\ifnum#3>\pgfmathprintnumber@STD@upperbound\relax
			\pgfmathprintnumber@SCI@issci#1#2e#3\relax%
		\else
			\begingroup
			\pgfmathprintnumber@STD@getlowerbound
			\ifnum#3<\c@pgf@counta
				\pgfmathprintnumber@SCI@issci#1#2e#3\relax%
			\else
				\pgfmathprintnumber@FIXED@issci#1#2e#3\relax%
			\fi
			\pgfmath@smuggleone\pgfmathresult
			\endgroup
		\fi
	\else% nan or inf:
		\pgfmathfloatrounddisplaystyle#1#2e#3\relax%
	\fi
}

\def\pgfmathprintnumber@RELATIVE#1{%
	% parse the input:
	\pgfmathfloatparsenumber{#1}%
	\pgfmathfloat@to@FMeE@style\pgfmathresult
	\expandafter\pgfmathprintnumber@RELATIVE@issci\pgfmathresult\relax
}

\def\pgfmathprintnumber@RELATIVE@choice@roundtofixed@warn{%
	\immediate\write16{! Package pgf warning: the use of /pgf/number format/relative is discouraged (buggy). Please use 'relative*' instead or type \string\pgfkeys{/pgf/number format/relative round mode=fixed} into your preamble.}%
	\global\let\pgfmathprintnumber@RELATIVE@choice@roundtofixed@warn=\relax
}

\def\pgfmathprintnumber@RELATIVE@issci#1#2e#3\relax{%
	\begingroup
		% format X / 10^{relative}:
		\c@pgf@counta=#3\relax
		\advance\c@pgf@counta by-\pgfmathprintnumber@RELATIVE@param\relax
		\pgfmathfloatcreate{#1}{#2}{\the\c@pgf@counta}%
		% OK, round it to the desired precision:
		\if0\pgfmathprintnumber@RELATIVE@choice@roundtofixed
			% relative round mode=mantissa
			\def\b@round@fixed{0}%
		\else 
			\if1\pgfmathprintnumber@RELATIVE@choice@roundtofixed
				% relative round mode=fixed
				\def\b@round@fixed{1}%
			\else
				\pgfmathprintnumber@RELATIVE@choice@roundtofixed@warn
				% relative round mode=compatible
				\ifnum\c@pgf@counta>0
					% hm. for positive exponents, we should round the
					% mantissa rather than only the fractional part.
					\def\b@round@fixed{0}%
				\else
					% negative exponent -> round fixed representation:
					\def\b@round@fixed{1}%
				\fi
			\fi
		\fi
		\if1\b@round@fixed
			% round fixed representation:
			\pgfmathfloattofixed\pgfmathresult
			\expandafter\pgfmathroundto\expandafter{\pgfmathresult}%
			\pgfmathfloatparsenumber{\pgfmathresult}%
			\pgfmathfloatroundhasperiodtrue% make sure the code below works:
		\else
			% round the mantissa:
			\expandafter\pgfmathfloatround\expandafter{\pgfmathresult}%
		\fi
		% Now, compute result * 10^{relative} and format the result:
		\pgfmathfloattoregisterstok\pgfmathresult\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
		\ifnum\pgfmathfloat@a@S=0
			\pgfmathfloat@a@E=\pgfmathfloat@a@S % avoid 0 * 10^8
		\else
			\advance\pgfmathfloat@a@E by+\pgfmathprintnumber@RELATIVE@param\relax
		\fi
		\edef\pgfmathresultX{%
			\the\pgfmathfloat@a@S
			\the\pgfmathfloat@a@Mtok 
			\ifpgfmathfloatroundhasperiod\else.0\fi
			e\the\pgfmathfloat@a@E}%
		% call another formatter for the result (but avoid rounding inside of it):
		\pgfqkeys{/pgf/number format}{/pgf/number format/every relative,
			fixed zerofill=false,% useless here!
			sci zerofill=false}%
		\ifx\pgfmathprintnumber@issci\pgfmathprintnumber@RELATIVE@issci
			\pgfmath@error{The '/pgf/number format/every relative' style should set a valid display style}%
		\fi
		\let\pgfmathfloat@round@precision@orig=\pgfmathfloat@round@precision
		\def\pgfmathfloat@round@precision{9999}%
		\expandafter\pgfmathprintnumber@issci\pgfmathresultX\relax%
		\pgfmath@smuggleone\pgfmathresult
	\endgroup
}

\def\pgfmathprintnumber@FIXED@RELATIVE#1{%
	% parse the input:
	\pgfmathfloatparsenumber{#1}%
	\pgfmathfloat@to@FMeE@style\pgfmathresult
	\expandafter\pgfmathprintnumber@FIXED@RELATIVE@issci\pgfmathresult\relax
}

\def\pgfmathprintnumber@FIXED@RELATIVE@issci#1#2e#3\relax{%
	\begingroup
	\pgfmathfloatcreate{#1}{#2}{#3}%
	% we want the first <precision> digits - not the first
	% <precision>+1 digits:
	\c@pgf@counta=\pgfmathfloat@round@precision\relax
	\advance\c@pgf@counta by-1
	\edef\pgfmathfloat@round@precision{\the\c@pgf@counta}%
	\pgfmathfloatround{\pgfmathresult}%
	\pgfmathfloattoregisterstok\pgfmathresult\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
	\ifnum\pgfmathfloat@a@S=0
		\pgfmathfloat@a@E=\pgfmathfloat@a@S % avoid 0 * 10^8
	\fi
	\edef\pgfmathresultX{%
		\the\pgfmathfloat@a@S
		\the\pgfmathfloat@a@Mtok 
		\ifpgfmathfloatroundhasperiod\else.0\fi
		e\the\pgfmathfloat@a@E}%
	\let\pgfmathfloat@round@precision@orig=\pgfmathfloat@round@precision
	\pgfmathfloat@usezerofill@fixedfalse
	\def\pgfmathfloat@round@precision{9999}% typeset all remaining digits!
	\expandafter\pgfmathprintnumber@FIXED@issci\pgfmathresultX\relax%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}

\def\pgfmathprintnumber@frac#1{%
	% parse the input:
	\pgfmathfloatparsenumber{#1}%
	\pgfmathfloatgetfrac{\pgfmathresult}%
	\expandafter\pgfmathprintnumber@frac@formatresult\pgfmathresult
}
\def\pgfmathprintnumber@frac@issci#1#2e#3\relax{%
	\pgfmathfloatcreate{#1}{#2}{#3}%
	\pgfmathfloatgetfrac{\pgfmathresult}%
	\expandafter\pgfmathprintnumber@frac@formatresult\pgfmathresult
}
\def\pgfmathprintnumber@frac@formatresult#1#2#3{%
	\begingroup
	\pgfkeysgetvalue{/pgf/number format/frac TeX}\pgfmathresult
	\toks0=\expandafter{\pgfmathresult}%
	\def\pgfmathfloat@loc@TMPa{#1}%
	\ifx\pgfmathfloat@loc@TMPa\pgfutil@empty
		\ifpgfmathprintnumber@showpositive
			\def\pgfmathfloat@loc@TMPa{+}%
		\fi
	\else
		\ifx\pgfmathfloat@loc@TMPa-%
		\else
			\ifx\pgfmathfloat@loc@TMPa+%
			\else
				\ifpgfmathprintnumber@showpositive
					\edef\pgfmathfloat@loc@TMPa{+\pgfmathfloat@loc@TMPa}%
				\fi
				\def\pgfmathfloat@loc@TMPb{\pgfkeysvalueof{/pgf/number format/frac whole format/.@cmd}}%
				\expandafter\pgfmathfloat@loc@TMPb\pgfmathfloat@loc@TMPa\pgfeov
				\let\pgfmathfloat@loc@TMPa=\pgfmathresult
			\fi
		\fi
	\fi
	\toks1=\expandafter{\pgfmathfloat@loc@TMPa}%
	\edef\pgfmathresult{%
		\the\toks1 \ifnum#2=0 \else\the\toks0 {#2}{#3}\fi%
	}%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%

% Defines \pgfmathresult to contain three sets of braces containing
% the sign (optionally containing any components >1), the numerator and the denominator for #1.
%
% \pgfmathfloatgetfrac{0.5}  -> \pgfmathresult contains {}{1}{2}
% \pgfmathfloatgetfrac{-0.5} -> \pgfmathresult contains {-}{1}{2}
% \pgfmathfloatgetfrac{1.5} ->  \pgfmathresult contains {1}{1}{2}
%
% special cases:
% \pgfmathfloatgetfrac{0}   ->  \pgfmathresult contains {0}{0}{1}
% \pgfmathfloatgetfrac{1}   ->  \pgfmathresult contains {1}{0}{1}
%
% The numerator and denominator is always a number (not empty)
\def\pgfmathfloatgetfrac#1{%
	\pgfutil@ifundefined{pgfmathfloatmultiply@}{%
		\pgfmath@PackageError{Sorry, the number format 'frac' requires '\string\usetikzlibrary{fpu}' (and, optionally, \string\usepackage{fp}) in order to work correctly}%
		\edef\pgfmathresult{{#1}{0}{1}}%
	}{%
		\pgfmathfloatgetfrac@{#1}%
	}%
}%
\def\pgfmathfloatgetfrac@#1{%
	\begingroup
		\edef\pgfmathfloat@arg{#1}%
		\expandafter\pgfmathfloat@decompose@tok\pgfmathfloat@arg\relax\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
		\def\pgfmathfloat@loc@TMPa{0}%
		\ifcase\pgfmathfloat@a@S
		% #1 = 0:
			\def\pgfmathresult{{0}{0}{1}}%
		\or% #1 > 0
			\pgfmathfloat@a@S=1
			\def\pgfmathfloat@loc@TMPa{1}%
		\or% #1 < 0
			\pgfmathfloat@a@S=-1
			\def\pgfmathfloat@loc@TMPa{1}%
		\or
			\edef\pgfmathresult{{}{NaN}{1}}%
		\or
			\edef\pgfmathresult{{}{\infty}{1}}%
		\or
			\edef\pgfmathresult{{-}{\infty}{1}}%
		\fi
		\if1\pgfmathfloat@loc@TMPa
			\ifnum\pgfmathfloat@a@E<0
				\def\pgfmathfloat@wholenumber{}%
			\else
				\pgfmathfloatcreate{1}{\the\pgfmathfloat@a@Mtok}{\the\pgfmathfloat@a@E}%
				\pgfmathfloattofixed\pgfmathresult%
				\def\pgfmathfloat@loc@TMPa##1.##2\relax{%
					\def\pgfmathfloat@wholenumber{##1}%
					\pgfmathfloatparsenumber{0.##2}%
				}%
				\expandafter\pgfmathfloat@loc@TMPa\pgfmathresult\relax
				\expandafter\pgfmathfloat@decompose@tok\pgfmathresult\relax\pgfmathfloat@b@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
			\fi
			%
			\def\pgfmathfloat@loc@TMPa##1.##2\relax{%
				\def\pgfmathfloat@mantissa@first{##1}%
				\def\pgfmathfloat@mantissa@ltone{0.##2}%
			}%
			\expandafter\pgfmathfloat@loc@TMPa\the\pgfmathfloat@a@Mtok\relax
			%
			\def\pgfmathfloat@loc@@to@int##1.##2\relax##3{%
				##3=##1
				\ifdim0.##2pt>0.5pt
					\advance##3 by1
				\fi
			}%
			%
			% alias registers names:
			\let\pgfmathresultnumerator=\pgfmathfloat@b@S
			\let\pgfmathresultdenom=\pgfmathfloat@b@E
			%
			\pgfkeysgetvalue{/pgf/number format/frac denom}\pgfmath@target@denominator
			\ifx\pgfmath@target@denominator\pgfutil@empty
			%
				\pgfmathfloat@a@E=-\pgfmathfloat@a@E
				\ifdim\pgfmathfloat@mantissa@ltone pt=0pt
					\def\pgfmathfloat@factor{1}%
					\edef\pgfmathfloat@scaled@numerator{\the\pgfmathfloat@a@Mtok}%
				\else
					% FIXME : this here is numerically instable.
					%
					% The errors of 1/r are magnified by 10^k which
					% doesn't work.
					\pgfutil@ifundefined{FPdiv}{%
						\pgfmathfloatparsenumber{\pgfmathfloat@mantissa@ltone}%
						\pgfmathfloatreciprocal@{\pgfmathresult}%
					}{%
						% \usepackage{fp}.
						% yields higher absolute precision.
						\FPmessagesfalse%
						\FPdebugfalse%
						\FPdiv\pgfmathresult{1}{\pgfmathfloat@mantissa@ltone}%
						\pgfmathfloatparsenumber{\pgfmathresult}%
					}%
					\let\pgfmathfloat@inv=\pgfmathresult
					\pgfmathfloatcreate{1}{1.0}{\pgfkeysvalueof{/pgf/number format/frac shift}}%
					\let\pgfmathfloat@scalebaseten=\pgfmathresult
					\pgfmathfloatmultiply@{\pgfmathfloat@inv}{\pgfmathfloat@scalebaseten}%
					\let\pgfmathfloat@factor=\pgfmathresult
					%
					\expandafter\pgfmathfloatparsenumber\expandafter{\the\pgfmathfloat@a@Mtok}%
					\let\pgfmathfloat@loc@TMPa=\pgfmathresult
					\pgfmathfloatmultiply@{\pgfmathfloat@factor}{\pgfmathfloat@loc@TMPa}%
					\pgfmathfloattofixed\pgfmathresult
					\let\pgfmathfloat@scaled@numerator=\pgfmathresult
					%
					\pgfmathfloattofixed\pgfmathfloat@factor
					\expandafter\pgfmathfloat@loc@@to@int\pgfmathresult\relax{\pgfmathfloat@b@S}%
					\edef\pgfmathfloat@factor{\the\pgfmathfloat@b@S}%
				\fi
				%
				%
				\pgfmathresultdenom=\pgfmathfloat@factor\relax
				\pgfmathfloat@multiply@ten@to@the@E\pgfmathresultdenom
				%
				\expandafter\pgfmathfloat@loc@@to@int\pgfmathfloat@scaled@numerator\relax{\pgfmathresultnumerator}%
	%\message{scale = \pgfmathfloat@factor;  Z = \the\pgfmathresultnumerator\space ( von \pgfmathfloat@scaled@numerator), N = \the\pgfmathresultdenom.}%
				%
				\pgfmathgreatestcommondivisor{\pgfmathresultnumerator}{\pgfmathresultdenom}%
				\divide\pgfmathresultnumerator by\pgfmathresult\relax
				\divide\pgfmathresultdenom by\pgfmathresult\relax
				\ifpgfmathprintnumber@frac@warn
					\ifnum\pgfmathresultdenom>1000
						\pgfutil@ifundefined{FPdiv}{%
							\pgfmathfloattosci@\pgfmathfloat@arg
							\immediate\write16{! Package pgf /pgf/number format/frac warning=true: /pgf/number format/frac of `\pgfmathresult' = \the\pgfmathresultnumerator\space / \the\pgfmathresultdenom\space might be large due to instabilities. Try \string\usepackage{fp} to improve accuracy.}%
						}{}%
					\fi
				\fi
			\else
				% use target denominator:
				\pgfmathresultdenom=\pgfmath@target@denominator\relax
				\pgfmathfloatcreate{1}{\the\pgfmathfloat@a@Mtok}{\the\pgfmathfloat@a@E}%
				\pgfmathfloattofixed\pgfmathresult
				\pgf@xa=\pgfmathresult pt
				\multiply\pgf@xa by\pgfmathresultdenom
				\edef\pgfmathfloat@scaled@numerator{\pgf@sys@tonumber\pgf@xa}%
				\expandafter\pgfmathfloat@loc@@to@int\pgfmathfloat@scaled@numerator\relax{\pgfmathresultnumerator}%
			\fi
			\ifpgfmathprintnumber@frac@whole
			\else
				\ifx\pgfmathfloat@wholenumber\pgfutil@empty
				\else
					\count0=\pgfmathfloat@wholenumber\relax
					\multiply\count0 by\pgfmathresultdenom
					\advance\pgfmathresultnumerator by\count0
					\def\pgfmathfloat@wholenumber{}%
				\fi
			\fi
			\ifnum\pgfmathfloat@a@S<0
				\edef\pgfmathresult{{-\pgfmathfloat@wholenumber}{\the\pgfmathresultnumerator}{\the\pgfmathresultdenom}}%
			\else
				\edef\pgfmathresult{{\pgfmathfloat@wholenumber}{\the\pgfmathresultnumerator}{\the\pgfmathresultdenom}}%
			\fi
		\fi
		\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%
\def\pgfmathfloat@gobble@until@relax#1\relax{}

% computes the greatest common divisor of two integer numbers (in
% integer arithmetics).
\def\pgfmathgreatestcommondivisor#1#2{%
	\begingroup
		\count0=#1\relax
		\count1=#2\relax
		\ifnum\count0=0
			\edef\pgfmathresult{\the\count1}%
		\else
			\pgfmathgreatestcommondivisor@loop
			\edef\pgfmathresult{\the\count0}%
		\fi
		\pgfmath@smuggleone\pgfmathresult
	\endgroup
}
\def\pgfmathgreatestcommondivisor@loop{%
	\ifnum\count1=0
	\else
		\ifnum\count0>\count1
			\advance\count0 by-\count1
		\else
			\advance\count1 by-\count0
		\fi
		\expandafter\pgfmathgreatestcommondivisor@loop
	\fi
}%

% multiplies a TeX register by 10^E where E is stored in the register
% \pgfmathfloat@a@E (and it should be positive!)%
%
% #1 a TeX register
\def\pgfmathfloat@multiply@ten@to@the@E#1{%
	\ifnum\pgfmathfloat@a@E>0
		\multiply#1 by10
		\advance\pgfmathfloat@a@E by-1
		\def\pgfmathfloat@multiply@ten@to@the@E@next{\pgfmathfloat@multiply@ten@to@the@E{#1}}%
	\else
		\let\pgfmathfloat@multiply@ten@to@the@E@next=\relax%
	\fi
	\pgfmathfloat@multiply@ten@to@the@E@next
}%

\def\pgfmathprintnumber@INT@TRUNC#1{%
	\pgfmathfloatparsenumber{#1}%
	\pgfmathfloat@to@FMeE@style\pgfmathresult
	\expandafter\pgfmathprintnumber@INT@TRUNC@issci\pgfmathresult\relax
}

\def\pgfmathprintnumber@INT@TRUNC@impl#1.#2\relax#3#4e#5\relax{%
	\pgfmathfloatroundhasperiodfalse
	\pgfmathprintnumber@fixed@style{#1}#3#4e#5\relax%
}
\def\pgfmathprintnumber@INT@TRUNC@issci#1#2e#3\relax{%
	\ifnum#1<3\relax
		\pgfmathfloatcreate{#1}{#2}{#3}%
		\pgfmathfloattofixed{\pgfmathresult}%
		\expandafter\pgfmathprintnumber@INT@TRUNC@impl\pgfmathresult\relax#1#2e#3\relax
	\else
		\pgfmathfloatrounddisplaystyle#1#2e#3\relax%
	\fi
}

% Invokes '#2' if '#1' is actually an integer or '#3' if not.
%
% As a side--effect, \pgfretval will be set to the integer value if it
% actually *is* an integer. Otherwise, \pgfretval will contain the
% parsed floating point number.
%
% #1 a number constant (not necessarily a parsed float).
\def\pgfmathifisint#1#2#3{%
	\gdef\pgfmathfloatisint@@{0}%
	\begingroup
	\pgfmathfloatparsenumber{#1}%
	\let\pgfretval\pgfmathresult
	\pgfmathfloat@to@FMeE@style\pgfmathresult
	\expandafter\pgfmathfloatisint@\pgfmathresult\relax
	\pgfmath@smuggleone\pgfretval
	\endgroup
	\if1\pgfmathfloatisint@@ #2\else #3\fi
}%
\def\pgfmathfloatisint@#1#2e#3\relax{%
	\ifnum#1<3\relax
		\pgfmathfloatcreate{#1}{#2}{#3}%
		\pgfmathfloattofixed{\pgfmathresult}%
		\def\pgfmathfloat@round@precision{6}%
		\expandafter\pgfmathroundto\expandafter{\pgfmathresult}%
		\ifpgfmathfloatroundhasperiod
		\else
			\let\pgfretval\pgfmathresult%
			\gdef\pgfmathfloatisint@@{1}%
		\fi
	\fi
}

\def\pgfmathprintnumber@INT@DETECT#1{%
	\pgfmathfloatparsenumber{#1}%
	\pgfmathfloat@to@FMeE@style\pgfmathresult
	\expandafter\pgfmathprintnumber@INT@DETECT@issci\pgfmathresult\relax
}

\def\pgfmathprintnumber@INT@DETECT@issci#1#2e#3\relax{%
	\begingroup
	\ifnum#1<3\relax
		\pgfmathfloatcreate{#1}{#2}{#3}%
		\pgfmathfloattofixed{\pgfmathresult}%
		\let\pgfmathfloat@round@precision@=\pgfmathfloat@round@precision
		\def\pgfmathfloat@round@precision{6}%
		\expandafter\pgfmathroundto\expandafter{\pgfmathresult}%
		\let\pgfmathfloat@round@precision=\pgfmathfloat@round@precision@
		\ifpgfmathfloatroundhasperiod
			\pgfmathprintnumber@SCI@issci#1#2e#3\relax
		\else
			\expandafter\pgfmathprintnumber@fixed@style\expandafter{\pgfmathresult}#1#2e#3\relax
		\fi
	\else
		\pgfmathfloatrounddisplaystyle#1#2e#3\relax%
	\fi
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}

\def\pgfmathprintnumber@FIXED#1{%
	\pgfmathfloatparsenumber{#1}%
	\pgfmathfloat@to@FMeE@style\pgfmathresult
	\expandafter\pgfmathprintnumber@FIXED@issci\pgfmathresult\relax
}

\def\pgfmathprintnumber@FIXED@issci#1#2e#3\relax{%
	\begingroup
	\ifnum#1<3
		\pgfmathfloatcreate{#1}{#2}{#3}%
		\pgfmathfloattofixed{\pgfmathresult}%
		\ifpgfmathfloat@usezerofill@fixed
			\expandafter\pgfmathroundtozerofill\expandafter{\pgfmathresult}%
		\else
			\expandafter\pgfmathroundto\expandafter{\pgfmathresult}%
		\fi
		\ifpgfmathfloatroundmayneedrenormalize
			\pgfmathfloat@a@E=#3\relax
			\advance\pgfmathfloat@a@E by1
			\edef\pgfmathfloat@loc@TMPb{\noexpand\pgfmathprintnumber@fixed@style{\pgfmathresult}#1#2e\the\pgfmathfloat@a@E}%
			\pgfmathfloat@loc@TMPb\relax%
		\else
			\expandafter\pgfmathprintnumber@fixed@style\expandafter{\pgfmathresult}#1#2e#3\relax%
		\fi
	\else% nan or inf:
		\pgfmathfloatrounddisplaystyle#1#2e#3\relax%
	\fi
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}


\def\pgfmathprintnumber@SCI#1{%
	\pgfmathfloatparsenumber{#1}%
	\pgfmathfloat@to@FMeE@style\pgfmathresult
	\expandafter\pgfmathprintnumber@SCI@issci\pgfmathresult\relax
}

\def\pgfmathprintnumber@SCI@issci#1#2e#3\relax{%
	\begingroup
	\pgfmathfloatcreate{#1}{#2}{#3}%
	\edef\pgfmathfloat@round@precision{\pgfmathprintnumber@sci@precision}%
	\ifpgfmathfloat@usezerofill@sci
		\pgfmathfloatroundzerofill{\pgfmathresult}%
	\else
		\pgfmathfloatround{\pgfmathresult}%
	\fi
	\pgfmathfloat@to@FMeE@style\pgfmathresult
	\expandafter\pgfmathfloatrounddisplaystyle\pgfmathresult\relax
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}

% Prints argument #1 using the current pretty printer environment (all
% variables in /pgf/number format).
%
% You may specify optional arguments with \pgfmathprintnumber[...].
\def\pgfmathprintnumber{%
	% \protect allows to supply \pgfmathprintnumber inside of latex
	% captions. The \csname yields \relax in case protect is undefined.
	\pgf@texdist@protect\pgfmathprintnumber@protected
}%
\def\pgfmathprintnumber@protected{%
	\pgfutil@ifnextchar[%
		{\pgfmathprintnumber@OPT}%
		{\pgfmathprintnumber@noopt}%
}

\def\pgfmathprintnumber@noopt#1{%
	\pgfmathprintnumber@{#1}%
	\ifpgfmathprintnumber@assumemathmode
		\pgfmathresult
	\else
		\pgfutilensuremath{\pgfmathresult}%
	\fi
}%
\def\pgfmathprintnumber@OPT[#1]#2{%
	\begingroup
	\pgfqkeys{/pgf/number format}{#1}%
	\pgfmathprintnumber@{#2}%
	\ifpgfmathprintnumber@assumemathmode
		\pgfmathresult
	\else
		\pgfutilensuremath{\pgfmathresult}%
	\fi
	\endgroup
}%

% As \pgfmathprintnumber, but it produces its output into the second
% argument.
\def\pgfmathprintnumberto{%
	\pgfutil@ifnextchar[%
		{\pgfmathprintnumberto@OPT}%
		{\pgfmathprintnumberto@noopt}%
}

\def\pgfmathprintnumberto@noopt#1#2{%
	\begingroup
	\pgfmathprintnumber@{#1}%
	\ifpgfmathprintnumber@assumemathmode
		\global\let\pgfmathfloat@glob@TMP=\pgfmathresult
	\else
		\toks0=\expandafter{\pgfmathresult}%
		\xdef\pgfmathfloat@glob@TMP{\noexpand\pgfutilensuremath{\the\toks0 }}%
	\fi
	\endgroup
	\let#2=\pgfmathfloat@glob@TMP
}%
\def\pgfmathprintnumberto@OPT[#1]#2#3{%
	\begingroup
	\pgfqkeys{/pgf/number format}{#1}%
	\pgfmathprintnumber@{#2}%
	\ifpgfmathprintnumber@assumemathmode
		\global\let\pgfmathfloat@glob@TMP=\pgfmathresult
	\else
		\toks0=\expandafter{\pgfmathresult}%
		\xdef\pgfmathfloat@glob@TMP{\noexpand\pgfutilensuremath{\the\toks0 }}%
	\fi
	\endgroup
	\let#3=\pgfmathfloat@glob@TMP
}%
	

% Changes the current number pretty printer to #1.
%
% #1 is the macro base name for the pretty print routine, without the
% leading '\'.
\def\pgfmath@set@number@printer#1{%
	\expandafter\let\expandafter\pgfmathprintnumber@\csname #1\endcsname
	\expandafter\let\expandafter\pgfmathprintnumber@issci\csname #1@issci\endcsname
}

\pgfkeys{/pgf/number format/std}

%%%%%%%%%%%%%%%%%%%%%%%%%%
% 
% IMPL
%
%%%%%%%%%%%%%%%%%%%%%%%%%%

% equals only itsself when compared with \ifx:
\def\pgfmathfloat@EOI{\pgfmathfloat@EOI}%

% Re-use counters internally.
%
% They are always grouped and only used inside of the rounding
% routines.
\let\c@pgfmathroundto@prec=\pgfmathfloat@b@S% ATTENTION: DOUBLE-USED REGISTERS!
\let\c@pgfmathroundto@offsetbehindperiod=\pgfmathfloat@b@E
\newcount\c@pgfmathroundto@lastzeros

\newif\ifpgfmathround@impl@PREPERIOD@is@negative@zero

% PRECONDITION:
%  	\ifpgfmathfloatroundhasperiod=\iftrue  holds outside of the
%  	current TeX group.
%
% POSTCONDITION:
%   \ifpgfmathfloatroundhasperiod will be set correctly AFTER the
%   current TeX group.
%   \ifpgfmathfloatroundmayneedrenormalize will be set globally
\def\pgfmathroundto@impl#1{%
	\edef\pgfmathround@input{#1}%
	\global\pgfmathfloatroundmayneedrenormalizefalse
	\pgfmathfloat@tmptoks={}%
	\let\pgfmathround@next=\pgfutil@empty
	\let\pgfmathround@cur=\pgfutil@empty
	\let\pgfmathresult=\pgfutil@empty
	\expandafter\c@pgfmathroundto@prec\pgfmathfloat@round@precision\relax
	\c@pgfmathroundto@lastzeros=0
	\c@pgfmathroundto@offsetbehindperiod=-1 % means: no period found so far
	\pgfmathround@impl@PREPERIOD@is@negative@zerotrue
	\expandafter\pgfmathroundto@impl@ITERATE@NODOT@firstcall\pgfmathround@input\pgfmathfloat@EOI
}

% \pgfmathroundto implementation in WORDS:
%
% coarse idea: 
%    1. collect all digits/sign BEFORE the first period in REVERSE order
%    2. then, collect UP TO \prec digits after the period in REVERSE order
% Steps 1. and 2. lead to the digit [sign] sequence
%    "x_{-p} x_{-p+1} ... x_{-2} x_{-1} '.' x_0 ... x_r"
% where 'r' is the total number of digits. The integer 'p' denotes the
% ACTUALLY collected number of digits behind the period.
%
% Let 'k' be the desired precision.
%
% Please note that pgfmathroundto rounds the mantissa, that means |abs(x)|.
%
% There are exactly TWO cases:
% 1. The case with p<=k and x_{-p-1} = end of input.
% 2. The case with p=k and x_{-p-1} is a further, next character.
%
% Then, for case 1.):
% 	discard any unused zeros at the tail of our number (possibly
% 	including the period)
%
% and in case 2.)
%   if NEXT DIGIT < 5:
%       do exactly the same as in case 1.) above and discard any
%       following digits.
%   else
%   	let q := -p
%   	while(x_q = 9 and q<=r )
%   		if q>=0
%   			set x_q = '0'
%   		else
%   			discard digit x_q='9'
%   		fi
%   		++q
%   		if q=0
%   			discard the period 
%   		fi
%   	end while
%   	if q = r+1
%   		insert a '1'
%   	else
%   		set x_q = x_q + 1
%   	fi
%   fi
%
% All these loops have been implemented in spaghetti-code below.
% Sorry, I fear its hard to understand. In principle, everything is
% realised using more or less finite state machines (with some number
% counting logic).
%
% Some comments:
%   - The token register \pgfmathfloat@tmptoks is used to accumulate the REVERSED input number.
%	- \pgfmathfloat@EOI always denotes 'END OF INPUT'.
%	- in the second stage, we need to reverse \pgfmathfloat@tmptoks.
%	  This is -again- done with \pgfmathfloat@tmptoks.

\def\pgfmathroundto@impl@discard@period#1.#2\pgfmathfloat@EOI{%
	\pgfmathfloatroundhasperiodfalse
	\aftergroup\pgfmathfloatroundhasperiodfalse
	\def\pgfmathresult{#1}%
}

\def\pgfmathroundto@impl@gobble@rest@and@start#1\pgfmathfloat@EOI{%
	\pgfmathroundto@impl@start
}
\def\pgfmathroundto@impl@gobble@and@start\pgfmathfloat@EOI{%
	\pgfmathroundto@impl@start
}
\def\pgfmathroundto@impl@gobble\pgfmathfloat@EOI{}%
\def\pgfmathroundto@impl@gobble@rest#1\pgfmathfloat@EOI{}%

% This method will be invoked as soon as the first step, the reverse
% collection of up to PREC digits after the period, has finished.
\def\pgfmathroundto@impl@start{%
	\ifx\pgfmathround@next\pgfutil@empty
		\ifnum\c@pgfmathroundto@offsetbehindperiod<0
			% no period found.
			\ifpgfmathfloat@fixed@digits@after@period
				\ifnum\c@pgfmathroundto@prec=0\relax
					\pgfmathfloatroundhasperiodfalse
					\aftergroup\pgfmathfloatroundhasperiodfalse
					\edef\pgfmathresult{\pgfmathround@input}%
				\else
					\pgfmathfloat@tmptoks=\expandafter{\pgfmathround@input.}%
					\c@pgfmathroundto@offsetbehindperiod=\c@pgfmathroundto@prec
					\pgfmathroundto@impl@append@zeros
					\edef\pgfmathresult{\the\pgfmathfloat@tmptoks}%
				\fi
			\else
				\pgfmathfloatroundhasperiodfalse
				\aftergroup\pgfmathfloatroundhasperiodfalse
				\edef\pgfmathresult{\pgfmathround@input}%
			\fi
		\else
			%\ifnum\c@pgfmathroundto@offsetbehindperiod>\c@pgfmathroundto@prec
			%	\pgfmath@error{Internal logic error in pgfmathroundto at [I] - should not have happened!?}{}%
			%\fi
			\pgfmathroundto@impl@finish@with@truncation
		\fi
	\else
		%\ifnum\c@pgfmathroundto@offsetbehindperiod=\c@pgfmathroundto@prec
		%\else
		%	\pgfmath@error{Internal logic error in pgfmathroundto at [II] - should not have happened!? I have offsetbehindperiod=\the\c@pgfmathroundto@offsetbehindperiod and prec = \the\c@pgfmathroundto@prec}{}%
		%\fi
		\expandafter\ifnum\pgfmathround@next<5\relax
			\pgfmathroundto@impl@finish@with@truncation
		\else
			\multiply\c@pgfmathroundto@offsetbehindperiod by-1
			\expandafter\pgfmathroundto@impl@ADD@ONE\the\pgfmathfloat@tmptoks\pgfmathfloat@EOI
		\fi
	\fi
}
			
% takes the current input and decides whether trailing zeros shall be
% discarded or more zeros need to be filled in.
\def\pgfmathroundto@impl@finish@with@truncation{%
	\ifpgfmathfloat@fixed@digits@after@period
		\expandafter\pgfmathroundto@impl@REVERSE\the\pgfmathfloat@tmptoks\pgfmathfloat@EOI
		\ifnum\c@pgfmathroundto@lastzeros=\c@pgfmathroundto@offsetbehindperiod
			\ifpgfmathround@impl@PREPERIOD@is@negative@zero
				% write '0.0000' instead of '-0.0000':
				\expandafter\pgfmathroundto@impl@discard@minus\the\pgfmathfloat@tmptoks\pgfmathfloat@EOI
			\fi
		\fi
		\ifnum\c@pgfmathroundto@prec=0\relax
			\expandafter\pgfmathroundto@impl@discard@period\the\pgfmathfloat@tmptoks\pgfmathfloat@EOI
		\else
			\advance\c@pgfmathroundto@prec by-\c@pgfmathroundto@offsetbehindperiod
			\c@pgfmathroundto@offsetbehindperiod=\c@pgfmathroundto@prec
			\pgfmathroundto@impl@append@zeros
			\edef\pgfmathresult{\the\pgfmathfloat@tmptoks}%
		\fi
	\else
		\pgfmathroundto@impl@discard@suffix@zeros
	\fi
}

\def\pgfmathroundto@impl@discard@minus-#1\pgfmathfloat@EOI{\pgfmathfloat@tmptoks={#1}}%

% appends \c@pgfmathroundto@offsetbehindperiod zeros at the end of \pgfmathfloat@tmptoks.
\def\pgfmathroundto@impl@append@zeros{%
	\ifnum\c@pgfmathroundto@offsetbehindperiod>0
		\pgfmathfloat@tmptoks=\expandafter{\the\pgfmathfloat@tmptoks0}%
		\advance\c@pgfmathroundto@offsetbehindperiod by-1
		\pgfmathroundto@impl@append@zeros
	\fi
}

\def\pgfmathroundto@impl@ADD@ONE{%
	\pgfmathfloat@tmptoks={}% no longer needed because its old value will be read from input
	\pgfmathroundto@impl@ADD@ONE@ITERATE
}
\def\pgfmathroundto@impl@ADD@ONE@ITERATE{%
	\pgfutil@ifnextchar\pgfmathfloat@EOI{%
		\global\pgfmathfloatroundmayneedrenormalizetrue
		\edef\pgfmathresult{1\the\pgfmathfloat@tmptoks}%
		\pgfmathroundto@impl@gobble
	}{%
		\pgfutil@ifnextchar.{%
			\ifnum\c@pgfmathroundto@prec=0
				% silently discard period in special case precision=0
				\def\pgfmathround@nextcmd{\pgfmathroundto@impl@ADD@ONE@ITERATE@gobble@dot}%
			\else
				\def\pgfmathround@nextcmd{\pgfmathroundto@impl@ADD@ONE@NEXT@COLLECT}%
			\fi
			\pgfmathround@nextcmd
		}{%
			\pgfutil@ifnextchar+{%
				\global\pgfmathfloatroundmayneedrenormalizetrue
				\edef\pgfmathresult{1\the\pgfmathfloat@tmptoks}%
				\pgfmathroundto@impl@gobble@rest
			}{%
				\pgfutil@ifnextchar-{%
					\global\pgfmathfloatroundmayneedrenormalizetrue
					\edef\pgfmathresult{-1\the\pgfmathfloat@tmptoks}%
					\pgfmathroundto@impl@gobble@rest
				}{%
					\pgfmathroundto@impl@ADD@ONE@NEXT
				}%
			}%
		}%
	}%
}

\def\pgfmathroundto@impl@ADD@ONE@ITERATE@gobble@dot.{%
	\pgfmathfloatroundhasperiodfalse
	\aftergroup\pgfmathfloatroundhasperiodfalse
	\pgfmathroundto@impl@ADD@ONE@ITERATE
}

\def\pgfmathroundto@impl@ADD@ONE@NEXT@COLLECT#1{%
	\pgfmathfloat@tmptoks=\expandafter{\expandafter#1\the\pgfmathfloat@tmptoks}%
	\pgfmathroundto@impl@ADD@ONE@ITERATE
}
\def\pgfmathroundto@impl@ADD@ONE@NEXT#1{%
	\ifnum#1=9
		\ifnum\c@pgfmathroundto@offsetbehindperiod<0
			\ifpgfmathfloat@fixed@digits@after@period
				\pgfmathfloat@tmptoks=\expandafter{\expandafter0\the\pgfmathfloat@tmptoks}%
			\else
				% silently DROP digit
			\fi
		\else
			\pgfmathfloat@tmptoks=\expandafter{\expandafter0\the\pgfmathfloat@tmptoks}%
		\fi
		\advance\c@pgfmathroundto@offsetbehindperiod by1
		\ifnum\c@pgfmathroundto@offsetbehindperiod=0
			\ifpgfmathfloat@fixed@digits@after@period
				\def\pgfmathround@nextcmd{\pgfmathroundto@impl@ADD@ONE@ITERATE}%
			\else
				\def\pgfmathround@nextcmd{\pgfmathroundto@impl@ADD@ONE@ITERATE@gobble@dot}%
			\fi
		\else
			\def\pgfmathround@nextcmd{\pgfmathroundto@impl@ADD@ONE@ITERATE}%
		\fi
	\else
		% re-use this counter:
		\c@pgfmathroundto@lastzeros=#1
		\advance\c@pgfmathroundto@lastzeros by1
		\edef\pgfmathresult{\the\c@pgfmathroundto@lastzeros\the\pgfmathfloat@tmptoks}%
		\pgfmathfloat@tmptoks=\expandafter{\pgfmathresult}%
		\def\pgfmathround@nextcmd{\pgfmathroundto@impl@REVERSE@ITERATE}%
	\fi
	\pgfmathround@nextcmd
}


\def\pgfmathroundto@impl@discard@suffix@zeros{%
	\ifnum\c@pgfmathroundto@lastzeros=\c@pgfmathroundto@offsetbehindperiod
		\ifpgfmathround@impl@PREPERIOD@is@negative@zero
			\pgfmathfloatroundhasperiodfalse
			\aftergroup\pgfmathfloatroundhasperiodfalse
			\def\pgfmathresult{0}% write '0' instead of '-0'
		\else
			\expandafter\pgfmathroundto@impl@discard@period\pgfmathround@input\pgfmathfloat@EOI
		\fi
	\else
		\ifnum\c@pgfmathroundto@lastzeros=0
			\expandafter\pgfmathroundto@impl@REVERSE\the\pgfmathfloat@tmptoks\pgfmathfloat@EOI
		\else
			\expandafter\pgfmathroundto@impl@discard@suffix@zeros@ITERATE\the\pgfmathfloat@tmptoks\pgfmathfloat@EOI
		\fi
	\fi
}

% PRECONDITION: 
%    \c@pgfmathroundto@lastzeros > 0
\def\pgfmathroundto@impl@discard@suffix@zeros@ITERATE#1{%
	\advance\c@pgfmathroundto@lastzeros by-1
	\ifnum\c@pgfmathroundto@lastzeros=0
		\def\pgfmathround@nextcmd{\pgfmathroundto@impl@REVERSE}%
	\else
		\def\pgfmathround@nextcmd{\pgfmathroundto@impl@discard@suffix@zeros@ITERATE}%
	\fi
	\pgfmathround@nextcmd
}

% Usage:
% \pgfmathroundto@impl@REVERSE#1\pgfmathfloat@EOI
% -> writes #1 reversed into \pgfmathfloat@tmptoks
\def\pgfmathroundto@impl@REVERSE{%
	\pgfmathfloat@tmptoks={}%
	\pgfmathroundto@impl@REVERSE@ITERATE
}

\def\pgfmathroundto@impl@REVERSE@ITERATE{%
	\pgfutil@ifnextchar\pgfmathfloat@EOI{%
		\edef\pgfmathresult{\the\pgfmathfloat@tmptoks}%
		\pgfmathroundto@impl@gobble
	}{%
		\pgfmathroundto@impl@REVERSE@NEXT
	}%
}

\def\pgfmathroundto@impl@REVERSE@NEXT#1{%
	\pgfmathfloat@tmptoks=\expandafter{\expandafter#1\the\pgfmathfloat@tmptoks}%
	\pgfmathroundto@impl@REVERSE@ITERATE
}

\def\pgfmathroundto@impl@BEGIN@DOT.{%
	\pgfmathfloat@tmptoks=\expandafter{\expandafter.\the\pgfmathfloat@tmptoks}%
	\c@pgfmathroundto@offsetbehindperiod=0
	\pgfmathroundto@impl@ITERATE@DOT
}
\def\pgfmathroundto@impl@ITERATE@DOT{%
	\pgfutil@ifnextchar\pgfmathfloat@EOI{%
		% finished.
		\pgfmathroundto@impl@gobble@and@start
	}{%
		\pgfmathroundto@impl@NEXT@DOT
	}%
}
\def\pgfmathroundto@impl@NEXT@DOT#1{%
	\ifnum\c@pgfmathroundto@offsetbehindperiod=\c@pgfmathroundto@prec
		\def\pgfmathround@next{#1}%
		\def\pgfmathround@nextcmd{\pgfmathroundto@impl@gobble@rest@and@start}%
	\else
		\advance\c@pgfmathroundto@offsetbehindperiod by1
		\ifnum#1=0
			\advance\c@pgfmathroundto@lastzeros by1
		\else
			\c@pgfmathroundto@lastzeros=0
		\fi
		\pgfmathfloat@tmptoks=\expandafter{\expandafter#1\the\pgfmathfloat@tmptoks}%
		\def\pgfmathround@nextcmd{\pgfmathroundto@impl@ITERATE@DOT}%
	\fi
	\pgfmathround@nextcmd
}%

% in contrast to pgfmathroundto@impl@ITERATE@NODOT, this method here
% checks also for signs
\def\pgfmathroundto@impl@ITERATE@NODOT@firstcall#1{%
	\def\pgfmathround@cur{#1}%
	\ifx\pgfmathround@cur\pgfmathfloat@EOI
		\pgfmathround@impl@PREPERIOD@is@negative@zerofalse
		\def\pgfmathround@nextcmd{\pgfmathroundto@impl@start}%
	\else
		\ifx\pgfmathround@cur\pgfmathfloatparsenumber@tok@PERIOD
			\pgfmathround@impl@PREPERIOD@is@negative@zerofalse
			\def\pgfmathround@nextcmd{\pgfmathroundto@impl@BEGIN@DOT.}%
		\else
			\ifx\pgfmathround@cur\pgfmathfloatparsenumber@tok@MINUS
			\else
				\pgfmathround@impl@PREPERIOD@is@negative@zerofalse
			\fi
			\pgfmathfloat@tmptoks=\expandafter{\expandafter#1\the\pgfmathfloat@tmptoks}%
			\def\pgfmathround@nextcmd{\pgfmathroundto@impl@ITERATE@NODOT}%
		\fi
	\fi
	\pgfmathround@nextcmd
}

\def\pgfmathroundto@impl@ITERATE@NODOT#1{%
	\def\pgfmathround@cur{#1}%
	\ifx\pgfmathround@cur\pgfmathfloat@EOI
		\def\pgfmathround@nextcmd{\pgfmathroundto@impl@start}%
	\else
		\ifx\pgfmathround@cur\pgfmathfloatparsenumber@tok@PERIOD
			\def\pgfmathround@nextcmd{\pgfmathroundto@impl@BEGIN@DOT.}%
		\else
			\ifx\pgfmathround@cur\pgfmathfloatparsenumber@tok@ZERO
			\else
				\pgfmathround@impl@PREPERIOD@is@negative@zerofalse
			\fi
			\pgfmathfloat@tmptoks=\expandafter{\expandafter#1\the\pgfmathfloat@tmptoks}%
			\def\pgfmathround@nextcmd{\pgfmathroundto@impl@ITERATE@NODOT}%
		\fi
	\fi
	\pgfmathround@nextcmd
}

%--------------------------------------------
% END of pgfmathroundto implementation.
%--------------------------------------------


% flags, mantissa and exponent has already been stored into
% \pgfmathfloat@a@* [using ...@Mtok]
%
% PRECONDITION:
%   \ifpgfmathfloatroundhasperiod = \iftrue outside of the current
%   group
%
% POSTCONDITION:
%   \ifpgfmathfloatroundhasperiod will be set after the current TeX
%   group.
\def\pgfmathfloatround@impl{%
	\expandafter\pgfmathroundto@impl\expandafter{\the\pgfmathfloat@a@Mtok}%
	\ifpgfmathfloatroundmayneedrenormalize
		\ifpgfmathfloatroundhasperiod
			\expandafter\pgfmathfloatround@impl@renormalize\pgfmathresult\pgfmathfloat@EOI%
		\else
			\expandafter\pgfmathfloatround@impl@renormalize\pgfmathresult.\pgfmathfloat@EOI%
		\fi
		\advance\pgfmathfloat@a@E by1
	\fi
	\pgfmathfloatcreate{\the\pgfmathfloat@a@S}{\pgfmathresult}{\the\pgfmathfloat@a@E}%
}

\def\pgfmathfloatround@impl@renormalize#1#2.#3\pgfmathfloat@EOI{%
	\pgfmathroundto@impl{#1.#2#3}%
}





% ATTENTION: this thing REQUIRES a period in the mantissa!
% collects everything into \pgfmathresult
\def\pgfmathfloattofixed@impl#1.#2\relax{%
	\ifnum\pgfmathfloat@a@E<0
		\ifcase-\pgfmathfloat@a@E
		\or%e-1
			\pgfmathfloat@a@Mtok={0.}%
		\or%e-2
			\pgfmathfloat@a@Mtok={0.0}%
		\or%e-3
			\pgfmathfloat@a@Mtok={0.00}%
		\or%e-4
			\pgfmathfloat@a@Mtok={0.000}%
		\or%e-5
			\pgfmathfloat@a@Mtok={0.0000}%
		\or%e-6
			\pgfmathfloat@a@Mtok={0.00000}%
		\or%e-7
			\pgfmathfloat@a@Mtok={0.000000}%
		\or%e-8
			\pgfmathfloat@a@Mtok={0.0000000}%
		\or%e-9
			\pgfmathfloat@a@Mtok={0.00000000}%
		\or%e-10
			\pgfmathfloat@a@Mtok={0.000000000}%
		\else%<= -11
			\pgfmathfloat@a@Mtok={0.0000000000}%
			\advance\pgfmathfloat@a@E by10
			\pgfutil@loop
			\ifnum\pgfmathfloat@a@E<-1
				\pgfmathfloat@a@Mtok=\expandafter{\the\pgfmathfloat@a@Mtok 0}%
				\advance\pgfmathfloat@a@E by1
			\pgfutil@repeat
		\fi
		\def\pgfmathfloat@loc@TMPb{#2}%
		\def\pgfmathfloat@loc@TMPc{0}%
		\ifx\pgfmathfloat@loc@TMPb\pgfmathfloat@loc@TMPc
			\edef\pgfmathresult{\the\pgfmathfloat@a@Mtok #1}%
		\else
			\edef\pgfmathresult{\the\pgfmathfloat@a@Mtok #1#2}%
		\fi
	\else
		%--------------------------------------------------
		% \ifnum\pgfmathfloat@a@E=0%
		% 	\edef\pgfmathresult{#1.#2}%
		% \else
		% 	\pgfmathfloat@a@Mtok={#1}%
		% 	\pgfmathfloattofixed@impl@collectmantissa#2\count\pgfmathfloat@a@E
		% 	\edef\pgfmathresult{\the\pgfmathfloat@a@Mtok}%
		% \fi
		%-------------------------------------------------- 
		\pgfmathfloat@a@Mtok{#1}%
		\pgfmathfloattofixed@impl@pos#2000000000\pgfmathfloat@EOI
		\edef\pgfmathresult{\the\pgfmathfloat@a@Mtok}%
	\fi
}

% FIXME: this implementation here is very fast, but it introduces trailing zeros. Is that acceptable?
\def\pgfmathfloattofixed@impl@pos#1#2#3#4#5#6#7#8#9\pgfmathfloat@EOI{%
	\ifcase\pgfmathfloat@a@E
	% e+0
		\pgfmathfloat@a@Mtok\expandafter{\the\pgfmathfloat@a@Mtok .#1#2#3#4#5#6#7#8#9}%
	\or%e+1
		\pgfmathfloat@a@Mtok\expandafter{\the\pgfmathfloat@a@Mtok #1.#2#3#4#5#6#7#8#9}%
	\or%e+2
		\pgfmathfloat@a@Mtok\expandafter{\the\pgfmathfloat@a@Mtok #1#2.#3#4#5#6#7#8#9}%
	\or%e+3
		\pgfmathfloat@a@Mtok\expandafter{\the\pgfmathfloat@a@Mtok #1#2#3.#4#5#6#7#8#9}%
	\or%e+4
		\pgfmathfloat@a@Mtok\expandafter{\the\pgfmathfloat@a@Mtok #1#2#3#4.#5#6#7#8#9}%
	\or%e+5
		\pgfmathfloat@a@Mtok\expandafter{\the\pgfmathfloat@a@Mtok #1#2#3#4#5.#6#7#8#9}%
	\or%e+6
		\pgfmathfloat@a@Mtok\expandafter{\the\pgfmathfloat@a@Mtok #1#2#3#4#5#6.#7#8#9}%
	\or%e+7
		\pgfmathfloat@a@Mtok\expandafter{\the\pgfmathfloat@a@Mtok #1#2#3#4#5#6#7.#8#9}%
	\or%e+8
		\pgfmathfloat@a@Mtok\expandafter{\the\pgfmathfloat@a@Mtok #1#2#3#4#5#6#7#8.#9}%
	\else%>=9
		\pgfmathfloat@a@Mtok\expandafter{\the\pgfmathfloat@a@Mtok #1#2#3#4#5#6#7#8}%
		\advance\pgfmathfloat@a@E by-8
		\pgfmathfloattofixed@impl@collectmantissa#9\count\pgfmathfloat@a@E
	\fi
}%

\def\pgfmathfloattofixed@impl@collectmantissa#1#2\count#3{%
	\pgfmathfloat@a@Mtok=\expandafter{\the\pgfmathfloat@a@Mtok #1}%
	\advance\pgfmathfloat@a@E by-1%
	\def\pgfmathfloat@loc@TMPb{#2}%
	\ifx\pgfmathfloat@loc@TMPb\pgfutil@empty
		\pgfutil@loop
		\ifnum\pgfmathfloat@a@E>0%
			\pgfmathfloat@a@Mtok=\expandafter{\the\pgfmathfloat@a@Mtok 0}%
			\advance\pgfmathfloat@a@E by-1%
		\pgfutil@repeat
		\pgfmathfloat@a@Mtok=\expandafter{\the\pgfmathfloat@a@Mtok .0}%
	\else
		\ifnum\pgfmathfloat@a@E=0
			\pgfmathfloat@a@Mtok=\expandafter{\the\pgfmathfloat@a@Mtok .#2}%
		\else
			\pgfmathfloattofixed@impl@collectmantissa#2\count#3%
		\fi
	\fi
}


% ============================================
%
%
% \pgfmathfloatparsenumber implementation
%
%
% ============================================

% accepted parser tokens:
\def\pgfmathfloatparsenumber@tok@ZERO{0}
\def\pgfmathfloatparsenumber@tok@PLUS{+}
\def\pgfmathfloatparsenumber@tok@MINUS{-}
\def\pgfmathfloatparsenumber@tok@PERIOD{.}

\newif\ifpgfmathfloatparsenumberpendingperiod

\def\pgfflt@EOI{p@EOI}%
\def\pgfflt@EOI@unexpanded{\pgfflt@EOI}%

% Starts a finite-start-machine parser to read a number.
%
% The machine's state is represented by the macro which is currently
% processed; state transitions are realised using \csname...#1\endcsname
% constructions.
%
% It assigns \pgfmathfloat@a@S, \pgfmathfloat@a@Mtok, \pgfmathfloat@a@E.
\def\pgfflt@impl#1{%
	\pgfmathfloatparsenumberpendingperiodfalse
	\pgfmathfloat@tmptoks={}% this register is used to collect PENDING ZEROS
	\pgfmathfloat@a@E=0
	% start parsing: check for sign:
	\expandafter\ifx\csname pgfflt@#1\endcsname\relax
		\pgfmathfloat@a@S=1
		\expandafter\pgfflt@init\expandafter#1%
	\else
		\expandafter\expandafter\csname pgfflt@#1\endcsname
	\fi
}
% State transitions:
\expandafter\def\csname pgfflt@+\endcsname{%
	\pgfmathfloat@a@S=1 %
	\pgfflt@init}%
\expandafter\def\csname pgfflt@-\endcsname{%
	\pgfmathfloat@a@S=2 %
	\pgfflt@init}%
\expandafter\def\csname pgfflt@\pgfflt@EOI\endcsname{%
	\pgfmathfloatparsenumber@handleerror{empty number}{}{}}%

\pgfkeys{
	/pgf/fpu/handlers/empty number/.style 2 args={%
		/pgf/fpu/handlers/invalid number={#1}{#2}%
	},
	/pgf/fpu/empty number is zero/.style={%
		/pgf/fpu/handlers/empty number/.code 2 args={%
			\pgfmathfloatcreate{0}{0.0}{0}%
		}%
	},%
	/pgf/fpu/handlers/invalid number/.code 2 args={%
		\pgfmath@error{Could not parse input '#1' as a floating point number, sorry. The unreadable part was near '#2'.}{}%
	},
	/pgf/fpu/handlers/wrong lowlevel format/.code 2 args={%
		\pgfmath@error{Sorry, an internal routine of the floating point unit got an ill-formatted floating point number `#1'. The unreadable part was near '#2'.}{}%
		\let\pgfmathresult=\pgfutil@empty
	},
}

% #1 the error handler
% #2 the number which was invalid.
% #3 the part which produced the error
%
% POSTCONDITION: the three registers
% 	\pgfmathfloat@a@S
% 	\pgfmathfloat@a@Mtok
% 	\pgfmathfloat@a@E
% will contain the number which results from the error handler.
\def\pgfmathfloatparsenumber@handleerror#1#2#3{%
	\let\pgfmathresult=\pgfutil@empty
	\pgfmathfloatparsenumberpendingperiodfalse
	\pgfkeys{/pgf/fpu/handlers/#1={#2}{#3}}%
	\ifx\pgfmathresult\pgfutil@empty
		\pgfmathfloat@a@S=3
		\pgfmathfloat@a@Mtok={0.0}%
		\pgfmathfloat@a@E=0
	\else
		\expandafter\pgfmathfloat@decompose@tok\pgfmathresult\relax\pgfmathfloat@a@S\pgfmathfloat@a@Mtok\pgfmathfloat@a@E
	\fi
}
\def\pgfflt@error#1\pgfflt@EOI{%
	\begingroup
	\pgfmathfloat@a@Mtok={#1}%
	\xdef\pgfmathfloat@glob@TMP{%
		\noexpand\pgfmathfloatparsenumber@handleerror
			{invalid number}{\pgfmathresult}{\the\pgfmathfloat@a@Mtok}}%
	\endgroup
	\pgfmathfloat@glob@TMP
}%



% FROM: checksign.
%
\def\pgfflt@init#1{%
	\expandafter\ifx\csname pgffltA@#1\endcsname\relax
		\expandafter\pgfflt@error\expandafter#1%
	\else
		\expandafter\expandafter\csname pgffltA@#1\endcsname
	\fi}
% state transitions:
\expandafter\def\csname pgffltA@0\endcsname{\pgfflt@leadingzero}% FIXME: inline optimization!
\expandafter\def\csname pgffltA@1\endcsname{\pgfflt@nonzerodigit1}%
\expandafter\def\csname pgffltA@2\endcsname{\pgfflt@nonzerodigit2}%
\expandafter\def\csname pgffltA@3\endcsname{\pgfflt@nonzerodigit3}%
\expandafter\def\csname pgffltA@4\endcsname{\pgfflt@nonzerodigit4}%
\expandafter\def\csname pgffltA@5\endcsname{\pgfflt@nonzerodigit5}%
\expandafter\def\csname pgffltA@6\endcsname{\pgfflt@nonzerodigit6}%
\expandafter\def\csname pgffltA@7\endcsname{\pgfflt@nonzerodigit7}%
\expandafter\def\csname pgffltA@8\endcsname{\pgfflt@nonzerodigit8}%
\expandafter\def\csname pgffltA@9\endcsname{\pgfflt@nonzerodigit9}%
\def\pgfflt@nonzerodigit#1{%
	\pgfmathfloat@a@Mtok={#1}%
	\pgfmathfloatparsenumberpendingperiodtrue
	\pgfflt@positiveexp}%
\expandafter\def\csname pgffltA@n\endcsname{\pgfflt@readnan}% FIXME: inlining?
\expandafter\def\csname pgffltA@N\endcsname{\pgfflt@readnan}% FIXME: inlining?
\expandafter\def\csname pgffltA@i\endcsname{\pgfflt@readinf}% FIXME: inlining?
\expandafter\def\csname pgffltA@I\endcsname{\pgfflt@readinf}% FIXME: inlining?
\expandafter\def\csname pgffltA@.\endcsname{% read '.9' like '0.9'
	\pgfmathfloat@a@E=-1
	\pgfflt@leadingzero@foundperiod}%

\def\pgfflt@finish#1\pgfflt@EOI{}

\def\pgfflt@readnan #1#2{%
	\def\pgfflt@readnan@ok{1}%
	\if#1a\else\if#1A\else\def\pgfflt@readnan@ok{0}\fi\fi
	\if#2n\else\if#2N\else\def\pgfflt@readnan@ok{0}\fi\fi
	\if\pgfflt@readnan@ok1%
		\pgfmathfloat@a@S=3\relax%
		\pgfmathfloat@a@Mtok={0.0}%
		\pgfmathfloat@a@E=0%
		\expandafter\pgfflt@finish
	\else
		\def\pgfflt@readnan@{\pgfflt@error #1#2}%
		\expandafter\pgfflt@readnan@
	\fi
}
\def\pgfflt@readinf #1#2{%
	\def\pgfflt@readinf@ok{1}%
	\if#1n\else\if#1N\else\def\pgfflt@readinf@ok{0}\fi\fi
	\if#2f\else\if#2F\else\def\pgfflt@readinf@ok{0}\fi\fi
	\if\pgfflt@readinf@ok1%
		\ifnum\pgfmathfloat@a@S=1 %
			\pgfmathfloat@a@S=4 %
			\pgfmathfloat@a@Mtok={0.0}%
		\else
			\pgfmathfloat@a@S=5 %
			\pgfmathfloat@a@Mtok={0.0}%
		\fi
		\pgfmathfloat@a@E=0 %
		\expandafter\pgfflt@finish
	\else
		\def\pgfflt@readinf@{\pgfflt@error #1#2}%
		\expandafter\pgfflt@readinf@
	\fi
}
\def\pgfflt@leadingzero#1{%
	\expandafter\ifx\csname pgffltB@#1\endcsname\relax
		\expandafter\pgfflt@error\expandafter#1%
	\else
		\expandafter\expandafter\csname pgffltB@#1\endcsname
	\fi}
% State transitions:
\expandafter\def\csname pgffltB@0\endcsname{\pgfflt@leadingzero}%
\expandafter\def\csname pgffltB@1\endcsname{\pgfmathfloat@a@Mtok={1}\pgfmathfloatparsenumberpendingperiodtrue \pgfflt@positiveexp}
\expandafter\def\csname pgffltB@2\endcsname{\pgfmathfloat@a@Mtok={2}\pgfmathfloatparsenumberpendingperiodtrue \pgfflt@positiveexp}
\expandafter\def\csname pgffltB@3\endcsname{\pgfmathfloat@a@Mtok={3}\pgfmathfloatparsenumberpendingperiodtrue \pgfflt@positiveexp}
\expandafter\def\csname pgffltB@4\endcsname{\pgfmathfloat@a@Mtok={4}\pgfmathfloatparsenumberpendingperiodtrue \pgfflt@positiveexp}
\expandafter\def\csname pgffltB@5\endcsname{\pgfmathfloat@a@Mtok={5}\pgfmathfloatparsenumberpendingperiodtrue \pgfflt@positiveexp}
\expandafter\def\csname pgffltB@6\endcsname{\pgfmathfloat@a@Mtok={6}\pgfmathfloatparsenumberpendingperiodtrue \pgfflt@positiveexp}
\expandafter\def\csname pgffltB@7\endcsname{\pgfmathfloat@a@Mtok={7}\pgfmathfloatparsenumberpendingperiodtrue \pgfflt@positiveexp}
\expandafter\def\csname pgffltB@8\endcsname{\pgfmathfloat@a@Mtok={8}\pgfmathfloatparsenumberpendingperiodtrue \pgfflt@positiveexp}
\expandafter\def\csname pgffltB@9\endcsname{\pgfmathfloat@a@Mtok={9}\pgfmathfloatparsenumberpendingperiodtrue \pgfflt@positiveexp}
\expandafter\def\csname pgffltB@\pgfmathfloat@POSTFLAGSCHAR\endcsname{\pgfmathfloat@a@Mtok={0}\pgfflt@readlowlevelfloat}%
\expandafter\def\csname pgffltB@.\endcsname{%
	\pgfmathfloat@a@E=-1
	\pgfflt@leadingzero@foundperiod}%
\expandafter\def\csname pgffltB@e\endcsname{%
	\pgfmathfloat@a@S=0\relax%
	\pgfmathfloat@a@Mtok={0.0}%
	\pgfmathfloat@a@E=0%
	\pgfflt@readexponent}%
\let\pgffltB@E=\pgffltB@e
\expandafter\def\csname pgffltB@\pgfflt@EOI\endcsname{%
	\pgfmathfloat@a@S=0\relax%
	\pgfmathfloat@a@Mtok={0.0}%
	\pgfmathfloat@a@E=0}%

\def\pgfflt@leadingzero@foundperiod#1{%
	\expandafter\ifx\csname pgffltC@#1\endcsname\relax
		\expandafter\pgfflt@error\expandafter#1%
	\else
		\expandafter\expandafter\csname pgffltC@#1\endcsname
	\fi}
% State transitions:
\expandafter\def\csname pgffltC@0\endcsname{%
	\advance\pgfmathfloat@a@E by-1
	\pgfflt@leadingzero@foundperiod}%
\expandafter\def\csname pgffltC@1\endcsname{\pgfmathfloat@a@Mtok={1}\pgfmathfloatparsenumberpendingperiodtrue\pgfflt@finish@number@after@period}%
\expandafter\def\csname pgffltC@2\endcsname{\pgfmathfloat@a@Mtok={2}\pgfmathfloatparsenumberpendingperiodtrue\pgfflt@finish@number@after@period}%
\expandafter\def\csname pgffltC@3\endcsname{\pgfmathfloat@a@Mtok={3}\pgfmathfloatparsenumberpendingperiodtrue\pgfflt@finish@number@after@period}%
\expandafter\def\csname pgffltC@4\endcsname{\pgfmathfloat@a@Mtok={4}\pgfmathfloatparsenumberpendingperiodtrue\pgfflt@finish@number@after@period}%
\expandafter\def\csname pgffltC@5\endcsname{\pgfmathfloat@a@Mtok={5}\pgfmathfloatparsenumberpendingperiodtrue\pgfflt@finish@number@after@period}%
\expandafter\def\csname pgffltC@6\endcsname{\pgfmathfloat@a@Mtok={6}\pgfmathfloatparsenumberpendingperiodtrue\pgfflt@finish@number@after@period}%
\expandafter\def\csname pgffltC@7\endcsname{\pgfmathfloat@a@Mtok={7}\pgfmathfloatparsenumberpendingperiodtrue\pgfflt@finish@number@after@period}%
\expandafter\def\csname pgffltC@8\endcsname{\pgfmathfloat@a@Mtok={8}\pgfmathfloatparsenumberpendingperiodtrue\pgfflt@finish@number@after@period}%
\expandafter\def\csname pgffltC@9\endcsname{\pgfmathfloat@a@Mtok={9}\pgfmathfloatparsenumberpendingperiodtrue\pgfflt@finish@number@after@period}%
\expandafter\def\csname pgffltC@e\endcsname{%
	\pgfmathfloat@a@S=0\relax%
	\pgfmathfloat@a@Mtok={0.0}%
	\pgfmathfloat@a@E=0%
	\pgfflt@readexponent}%
\let\pgffltC@E=\pgffltC@e
\expandafter\def\csname pgffltC@\pgfflt@EOI\endcsname{%
	\pgfmathfloat@a@S=0\relax%
	\pgfmathfloat@a@Mtok={0.0}%
	\pgfmathfloat@a@E=0}%


\def\pgfflt@positiveexp#1{%
	\expandafter\ifx\csname pgffltD@#1\endcsname\relax
		\expandafter\pgfflt@error\expandafter#1%
	\else
		\expandafter\expandafter\csname pgffltD@#1\endcsname
	\fi}
% State transitions:
\expandafter\def\csname pgffltD@0\endcsname{%
	\advance\pgfmathfloat@a@E by1
	\pgfmathfloat@tmptoks=\expandafter{\the\pgfmathfloat@tmptoks0}%
	\pgfflt@pendingzeros@positiveexp}%
\expandafter\def\csname pgffltD@1\endcsname{\pgffltD@nonzerodigit1}%
\expandafter\def\csname pgffltD@2\endcsname{\pgffltD@nonzerodigit2}%
\expandafter\def\csname pgffltD@3\endcsname{\pgffltD@nonzerodigit3}%
\expandafter\def\csname pgffltD@4\endcsname{\pgffltD@nonzerodigit4}%
\expandafter\def\csname pgffltD@5\endcsname{\pgffltD@nonzerodigit5}%
\expandafter\def\csname pgffltD@6\endcsname{\pgffltD@nonzerodigit6}%
\expandafter\def\csname pgffltD@7\endcsname{\pgffltD@nonzerodigit7}%
\expandafter\def\csname pgffltD@8\endcsname{\pgffltD@nonzerodigit8}%
\expandafter\def\csname pgffltD@9\endcsname{\pgffltD@nonzerodigit9}%
\expandafter\def\csname pgffltD@\pgfmathfloat@POSTFLAGSCHAR\endcsname{\pgfflt@readlowlevelfloat}%
\expandafter\def\csname pgffltD@.\endcsname{\pgfflt@finish@number@after@period}% FIXME : inlining?
\expandafter\def\csname pgffltD@e\endcsname{\pgfflt@readexponent}% FIXME : inlining?
\let\pgffltD@E=\pgffltD@e
\expandafter\def\csname pgffltD@\pgfflt@EOI\endcsname{}% NOP
\def\pgffltD@nonzerodigit#1{%
	\advance\pgfmathfloat@a@E by1
	\ifpgfmathfloatparsenumberpendingperiod
		\pgfmathfloat@a@Mtok=\expandafter{\the\pgfmathfloat@a@Mtok.}%
		\pgfmathfloatparsenumberpendingperiodfalse
	\fi
	\pgfmathfloat@a@Mtok=\expandafter{\the\pgfmathfloat@a@Mtok#1}%
	\pgfflt@positiveexp}%

% Read a low-level floating point.
% Since we are in the second state, \pgfmathfloat@a@Mtok contains the
% FLAGS. The post-flags-char has also been read.
\def\pgfflt@readlowlevelfloat#1e#2]\pgfflt@EOI{%
	\pgfmathfloatparsenumberpendingperiodfalse
	\pgfmathfloat@a@S=\the\pgfmathfloat@a@Mtok\relax
	\pgfmathfloat@a@Mtok={#1}%
	\pgfmathfloat@a@E=#2
}%

\def\pgfflt@readexponent#1\pgfflt@EOI{%
	\afterassignment\pgfflt@readexponent@
	\pgfmathfloat@b@E=#1 \pgfflt@EOI% the white space is important, otherwise \pgfflt@EOI will be expanded.
}
\def\pgfflt@readexponent@#1{%
	\advance\pgfmathfloat@a@E by\pgfmathfloat@b@E\relax
	%
	% sanity checking:
	\def\pgfmathfloat@loc@TMPb{#1}%
	\ifx\pgfmathfloat@loc@TMPb\pgfflt@EOI@unexpanded
	\else
		\def\pgfmathfloat@loc@TMPb{\pgfflt@error#1}%
		\expandafter\pgfmathfloat@loc@TMPb
	\fi
}

\def\pgfflt@pendingzeros@positiveexp#1{%
	\expandafter\ifx\csname pgffltE@#1\endcsname\relax
		\expandafter\pgfflt@error\expandafter#1%
	\else
		\expandafter\expandafter\csname pgffltE@#1\endcsname
	\fi}
% State transitions:
\expandafter\def\csname pgffltE@0\endcsname{%
	\pgfmathfloat@tmptoks=\expandafter{\the\pgfmathfloat@tmptoks0}%
	\advance\pgfmathfloat@a@E by1
	\pgfflt@pendingzeros@positiveexp}%
\expandafter\def\csname pgffltE@1\endcsname{\pgffltE@nonzerodigit1}%
\expandafter\def\csname pgffltE@2\endcsname{\pgffltE@nonzerodigit2}%
\expandafter\def\csname pgffltE@3\endcsname{\pgffltE@nonzerodigit3}%
\expandafter\def\csname pgffltE@4\endcsname{\pgffltE@nonzerodigit4}%
\expandafter\def\csname pgffltE@5\endcsname{\pgffltE@nonzerodigit5}%
\expandafter\def\csname pgffltE@6\endcsname{\pgffltE@nonzerodigit6}%
\expandafter\def\csname pgffltE@7\endcsname{\pgffltE@nonzerodigit7}%
\expandafter\def\csname pgffltE@8\endcsname{\pgffltE@nonzerodigit8}%
\expandafter\def\csname pgffltE@9\endcsname{\pgffltE@nonzerodigit9}%
\expandafter\def\csname pgffltE@.\endcsname{\pgfflt@finish@number@after@period}% FIXME : inlining?
\def\pgffltE@e{\pgfflt@readexponent}% FIXME : inlining?
\let\pgffltE@E=\pgffltE@e
\expandafter\def\csname pgffltE@\pgfflt@EOI\endcsname{}% NOP
\def\pgffltE@nonzerodigit#1{%
	\advance\pgfmathfloat@a@E by1
	\ifpgfmathfloatparsenumberpendingperiod
		\pgfmathfloat@a@Mtok=\expandafter{\the\pgfmathfloat@a@Mtok.}%
		\pgfmathfloatparsenumberpendingperiodfalse
	\fi
	\pgfmathfloat@a@Mtok=\expandafter\expandafter\expandafter{\expandafter\the\expandafter\pgfmathfloat@a@Mtok\the\pgfmathfloat@tmptoks}%
	\pgfmathfloat@tmptoks={}%
	\pgfmathfloat@a@Mtok=\expandafter{\the\pgfmathfloat@a@Mtok#1}%
	\pgfflt@positiveexp}%

\def\pgfflt@finish@number@after@period#1{%
	\expandafter\ifx\csname pgffltF@#1\endcsname\relax
		\expandafter\pgfflt@error\expandafter#1%
	\else
		\expandafter\expandafter\csname pgffltF@#1\endcsname
	\fi}
% State transitions:
\expandafter\def\csname pgffltF@0\endcsname{%
	\pgfmathfloat@tmptoks=\expandafter{\the\pgfmathfloat@tmptoks0}%
	\pgfflt@pendingzeros}%
\expandafter\def\csname pgffltF@1\endcsname{\pgffltF@nonzerodigit1}%
\expandafter\def\csname pgffltF@2\endcsname{\pgffltF@nonzerodigit2}%
\expandafter\def\csname pgffltF@3\endcsname{\pgffltF@nonzerodigit3}%
\expandafter\def\csname pgffltF@4\endcsname{\pgffltF@nonzerodigit4}%
\expandafter\def\csname pgffltF@5\endcsname{\pgffltF@nonzerodigit5}%
\expandafter\def\csname pgffltF@6\endcsname{\pgffltF@nonzerodigit6}%
\expandafter\def\csname pgffltF@7\endcsname{\pgffltF@nonzerodigit7}%
\expandafter\def\csname pgffltF@8\endcsname{\pgffltF@nonzerodigit8}%
\expandafter\def\csname pgffltF@9\endcsname{\pgffltF@nonzerodigit9}%
\def\pgffltF@e{\pgfflt@readexponent}%
\let\pgffltF@E=\pgffltF@e
\expandafter\def\csname pgffltF@\pgfflt@EOI\endcsname{}% NOP
\def\pgffltF@nonzerodigit#1{%
	\ifpgfmathfloatparsenumberpendingperiod
		\pgfmathfloat@a@Mtok=\expandafter{\the\pgfmathfloat@a@Mtok.}%
		\pgfmathfloatparsenumberpendingperiodfalse
	\fi
	\pgfmathfloat@a@Mtok=\expandafter\expandafter\expandafter{\expandafter\the\expandafter\pgfmathfloat@a@Mtok\the\pgfmathfloat@tmptoks}%
	\pgfmathfloat@tmptoks={}%
	\pgfmathfloat@a@Mtok=\expandafter{\the\pgfmathfloat@a@Mtok#1}%
	\pgfflt@finish@number@after@period}%


\def\pgfflt@pendingzeros#1{%
	\expandafter\ifx\csname pgffltG@#1\endcsname\relax
		\expandafter\pgfflt@error\expandafter#1%
	\else
		\expandafter\expandafter\csname pgffltG@#1\endcsname
	\fi}
% State transitions:
\expandafter\def\csname pgffltG@0\endcsname{%
	\pgfmathfloat@tmptoks=\expandafter{\the\pgfmathfloat@tmptoks0}%
	\pgfflt@pendingzeros}%
\expandafter\def\csname pgffltG@1\endcsname{\pgffltG@nonzerodigit1}%
\expandafter\def\csname pgffltG@2\endcsname{\pgffltG@nonzerodigit2}%
\expandafter\def\csname pgffltG@3\endcsname{\pgffltG@nonzerodigit3}%
\expandafter\def\csname pgffltG@4\endcsname{\pgffltG@nonzerodigit4}%
\expandafter\def\csname pgffltG@5\endcsname{\pgffltG@nonzerodigit5}%
\expandafter\def\csname pgffltG@6\endcsname{\pgffltG@nonzerodigit6}%
\expandafter\def\csname pgffltG@7\endcsname{\pgffltG@nonzerodigit7}%
\expandafter\def\csname pgffltG@8\endcsname{\pgffltG@nonzerodigit8}%
\expandafter\def\csname pgffltG@9\endcsname{\pgffltG@nonzerodigit9}%
\def\pgffltG@e{\pgfflt@readexponent}% FIXME: inlining?
\let\pgffltG@E=\pgffltG@e
\expandafter\def\csname pgffltG@\pgfflt@EOI\endcsname{}% NOP
\def\pgffltG@nonzerodigit#1{%
	\ifpgfmathfloatparsenumberpendingperiod
		\pgfmathfloat@a@Mtok=\expandafter{\the\pgfmathfloat@a@Mtok.}%
		\pgfmathfloatparsenumberpendingperiodfalse
	\fi
	\pgfmathfloat@a@Mtok=\expandafter\expandafter\expandafter{\expandafter\the\expandafter\pgfmathfloat@a@Mtok\the\pgfmathfloat@tmptoks}%
	\pgfmathfloat@tmptoks={}%
	\pgfmathfloat@a@Mtok=\expandafter{\the\pgfmathfloat@a@Mtok#1}%
	\pgfflt@finish@number@after@period}%

\endinput

pgfmathfunctions.base.code.tex
% Copyright 2007 by Mark Wibrow
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.
%
% This file provides basic macros for converting between bases.
%
% Version 1.4142135 8/11/2008

% Base conversion operations for the parser.
%
\pgfmathdeclarefunction{bin}{1}{%
	\begingroup%
		\afterassignment\pgfmath@gobbletilpgfmath@%
		\c@pgfmath@counta=#1\relax\pgfmath@%
		\expandafter\pgfmathbasetobase\expandafter\pgfmathresult\expandafter{\the\c@pgfmath@counta}{10}{2}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}
\pgfmathdeclarefunction{hex}{1}{%
	\begingroup%
		\afterassignment\pgfmath@gobbletilpgfmath@%
		\c@pgfmath@counta=#1\relax\pgfmath@%
		\expandafter\pgfmathbasetobase\expandafter\pgfmathresult\expandafter{\the\c@pgfmath@counta}{10}{16}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}	

\pgfmathdeclarefunction{Hex}{1}{%
	\begingroup%
		\afterassignment\pgfmath@gobbletilpgfmath@%
		\c@pgfmath@counta=#1\relax\pgfmath@%
		\expandafter\pgfmathbasetoBase\expandafter\pgfmathresult\expandafter{\the\c@pgfmath@counta}{10}{16}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

\pgfmathdeclarefunction{oct}{1}{%
	\begingroup%
		\afterassignment\pgfmath@gobbletilpgfmath@%
		\c@pgfmath@counta=#1\relax\pgfmath@%
		\expandafter\pgfmathbasetobase\expandafter\pgfmathresult\expandafter{\the\c@pgfmath@counta}{10}{8}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% Additional macros:

% \pgfmathbasetodec
%
% Convert a representation of an integer from 
% the spcified base to base 10.
%
% #1 - a macro to store the result.
% #2 - the representation of a number (i.e. not a register)
% #3 - the current base.
%
% e.g.
%
% \pgfmathbasetodec\mynumber{10111}{2}
%
% \mynumber <- 23
%
\def\pgfmathbasetodec#1#2#3{%
	\pgfmath@checknumber{#2}%
	\pgfmath@checkbase{#3}%
	\def\pgfmath@base{#3}%
	\def\pgfmath@base@macro{#1}%
	\c@pgfmath@counta=1\relax%
	\let\pgfmath@reversed=\pgfmath@empty%
	\expandafter\pgfmathbasetodec@#2\pgfmath@base@stop}
	
\def\pgfmathbasetodec@#1{%
	\ifx#1\pgfmath@base@stop%
		\c@pgfmath@countb=0%
		\divide\c@pgfmath@counta by\pgfmath@base\relax%
		\expandafter\pgfmathbasetodec@@%
	\else%
		\edef\pgfmath@reversed{\pgfmath@reversed#1}%
		\expandafter\multiply\expandafter\c@pgfmath@counta\pgfmath@base\relax%
		\expandafter\pgfmathbasetodec@%
	\fi}

\def\pgfmathbasetodec@@{\expandafter\pgfmathbasetodec@@@\pgfmath@reversed\pgfmathbasetodec}
	
\def\pgfmathbasetodec@@@#1{%
	\ifx\pgfmathbasetodec#1\relax%
		\expandafter\edef\pgfmath@base@macro{\the\c@pgfmath@countb}%
		\let\pgfmath@next=\pgfmathbasetodec@@@@%
	\else%
		\chardef\pgfmath@charnum`#1\relax%
		\c@pgfmath@countc=\pgfmath@charnum\relax%
		\ifnum\c@pgfmath@countc>96\relax%
			\advance\c@pgfmath@countc by-87\relax%
		\else
			\ifnum\c@pgfmath@countc>64\relax%
				\advance\c@pgfmath@countc by-55\relax%
			\else
				\advance\c@pgfmath@countc by-48\relax%
			\fi%
		\fi%
		\ifnum\c@pgfmath@countc<\pgfmath@base\relax%
			\multiply\c@pgfmath@countc by\c@pgfmath@counta%
			\advance\c@pgfmath@countb by\c@pgfmath@countc%
			\divide\c@pgfmath@counta by\pgfmath@base\relax%
			\let\pgfmath@next\pgfmathbasetodec@@@%
		\else
			\pgfmath@error{Digit `#1' invalid for base \pgfmath@base}%
			\let\pgfmath@next=\relax%
		\fi%	
	\fi%
	\pgfmath@next}
\def\pgfmathbasetodec@@@@{%
	\expandafter\pgfmath@ensurenumberlength\expandafter{\pgfmath@base@macro}%
}

% \pgfmathdectobase
%
% Convert a representation of an integer from 
% base 10 to the spcified base. Letters for bases
% greater than 10 are in lowercase.
%
% #1 - a macro to store the result.
% #2 - a number in base 10 (in a macro, not a register)
% #3 - the required base.
%
% e.g.
%
% \pgfmathdectobase\mynumber{127}{16}
%
% \mynumber <- 7f
%
\def\pgfmathdectobase#1#2#3{%
	\pgfmath@checknumber{#2}%
	\pgfmath@checkbase{#3}%
	\c@pgfmath@counta=#2\relax%
	\let#1=\pgfmath@empty%
	\pgfmathloop
		\ifnum\c@pgfmath@counta>0\relax%
			\c@pgfmath@countb=\c@pgfmath@counta%
			\divide\c@pgfmath@countb by#3\relax%
			\multiply\c@pgfmath@countb by-#3\relax%
			\advance\c@pgfmath@countb by\c@pgfmath@counta%
			\edef#1{\csname pgfmath@lowercase digit@\the\c@pgfmath@countb\endcsname#1}%
			\divide\c@pgfmath@counta by#3\relax%
	\repeatpgfmathloop%
	\pgfmath@ensurenumberlength{#1}}

% \pgfmathdectoBase
%
% Convert a representation of an integer from 
% base 10 to the spcified base. Letters for bases
% greater than 10 are in uppercase.
%
% #1 - a macro to store the result.
% #2 - a number in base 10 (in a macro, not a register)
% #3 - the required base.
%
% e.g.
%
% \pgfmathdectoBase\mynumber{127}{16}
%
% \mynumber <- 7F
%	
\def\pgfmathdectoBase#1#2#3{%
	\pgfmath@checkbase{#3}%
	\pgfmath@checknumber{#2}%
	\c@pgfmath@counta=#2\relax%
	\let#1=\pgfmath@empty%
	\pgfmathloop
		\ifnum\c@pgfmath@counta>0\relax%
			\c@pgfmath@countb=\c@pgfmath@counta%
			\divide\c@pgfmath@countb by#3\relax%
			\multiply\c@pgfmath@countb by-#3\relax%
			\advance\c@pgfmath@countb by\c@pgfmath@counta%
			\edef#1{\csname pgfmath@uppercase digit@\the\c@pgfmath@countb\endcsname#1}%
			\divide\c@pgfmath@counta by#3\relax%
	\repeatpgfmathloop%
	\pgfmath@ensurenumberlength{#1}}

\def\pgfmath@base@digits@create{%
	\def\pgfmath@base@digit@style{lowercase digit}%
	\c@pgfmath@counta=0\relax%
	\pgfmath@base@digits@create@0123456789abcdefghijklmnopqrstuvwxyz\pgfmath@base@digits@create%
	\def\pgfmath@base@digit@style{uppercase digit}%
	\c@pgfmath@counta=0\relax%
	\pgfmath@base@digits@create@0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\pgfmath@base@digits@create}

\def\pgfmath@base@digits@create@#1{%
	\ifx\pgfmath@base@digits@create#1\relax%
	\else%
		\expandafter\pgfmath@def\expandafter{\pgfmath@base@digit@style}{\the\c@pgfmath@counta}{#1}%
		\advance\c@pgfmath@counta by1\relax%
		\expandafter\pgfmath@base@digits@create@%
	\fi}
\pgfmath@base@digits@create

% \pgfmathbasetobase
%
% Convert a representation of an integer from 
% between the specified bases. Letters for target
% bases greater than 10 are in lppercase.
%
% #1 - a macro to store the result.
% #2 - a number (in a macro, not a register)
% #3 - the source base.
% #4 - the target base.
%
% e.g.
%
% \pgfmathbasetobase\mynumber{4321}{5}{9}
%
% \mynumber <- 721
%	
\def\pgfmathbasetobase#1#2#3#4{%
	\pgfmathbasetodec{\pgfmath@base@temp}{#2}{#3}%
	\pgfmathdectobase{#1}{\pgfmath@base@temp}{#4}%
}

% \pgfmathbasetobase
%
% Convert a representation of an integer from 
% between the specified bases. Letters for target
% bases greater than 10 are in uppercase.
%
% #1 - a macro to store the result.
% #2 - a number (in a macro, not a register)
% #3 - the source base.
% #4 - the target base.
%
% e.g.
%
% \pgfmathbasetobase\mynumber{1234}{5}{12}
%
% \mynumber <- 142
%	
\def\pgfmathbasetoBase#1#2#3#4{%
	\pgfmathbasetodec{\pgfmath@base@temp}{#2}{#3}%
	\pgfmathdectoBase{#1}{\pgfmath@base@temp}{#4}%
}

\def\pgfmath@checkbase#1{%
	\ifnum#1<2\relax%
		\pgfmath@error{Cannot process numbers in base `#1'.}%
	\else%
		\ifnum#1>36\relax%
			\pgfmath@error{Cannot process numbers in base `#1'.}%
		\fi%
	\fi}
	
\def\pgfmath@checknumber#1{%
	\expandafter\pgfmath@checknumber@#1\pgfmath@}
\def\pgfmath@checknumber@#1#2\pgfmath@{%
	\ifx#1-%
		\pgfmath@error{Cannot process negative numbers.}%
	\fi}

% \pgfmath@ensurenumberlength
%
% Internal macro for making a representation of a number have
% a specific length, byt prefixing zeros to the number.
%
% #1 - a macro contatining a representation of an integer.
% #2 - the number of digits to ensure.
%
% e.g.
%
% \foo <- 7FF
%
% \pgfmathsetnumberlength{8}%
% \pgfmath@ensurenumberlength\foo
%
% \foo <- 000007FF
%
\def\pgfmath@ensurenumberlength#1{%
	\def\pgfmath@base@tempa{#1}%
	\expandafter\c@pgfmath@counta\pgfmath@basenumberlength\relax%
	\expandafter\pgfmath@ensurenumberlength@#1\pgfmath@ensurenumberlength}
\def\pgfmath@ensurenumberlength@#1{%
	\ifx\pgfmath@ensurenumberlength#1\relax%
		\expandafter\pgfmath@ensurenumberlength@@%
	\else%
		\advance\c@pgfmath@counta by-1\relax%
		\expandafter\pgfmath@ensurenumberlength@
	\fi}

\def\pgfmath@ensurenumberlength@@{%
	\edef\pgfmath@base@tempb{\pgfmath@base@tempa}%
	\pgfmath@ensurenumberlength@@@}
\def\pgfmath@ensurenumberlength@@@{%
	\ifnum\c@pgfmath@counta>0\relax%
		\advance\c@pgfmath@counta by-1\relax%
		\edef\pgfmath@base@tempb{0\pgfmath@base@tempb}%
		\expandafter\pgfmath@ensurenumberlength@@@%
	\fi%
	\expandafter\edef\pgfmath@base@tempa{\pgfmath@base@tempb}}
	
\def\pgfmathsetbasenumberlength#1{\def\pgfmath@basenumberlength{#1}}
\pgfmathsetbasenumberlength{1}%

% \pgfmathtodigitlist\marg{macro}\marg{number}}
%
%	This command converts \meta{number} into a comma-separated
%	list of digits and stores the result in \meta{macro}. 
%	The \marg{number} is \emph{not} parsed before processing.
%
\def\pgfmathtodigitlist#1#2{%
	\def\pgfmath@temp{#1}%
	\let\pgfmath@digitlist=\pgfutil@empty%
	\edef\pgfmath@@tmp{#2}%
	\expandafter\pgfmath@todigitlist\pgfmath@@tmp @%
}
\def\pgfmath@base@atchar{@}
\def\pgfmath@todigitlist#1{%
	\def\pgfmath@digit{#1}%
	\ifx\pgfmath@digit\pgfmath@base@atchar%
		\expandafter\let\pgfmath@temp=\pgfmath@digitlist%
	\else%
		\ifx\pgfmath@digitlist\pgfutil@empty%
			\edef\pgfmath@digitlist{#1}%
		\else%
			\edef\pgfmath@digitlist{\pgfmath@digitlist,#1}%
		\fi%
		\expandafter\pgfmath@todigitlist%
	\fi%
}


pgfmathfunctions.basic.code.tex
% Copyright 2007 by Mark Wibrow
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

% This file defines the mathematical functions and operators.
%
% Version 1.4142135 25/8/2008

% add function.
%
\pgfmathdeclarefunction{add}{2}{%
	\begingroup%
    \pgfmath@x=#1pt\relax%
    \pgfmath@y=#2pt\relax%
    \advance\pgfmath@x by\pgfmath@y%
    \pgfmath@returnone\pgfmath@x%
  \endgroup%
}


% subtract function.
%
\pgfmathdeclarefunction{subtract}{2}{%
	\begingroup%
    \pgfmath@x=#1pt\relax%
    \pgfmath@y=#2pt\relax%
    \advance\pgfmath@x by-\pgfmath@y%
    \pgfmath@returnone\pgfmath@x%
  \endgroup%
}

% neg function.
%
\pgfmathdeclarefunction{neg}{1}{%
	\begingroup%
		\pgfmath@x=-#1pt\relax%
		\edef\pgfmathresult{\pgfmath@tonumber{\pgfmath@x}}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}
% change the precedence for neg.
% Otherwise, unary minus and exponentiation won't have the correct precedence
% (test '-2^2')
\def\pgfmath@operation@neg@precedence{500}

% multiply function.
%
\pgfmathdeclarefunction{multiply}{2}{%
  \begingroup%
    \pgfmath@x=#1pt\relax%
    \pgfmath@y=#2pt\relax%
    \pgfmath@x=\pgfmath@tonumber{\pgfmath@y}\pgfmath@x%
    \pgfmath@returnone\pgfmath@x%
  \endgroup%
}

% divide function.
%
\newif\ifpgfmath@divide@period

\pgfmathdeclarefunction{divide}{2}{%
	\begingroup%
		\pgfmath@x=#1pt\relax%
		\pgfmath@y=#2pt\relax%
		\let\pgfmath@sign=\pgfmath@empty%
		\ifdim0pt=\pgfmath@y%
			\pgfmath@error{You've asked me to divide `#1' by `#2', %
				but I cannot divide any number by `#2'}%				
		\fi%
		\afterassignment\pgfmath@xa%
		\c@pgfmath@counta\the\pgfmath@y\relax%
		\ifdim0pt=\pgfmath@xa%
			\divide\pgfmath@x by\c@pgfmath@counta%
		\else%
			\ifdim0pt>\pgfmath@x%
				\def\pgfmath@sign{-}%
				\pgfmath@x=-\pgfmath@x%
			\fi%
			\ifdim0pt>\pgfmath@y%
				\expandafter\def\expandafter\pgfmath@sign\expandafter{\pgfmath@sign-}%
				\pgfmath@y=-\pgfmath@y%
			\fi%
			\ifdim1pt>\pgfmath@y%
				\pgfmathreciprocal@{\pgfmath@tonumber{\pgfmath@y}}%
				\pgfmath@x=\pgfmath@sign\pgfmathresult\pgfmath@x%
			\else%
				\def\pgfmathresult{0}%
				\pgfmath@divide@periodtrue%
				\c@pgfmath@counta=0\relax%
				\pgfmathdivide@@%
				\pgfmath@x=\pgfmath@sign\pgfmathresult pt\relax%
			\fi%
		\fi%
		\pgfmath@returnone\pgfmath@x%
	\endgroup%	
}

\def\pgfmath@small@number{0.00002}

\def\pgfmathdivide@@{%
	\let\pgfmath@next=\relax%
	\ifdim\pgfmath@small@number pt<\pgfmath@x%
		\ifdim\pgfmath@small@number pt<\pgfmath@y%
			\ifdim\pgfmath@y>\pgfmath@x%
				\ifpgfmath@divide@period%
					\expandafter\def\expandafter\pgfmathresult\expandafter{\pgfmathresult.}%
					\pgfmath@divide@periodfalse%
				\fi%
				\pgfmathdivide@dimenbyten\pgfmath@y%
				\ifdim\pgfmath@y>\pgfmath@x%
					\expandafter\def\expandafter\pgfmathresult\expandafter{\pgfmathresult0}%
				\fi%
			\else%
				\c@pgfmath@counta=\pgfmath@x%
				\c@pgfmath@countb=\pgfmath@y%
				\divide\c@pgfmath@counta by\c@pgfmath@countb%
				\pgfmath@ya=\c@pgfmath@counta\pgfmath@y%
				\advance\pgfmath@x by-\pgfmath@ya%
				\def\pgfmath@next{%
					\toks0=\expandafter{\pgfmathresult}%
					\edef\pgfmathresult{\the\toks0 \the\c@pgfmath@counta}%
				}%
				\ifpgfmath@divide@period
				\else
					% we are behind the period. It may happen that the
					% result is more than one digit - in that case,
					% introduce special handling:
					\ifnum\c@pgfmath@counta>9 %
						\expandafter\pgfmathdivide@advance@last@digit\pgfmathresult CCCCC\@@
						\advance\c@pgfmath@counta by-10 %
						\ifnum\c@pgfmath@counta=0
							\let\pgfmath@next=\relax
						\fi
					\fi
				\fi
				\pgfmath@next
			\fi%
			\let\pgfmath@next=\pgfmathdivide@@%
		\fi%
	\fi%
	\pgfmath@next%
}

% advances the last digit found in the number. Any missing digits are
% supposed to be filled with 'C'.
\def\pgfmathdivide@advance@last@digit#1.#2#3#4#5#6#7\@@{%
	\pgfmath@ya=\pgfmathresult pt %
	\if#2C%
		\pgfmath@xa=1pt %
	\else
		\if#3C%
			\pgfmath@xa=0.1pt %
		\else
			\if#4C%
				\pgfmath@xa=0.01pt %
			\else
				\if#5C%
					\pgfmath@xa=0.001pt %
				\else
					\if#6C%
						\pgfmath@xa=0.0001pt %
					\else
						\pgfmath@xa=0.00001pt %
					\fi
				\fi
			\fi
		\fi
	\fi
	\advance\pgfmath@ya by\pgfmath@xa
	\edef\pgfmathresult{\pgfmath@tonumber@notrailingzero\pgfmath@ya}%
}%

{
\catcode`\p=12
\catcode`\t=12
\gdef\Pgf@geT@NO@TRAILING@ZERO#1.#2pt{%
	#1.%
	\ifnum#2=0 \else #2\fi
}
}
\def\pgfmath@tonumber@notrailingzero#1{\expandafter\Pgf@geT@NO@TRAILING@ZERO\the#1}


\def\pgfmathdivide@dimenbyten#1{%
	\edef\pgfmath@temp{\pgfmath@tonumber{#1}}%
	\expandafter\pgfmathdivide@@dimenbyten\pgfmath@temp\@@#1\@@}
\def\pgfmathdivide@@dimenbyten#1.#2\@@#3\@@{%
	\pgfmath@tempcnta=#1\relax%
	\divide\pgfmath@tempcnta by10\relax%
	\pgfmath@tempcntb=\pgfmath@tempcnta%
	\multiply\pgfmath@tempcnta by-10\relax%
	\advance\pgfmath@tempcnta by#1\relax%
	#3=\the\pgfmath@tempcntb.\the\pgfmath@tempcnta#2pt\relax%
}


% reciprocal function.
%
\pgfmathdeclarefunction{reciprocal}{1}{%
	\begingroup%
		\expandafter\pgfmath@x#1pt\relax%
		\ifdim\pgfmath@x=0pt\relax%
			\pgfmath@error{You asked me to calculate `1/#1', but I cannot divide any number by zero}{}%
		\fi%
		\edef\pgfmath@reciprocaltemp{\pgfmath@tonumber{\pgfmath@x}}%
		\expandafter\pgfmathreciprocal@@\pgfmath@reciprocaltemp0000000\pgfmath@}
\def\pgfmathreciprocal@@#1.#2#3#4#5#6#7\pgfmath@{%
		\c@pgfmath@counta#2#3#4#5#6\relax%
		% If the number is an integer, use TeX arithmatic.
		\ifnum\c@pgfmath@counta=0\relax%
			\pgfmath@x1pt\relax%
			\divide\pgfmath@x#1\relax%
		\else%
			\ifnum#1>100\relax%
				\c@pgfmath@counta#1#2#3#4\relax%
				\c@pgfmath@countb1000000000\relax%
				\divide\c@pgfmath@countb\c@pgfmath@counta%
				\c@pgfmath@counta\c@pgfmath@countb%
				\divide\c@pgfmath@counta10000\relax%
				\pgfmath@x\c@pgfmath@counta pt\relax%
				\multiply\c@pgfmath@counta-10000\relax%
				\advance\c@pgfmath@countb\c@pgfmath@counta%
				\pgfmath@y\c@pgfmath@countb pt\relax%
				\divide\pgfmath@y1000000\relax%		
				\advance\pgfmath@x\pgfmath@y%
			\else%
				\c@pgfmath@counta#1#2#3#4#5#6\relax%
				\c@pgfmath@countb1000000000\relax%
				\divide\c@pgfmath@countb\c@pgfmath@counta%
				\c@pgfmath@counta\c@pgfmath@countb%
				\divide\c@pgfmath@counta10000\relax%
				\pgfmath@x\c@pgfmath@counta pt\relax%
				\multiply\c@pgfmath@counta-10000\relax%
				\advance\c@pgfmath@countb\c@pgfmath@counta%
				\pgfmath@y\c@pgfmath@countb pt\relax%
				\pgfmath@y.1\pgfmath@y% Yes! This way is more accurate. Go figure...
				\pgfmath@y.1\pgfmath@y%	
				\pgfmath@y.1\pgfmath@y%	
				\pgfmath@y.1\pgfmath@y%		
				\advance\pgfmath@x\pgfmath@y%
			\fi%
		\fi%
		\pgfmath@returnone\pgfmath@x%
	\endgroup%
}

% div function.
%
\pgfmathdeclarefunction{div}{2}{%
	\begingroup%
		\pgfmathdivide@{#1}{#2}%
		\ifdim\pgfmathresult pt<0pt\relax%
			\pgfmathceil@{\pgfmathresult}%
		\else%
			\pgfmathfloor@{\pgfmathresult}%
		\fi%
		\afterassignment\pgfmath@gobbletilpgfmath@%
		\c@pgfmath@counta=\pgfmathresult\relax\pgfmath@%
		\edef\pgfmathresult{\the\c@pgfmath@counta}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% mod function.
%
\pgfmathdeclarefunction{mod}{2}{%
  \begingroup%
    \pgfmath@xa#1pt%
    \pgfmath@xb#2pt%
    \pgfmath@x\pgfmath@xa%
    \c@pgfmath@counta\pgfmath@xa%
    \c@pgfmath@countb\pgfmath@xb%
    \divide\c@pgfmath@counta\c@pgfmath@countb%
    \multiply\pgfmath@xb\c@pgfmath@counta%
    \advance\pgfmath@x-\pgfmath@xb%
    \pgfmath@returnone\pgfmath@x%
  \endgroup%
}

% Mod function (never negative).
%
\pgfmathdeclarefunction{Mod}{2}{%
	\begingroup%
		\pgfmathmod@{#1}{#2}%
		\pgfmath@x=\pgfmathresult pt\relax%
		\ifdim\pgfmath@x<0pt\relax%
			\advance\pgfmath@x by#2pt\relax%
		\fi%
		\edef\pgfmathresult{\pgfmath@tonumber{\pgfmath@x}}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% abs function.
%
\pgfmathdeclarefunction{abs}{1}{%
	\begingroup%
		\expandafter\pgfmath@x#1pt\relax%
		\ifdim\pgfmath@x<0pt\relax%
			\pgfmath@x-\pgfmath@x%
		\fi%
	\pgfmath@returnone\pgfmath@x%
	\endgroup%
}

% e constant.
%
\pgfmathdeclarefunction{e}{0}{\def\pgfmathresult{2.718281828}}

% ln function.
%
% This is based on an algorithm due to Rouben Rostamian and
% uses coefficients contributed by Alain Matthes.
%
\pgfmathdeclarefunction{ln}{1}{%
	\begingroup%
		\expandafter\pgfmath@x#1pt\relax%
		\ifdim\pgfmath@x>0pt\else%
			\pgfmath@error{I cannot calculate the logarithm of `#1'}{}%
		\fi%		
		\c@pgfmath@counta=0\relax%
		\ifdim\pgfmath@x>2pt\relax%
			\ifdim\pgfmath@x<128pt\relax%
				\ifdim\pgfmath@x<8pt\relax%
					\ifdim\pgfmath@x<4pt\relax%
						\divide\pgfmath@x by2\relax%
						\c@pgfmath@counta=1\relax%
					\else%
						\divide\pgfmath@x by4\relax%
						\c@pgfmath@counta=2\relax%
					\fi%
				\else%
					\ifdim\pgfmath@x<32pt\relax%
						\ifdim\pgfmath@x<16pt\relax%
							\divide\pgfmath@x by8\relax%
							\c@pgfmath@counta=3\relax%
						\else%
							\divide\pgfmath@x by16\relax%
							\c@pgfmath@counta=4\relax%
						\fi%
					\else%
						\ifdim\pgfmath@x<64pt\relax%
							\divide\pgfmath@x by32\relax%
							\c@pgfmath@counta=5\relax%
						\else%
							\divide\pgfmath@x by64\relax%
							\c@pgfmath@counta=6\relax%
						\fi%
					\fi%
				\fi%
			\else%
				\ifdim\pgfmath@x<2048pt\relax%
					\ifdim\pgfmath@x<512pt\relax%
						\ifdim\pgfmath@x<256pt\relax%
							\divide\pgfmath@x by128\relax%
							\c@pgfmath@counta=7\relax%
						\else%
							\divide\pgfmath@x by256\relax%
							\c@pgfmath@counta=8\relax%
						\fi%
					\else%
						\ifdim\pgfmath@x<1024pt\relax%
							\divide\pgfmath@x by512\relax%
							\c@pgfmath@counta=9\relax%
						\else%
							\divide\pgfmath@x by1024\relax%
							\c@pgfmath@counta=10\relax%
						\fi%
					\fi%
				\else%
					\ifdim\pgfmath@x<8192pt\relax%
						\ifdim\pgfmath@x<4096pt\relax%
							\divide\pgfmath@x by2048\relax%
							\c@pgfmath@counta=11\relax%
						\else%
							\divide\pgfmath@x by4096\relax%
							\c@pgfmath@counta =12\relax%
						\fi%
					\else%
						\divide\pgfmath@x by8192\relax%
						\c@pgfmath@counta=13\relax%
					\fi%
				\fi%
			\fi%	
		\else%
			\ifdim\pgfmath@x<1pt\relax%
				\ifdim\pgfmath@x>0.0078125pt\relax% 2^-7
					\ifdim\pgfmath@x>0.125pt\relax% 2^-3
						\ifdim\pgfmath@x>0.5pt\relax% 2^-1
							\multiply\pgfmath@x by2\relax%
							\c@pgfmath@counta=-1\relax%
						\else%
							\multiply\pgfmath@x by4\relax%
							\c@pgfmath@counta=-2\relax%
						\fi%
					\else%
						\ifdim\pgfmath@x>0.03125pt\relax% 2^-5
							\ifdim\pgfmath@x>0.0625pt\relax%
								\multiply\pgfmath@x by8\relax%
								\c@pgfmath@counta=-3\relax%
							\else%
								\multiply\pgfmath@x by16\relax%
								\c@pgfmath@counta=-4\relax%
							\fi%
						\else%
							\ifdim\pgfmath@x>0.015625pt\relax% 2^-6
								\multiply\pgfmath@x by32\relax%
								\c@pgfmath@counta=-5\relax%
							\else%
								\multiply\pgfmath@x by64\relax%
								\c@pgfmath@counta=-6\relax%
							\fi%
						\fi%
					\fi%
				\else%
					\ifdim\pgfmath@x>0.000244140625pt\relax% 2^-11
						\ifdim\pgfmath@x>0.001953125pt\relax% 2^-9
							\ifdim\pgfmath@x>0.00390625pt\relax% 2^-8
								\multiply\pgfmath@x by128\relax%
								\c@pgfmath@counta=-7\relax%
							\else%
								\multiply\pgfmath@x by256\relax%
								\c@pgfmath@counta=-8\relax%
							\fi%
						\else%
							\ifdim\pgfmath@x>0.0009765625pt\relax% 2^-10
								\multiply\pgfmath@x by512\relax%
								\c@pgfmath@counta=-9\relax%
							\else%
								\multiply\pgfmath@x by1024\relax%
								\c@pgfmath@counta=-10\relax%
							\fi%
						\fi%
					\else%
						\ifdim\pgfmath@x>0.0001220703125pt\relax% 2^13
							\ifdim\pgfmath@x>0.0002441406256pt\relax% 2^12
								\multiply\pgfmath@x by2048\relax%
								\c@pgfmath@counta=-11\relax%
							\else%
								\multiply\pgfmath@x by4096\relax%
								\c@pgfmath@counta=-12\relax%
							\fi%
						\else%
							\multiply\pgfmath@x by8192\relax%
							\c@pgfmath@counta=-13\relax%
						\fi%
					\fi%
				\fi%
			\fi%	
		\fi%
		%
		% Use A+(B+(C+(D+(E+F*x)*x)*x)*x)*x
		%
		% where:
		% A = -2.787927935
		% B =  5.047861502
		% C = -3.489886985
		% D =  1.589480044
		% E = -.4025153233
		% F =  0.04300521312
		%
		\edef\pgfmath@temp{\pgfmath@tonumber{\pgfmath@x}}%
		\pgfmath@x=0.04300521312\pgfmath@x%
		\advance\pgfmath@x by-.4025153233pt\relax%
		\pgfmath@x=\pgfmath@temp\pgfmath@x%
		\advance\pgfmath@x by1.589480044pt\relax%
		\pgfmath@x=\pgfmath@temp\pgfmath@x%
		\advance\pgfmath@x by-3.489886985pt\relax%
		\pgfmath@x=\pgfmath@temp\pgfmath@x%
		\advance\pgfmath@x by5.047861502pt\relax%
		\pgfmath@x=\pgfmath@temp\pgfmath@x%
		\advance\pgfmath@x by-2.787927935pt\relax%
		\advance\pgfmath@x by\c@pgfmath@counta pt\relax%
		\pgfmath@x=0.6931471806\pgfmath@x%	
		\pgfmath@returnone\pgfmath@x%
	\endgroup%
}

% log2 function.
%
\pgfmathdeclarefunction{log2}{1}{%
	\begingroup%
		\pgfmathln@{#1}%
		\pgfmath@x=\pgfmathresult pt\relax%
		\pgfmath@x=1.442695041\pgfmath@x% 1/ln(2).
		\pgfmath@returnone\pgfmath@x%
	\endgroup%
}

% log10 function
%
\pgfmathdeclarefunction{log10}{1}{%	
	\begingroup%
		\pgfmathln@{#1}%
		\pgfmath@x=\pgfmathresult pt\relax%
		\pgfmath@x=0.43429441\pgfmath@x% 1/ln(10).
		\pgfmath@returnone\pgfmath@x%
	\endgroup%
}

% exp function.
%
\pgfmathdeclarefunction{exp}{1}{%	
  \begingroup
    \pgfmath@xc=#1pt\relax
    \pgfmath@yc=#1pt\relax
    \ifdim\pgfmath@xc<-9pt
      \pgfmath@x=1sp\relax
    \else
      \ifdim\pgfmath@xc<0pt
        \pgfmath@xc=-\pgfmath@xc
      \fi
      \pgfmath@x=1pt\relax
      \pgfmath@xa=1pt\relax
      \pgfmath@xb=\pgfmath@x
      \pgfmathloop%
        \divide\pgfmath@xa by\pgfmathcounter
        \pgfmath@xa=\pgfmath@tonumber\pgfmath@xc\pgfmath@xa%
        \advance\pgfmath@x by\pgfmath@xa
      \ifdim\pgfmath@x=\pgfmath@xb
      \else
        \pgfmath@xb=\pgfmath@x
      \repeatpgfmathloop%
      \ifdim\pgfmath@yc<0pt
        \pgfmathreciprocal@{\pgfmath@tonumber\pgfmath@x}%
        \pgfmath@x=\pgfmathresult pt\relax
      \fi
    \fi
    \pgfmath@returnone\pgfmath@x%
  \endgroup
}

% sqrt function.
%
\pgfmathdeclarefunction{sqrt}{1}{%	
	\begingroup%
		\expandafter\pgfmath@x#1pt\relax%
		\ifdim\pgfmath@x<0pt\relax%
			\pgfmath@error{I cannot calculate the square-root of the negative number `#1'}{}%
		\else%
			\ifdim\pgfmath@x<10pt\relax%
				\def\pgfmath@zeros{0}%
				\def\pgfmath@targetiterations{1}%
			\else%
				\ifdim\pgfmath@x<100pt\relax%
					\def\pgfmath@zeros{}%
					\def\pgfmath@targetiterations{1}%
				\else%
					\ifdim\pgfmath@x<1000pt\relax%
						\def\pgfmath@zeros{0}%
						\def\pgfmath@targetiterations{2}%
					\else%
						\ifdim\pgfmath@x<10000pt\relax%
							\def\pgfmath@zeros{}%
							\def\pgfmath@targetiterations{2}%
					\else%
							\def\pgfmath@zeros{0}%
							\def\pgfmath@targetiterations{3}%
		\fi\fi\fi\fi\fi%
		\edef\pgfmath@temp{\pgfmath@zeros\pgfmath@tonumber{\pgfmath@x}}%
		\expandafter\pgfmath@sqrt@\pgfmath@temp\pgfmath@%
}
\def\pgfmath@sqrt@#1.#2\pgfmath@{\pgfmath@@sqrt@#1#2\pgfmath@empty\pgfmath@empty\pgfmath@}

\def\pgfmath@@sqrt@#1#2{%
		\c@pgfmath@countb=#1#2\relax%
		\ifnum\c@pgfmath@countb>35\relax%
			\ifnum\c@pgfmath@countb>63\relax%
				\ifnum\c@pgfmath@countb>80\relax%
					\c@pgfmath@counta=9\relax%
				\else%
					\c@pgfmath@counta=8\relax%
				\fi%
			\else%
				\ifnum\c@pgfmath@countb>48\relax%
					\c@pgfmath@counta=7\relax%
				\else%
					\c@pgfmath@counta=6\relax%
				\fi%
			\fi%
		\else%
			\ifnum\c@pgfmath@countb>15\relax%
				\ifnum\c@pgfmath@countb>24\relax%
					\c@pgfmath@counta5\relax%
				\else%
					\c@pgfmath@counta=4\relax%
				\fi%
			\else%
				\ifnum\c@pgfmath@countb>3\relax%
					\ifnum\c@pgfmath@countb>8\relax%
						\c@pgfmath@counta=3\relax%
					\else%
						\c@pgfmath@counta=2\relax%
					\fi%
				\else%
					\ifnum\c@pgfmath@countb>0\relax%
						\c@pgfmath@counta=1\relax%
					\else%
						\c@pgfmath@counta=0\relax%
					\fi%
				\fi%
			\fi%
		\fi%
		\edef\pgfmath@root{\the\c@pgfmath@counta}%
		\edef\pgfmath@rootspecial{\the\c@pgfmath@counta}%
		\multiply\c@pgfmath@counta by-\c@pgfmath@counta\relax%
		\advance\c@pgfmath@counta by#1#2\relax%
		\edef\pgfmath@remainder{\the\c@pgfmath@counta}%
		\pgfmath@@@sqrt@%
}

\def\pgfmath@@@sqrt@#1#2{%
		\ifx\pgfmath@empty#1%
			\edef\pgfmath@remainder{\pgfmath@remainder00}%
			\def\pgfmath@tokens{\pgfmath@empty\pgfmath@empty}%
		\else%
			\ifx\pgfmath@empty#2%
				\edef\pgfmath@remainder{\pgfmath@remainder#10}%
				\def\pgfmath@tokens{\pgfmath@empty\pgfmath@empty}%
			\else%
				\edef\pgfmath@remainder{\pgfmath@remainder#1#2}%
				\def\pgfmath@tokens{}%
		\fi\fi%
		\c@pgfmath@counta=\pgfmath@rootspecial\relax%
		\multiply\c@pgfmath@counta by20\relax%
		\c@pgfmath@countb=\c@pgfmath@counta%
		\multiply\c@pgfmath@countb by6\relax%
		\advance\c@pgfmath@countb by36\relax%
		\c@pgfmath@countc=\c@pgfmath@counta%
		\multiply\c@pgfmath@countc by2\relax%
		\ifnum\c@pgfmath@countb>\pgfmath@remainder\relax% 
			\advance\c@pgfmath@countb by-\c@pgfmath@countc%
			\advance\c@pgfmath@countb by-20\relax%
			\ifnum\c@pgfmath@countb>\pgfmath@remainder\relax%
				\advance\c@pgfmath@countb by-\c@pgfmath@countc%
				\advance\c@pgfmath@countb by-12\relax%
				\ifnum\c@pgfmath@countb>\pgfmath@remainder\relax%
					\advance\c@pgfmath@countb by-\c@pgfmath@counta%
					\advance\c@pgfmath@countb by-3\relax%
					\ifnum\c@pgfmath@countb>\pgfmath@remainder\relax%
						\def\pgfmath@digit{0}%
					\else%
						\def\pgfmath@digit{1}%
					\fi%
				\else%
					\advance\c@pgfmath@countb by\c@pgfmath@counta%
					\advance\c@pgfmath@countb by5\relax%
					\ifnum\c@pgfmath@countb>\pgfmath@remainder\relax%
						\def\pgfmath@digit{2}%
					\else%
						\def\pgfmath@digit{3}%
					\fi%
				\fi%
			\else%
				\advance\c@pgfmath@countb by\c@pgfmath@counta%
				\advance\c@pgfmath@countb by9\relax%
				\ifnum\c@pgfmath@countb>\pgfmath@remainder\relax%
					\def\pgfmath@digit{4}%
				\else%
					\def\pgfmath@digit{5}%
				\fi%
			\fi%
		\else%
			\advance\c@pgfmath@countb by\c@pgfmath@countc%
			\advance\c@pgfmath@countb by28\relax%
			\ifnum\c@pgfmath@countb>\pgfmath@remainder\relax%
				\advance\c@pgfmath@countb by-\c@pgfmath@counta%
				\advance\c@pgfmath@countb by-15\relax%
				\ifnum\c@pgfmath@countb>\pgfmath@remainder\relax%
					\def\pgfmath@digit{6}%
				\else%
					\def\pgfmath@digit{7}%
				\fi%
			\else%
				\advance\c@pgfmath@countb by\c@pgfmath@counta%
				\advance\c@pgfmath@countb by17\relax%
				\ifnum\c@pgfmath@countb>\pgfmath@remainder\relax%
					\def\pgfmath@digit{8}%
				\else%
					\def\pgfmath@digit{9}%
				\fi%
			\fi%
		\fi%
		\edef\pgfmath@rootspecial{\pgfmath@rootspecial\pgfmath@digit}%
		\advance\c@pgfmath@counta by\pgfmath@digit\relax%
		\multiply\c@pgfmath@counta by-\pgfmath@digit\relax%
		\advance\c@pgfmath@counta by\pgfmath@remainder\relax%
		\edef\pgfmath@remainder{\the\c@pgfmath@counta}%
		\c@pgfmath@counta=\pgfmath@targetiterations\relax%
		\advance\c@pgfmath@counta by-1\relax%
		\edef\pgfmath@targetiterations{\the\c@pgfmath@counta}%
		\ifnum\c@pgfmath@counta=0\relax%
			\edef\pgfmath@root{\pgfmath@root.\pgfmath@digit}%
		\else%
			\edef\pgfmath@root{\pgfmath@root\pgfmath@digit}%
		\fi%
		\ifnum\c@pgfmath@counta=-4\relax% -n+1 digits of precision.
			\let\pgfmath@next\pgfmath@sqrt@end%
		\else%
			\let\pgfmath@next\pgfmath@@@sqrt@%
		\fi%
		\expandafter\pgfmath@next\pgfmath@tokens%
}

\def\pgfmath@sqrt@end#1\pgfmath@{%
		\edef\pgfmathresult{\pgfmath@root}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup}

% \pgfmathpow
%
% Calculates #1 ^ #2
%
\pgfmathdeclarefunction{pow}{2}{%	
  \begingroup%
    \pgfmath@xa=#1pt%
    \pgfmath@xb=#2pt%
    \ifdim\pgfmath@xa=0pt\relax%
      \ifdim\pgfmath@xb=0pt\relax%
        \pgfmath@x=1pt\relax%
      \else%
        \pgfmath@x=0pt\relax%
      \fi%
    \else%
      \afterassignment\pgfmath@x%
      \expandafter\c@pgfmath@counta\the\pgfmath@xb\relax%
      \ifnum\c@pgfmath@counta<0\relax%
        \c@pgfmath@counta=-\c@pgfmath@counta%
        \pgfmathreciprocal@{#1}%
        \pgfmath@xa=\pgfmathresult pt\relax%
      \fi
      \ifdim\pgfmath@x=0pt\relax%
        \pgfmath@x=1pt\relax%
        \pgfmathloop%
          \ifnum\c@pgfmath@counta>0\relax%
            \ifodd\c@pgfmath@counta%
              \pgfmath@x=\pgfmath@tonumber{\pgfmath@x}\pgfmath@xa%
            \fi
            \ifnum\c@pgfmath@counta>1\relax%
              \pgfmath@xa=\pgfmath@tonumber{\pgfmath@xa}\pgfmath@xa%
            \fi%
            \divide\c@pgfmath@counta by2\relax%
        \repeatpgfmathloop%
      \else%
        \pgfmathln@{#1}%
        \pgfmath@x=\pgfmathresult pt\relax%
        \pgfmath@x=\pgfmath@tonumber{\pgfmath@xb}\pgfmath@x%
        \pgfmathexp@{\pgfmath@tonumber{\pgfmath@x}}%
        \pgfmath@x=\pgfmathresult pt\relax%
      \fi%
    \fi              
    \pgfmath@returnone\pgf@x%
  \endgroup%
}

% factorial function.
%
\pgfmathdeclarefunction{factorial}{1}{%	
	\begingroup%
		\afterassignment\pgfmath@gobbletilpgfmath@%
		\c@pgfmath@counta=#1\relax\pgfmath@%
		\pgfmath@x=1pt\relax%
		\pgfmathloop%
		\ifnum\c@pgfmath@counta<2\relax%
		\else%
			\multiply\pgfmath@x by\c@pgfmath@counta%
			\advance\c@pgfmath@counta by-1\relax%
		\repeatpgfmathloop%
		\edef\pgfmathresult{\pgfmath@tonumber{\pgfmath@x}}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% Local Variables:
% coding: undecided-unix
% End:

pgfmathfunctions.code.tex
% Copyright 2007 by Mark Wibrow
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

% Declare a function for the parser.
%
% #1 - the name of the function.
% #2 - arity (or ... for variable arguments).
% #3 - the code for the function.
%
% Use \pgfmathdeclarefunction* to force a redefinition if the function exists already.
\def\pgfmathdeclarefunction{\pgfmath@ifnextchar*\pgfmathdeclarefunction@force\pgfmathdeclarefunction@check}
\def\pgfmathdeclarefunction@check#1#2#3{%
	\expandafter\ifx\csname pgfmath@function@#1\endcsname\relax%
		\pgfmath@declarefunction{#1}{#2}{#3}%
	\else%
		\pgfmath@error{The function `#1' already exists}{}%
	\fi%
}
\def\pgfmathdeclarefunction@force*{\pgfmath@declarefunction}%

\def\pgfmathredeclarefunction#1#2{%
	\expandafter\ifx\csname pgfmath@function@#1\endcsname\relax%
		\pgfmath@error{The function `#1' does not exist}{}%
	\else%
		\pgfmath@namedef{pgfmath#1@}{#2}%
	\fi%
}

\def\pgfmath@declarefunction#1#2{%
	\pgfmath@namedef{pgfmath@function@#1}{#1}%
	\pgfmath@namedef{pgfmath@operation@#1@type}{function}%
	\pgfmath@namedef{pgfmath@operation@#1@arity}{#2}%
	\pgfmath@namedef{pgfmath@operation@#1@infix}{#1}%
	\pgfmath@namedef{pgfmath@operation@#1@precedence}{1000}%
	\expandafter\ifx\csname pgfmath@operation@#1@arity\endcsname\pgfmath@dots%
		\pgfmath@namedef{pgfmath@operation@#1@arity}{1}% 
	\else%
		\ifnum\csname pgfmath@operation@#1@arity\endcsname>9\relax%
				\pgfmath@namedef{pgfmath@operation@#1@arity}{1}%
		\fi%
	\fi%
	\edef\pgfmath@marshal{%
		\noexpand\pgfmath@@declarefunction%
		{\expandafter\noexpand\csname pgfmath#1\endcsname}%
		{\expandafter\noexpand\csname pgfmath#1@\endcsname}%
		{\csname pgfmath@operation@#1@arity\endcsname}%
	}%
	\pgfmath@marshal%
}

% #1 - \pgfmath<name>.
% #2 - \pgfmath<name>@.
% #3 - arity.
% #4 - code for function <name>.
%
\def\pgfmath@@declarefunction#1#2#3#4{% Function of arity 0 - 9.
	\ifcase#3\relax%
		\def#1{#2}%
		\def#2{#4}%
	\or
		\def#1##1{\pgfmathparse{##1}\expandafter#2\expandafter{\pgfmathresult}}%
		\def#2##1{#4}%
	\else%
		\pgfmath@toks={}%
		\pgfmathloop%	
		\ifnum\pgfmathcounter>#3\relax%
		\else%
			\expandafter\pgfmath@addto@toks\expandafter{\pgfmath@char@hash}%
			\expandafter\pgfmath@addto@toks\expandafter{\pgfmathcounter}%
		\repeatpgfmathloop%
		\edef\pgfmath@head{\noexpand\def\noexpand#1\the\pgfmath@toks}%
		\edef\pgfmath@@head{\noexpand\def\noexpand#2\the\pgfmath@toks}%
		\pgfmath@toks={}%
		\def\pgfmath@arguments{}%
		\pgfmathloop%		
		\ifnum\pgfmathcounter>#3\relax%
		\else%
			\pgfmath@addto@toks{\pgfmathparse}%
			\expandafter\expandafter\expandafter\pgfmath@addto@toks%
				\expandafter\expandafter\expandafter{\expandafter\expandafter\expandafter%
					{\expandafter\pgfmath@char@hash\pgfmathcounter}}%
			\pgfmath@addto@toks{\let}%
			\expandafter\pgfmath@addto@toks\expandafter{%
				\csname pgfmath@argument@\pgfmathcounter\endcsname=\pgfmathresult}%
			\expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter%
				\pgfmath@arguments\expandafter\expandafter\expandafter{\expandafter%
					\pgfmath@arguments\expandafter{\csname pgfmath@argument@\pgfmathcounter\endcsname}}%
		\repeatpgfmathloop%
		\expandafter\pgfmath@addto@toks\expandafter{\expandafter#2\pgfmath@arguments}%
		\edef\pgfmath@body{{\the\pgfmath@toks}}%
		\expandafter\pgfmath@head\pgfmath@body%
		\pgfmath@@head{#4}%
	\fi%
}

\def\pgfmath@addto@toks#1{%
	\edef\pgfmath@toks@expanded{\the\pgfmath@toks}%
	\expandafter\pgfmath@toks\expandafter{\pgfmath@toks@expanded#1}}	

% Key for declaring local functions.
%
\pgfkeys{%
	/pgf/declare function/.code={%
		\pgfmath@local@functions#1@=@;%
	}
}

\def\pgfmath@local@gobbleone#1{}
\def\pgfmath@local@at{@}%

\def\pgfmath@local@functions{%
	\pgfutil@ifnextchar x{\pgfmath@local@@functions}{\pgfmath@local@@functions}%
}

\def\pgfmath@local@@functions#1=#2;{%
	\def\pgfmath@local@temp{#1}%
	\ifx\pgfmath@local@temp\pgfmath@local@at%
		\let\pgfmath@local@next=\relax%
	\else%
		\pgfmath@local@function#1=#2;%
		\let\pgfmath@local@next=\pgfmath@local@functions%
	\fi%
	\pgfmath@local@next%
}

\def\pgfmath@local@function{%
	\let\pgfmath@local@name=\pgfutil@empty%
	\let\pgfmath@local@args=\pgfutil@empty%
	\let\pgfmath@local@body=\pgfutil@empty%
	\pgfmath@local@@function}

\def\pgfmath@local@@function#1{%
	\if#1=%
		\let\pgfmath@local@next=\pgfmath@local@function@body%
	\else%
		\if#1(%
			\let\pgfmath@local@next=\pgfmath@local@function@args%
		\else%
			\expandafter\def\expandafter\pgfmath@local@name\expandafter{\pgfmath@local@name#1}%
			\let\pgfmath@local@next=\pgfmath@local@@function%
		\fi%
	\fi%
	\pgfmath@local@next%
}

\def\pgfmath@local@function@args#1){%
	\def\pgfmath@local@args{#1}%
	\pgfmath@local@@function}

\def\pgfmath@local@function@body#1;{%
	\def\pgfmath@local@body{#1}%
	\begingroup%
		\c@pgf@counta=0\relax%
		\ifx\pgfmath@local@args\pgfmath@empty%
			\expandafter\pgfmath@toks\expandafter=\expandafter{\pgfmath@local@body}%
		\else%
			\pgfmath@toks={}%
			\expandafter\pgfmath@local@function@@body\pgfmath@local@args,,%
		\fi%
		\xdef\pgfmath@local@temp{%
			\noexpand\pgfmathdeclarefunction{\pgfmath@local@name}{\the\c@pgf@counta}%
				{\noexpand\pgfmathparse{\the\pgfmath@toks}}%
		}%
	\endgroup%
	\pgfmath@local@temp%
}

\def\pgfmath@local@function@@body#1,{%
	\def\pgfmath@local@test{#1}%
	\ifx\pgfmath@local@test\pgfutil@empty%
		\let\pgfmath@local@next=\relax%
	\else%
		\edef\pgfmath@local@var@string{@\expandafter\pgfmath@local@gobbleone\string#1}%
		\advance\c@pgf@counta by1\relax%
		\expandafter\expandafter\expandafter\pgfmath@toks\expandafter\expandafter\expandafter=%
			\expandafter\expandafter\expandafter{\expandafter\pgfmath@char@hash\the\c@pgf@counta}%
		\edef#1{\the\pgfmath@toks}%
		\pgfmath@toks={}%
		\expandafter\pgfmath@local@function@@@body\pgfmath@local@body @%
		\edef\pgfmath@local@body{\the\pgfmath@toks}%
		\let\pgfmath@local@next=\pgfmath@local@function@@body%
	\fi%
	\pgfmath@local@next%	
}
		
\def\pgfmath@local@function@@@body{%
	\pgfutil@ifnextchar\bgroup{\pgfmath@local@function@@@body@bgroup}%
		{\pgfmath@local@function@@@body@nobgroup}}%

\def\pgfmath@local@function@@@body@bgroup#1{%
	\begingroup%
		\pgfmath@toks={}%
		\pgfmath@local@function@@@body#1 @%
		\xdef\pgfmath@local@temp{{\the\pgfmath@toks}}%
	\endgroup%
	\expandafter\pgfmath@addto@toks\expandafter{\pgfmath@local@temp}%
	\pgfmath@local@function@@@body%
}

\def\pgfmath@local@function@@@body@nobgroup#1{%
	\ifx#1@%
		\let\pgfmath@local@next=\relax%
	\else%
		\let\pgfmath@local@next=\pgfmath@local@function@@@body%
		\edef\pgfmath@local@var@@string{@\expandafter\pgfmath@local@gobbleone\string#1}%
		\ifx\pgfmath@local@var@@string\pgfmath@local@var@string%
			\expandafter\pgfmath@addto@toks\expandafter{#1}%
		\else%
			\edef\pgfmath@local@temp{\the\pgfmath@toks}%
			\pgfmath@toks={#1}%
			\edef\pgfmath@local@@temp{\the\pgfmath@toks}%
			\expandafter\pgfmath@toks\expandafter=\expandafter{\pgfmath@local@temp}%
			\expandafter\pgfmath@addto@toks\expandafter{\pgfmath@local@@temp}%
		\fi%
	\fi%
	\pgfmath@local@next%			
}

% Allows to define 'x' as some \TeX command '#2'.
\def\pgfmathdeclarepseudoconstant#1#2{%
	\pgfmathdeclarefunction*{#1}{0}{#2}%
}%
% Redefines a pseudo constant '#1'.
\def\pgfmathredeclarepseudoconstant#1#2{%
	\pgfmathredeclarefunction{#1}{#2}%
}%
	
\input pgfmathfunctions.basic.code.tex
\input pgfmathfunctions.trigonometric.code.tex
\input pgfmathfunctions.random.code.tex
\input pgfmathfunctions.comparison.code.tex 
\input pgfmathfunctions.base.code.tex 
\input pgfmathfunctions.round.code.tex 
\input pgfmathfunctions.misc.code.tex 
\input pgfmathfunctions.integerarithmetics.code.tex



% Local Variables:
% tab-width: 2
% End:

pgfmathfunctions.comparison.code.tex
% Copyright 2007 by Mark Wibrow
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

% This file defines the mathematical functions and operators.
%
% Version 1.4142135 11/8/2008

\pgfmathdeclarefunction{greater}{2}{%
  \begingroup%
    \ifdim#1pt>#2pt\relax%
    	\def\pgfmathresult{1}%
    \else%
      \def\pgfmathresult{0}%
    \fi%
    \pgfmath@smuggleone\pgfmathresult%
  \endgroup%
}
\let\pgfmathgreaterthan=\pgfmathgreater

\pgfmathdeclarefunction{less}{2}{%
  \begingroup%
    \ifdim#1pt<#2pt\relax%
    	\def\pgfmathresult{1}%
    \else%
      \def\pgfmathresult{0}%
    \fi%
    \pgfmath@smuggleone\pgfmathresult%
  \endgroup%
}
\let\pgfmathlessthan=\pgfmathless

\pgfmathdeclarefunction{equal}{2}{%
  \begingroup%
    \ifdim#1pt=#2pt\relax%
    	\def\pgfmathresult{1}%
    \else%
      \def\pgfmathresult{0}%
    \fi%
    \pgfmath@smuggleone\pgfmathresult%
  \endgroup%
}
\let\pgfmathequalto=\pgfmathequal


% approxequalto function from Christian Feuersanger.
%
\newif\ifpgfmathcomparison
\pgfmathdeclarefunction{approxequalto}{2}{%
	\begingroup%
		\pgfmath@x=#1pt\relax%
		\pgfmath@y=#2pt\relax%
		\advance\pgfmath@x by-\pgfmath@y%
		\ifdim\pgfmath@x<0pt\relax%
			\multiply\pgfmath@x by-1\relax%
		\fi
		\ifdim\pgfmath@x<0.0001pt\relax%
			\def\pgfmathresult{1.0}%
			\global\pgfmathcomparisontrue%
		\else%
			\def\pgfmathresult{0.0}%
			\global\pgfmathcomparisonfalse%
		\fi%
	\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}



% ifthenelse function.
%
\pgfmathdeclarefunction{ifthenelse}{3}{%
	\begingroup%
		\ifdim#1pt=0.0pt\relax%
			\expandafter\def\expandafter\pgfmathresult\expandafter{#3}%
		\else%
			\expandafter\def\expandafter\pgfmathresult\expandafter{#2}%
		\fi%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% notequal function.
%
\pgfmathdeclarefunction{notequal}{2}{%
  \begingroup%
    \ifdim#1pt=#2pt\relax%
 			\def\pgfmathresult{0}%
    \else%
      \def\pgfmathresult{1}%
    \fi%
    \pgfmath@smuggleone\pgfmathresult%
  \endgroup%
}

% notless function.
%
\pgfmathdeclarefunction{notless}{2}{%
  \begingroup%
    \ifdim#1pt<#2pt\relax%
 			\def\pgfmathresult{0}%
    \else%
      \def\pgfmathresult{1}%
    \fi%
    \pgfmath@smuggleone\pgfmathresult%
  \endgroup%
}

% notgreater function.
%
\pgfmathdeclarefunction{notgreater}{2}{%
  \begingroup%
    \ifdim#1pt>#2pt\relax%
 			\def\pgfmathresult{0}%
    \else%
      \def\pgfmathresult{1}%
    \fi%
    \pgfmath@smuggleone\pgfmathresult%
  \endgroup%
}

% and function.
%
\pgfmathdeclarefunction{and}{2}{%
  \begingroup%
  	\def\pgfmathresult{1}%
    \ifdim#1pt=0pt\relax%
 			\def\pgfmathresult{0}%
 		\else%
 			\ifdim#2pt=0pt\relax%
				\def\pgfmathresult{0}%
			\fi%
		\fi%
	 \pgfmath@smuggleone\pgfmathresult%
  \endgroup%
}

% or function.
%
\pgfmathdeclarefunction{or}{2}{%
  \begingroup%
  	\def\pgfmathresult{0}%
    \ifdim#1pt=0pt\relax%	
 			\ifdim#2pt=0pt\relax%
 			\else%
				\def\pgfmathresult{1}%
			\fi%
		\else%
			\def\pgfmathresult{1}%
		\fi%
	\pgfmath@smuggleone\pgfmathresult%
  \endgroup%
}

% not function.
%
\pgfmathdeclarefunction{not}{1}{%
  \begingroup%
  	\ifdim#1pt=0pt\relax%	
 			\def\pgfmathresult{1}%
		\else%
			\def\pgfmathresult{0}%
		\fi%
	\pgfmath@smuggleone\pgfmathresult%
  \endgroup%
}

% true function.
%
\pgfmathdeclarefunction{true}{0}{\def\pgfmathresult{1}}

% false function.
%
\pgfmathdeclarefunction{false}{0}{\def\pgfmathresult{0}}

pgfmathfunctions.integerarithmetics.code.tex
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

% Macros contributed by Alain Matthes and adapted by CJ
\pgfmathdeclarefunction{gcd}{2}{%
  \begingroup
    \pgfmathcontinuelooptrue
    \pgfmath@xa=#1pt
    \pgfmath@xb=#2pt
    \ifdim\pgfmath@xa=0pt 
      \pgfmathcontinueloopfalse
      \pgfmath@xa=\pgfmath@xb
    \fi 
    \ifdim\pgfmath@xb=0pt
      \pgfmathcontinueloopfalse
      \pgfmath@xb=\pgfmath@xa
    \fi
    \ifdim\pgfmath@xa<0pt
      \pgfmath@xa=-\pgfmath@xa
    \fi
    \ifdim\pgfmath@xb<0pt
      \pgfmath@xb=-\pgfmath@xb
    \fi
    \loop
      \ifpgfmathcontinueloop 
      \ifdim\pgfmath@xa=\pgfmath@xb
        \pgfmathcontinueloopfalse
      \else
        \ifdim\pgfmath@xa>\pgfmath@xb 
          \advance\pgfmath@xa by-\pgfmath@xb
        \else 
          \advance\pgfmath@xb by-\pgfmath@xa
        \fi
      \fi
    \repeat
    \pgfmathparse{int(\pgfmath@xa)}%
    \pgfmath@smuggleone\pgfmathresult
  \endgroup}

\newif\ifpgfmath@isprime@unknown
\newif\ifpgfmath@isprime 

\pgfmathdeclarefunction{isprime}{1}{%
  \begingroup
    \pgfmath@isprime@unknowntrue
    \pgfmathsetcount\c@pgfmath@counta{abs(int(#1))}%
    \ifcase\c@pgfmath@counta\relax 
      % |#1| = 0 
      \pgfmath@isprimefalse
      \pgfmath@isprime@unknownfalse
    \or
      % |#1| = 1
      \pgfmath@isprimefalse
      \pgfmath@isprime@unknownfalse
    \or
      % |#1| = 2
      \pgfmath@isprimetrue
      \pgfmath@isprime@unknownfalse
    \or
      % |#1| = 3
      \pgfmath@isprimetrue
      \pgfmath@isprime@unknownfalse
    \else
      % |#1| > 3
      \ifodd\c@pgfmath@counta\relax 
      \else
        \pgfmath@isprimefalse
        \pgfmath@isprime@unknownfalse
      \fi
    \fi  
    \ifpgfmath@isprime@unknown
      \c@pgfmath@countd=3
      \pgfmath@isprimetrue
      \pgfmathloop
        \c@pgfmath@countb=\c@pgfmath@counta  
        \divide\c@pgfmath@countb by\c@pgfmath@countd
        \ifnum\c@pgfmath@countb>\c@pgfmath@countd
          \pgfmath@isprime@unknowntrue
        \else
          \pgfmath@isprime@unknownfalse
        \fi
        \multiply\c@pgfmath@countb by\c@pgfmath@countd
        \ifnum\c@pgfmath@countb=\c@pgfmath@counta  
          \global\pgfmath@isprimefalse
          \pgfmath@isprime@unknownfalse
        \fi
      \ifpgfmath@isprime@unknown\advance\c@pgfmath@countd by 2
      \repeatpgfmathloop
    \fi
    \ifpgfmath@isprime
      \def\pgfmathresult{1}%
    \else
      \def\pgfmathresult{0}%
    \fi
    \pgfmath@smuggleone\pgfmathresult
  \endgroup}

\pgfmathdeclarefunction{isodd}{1}{%
  \begingroup
    \pgfmathsetcount\c@pgfmath@counta{abs(int(#1))}%
    \ifodd\c@pgfmath@counta
      \def\pgfmathresult{1}%
    \else
      \def\pgfmathresult{0}%
    \fi
    \pgfmath@smuggleone\pgfmathresult
  \endgroup}

\pgfmathdeclarefunction{iseven}{1}{%
  \begingroup
    \pgfmathsetcount\c@pgfmath@counta{abs(int(#1))}%
    \ifodd\c@pgfmath@counta
      \def\pgfmathresult{0}%
    \else
      \def\pgfmathresult{1}%
    \fi
    \pgfmath@smuggleone\pgfmathresult
  \endgroup}

\endinput
pgfmathfunctions.misc.code.tex
% Copyright 2007 by Mark Wibrow
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

% This file defines the mathematical functions and operators.
%
% Version 1.414213 29/9/2007

% veclen function adpated from ideas due to Rouben Rostamian.
%
% Calcluate the Eulidean length of a 2D vector.
%
%
\pgfmathdeclarefunction{veclen}{2}{%	
  \begingroup%
    \pgfmath@x#1pt\relax%
    \pgfmath@y#2pt\relax%
		\ifdim\pgfmath@x<0pt\relax%
			\pgfmath@x-\pgfmath@x%
		\fi%
		\ifdim\pgfmath@y<0pt\relax%
			\pgfmath@y-\pgfmath@y%
		\fi%
		\ifdim\pgfmath@x=0pt\relax%
			\pgfmath@x\pgfmath@y%
		\else%
			\ifdim\pgfmath@y=0pt\relax%
			\else%
				\ifdim\pgfmath@x>\pgfmath@y%
					\pgfmath@xa\pgfmath@x%
					\pgfmath@x\pgfmath@y%
					\pgfmath@y\pgfmath@xa%
				\fi%
				% We use a scaling factor to reduce errors.
				\ifdim\pgfmath@y>10000pt\relax%
					\c@pgfmath@counta1500\relax%
				\else%
					\ifdim\pgfmath@y>1000pt\relax%
						\c@pgfmath@counta150\relax%
					\else%
						\ifdim\pgfmath@y>100pt\relax%
							\c@pgfmath@counta50\relax%
						\else%
							\c@pgfmath@counta1\relax%
						\fi%
					\fi%
				\fi%
				\divide\pgfmath@x\c@pgfmath@counta\relax%
				\divide\pgfmath@y\c@pgfmath@counta\relax%
				\pgfmathreciprocal@{\pgfmath@tonumber{\pgfmath@y}}%
				\pgfmath@x\pgfmathresult\pgfmath@x%
				\pgfmath@xa\pgfmath@tonumber{\pgfmath@x}\pgfmath@x%
				\edef\pgfmath@temp{\pgfmath@tonumber{\pgfmath@xa}}%
				%
				% Use A+x^2*(B+x^2*(C+x^2*(D+E*x^2))) 
				% where
				% A = +1.000012594
				% B = +0.4993615349 
				% C = -0.1195159052
				% D = +0.04453994279
				% E = -0.01019210944
				%
				\pgfmath@x-0.01019210944\pgfmath@xa%
				\advance\pgfmath@x0.04453994279pt\relax%
				\pgfmath@x\pgfmath@temp\pgfmath@x%
				\advance\pgfmath@x-0.1195159052pt\relax%
				\pgfmath@x\pgfmath@temp\pgfmath@x%
				\advance\pgfmath@x0.4993615349pt\relax%
				\pgfmath@x\pgfmath@temp\pgfmath@x%
				\advance\pgfmath@x1.000012594pt\relax%
				\ifdim\pgfmath@y<0pt\relax%
					\pgfmath@y-\pgfmath@y%
				\fi%
				\pgfmath@x\pgfmath@tonumber{\pgfmath@y}\pgfmath@x%
				% Invert the scaling factor.
				\multiply\pgfmath@x\c@pgfmath@counta\relax%
			\fi%
		\fi%
		\pgfmath@returnone\pgfmath@x%
	\endgroup%
}

% Hyperbolic functions contributed by Martin Heller.
%
\pgfmathdeclarefunction{cosh}{1}{%
	\begingroup
		\edef\pgfmath@arg{#1}%
		\pgfmathexp@{\pgfmath@arg}%
		\pgfmath@x=\pgfmathresult pt\relax%
		\pgfmathexp@{-\pgfmath@arg}%
		\advance\pgfmath@x by\pgfmathresult pt\relax%
		\divide\pgfmath@x by2\relax%
		\pgfmath@returnone\pgfmath@x%
	\endgroup}

\pgfmathdeclarefunction{sinh}{1}{%
	\begingroup
		\edef\pgfmath@arg{#1}%
		\pgfmathexp@{\pgfmath@arg}%
		\pgfmath@x=\pgfmathresult pt\relax%
		\pgfmathexp@{-\pgfmath@arg}%
		\advance\pgfmath@x by-\pgfmathresult pt\relax%
		\divide\pgfmath@x by2\relax%
		\pgfmath@returnone\pgfmath@x%
	\endgroup
}%

\pgfmathdeclarefunction{tanh}{1}{%
	\begingroup
		\edef\pgfmath@arg{#1}%
		\pgfmathsinh@{\pgfmath@arg}%
		\pgfmath@x=\pgfmathresult pt\relax%
		\pgfmathcosh@{\pgfmath@arg}%
		\pgfmath@y=\pgfmathresult pt\relax%	
		\pgfmathdivide@{\pgfmath@tonumber{\pgfmath@x}}{\pgfmath@tonumber{\pgfmath@y}}%
		\pgfmath@x=\pgfmathresult pt\relax%
		\pgfmath@returnone\pgfmath@x%
	\endgroup
}%

% \pgfmathscientific
%
% Return the value of #1e#2
%
% e.g. \pgfmathscientific{1.23456789123}{4}
%
% defines \pgfmathresult as 12345.67891
%
% NB These arguments *are not parsed*, as the long mantissa would be lost.
%
\def\pgfmathscientific#1#2{%
	\begingroup%
		\edef\pgfmath@sci@exponent{#2}%
		\pgfmath@x#1pt\relax%
		\ifdim\pgfmath@x<0pt\relax%
			\pgfmath@x-\pgfmath@x%
			\edef\pgfmath@sci@sign{-}%	
			\expandafter\edef\expandafter\pgfmath@temp\expandafter{\expandafter\pgfmath@gobbleone#1}%		
		\else%
			\edef\pgfmath@sci@sign{+}%
			\edef\pgfmath@temp{#1}%
		\fi%
		\expandafter\pgfmath@in@\expandafter.\expandafter{#1}%
		\ifpgfmath@in@%
		\else%
			\edef\pgfmath@temp{\pgfmath@temp.0}%
		\fi%
		\expandafter\pgfmath@scientific@@\pgfmath@temp00000000000\pgfmath@}

\def\pgfmath@scientific@@#1.#2#3#4#5#6{%
		\edef\pgfmath@sci@int{#1}%
		\edef\pgfmath@sci@mantissaA{#2#3#4#5#6}%
		\pgfmath@scientific@@@}
	
\def\pgfmath@scientific@@@#1#2#3#4#5#6\pgfmath@{%
		\edef\pgfmath@sci@mantissaB{#1#2#3#4#5}%
		\c@pgfmath@counta\pgfmath@sci@exponent\relax%
                \ifnum\c@pgfmath@counta<-4\relax%
                  \pgfmath@x0pt\relax%
                \else%
		\c@pgfmath@countb\c@pgfmath@counta%
		\ifnum\c@pgfmath@counta<0\relax%
			\c@pgfmath@counta-\c@pgfmath@counta%
		\fi%
		\pgfmathpow@{10}{\the\c@pgfmath@counta}%
		\afterassignment\pgfmath@gobbletilpgfmath@
		\c@pgfmath@countc\pgfmathresult\relax\pgfmath@
		\edef\pgfmath@sci@factor{\the\c@pgfmath@countc}%
		\ifnum\c@pgfmath@countb<0\relax%
			% xE-y: easy...
			\pgfmath@x\pgfmath@sci@int.\pgfmath@sci@mantissaA pt\relax%
			\divide\pgfmath@x\pgfmath@sci@factor\relax%
		\else%
			% xE+y: 
			% Must do this way so as not lose digits in a long mantissa. Sigh...
			\c@pgfmath@counta\pgfmath@sci@int%
			\c@pgfmath@countb\pgfmath@sci@mantissaA%
			\multiply\c@pgfmath@counta\pgfmath@sci@factor\relax%
			\multiply\c@pgfmath@countb\pgfmath@sci@factor\relax%
			\c@pgfmath@countc\c@pgfmath@countb%
			\divide\c@pgfmath@countb100000\relax%
			\advance\c@pgfmath@counta\c@pgfmath@countb%
			\multiply\c@pgfmath@countb100000\relax%
			\advance\c@pgfmath@countc-\c@pgfmath@countb%
			\c@pgfmath@countb\pgfmath@sci@mantissaB\relax%
			\multiply\c@pgfmath@countb\pgfmath@sci@factor\relax%
			\divide\c@pgfmath@countb100000\relax%
			\advance\c@pgfmath@countc\c@pgfmath@countb%
			\advance\c@pgfmath@countc100000\relax%
			\edef\pgfmath@sci@result{\pgfmath@sci@sign\the\c@pgfmath@counta.\expandafter\pgfmath@gobbleone\the\c@pgfmath@countc pt}%
			\pgfmath@x\pgfmath@sci@result\relax%
		\fi\fi%
		\pgfmath@returnone\pgfmath@x%
	\endgroup}
	


% width function.
%
\pgfmathdeclarefunction{width}{1}{%
	\begingroup%
		\setbox\pgfmath@box=\hbox{{\pgfmath@selectfont{#1}}}%
		\pgfmath@x=\wd\pgfmath@box%
		\edef\pgfmathresult{\pgfmath@tonumber{\pgfmath@x}}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}


% height function.
%
\pgfmathdeclarefunction{height}{1}{%
	\begingroup%
		\setbox\pgfmath@box=\hbox{{\pgfmath@selectfont{#1}}}%
		\pgfmath@x=\ht\pgfmath@box%
		\edef\pgfmathresult{\pgfmath@tonumber{\pgfmath@x}}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% depth function.
%
\pgfmathdeclarefunction{depth}{1}{%
	\begingroup%
		\setbox\pgfmath@box=\hbox{{\pgfmath@selectfont{#1}}}%
		\pgfmath@x=\dp\pgfmath@box%
		\edef\pgfmathresult{\pgfmath@tonumber{\pgfmath@x}}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}


% array function.
%
\pgfmathdeclarefunction{array}{2}{%
	\begingroup%
		\afterassignment\pgfmath@gobbletilpgfmath@\pgfmath@count=#2\relax\pgfmath@%
		\expandafter\pgfmatharray@@#1\pgfmath@stop%
}

\def\pgfmath@token@stop{\pgfmath@stop}%
\def\pgfmatharray@@#1{%
	\def\pgfmath@temp{#1}%
	\advance\pgfmath@count by-1\relax%
	\ifx\pgfmath@temp\pgfmath@token@stop%
		\pgfmath@error{Array index out of bounds.}{}%
		\def\pgfmathresult{0}%
		\pgfmath@smuggleone\pgfmathresult\endgroup%
		\let\pgfmath@next=\relax%
	\else%
		\ifnum\pgfmath@count=-1\relax%
			\def\pgfmathresult{#1}%
			\let\pgfmath@next=\pgfmatharray@@@%
		\else%
			\let\pgfmath@next=\pgfmatharray@@%
		\fi%
	\fi%
	\pgfmath@next}

\def\pgfmatharray@@@#1\pgfmath@stop{%
	\pgfmath@smuggleone\pgfmathresult\endgroup%
}

% dim function: return dimension of an array
% dim({1,2,3}) return 3
% dim({{1,2,3},{4,5,6}}) return 2
\pgfmathdeclarefunction{dim}{1}{%
  \begingroup
    \pgfmath@count=0\relax
    \expandafter\pgfmath@dim@i\pgfutil@firstofone#1\pgfmath@token@stop
    \edef\pgfmathresult{\the\pgfmath@count}%
    \pgfmath@smuggleone\pgfmathresult%
  \endgroup}

\def\pgfmath@dim@i#1{%
    \ifx\pgfmath@token@stop#1%
    \else
      \advance\pgfmath@count by 1\relax
      \expandafter\pgfmath@dim@i
    \fi}


% max function.
%
\pgfmathdeclarefunction{max}{...}{%
	\begingroup%
		\pgfmath@x=-16383pt\relax%
		\pgfmathmax@@#1{}}

\def\pgfmathmax@@#1{%
	\def\pgfmath@temp{#1}%
	\ifx\pgfmath@temp\pgfmath@empty%
		\let\pgfmath@next=\pgfmathmax@@@%
	\else%
		\ifdim#1pt>\pgfmath@x%
			\pgfmath@x=#1pt\relax%
		\fi%
		\let\pgfmath@next=\pgfmathmax@@%
	\fi%
	\pgfmath@next}

\def\pgfmathmax@@@{\pgfmath@returnone\pgfmath@x\endgroup}%

% For compatability with old code.
\def\pgfmathmax#1#2{%
	\pgfmathparse{#1,#2}%
	\expandafter\pgfmathmax@\expandafter{\pgfmathresult}%
}

% min function.
%
\pgfmathdeclarefunction{min}{...}{%
	\begingroup%
		\pgfmath@x=16383pt\relax%
		\pgfmathmin@@#1{}}

\def\pgfmathmin@@#1{%
	\def\pgfmath@temp{#1}%
	\ifx\pgfmath@temp\pgfmath@empty%
		\let\pgfmath@next=\pgfmathmin@@@%
	\else%
		\ifdim#1pt<\pgfmath@x%
			\pgfmath@x=#1pt\relax%
		\fi%
		\let\pgfmath@next=\pgfmathmin@@%
	\fi%
	\pgfmath@next}

\def\pgfmathmin@@@{\pgfmath@returnone\pgfmath@x\endgroup}%

% For compatability with old code.
\def\pgfmathmin#1#2{%
	\pgfmathparse{#1,#2}%
	\expandafter\pgfmathmin@\expandafter{\pgfmathresult}%
}


pgfmathfunctions.random.code.tex
% Copyright 2007 by Mark Wibrow
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

% This file defines the pesudorandom numbers.
%
% Version 1.414213 29/9/2007

% Pseudo-random number generation.
%
% See:
% \book@{pressetal1992,
%    author    = {William H. Press and Brian P. Flannery and Saul A. 
%                 Teukolsky and William T. Vetterling}, 
%    title     = {Numerical Recipies in C},
%    edition   = {Second},
%    publisher = {Cambridge University Press}
% }
%
% See also, the documentation for the lcg package by Erich Janka:
% (http://www.ctan.org/tex-archive/macros/latex/contrib/lcg/lcg.pdf)
%
\def\pgfmath@rnd@m{2147483647}% LaTeX Maximum.

\begingroup
\c@pgfmath@counta=\time%
\multiply\c@pgfmath@counta by\year%
\xdef\pgfmath@rnd@z{\the\c@pgfmath@counta}% The seed. 
\endgroup

% \pgfmathsetseed
%
% Explictly set the seed for the generator
%   
% #1 -> the new seed.
%
\def\pgfmathsetseed#1{\pgfmathparse{#1}\expandafter\pgfmath@setseed\pgfmathresult.0\pgfmath@stop}%
\def\pgfmath@setseed#1.#2\pgfmath@stop{\def\pgfmath@rnd@z{#1}}%  

% Alternative paramaters - see Press et al (1992) p278-279, 
% for discussion.
%
% a=16807 q=127773 r=2836
% a=48271 q=4488   r=3399
%
\def\pgfmath@rnd@a{69621}
\def\pgfmath@rnd@r{23902}
\def\pgfmath@rnd@q{30845}

% \pgfmathgeneratepseudorandomnumber
% 
% A linear congruency generator for generating
% pseudo-random numbers. Generates numbers in
% the range 1 - 2^31-1.
%
\def\pgfmathgeneratepseudorandomnumber{%
	\begingroup%
		\c@pgfmath@counta=\pgfmath@rnd@z%
		\c@pgfmath@countb=\pgfmath@rnd@z%
		\c@pgfmath@countc=\pgfmath@rnd@q%
		\divide\c@pgfmath@counta by\c@pgfmath@countc%
		\multiply\c@pgfmath@counta by-\c@pgfmath@countc%
		\advance\c@pgfmath@counta by\c@pgfmath@countb
		\c@pgfmath@countc=\pgfmath@rnd@a%
		\multiply\c@pgfmath@counta by\c@pgfmath@countc%
		\c@pgfmath@countc=\pgfmath@rnd@q%
		\divide\c@pgfmath@countb by\c@pgfmath@countc%
		\c@pgfmath@countc=\pgfmath@rnd@r%
		\multiply\c@pgfmath@countb by\c@pgfmath@countc%
		\advance\c@pgfmath@counta by-\c@pgfmath@countb%
		\ifnum\c@pgfmath@counta<0\relax%
			\c@pgfmath@countb=\pgfmath@rnd@m%
			\advance\c@pgfmath@counta by\c@pgfmath@countb%
		\fi%
		\xdef\pgfmath@rnd@z{\the\c@pgfmath@counta}%
	\endgroup%
	\edef\pgfmathresult{\pgfmath@rnd@z}%
}

% \pgfmathrnd
%
% Generates a pseudo-random number between 0 and 1.
%
\pgfmathdeclarefunction{rnd}{0}{%
	\begingroup%
		\pgfmathgeneratepseudorandomnumber%
		\c@pgfmath@counta\pgfmathresult%
		\c@pgfmath@countb\c@pgfmath@counta%
		\divide\c@pgfmath@countb100001\relax% To get one.
		\multiply\c@pgfmath@countb-100001\relax%
		\advance\c@pgfmath@countb\c@pgfmath@counta%
		\advance\c@pgfmath@countb1000000\relax%
		\expandafter\pgfmathrnd@@\the\c@pgfmath@countb\pgfmath@%
		\pgfmath@returnone\pgfmath@x%
	\endgroup%
}%

\def\pgfmathrnd@@#1#2#3\pgfmath@{%
	\edef\pgfmath@temp{#2.#3}%
	\pgfmath@x=\pgfmath@temp pt\relax%
}%

% \pgfmathrand
%
% Generates a pseudo-random number between -1 and 1.
%
\pgfmathdeclarefunction{rand}{0}{%
	\begingroup%
		\pgfmathgeneratepseudorandomnumber%
		\c@pgfmath@counta\pgfmathresult%
		\c@pgfmath@countb\c@pgfmath@counta%
		\divide\c@pgfmath@countb200001\relax%
		\multiply\c@pgfmath@countb-200001\relax%
		\advance\c@pgfmath@countb\c@pgfmath@counta%
		\advance\c@pgfmath@countb-100000\relax%
		\ifnum\c@pgfmath@countb<0\relax%
			\advance\c@pgfmath@countb-1000000\relax%
		\else%
			\advance\c@pgfmath@countb1000000\relax%
		\fi%
		\expandafter\pgfmathrand@@\the\c@pgfmath@countb\pgfmath@%
		\pgfmath@returnone\pgfmath@x%
	\endgroup%
}%

\def\pgfmathrand@@#1#2#3#4\pgfmath@{%
	\ifx#1-%
		\edef\pgfmath@temp{-#3.#4}%
	\else%
		\edef\pgfmath@temp{#2.#3#4}%
	\fi%
	\pgfmath@x=\pgfmath@temp pt\relax%
}%

\pgfmathdeclarefunction{random}{...}{%
	\begingroup%
		\def\pgfmath@temp{#1}%
		\ifx\pgfmath@temp\pgfmath@empty%
			\pgfmathrnd@%
		\else%
			\expandafter\pgfmathrandom@@#1\pgfmath@stop%
		\fi%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup}

\def\pgfmathrandom@@{\futurelet\pgfmath@token\pgfmathrandom@@@}
\def\pgfmathrandom@@@{%
	\ifx\pgfmath@token\bgroup%
		\expandafter\pgfmath@random@@@@%
	\else%
		\expandafter\pgfmath@random@@@@@%
	\fi%
}
\def\pgfmath@random@@@@@#1\pgfmath@stop{%
	\pgfmathrandominteger\pgfmathresult{1}{#1}%
}
\def\pgfmath@random@@@@#1#2\pgfmath@stop{%
	\pgfmathrandominteger\pgfmathresult{#1}{#2}%
}

% \pgfmathrandominteger
%
% Return a 'randomly' selected integer in the range #2 - #3 (inclusive).
%
% #1 - a macro to store the integer (not a count register).
% #2 - the lower limit of the range.
% #3 - the upper limit of the range.
%
\def\pgfmathrandominteger#1#2#3{%
	\begingroup%
		\pgfmathgeneratepseudorandomnumber%
		\c@pgfmath@counta#2\relax%
		\c@pgfmath@countb#3\relax%
		\c@pgfmath@countc\c@pgfmath@countb%
		% OK. Maybe #2 > #3.
		\ifnum\c@pgfmath@counta>\c@pgfmath@countb\relax%
			\c@pgfmath@countc\c@pgfmath@countb%
			\c@pgfmath@countb\c@pgfmath@counta%
			\c@pgfmath@counta\c@pgfmath@countc%
		\fi%
		\advance\c@pgfmath@countc1\relax%
		\advance\c@pgfmath@countc-\c@pgfmath@counta%
		\c@pgfmath@counta\pgfmathresult\relax%
		\c@pgfmath@countb\c@pgfmath@counta%
		\divide\c@pgfmath@countb\c@pgfmath@countc%
		\multiply\c@pgfmath@countb-\c@pgfmath@countc%
		\advance\c@pgfmath@counta\c@pgfmath@countb%
		\advance\c@pgfmath@counta#2\relax%
		\edef\pgfmathresult{\the\c@pgfmath@counta}%
		\pgfmath@smuggleone{\pgfmathresult}%
	\endgroup%
	\edef#1{\pgfmathresult}%
}

% \pgfmathdeclarerandomlist
%
% Create a list to be used with \pgfmathrandomelement.
%
% #1 - the name of the list
% #2 - a list of comma separated elements.
%
\def\pgfmathdeclarerandomlist#1#2{%
	\def\pgfmath@randomlistname{#1}%
	\begingroup%
		\c@pgfmath@counta=1\relax%
		% {} is a possible random element so (locally) 
		% redefine \pgfmath@empty.
		\def\pgfmath@empty{pgfmath@empty}% 
		\expandafter\pgfmath@scanrandomlist#2{pgfmath@empty}}
\def\pgfmath@scanrandomlist#1{%
	\def\pgfmath@scanneditem{#1}%
	\ifx\pgfmath@scanneditem\pgfmath@empty%
		\advance\c@pgfmath@counta-1\relax%
		\expandafter\xdef\csname pgfmath@randomlist@\pgfmath@randomlistname\endcsname{\the\c@pgfmath@counta}%
		\endgroup%	
	\else%
		\expandafter\gdef\csname pgfmath@randomlist@\pgfmath@randomlistname @\the\c@pgfmath@counta\endcsname{#1}%
		\advance\c@pgfmath@counta1\relax%
		\expandafter\pgfmath@scanrandomlist%
	\fi}

% \pgfmathrandomitem
%
% Return a 'randomly' selected element from a list.
%
% #1 - a macro to store the item.
% #2 - the name of the list.
%
\def\pgfmathrandomitem#1#2{%
	\pgfmath@ifundefined{pgfmath@randomlist@#2}{\pgfmath@error{Unknown random list `#2'}}{%
		\edef\pgfmath@randomlistlength{\csname pgfmath@randomlist@#2\endcsname}%
		\pgfmathrandominteger{\pgfmath@randomtemp}{1}{\pgfmath@randomlistlength}%
		\def#1{\csname pgfmath@randomlist@#2@\pgfmath@randomtemp\endcsname}}}
		
pgfmathfunctions.round.code.tex
% Copyright 2007 by Mark Wibrow
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

% This file defines the mathematical functions and operators.
%
% Version 1.414213 29/9/2007

% round function. Uses asymmetric half-up rounding.
%
\pgfmathdeclarefunction{round}{1}{%	
	\begingroup%
		\expandafter\pgfmath@x#1pt\relax%
		\afterassignment\pgfmath@xa%
		\expandafter\c@pgfmath@counta\the\pgfmath@x\relax%
		\pgfmath@xb\pgfmath@x%
		\ifdim\pgfmath@xb<0pt\relax%
			\ifdim\pgfmath@xa<0.5pt\relax%
			\else%
				\advance\c@pgfmath@counta-1\relax%
			\fi%
		\else%
			\ifdim\pgfmath@xa<0.5pt\relax%
			\else%
				\advance\c@pgfmath@counta1\relax%
			\fi%
		\fi%
		\pgfmath@returnone\the\c@pgfmath@counta pt%
	\endgroup%
}%

% floor function.
%
\pgfmathdeclarefunction{floor}{1}{%	
	\begingroup%
		\expandafter\pgfmath@x#1pt\relax%
		\afterassignment\pgfmath@gobbletilpgfmath@%
		\expandafter\c@pgfmath@counta\the\pgfmath@x\relax\pgfmath@%
		\expandafter\pgfmath@x#1pt\relax%
		\ifdim\pgfmath@x<0pt\relax%
			\advance\c@pgfmath@counta by -1\relax%
		\fi%
		\pgfmath@x\c@pgfmath@counta pt\relax%
		\pgfmath@returnone\pgfmath@x%
	\endgroup%
}%

% ceil function.
%
\pgfmathdeclarefunction{ceil}{1}{%	
	\begingroup%
		\expandafter\pgfmath@x#1pt\relax%
		\afterassignment\pgfmath@gobbletilpgfmath@%
		\expandafter\c@pgfmath@counta\the\pgfmath@x\relax\pgfmath@%
		\pgfmath@y\pgfmath@x%
		\advance\pgfmath@y-\c@pgfmath@counta pt\relax%
		\pgfmath@x\c@pgfmath@counta pt\relax%
		\ifdim\pgfmath@y>0pt\relax%
			\advance\pgfmath@x1pt\relax%
		\fi%
	\pgfmath@returnone\pgfmath@x%
	\endgroup%
}%

% int function
%
\pgfmathdeclarefunction{int}{1}{%
	\begingroup%
		\expandafter\pgfmathint@@#1.\pgfmath@stop
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup}

\def\pgfmathint@@#1.#2\pgfmath@stop{%
	\def\pgfmath@temp{#1}%
	\ifx\pgfmath@temp\pgfmath@empty%
		\def\pgfmathresult{0}%
	\else%
		\pgfmath@in@{#1}{+-+0-0}%
		\ifpgfmath@in@
			\def\pgfmathresult{0}%
		\else%
			\def\pgfmathresult{#1}%
		\fi%
	\fi}

% frac function.
%
\pgfmathdeclarefunction{frac}{1}{%	
	\begingroup%
		\expandafter\pgfmathfrac@@#1.\pgfmath@stop%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup}

\def\pgfmathfrac@@#1.{%
	\pgfmath@ifnextchar\pgfmath@stop{\def\pgfmathresult{0.0}\pgfmath@gobbleone}{\pgfmathfrac@@@}%
}
\def\pgfmathfrac@@@#1.\pgfmath@stop{\def\pgfmathresult{0.#1}}

% real function.
%
\pgfmathdeclarefunction{real}{1}{%
	\begingroup%
		\pgfmath@x=#1pt\relax%
		\edef\pgfmathresult{\pgfmath@tonumber{\pgfmath@x}}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

pgfmathfunctions.trigonometric.code.tex
% Copyright 2007 by Mark Wibrow
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

% This file defines the trigonometric functions/functions.
%
% Much of this file is based on ideas and code (particularly 
% the old \pgfcoremath.code.tex) due to Till Tantau.
%
% Version 1.414213 29/9/2007

% \pgfmathpi
%
\pgfmathdeclarefunction{pi}{0}{\def\pgfmathresult{3.141592654}}

% \pgfmathradians 
% (for comptability with 1.18 beta, will be deprecated)
% 
% Convert #1 from radians to degrees (accurate to 1 deg).
%
\pgfmathdeclarefunction{radians}{1}{%
  \begingroup%
    \expandafter\pgfmath@x#1pt\relax%
    \pgfmath@x57.29577\pgfmath@x\relax% 57.29577 = 360/(2*pi)
    \pgfmath@returnone\pgfmath@x%
  \endgroup%
}%

% \pgfmathdeg
% 
% Convert #1 from radians to degrees.
%
\pgfmathdeclarefunction{deg}{1}{%  
  \begingroup%
    \expandafter\pgfmath@x#1pt\relax%
    \pgfmath@x57.29577\pgfmath@x\relax% 57.29577 = 360/(2*pi)
    \pgfmath@returnone\pgfmath@x%
  \endgroup%
}%

% \pgfmathrad
% 
% Convert #1 from degrees to radians.
%
\pgfmathdeclarefunction{rad}{1}{%  
  \begingroup%
    \expandafter\pgfmath@x#1pt\relax%
    \pgfmath@x3.14159\pgfmath@x% 
    \divide\pgfmath@x180\relax%
    \pgfmath@returnone\pgfmath@x%
  \endgroup%
}%

% \pgfmathsin
% 
% Calculate the sine of #1 (in degrees).
%
\pgfmathdeclarefunction{sin}{1}{%
  % Let #1 = a.b
  % Then sin(#1) \approx (1-b)*sin(a) + b*sin(a+1)
  %
  \begingroup%
    \expandafter\pgfmath@x#1pt\relax%
    \advance\pgfmath@x-90pt\relax%
    \afterassignment\pgfmath@gobbletilpgfmath@
    \expandafter\c@pgfmath@counta\the\pgfmath@x\relax\pgfmath@
    \divide\c@pgfmath@counta360\relax%
    \multiply\c@pgfmath@counta-360\relax%
    \advance\pgfmath@x\c@pgfmath@counta pt\relax%
    \ifdim\pgfmath@x<0pt\relax\pgfmath@x-\pgfmath@x\fi%
    \ifdim\pgfmath@x<180pt\relax%
    \else
      \pgfmath@x-\pgfmath@x%
      \advance\pgfmath@x360pt\relax%
    \fi%
    % Now 0 <= x < 179. So split x into integer and decimal...
    %
    \afterassignment\pgfmath@xa%
    \expandafter\c@pgfmath@counta\the\pgfmath@x\relax%
    %
    % ...if #1 is an integer, don't do anything fancy.
    \ifdim\pgfmath@xa=0pt%
      \expandafter\pgfmath@x\csname pgfmath@cos@\the\c@pgfmath@counta\endcsname pt\relax%
    \else%
      \pgfmath@x-\pgfmath@xa%
      \advance\pgfmath@x1pt\relax%
      \expandafter\pgfmath@x\csname pgfmath@cos@\the\c@pgfmath@counta\endcsname\pgfmath@x%
      \advance\c@pgfmath@counta1\relax%
      \ifnum\c@pgfmath@counta=181\relax\c@pgfmath@counta179\relax\fi%
      \expandafter\advance\expandafter\pgfmath@x\csname pgfmath@cos@\the\c@pgfmath@counta\endcsname\pgfmath@xa%
    \fi%
    \pgfmath@returnone\pgfmath@x%
  \endgroup
}

% \pgfmathcos
% 
% Calculate the cosine of #1 (in degrees).
%
\pgfmathdeclarefunction{cos}{1}{%
  % Let x = a.b
  % Then cos(x) \approx (1-b)*cos(a) + b*cos(a+1)
  %
  \begingroup%
    \expandafter\pgfmath@x#1pt\relax%
    \afterassignment\pgfmath@gobbletilpgfmath@%
    \expandafter\c@pgfmath@counta\the\pgfmath@x\relax\pgfmath@% 
    \divide\c@pgfmath@counta360\relax%
    \multiply\c@pgfmath@counta-360\relax%
    \advance\pgfmath@x\c@pgfmath@counta pt\relax%
    \ifdim\pgfmath@x<0pt\relax\pgfmath@x-\pgfmath@x\fi%
    \ifdim\pgfmath@x<180pt\relax%
    \else%
      \pgfmath@x-\pgfmath@x%
      \advance\pgfmath@x360pt\relax%
    \fi%
    % Now 0 <= x < 179. So split x into integer and decimal...
    %
    \afterassignment\pgfmath@xa%
    \expandafter\c@pgfmath@counta\the\pgfmath@x\relax%
    %
    % ...if #1 is an integer, don't do anything fancy.
    \ifdim\pgfmath@xa=0pt%
      \expandafter\pgfmath@x\csname pgfmath@cos@\the\c@pgfmath@counta\endcsname pt%
    \else%
      \pgfmath@x-\pgfmath@xa%
      \advance\pgfmath@x1pt\relax%
      \expandafter\pgfmath@x\csname pgfmath@cos@\the\c@pgfmath@counta\endcsname\pgfmath@x%
      \advance\c@pgfmath@counta1\relax%
      \ifnum\c@pgfmath@counta=181\relax\c@pgfmath@counta179\relax\fi%
      \expandafter\advance\expandafter\pgfmath@x\csname pgfmath@cos@\the\c@pgfmath@counta\endcsname\pgfmath@xa%
    \fi%
    \pgfmath@returnone\pgfmath@x%
  \endgroup%
}

% \pgfmathsincos
% 
% Calculate the sin and cosine of #1 (in degrees).
%
\def\pgfmathsincos#1{%
  \pgfmathparse{#1}%
  \expandafter\pgfmathsincos@\expandafter{\pgfmathresult}}
\def\pgfmathsincos@#1{%
  \edef\pgfmath@temparg{#1}%
  \pgfmathsin@{\pgfmath@temparg}\edef\pgfmathresulty{\pgfmathresult}%
  \pgfmathcos@{\pgfmath@temparg}\edef\pgfmathresultx{\pgfmathresult}%
}

% \pgfmathtan
% 
% Calculate the tangent of #1 (in degrees).
%
\pgfmathdeclarefunction{tan}{1}{%
  \begingroup%
    \edef\pgfmath@temparg{#1}%
    \pgfmathcos@{\pgfmath@temparg}%
    \expandafter\pgfmathreciprocal@\expandafter{\pgfmathresult}%
    \edef\pgfmath@tantemp{\pgfmathresult}%
    \pgfmathsin@{\pgfmath@temparg}%
    \pgfmath@x\pgfmathresult pt\relax%
    \pgfmath@x\pgfmath@tantemp\pgfmath@x%
    \pgfmath@returnone\pgfmath@x%
  \endgroup%
}

% \pgfmathcosec
% 
% Calculate the cosec of #1 (in degrees).
%
\pgfmathdeclarefunction{cosec}{1}{%  
  \expandafter\pgfmathsin@\expandafter{#1}%
  \pgfmathreciprocal@{\pgfmathresult}%
}

% \pgfmathsec
% 
% Calculate the sec of #1 (in degrees).
%
\pgfmathdeclarefunction{sec}{1}{%
  \expandafter\pgfmathcos@\expandafter{#1}%
  \pgfmathreciprocal@{\pgfmathresult}%
}

% \pgfmathcot
% 
% Calculate the cotangent of #1 (in degrees).
%
\pgfmathdeclarefunction{cot}{1}{%  
  \begingroup%
    \edef\pgfmath@temparg{#1}%
    \pgfmathsin@{\pgfmath@temparg}%
    \expandafter\pgfmathreciprocal@\expandafter{\pgfmathresult}%
    \edef\pgfmath@tantemp{\pgfmathresult}%
    \pgfmathcos@{\pgfmath@temparg}%
    \pgfmath@x\pgfmathresult pt\relax%
    \pgfmath@x\pgfmath@tantemp\pgfmath@x%
    \pgfmath@returnone\pgfmath@x%
  \endgroup%
}

\def\pgfmath@multiply@thousand#1.#2#3#4#5\relax{%
  \edef\pgfmathresult{#1#2#3#4.#5}%
}%

% \pgfmathasin
%
% The asin of #1
%
\pgfmathdeclarefunction{asin}{1}{%
  \begingroup%
    \pgfmath@x=#1pt %
    \pgfmath@xa\pgfmath@x%
    \edef\pgf@temp{\pgf@sys@tonumber\pgfmath@x}%
    % compute lossless '*1000' operation:
    \expandafter\pgfmath@multiply@thousand\pgf@temp 000\relax
    \pgfmath@x=\pgfmathresult pt %
    \ifdim\pgfmath@x<0pt\relax%
      \pgfmath@x-\pgfmath@x%
    \fi%
    \pgfmath@table@lookup{\pgfmath@x}{pgfmath@acos@}{1001}%
    \pgfmath@x=-\pgfmath@x
    \advance\pgfmath@x90pt\relax%
    \ifdim\pgfmath@xa<0pt\relax%
      \pgfmath@x-\pgfmath@x%
    \fi%
    \pgfmath@returnone\pgfmath@x%
  \endgroup%
}

% Defines \pgfmath@x to be the result of the table lookup for value
% '#1' in table '#2'
%
% #1: a value for which lookup should be performed
% #2: the table's prefix name
% #3: the table's size
\def\pgfmath@table@lookup#1#2#3{%
  \pgfmath@x=#1\relax
  \expandafter\pgfmath@table@lookup@\the\pgfmath@x\relax{#2}{#3}%
}
\def\pgfmath@table@lookup@#1.#2\relax#3#4{%
  \edef\pgf@temp{\Pgf@geT#2}% strip 'pt' suffix.
  %
  % prepare constant interpolant (i.e. the value at node '#1'):
  \pgfmath@x=\csname #3#1\endcsname pt %
  %
  \c@pgfmath@countc=#1 %
  \advance\c@pgfmath@countc by1 %
  \ifnum\c@pgfmath@countc<#4 %
    % Ah - we have enough elements in the table.
    %
    % perform linear interpolation:
    \pgfmath@ya=\csname #3\the\c@pgfmath@countc\endcsname pt %
    \advance\pgfmath@ya by-\pgfmath@x %
    \advance\pgfmath@x by0.\pgf@temp\pgfmath@ya
  \fi
}%

% \pgfmathacos
%
% The acos of #1
%  
\pgfmathdeclarefunction{acos}{1}{%
  \begingroup%
    \pgfmath@x#1pt\relax%
    \pgfmath@xa\pgfmath@x%
    \edef\pgf@temp{\pgf@sys@tonumber\pgfmath@x}%
    % compute lossless '*1000' operation:
    \expandafter\pgfmath@multiply@thousand\pgf@temp 000\relax
    \pgfmath@x=\pgfmathresult pt %
    \ifdim\pgfmath@x<0pt\relax%
      \pgfmath@x-\pgfmath@x%
    \fi%
    \pgfmath@table@lookup{\pgfmath@x}{pgfmath@acos@}{1001}%
    \ifdim\pgfmath@xa<0pt\relax%
      \pgfmath@x-\pgfmath@x%
      \advance\pgfmath@x by180pt\relax%
    \fi%
    \pgfmath@returnone\pgfmath@x%
  \endgroup%
}

\pgfmathdeclarefunction{atan}{1}{%
  \begingroup%
    \expandafter\pgfmath@x#1pt\relax%
    \pgfmath@xa\pgfmath@x%
    \ifdim\pgfmath@x<0pt\relax%
      \pgfmath@x-\pgfmath@x%
    \fi%
    \pgfmath@xb\pgfmath@x%
    \ifdim\pgfmath@x>1pt\relax%
      \edef\pgfmath@temp{\pgfmath@tonumber{\pgfmath@x}}%
      \pgfmathreciprocal@{\pgfmath@temp}%
      \pgfmath@x\pgfmathresult pt\relax%
    \fi%
    % compute lossless '*1000' operation:
    \edef\pgf@temp{\pgf@sys@tonumber\pgfmath@x}%
    \expandafter\pgfmath@multiply@thousand\pgf@temp 000\relax
    \pgfmath@x=\pgfmathresult pt %
    \pgfmath@table@lookup{\pgfmath@x}{pgfmath@atan@}{1001}%xxx
    \ifdim\pgfmath@xb>1pt\relax%
      \pgfmath@x=-\pgfmath@x%
      \advance\pgfmath@x90pt%
    \fi%
    \ifdim\pgfmath@xa<0pt\relax%
      \pgfmath@x-\pgfmath@x%
    \fi%
    \pgfmath@returnone\pgfmath@x%
  \endgroup%
}

\pgfmathdeclarefunction{atan2}{2}{%
  % Note: first parameter is y (!), second is x (!)
  \begingroup%
    \pgfmath@y=#1pt\relax%
    \ifdim\pgfmath@y<0pt\relax%
      \pgfmath@y=-\pgfmath@y%
    \fi%
    \ifdim\pgfmath@y<0.001pt\relax%
      \ifdim#2pt<0pt\relax%
        \pgfmath@x=-180pt\relax%
      \else%
        \ifdim#2pt>0pt\relax%
          \pgfmath@x=0pt\relax%
        \else%
          \ifdim#1pt<0pt%
            \pgfmath@x=-90pt\relax%
          \else%
            \pgfmath@x=90pt\relax%
          \fi%
        \fi%
      \fi%
    \else%
      \pgfmathabs@{#1}\let\pgfmath@tempa\pgfmathresult%
      \pgfmathabs@{#2}\let\pgfmath@tempb\pgfmathresult%
      \ifdim\pgfmath@tempa pt>\pgfmath@tempb pt%
        \pgfmathdivide@{#2}{\pgfmath@tempa}%
        \expandafter\pgfmathatan@\expandafter{\pgfmathresult}%
        \pgfmath@x=90pt%
        \advance\pgfmath@x by-\pgfmathresult pt\relax%
      \else%
        \pgfmathdivide@{\pgfmath@tempa}{#2}%
        \expandafter\pgfmathatan@\expandafter{\pgfmathresult}%
        \pgfmath@x=\pgfmathresult pt\relax%
        \ifdim#2pt<0pt%
          \advance\pgfmath@x by180pt\relax%
        \fi%
      \fi%
      \ifdim#1pt<0pt\relax%
        \pgfmath@x=-\pgfmath@x%
      \fi%
    \fi%
    \pgfmath@returnone\pgfmath@x%
  \endgroup%    
}

% This is needed since \pgfmathatan2 is not a legal macro name
\expandafter\let\expandafter\pgfmathatantwo\csname pgfmathatan2\endcsname
\expandafter\let\expandafter\pgfmathatantwo@\csname pgfmathatan2@\endcsname

\def\pgfmath@def#1#2#3{\expandafter\def\csname pgfmath@#1@#2\endcsname{#3}}
\pgfmath@def{cos}{0}{1.00000}    \pgfmath@def{cos}{1}{0.99985}
\pgfmath@def{cos}{2}{0.99939}    \pgfmath@def{cos}{3}{0.99863}
\pgfmath@def{cos}{4}{0.99756}    \pgfmath@def{cos}{5}{0.99619}
\pgfmath@def{cos}{6}{0.99452}    \pgfmath@def{cos}{7}{0.99255}
\pgfmath@def{cos}{8}{0.99027}    \pgfmath@def{cos}{9}{0.98769}
\pgfmath@def{cos}{10}{0.98481}    \pgfmath@def{cos}{11}{0.98163}
\pgfmath@def{cos}{12}{0.97815}    \pgfmath@def{cos}{13}{0.97437}
\pgfmath@def{cos}{14}{0.97030}    \pgfmath@def{cos}{15}{0.96593}
\pgfmath@def{cos}{16}{0.96126}    \pgfmath@def{cos}{17}{0.95630}
\pgfmath@def{cos}{18}{0.95106}    \pgfmath@def{cos}{19}{0.94552}
\pgfmath@def{cos}{20}{0.93969}    \pgfmath@def{cos}{21}{0.93358}
\pgfmath@def{cos}{22}{0.92718}    \pgfmath@def{cos}{23}{0.92050}
\pgfmath@def{cos}{24}{0.91355}    \pgfmath@def{cos}{25}{0.90631}
\pgfmath@def{cos}{26}{0.89879}    \pgfmath@def{cos}{27}{0.89101}
\pgfmath@def{cos}{28}{0.88295}    \pgfmath@def{cos}{29}{0.87462}
\pgfmath@def{cos}{30}{0.86603}    \pgfmath@def{cos}{31}{0.85717}
\pgfmath@def{cos}{32}{0.84805}    \pgfmath@def{cos}{33}{0.83867}
\pgfmath@def{cos}{34}{0.82904}    \pgfmath@def{cos}{35}{0.81915}
\pgfmath@def{cos}{36}{0.80902}    \pgfmath@def{cos}{37}{0.79864}
\pgfmath@def{cos}{38}{0.78801}    \pgfmath@def{cos}{39}{0.77715}
\pgfmath@def{cos}{40}{0.76604}    \pgfmath@def{cos}{41}{0.75471}
\pgfmath@def{cos}{42}{0.74314}    \pgfmath@def{cos}{43}{0.73135}
\pgfmath@def{cos}{44}{0.71934}    \pgfmath@def{cos}{45}{0.70711}
\pgfmath@def{cos}{46}{0.69466}    \pgfmath@def{cos}{47}{0.68200}
\pgfmath@def{cos}{48}{0.66913}    \pgfmath@def{cos}{49}{0.65606}
\pgfmath@def{cos}{50}{0.64279}    \pgfmath@def{cos}{51}{0.62932}
\pgfmath@def{cos}{52}{0.61566}    \pgfmath@def{cos}{53}{0.60182}
\pgfmath@def{cos}{54}{0.58779}    \pgfmath@def{cos}{55}{0.57358}
\pgfmath@def{cos}{56}{0.55919}    \pgfmath@def{cos}{57}{0.54464}
\pgfmath@def{cos}{58}{0.52992}    \pgfmath@def{cos}{59}{0.51504}
\pgfmath@def{cos}{60}{0.50000}    \pgfmath@def{cos}{61}{0.48481}
\pgfmath@def{cos}{62}{0.46947}    \pgfmath@def{cos}{63}{0.45399}
\pgfmath@def{cos}{64}{0.43837}    \pgfmath@def{cos}{65}{0.42262}
\pgfmath@def{cos}{66}{0.40674}    \pgfmath@def{cos}{67}{0.39073}
\pgfmath@def{cos}{68}{0.37461}    \pgfmath@def{cos}{69}{0.35837}
\pgfmath@def{cos}{70}{0.34202}    \pgfmath@def{cos}{71}{0.32557}
\pgfmath@def{cos}{72}{0.30902}    \pgfmath@def{cos}{73}{0.29237}
\pgfmath@def{cos}{74}{0.27564}    \pgfmath@def{cos}{75}{0.25882}
\pgfmath@def{cos}{76}{0.24192}    \pgfmath@def{cos}{77}{0.22495}
\pgfmath@def{cos}{78}{0.20791}    \pgfmath@def{cos}{79}{0.19081}
\pgfmath@def{cos}{80}{0.17365}    \pgfmath@def{cos}{81}{0.15643}
\pgfmath@def{cos}{82}{0.13917}    \pgfmath@def{cos}{83}{0.12187}
\pgfmath@def{cos}{84}{0.10453}    \pgfmath@def{cos}{85}{0.08716}
\pgfmath@def{cos}{86}{0.06976}    \pgfmath@def{cos}{87}{0.05234}
\pgfmath@def{cos}{88}{0.03490}    \pgfmath@def{cos}{89}{0.01745}
\pgfmath@def{cos}{90}{0.00000}    \pgfmath@def{cos}{91}{-0.01745}
\pgfmath@def{cos}{92}{-0.03490}    \pgfmath@def{cos}{93}{-0.05234}
\pgfmath@def{cos}{94}{-0.06976}    \pgfmath@def{cos}{95}{-0.08716}
\pgfmath@def{cos}{96}{-0.10453}    \pgfmath@def{cos}{97}{-0.12187}
\pgfmath@def{cos}{98}{-0.13917}    \pgfmath@def{cos}{99}{-0.15643}
\pgfmath@def{cos}{100}{-0.17365}    \pgfmath@def{cos}{101}{-0.19081}
\pgfmath@def{cos}{102}{-0.20791}    \pgfmath@def{cos}{103}{-0.22495}
\pgfmath@def{cos}{104}{-0.24192}    \pgfmath@def{cos}{105}{-0.25882}
\pgfmath@def{cos}{106}{-0.27564}    \pgfmath@def{cos}{107}{-0.29237}
\pgfmath@def{cos}{108}{-0.30902}    \pgfmath@def{cos}{109}{-0.32557}
\pgfmath@def{cos}{110}{-0.34202}    \pgfmath@def{cos}{111}{-0.35837}
\pgfmath@def{cos}{112}{-0.37461}    \pgfmath@def{cos}{113}{-0.39073}
\pgfmath@def{cos}{114}{-0.40674}    \pgfmath@def{cos}{115}{-0.42262}
\pgfmath@def{cos}{116}{-0.43837}    \pgfmath@def{cos}{117}{-0.45399}
\pgfmath@def{cos}{118}{-0.46947}    \pgfmath@def{cos}{119}{-0.48481}
\pgfmath@def{cos}{120}{-0.50000}    \pgfmath@def{cos}{121}{-0.51504}
\pgfmath@def{cos}{122}{-0.52992}    \pgfmath@def{cos}{123}{-0.54464}
\pgfmath@def{cos}{124}{-0.55919}    \pgfmath@def{cos}{125}{-0.57358}
\pgfmath@def{cos}{126}{-0.58779}    \pgfmath@def{cos}{127}{-0.60182}
\pgfmath@def{cos}{128}{-0.61566}    \pgfmath@def{cos}{129}{-0.62932}
\pgfmath@def{cos}{130}{-0.64279}    \pgfmath@def{cos}{131}{-0.65606}
\pgfmath@def{cos}{132}{-0.66913}    \pgfmath@def{cos}{133}{-0.68200}
\pgfmath@def{cos}{134}{-0.69466}    \pgfmath@def{cos}{135}{-0.70711}
\pgfmath@def{cos}{136}{-0.71934}    \pgfmath@def{cos}{137}{-0.73135}
\pgfmath@def{cos}{138}{-0.74314}    \pgfmath@def{cos}{139}{-0.75471}
\pgfmath@def{cos}{140}{-0.76604}    \pgfmath@def{cos}{141}{-0.77715}
\pgfmath@def{cos}{142}{-0.78801}    \pgfmath@def{cos}{143}{-0.79864}
\pgfmath@def{cos}{144}{-0.80902}    \pgfmath@def{cos}{145}{-0.81915}
\pgfmath@def{cos}{146}{-0.82904}    \pgfmath@def{cos}{147}{-0.83867}
\pgfmath@def{cos}{148}{-0.84805}    \pgfmath@def{cos}{149}{-0.85717}
\pgfmath@def{cos}{150}{-0.86603}    \pgfmath@def{cos}{151}{-0.87462}
\pgfmath@def{cos}{152}{-0.88295}    \pgfmath@def{cos}{153}{-0.89101}
\pgfmath@def{cos}{154}{-0.89879}    \pgfmath@def{cos}{155}{-0.90631}
\pgfmath@def{cos}{156}{-0.91355}    \pgfmath@def{cos}{157}{-0.92050}
\pgfmath@def{cos}{158}{-0.92718}    \pgfmath@def{cos}{159}{-0.93358}
\pgfmath@def{cos}{160}{-0.93969}    \pgfmath@def{cos}{161}{-0.94552}
\pgfmath@def{cos}{162}{-0.95106}    \pgfmath@def{cos}{163}{-0.95630}
\pgfmath@def{cos}{164}{-0.96126}    \pgfmath@def{cos}{165}{-0.96593}
\pgfmath@def{cos}{166}{-0.97030}    \pgfmath@def{cos}{167}{-0.97437}
\pgfmath@def{cos}{168}{-0.97815}    \pgfmath@def{cos}{169}{-0.98163}
\pgfmath@def{cos}{170}{-0.98481}    \pgfmath@def{cos}{171}{-0.98769}
\pgfmath@def{cos}{172}{-0.99027}    \pgfmath@def{cos}{173}{-0.99255}
\pgfmath@def{cos}{174}{-0.99452}    \pgfmath@def{cos}{175}{-0.99619}
\pgfmath@def{cos}{176}{-0.99756}    \pgfmath@def{cos}{177}{-0.99863}
\pgfmath@def{cos}{178}{-0.99939}    \pgfmath@def{cos}{179}{-0.99985}
\pgfmath@def{cos}{180}{-1.00000}     \pgfmath@def{cos}{181}{-0.99985}

\pgfmath@def{cosfrac}{0}{1.00000}    \pgfmath@def{cosfrac}{1}{0.99995}
\pgfmath@def{cosfrac}{2}{0.99980}    \pgfmath@def{cosfrac}{3}{0.99955}
\pgfmath@def{cosfrac}{4}{0.99920}    \pgfmath@def{cosfrac}{5}{0.99875}
\pgfmath@def{cosfrac}{6}{0.99820}    \pgfmath@def{cosfrac}{7}{0.99755}
\pgfmath@def{cosfrac}{8}{0.99681}    \pgfmath@def{cosfrac}{9}{0.99597}
\pgfmath@def{cosfrac}{10}{0.99503}    \pgfmath@def{cosfrac}{11}{0.99400}
\pgfmath@def{cosfrac}{12}{0.99287}    \pgfmath@def{cosfrac}{13}{0.99165}
\pgfmath@def{cosfrac}{14}{0.99034}    \pgfmath@def{cosfrac}{15}{0.98893}
\pgfmath@def{cosfrac}{16}{0.98744}    \pgfmath@def{cosfrac}{17}{0.98585}
\pgfmath@def{cosfrac}{18}{0.98418}    \pgfmath@def{cosfrac}{19}{0.98242}
\pgfmath@def{cosfrac}{20}{0.98058}    \pgfmath@def{cosfrac}{21}{0.97865}
\pgfmath@def{cosfrac}{22}{0.97664}    \pgfmath@def{cosfrac}{23}{0.97455}
\pgfmath@def{cosfrac}{24}{0.97238}    \pgfmath@def{cosfrac}{25}{0.97014}
\pgfmath@def{cosfrac}{26}{0.96782}    \pgfmath@def{cosfrac}{27}{0.96542}
\pgfmath@def{cosfrac}{28}{0.96296}    \pgfmath@def{cosfrac}{29}{0.96042}
\pgfmath@def{cosfrac}{30}{0.95782}    \pgfmath@def{cosfrac}{31}{0.95515}
\pgfmath@def{cosfrac}{32}{0.95242}    \pgfmath@def{cosfrac}{33}{0.94962}
\pgfmath@def{cosfrac}{34}{0.94677}    \pgfmath@def{cosfrac}{35}{0.94385}
\pgfmath@def{cosfrac}{36}{0.94088}    \pgfmath@def{cosfrac}{37}{0.93786}
\pgfmath@def{cosfrac}{38}{0.93478}    \pgfmath@def{cosfrac}{39}{0.93165}
\pgfmath@def{cosfrac}{40}{0.92847}    \pgfmath@def{cosfrac}{41}{0.92525}
\pgfmath@def{cosfrac}{42}{0.92198}    \pgfmath@def{cosfrac}{43}{0.91866}
\pgfmath@def{cosfrac}{44}{0.91531}    \pgfmath@def{cosfrac}{45}{0.91192}
\pgfmath@def{cosfrac}{46}{0.90849}    \pgfmath@def{cosfrac}{47}{0.90502}
\pgfmath@def{cosfrac}{48}{0.90152}    \pgfmath@def{cosfrac}{49}{0.89799}
\pgfmath@def{cosfrac}{50}{0.89442}    \pgfmath@def{cosfrac}{51}{0.89083}
\pgfmath@def{cosfrac}{52}{0.88721}    \pgfmath@def{cosfrac}{53}{0.88357}
\pgfmath@def{cosfrac}{54}{0.87990}    \pgfmath@def{cosfrac}{55}{0.87621}
\pgfmath@def{cosfrac}{56}{0.87250}    \pgfmath@def{cosfrac}{57}{0.86877}
\pgfmath@def{cosfrac}{58}{0.86503}    \pgfmath@def{cosfrac}{59}{0.86126}
\pgfmath@def{cosfrac}{60}{0.85749}    \pgfmath@def{cosfrac}{61}{0.85370}
\pgfmath@def{cosfrac}{62}{0.84990}    \pgfmath@def{cosfrac}{63}{0.84609}
\pgfmath@def{cosfrac}{64}{0.84227}    \pgfmath@def{cosfrac}{65}{0.83844}
\pgfmath@def{cosfrac}{66}{0.83460}    \pgfmath@def{cosfrac}{67}{0.83077}
\pgfmath@def{cosfrac}{68}{0.82692}    \pgfmath@def{cosfrac}{69}{0.82308}
\pgfmath@def{cosfrac}{70}{0.81923}    \pgfmath@def{cosfrac}{71}{0.81538}
\pgfmath@def{cosfrac}{72}{0.81153}    \pgfmath@def{cosfrac}{73}{0.80768}
\pgfmath@def{cosfrac}{74}{0.80384}    \pgfmath@def{cosfrac}{75}{0.80000}
\pgfmath@def{cosfrac}{76}{0.79616}    \pgfmath@def{cosfrac}{77}{0.79232}
\pgfmath@def{cosfrac}{78}{0.78850}    \pgfmath@def{cosfrac}{79}{0.78468}
\pgfmath@def{cosfrac}{80}{0.78086}    \pgfmath@def{cosfrac}{81}{0.77706}
\pgfmath@def{cosfrac}{82}{0.77326}    \pgfmath@def{cosfrac}{83}{0.76948}
\pgfmath@def{cosfrac}{84}{0.76570}    \pgfmath@def{cosfrac}{85}{0.76193}
\pgfmath@def{cosfrac}{86}{0.75818}    \pgfmath@def{cosfrac}{87}{0.75444}
\pgfmath@def{cosfrac}{88}{0.75071}    \pgfmath@def{cosfrac}{89}{0.74699}
\pgfmath@def{cosfrac}{90}{0.74329}    \pgfmath@def{cosfrac}{91}{0.73960}
\pgfmath@def{cosfrac}{92}{0.73593}    \pgfmath@def{cosfrac}{93}{0.73227}
\pgfmath@def{cosfrac}{94}{0.72862}    \pgfmath@def{cosfrac}{95}{0.72499}
\pgfmath@def{cosfrac}{96}{0.72138}    \pgfmath@def{cosfrac}{97}{0.71779}
\pgfmath@def{cosfrac}{98}{0.71421}    \pgfmath@def{cosfrac}{99}{0.71065}
\pgfmath@def{cosfrac}{100}{0.70710}  

% Oh No! Some really loooooong tables.
\pgfmath@def{atan}{0}{0.00000}    \pgfmath@def{atan}{1}{0.05729}
\pgfmath@def{atan}{2}{0.11459}    \pgfmath@def{atan}{3}{0.17188}
\pgfmath@def{atan}{4}{0.22918}    \pgfmath@def{atan}{5}{0.28647}
\pgfmath@def{atan}{6}{0.34377}    \pgfmath@def{atan}{7}{0.40106}
\pgfmath@def{atan}{8}{0.45835}    \pgfmath@def{atan}{9}{0.51564}
\pgfmath@def{atan}{10}{0.57293}    \pgfmath@def{atan}{11}{0.63022}
\pgfmath@def{atan}{12}{0.68751}    \pgfmath@def{atan}{13}{0.74480}
\pgfmath@def{atan}{14}{0.80208}    \pgfmath@def{atan}{15}{0.85937}
\pgfmath@def{atan}{16}{0.91665}    \pgfmath@def{atan}{17}{0.97393}
\pgfmath@def{atan}{18}{1.03121}    \pgfmath@def{atan}{19}{1.08848}
\pgfmath@def{atan}{20}{1.14576}    \pgfmath@def{atan}{21}{1.20303}
\pgfmath@def{atan}{22}{1.26030}    \pgfmath@def{atan}{23}{1.31757}
\pgfmath@def{atan}{24}{1.37483}    \pgfmath@def{atan}{25}{1.43209}
\pgfmath@def{atan}{26}{1.48935}    \pgfmath@def{atan}{27}{1.54661}
\pgfmath@def{atan}{28}{1.60386}    \pgfmath@def{atan}{29}{1.66111}
\pgfmath@def{atan}{30}{1.71835}    \pgfmath@def{atan}{31}{1.77560}
\pgfmath@def{atan}{32}{1.83284}    \pgfmath@def{atan}{33}{1.89007}
\pgfmath@def{atan}{34}{1.94730}    \pgfmath@def{atan}{35}{2.00453}
\pgfmath@def{atan}{36}{2.06175}    \pgfmath@def{atan}{37}{2.11897}
\pgfmath@def{atan}{38}{2.17619}    \pgfmath@def{atan}{39}{2.23340}
\pgfmath@def{atan}{40}{2.29061}    \pgfmath@def{atan}{41}{2.34781}
\pgfmath@def{atan}{42}{2.40500}    \pgfmath@def{atan}{43}{2.46220}
\pgfmath@def{atan}{44}{2.51938}    \pgfmath@def{atan}{45}{2.57657}
\pgfmath@def{atan}{46}{2.63374}    \pgfmath@def{atan}{47}{2.69092}
\pgfmath@def{atan}{48}{2.74808}    \pgfmath@def{atan}{49}{2.80524}
\pgfmath@def{atan}{50}{2.86240}    \pgfmath@def{atan}{51}{2.91955}
\pgfmath@def{atan}{52}{2.97669}    \pgfmath@def{atan}{53}{3.03383}
\pgfmath@def{atan}{54}{3.09097}    \pgfmath@def{atan}{55}{3.14809}
\pgfmath@def{atan}{56}{3.20521}    \pgfmath@def{atan}{57}{3.26232}
\pgfmath@def{atan}{58}{3.31943}    \pgfmath@def{atan}{59}{3.37653}
\pgfmath@def{atan}{60}{3.43363}    \pgfmath@def{atan}{61}{3.49071}
\pgfmath@def{atan}{62}{3.54779}    \pgfmath@def{atan}{63}{3.60487}
\pgfmath@def{atan}{64}{3.66193}    \pgfmath@def{atan}{65}{3.71899}
\pgfmath@def{atan}{66}{3.77604}    \pgfmath@def{atan}{67}{3.83308}
\pgfmath@def{atan}{68}{3.89012}    \pgfmath@def{atan}{69}{3.94715}
\pgfmath@def{atan}{70}{4.00417}    \pgfmath@def{atan}{71}{4.06118}
\pgfmath@def{atan}{72}{4.11819}    \pgfmath@def{atan}{73}{4.17518}
\pgfmath@def{atan}{74}{4.23217}    \pgfmath@def{atan}{75}{4.28915}
\pgfmath@def{atan}{76}{4.34612}    \pgfmath@def{atan}{77}{4.40308}
\pgfmath@def{atan}{78}{4.46004}    \pgfmath@def{atan}{79}{4.51698}
\pgfmath@def{atan}{80}{4.57392}    \pgfmath@def{atan}{81}{4.63084}
\pgfmath@def{atan}{82}{4.68776}    \pgfmath@def{atan}{83}{4.74467}
\pgfmath@def{atan}{84}{4.80157}    \pgfmath@def{atan}{85}{4.85846}
\pgfmath@def{atan}{86}{4.91534}    \pgfmath@def{atan}{87}{4.97221}
\pgfmath@def{atan}{88}{5.02907}    \pgfmath@def{atan}{89}{5.08592}
\pgfmath@def{atan}{90}{5.14276}    \pgfmath@def{atan}{91}{5.19959}
\pgfmath@def{atan}{92}{5.25641}    \pgfmath@def{atan}{93}{5.31322}
\pgfmath@def{atan}{94}{5.37002}    \pgfmath@def{atan}{95}{5.42681}
\pgfmath@def{atan}{96}{5.48359}    \pgfmath@def{atan}{97}{5.54035}
\pgfmath@def{atan}{98}{5.59711}    \pgfmath@def{atan}{99}{5.65385}
\pgfmath@def{atan}{100}{5.71059}    \pgfmath@def{atan}{101}{5.76731}
\pgfmath@def{atan}{102}{5.82402}    \pgfmath@def{atan}{103}{5.88072}
\pgfmath@def{atan}{104}{5.93741}    \pgfmath@def{atan}{105}{5.99409}
\pgfmath@def{atan}{106}{6.05075}    \pgfmath@def{atan}{107}{6.10741}
\pgfmath@def{atan}{108}{6.16405}    \pgfmath@def{atan}{109}{6.22068}
\pgfmath@def{atan}{110}{6.27729}    \pgfmath@def{atan}{111}{6.33390}
\pgfmath@def{atan}{112}{6.39049}    \pgfmath@def{atan}{113}{6.44707}
\pgfmath@def{atan}{114}{6.50364}    \pgfmath@def{atan}{115}{6.56019}
\pgfmath@def{atan}{116}{6.61673}    \pgfmath@def{atan}{117}{6.67326}
\pgfmath@def{atan}{118}{6.72978}    \pgfmath@def{atan}{119}{6.78628}
\pgfmath@def{atan}{120}{6.84277}    \pgfmath@def{atan}{121}{6.89924}
\pgfmath@def{atan}{122}{6.95571}    \pgfmath@def{atan}{123}{7.01216}
\pgfmath@def{atan}{124}{7.06859}    \pgfmath@def{atan}{125}{7.12501}
\pgfmath@def{atan}{126}{7.18142}    \pgfmath@def{atan}{127}{7.23781}
\pgfmath@def{atan}{128}{7.29419}    \pgfmath@def{atan}{129}{7.35056}
\pgfmath@def{atan}{130}{7.40691}    \pgfmath@def{atan}{131}{7.46324}
\pgfmath@def{atan}{132}{7.51957}    \pgfmath@def{atan}{133}{7.57587}
\pgfmath@def{atan}{134}{7.63217}    \pgfmath@def{atan}{135}{7.68844}
\pgfmath@def{atan}{136}{7.74471}    \pgfmath@def{atan}{137}{7.80095}
\pgfmath@def{atan}{138}{7.85719}    \pgfmath@def{atan}{139}{7.91340}
\pgfmath@def{atan}{140}{7.96961}    \pgfmath@def{atan}{141}{8.02579}
\pgfmath@def{atan}{142}{8.08196}    \pgfmath@def{atan}{143}{8.13812}
\pgfmath@def{atan}{144}{8.19426}    \pgfmath@def{atan}{145}{8.25038}
\pgfmath@def{atan}{146}{8.30649}    \pgfmath@def{atan}{147}{8.36258}
\pgfmath@def{atan}{148}{8.41866}    \pgfmath@def{atan}{149}{8.47472}
\pgfmath@def{atan}{150}{8.53076}    \pgfmath@def{atan}{151}{8.58679}
\pgfmath@def{atan}{152}{8.64280}    \pgfmath@def{atan}{153}{8.69879}
\pgfmath@def{atan}{154}{8.75477}    \pgfmath@def{atan}{155}{8.81073}
\pgfmath@def{atan}{156}{8.86667}    \pgfmath@def{atan}{157}{8.92260}
\pgfmath@def{atan}{158}{8.97851}    \pgfmath@def{atan}{159}{9.03440}
\pgfmath@def{atan}{160}{9.09027}    \pgfmath@def{atan}{161}{9.14613}
\pgfmath@def{atan}{162}{9.20197}    \pgfmath@def{atan}{163}{9.25779}
\pgfmath@def{atan}{164}{9.31359}    \pgfmath@def{atan}{165}{9.36938}
\pgfmath@def{atan}{166}{9.42515}    \pgfmath@def{atan}{167}{9.48090}
\pgfmath@def{atan}{168}{9.53663}    \pgfmath@def{atan}{169}{9.59235}
\pgfmath@def{atan}{170}{9.64804}    \pgfmath@def{atan}{171}{9.70372}
\pgfmath@def{atan}{172}{9.75938}    \pgfmath@def{atan}{173}{9.81502}
\pgfmath@def{atan}{174}{9.87064}    \pgfmath@def{atan}{175}{9.92624}
\pgfmath@def{atan}{176}{9.98182}    \pgfmath@def{atan}{177}{10.03739}
\pgfmath@def{atan}{178}{10.09294}    \pgfmath@def{atan}{179}{10.14846}
\pgfmath@def{atan}{180}{10.20397}    \pgfmath@def{atan}{181}{10.25946}
\pgfmath@def{atan}{182}{10.31493}    \pgfmath@def{atan}{183}{10.37037}
\pgfmath@def{atan}{184}{10.42580}    \pgfmath@def{atan}{185}{10.48121}
\pgfmath@def{atan}{186}{10.53660}    \pgfmath@def{atan}{187}{10.59197}
\pgfmath@def{atan}{188}{10.64732}    \pgfmath@def{atan}{189}{10.70265}
\pgfmath@def{atan}{190}{10.75796}    \pgfmath@def{atan}{191}{10.81325}
\pgfmath@def{atan}{192}{10.86852}    \pgfmath@def{atan}{193}{10.92377}
\pgfmath@def{atan}{194}{10.97900}    \pgfmath@def{atan}{195}{11.03420}
\pgfmath@def{atan}{196}{11.08939}    \pgfmath@def{atan}{197}{11.14456}
\pgfmath@def{atan}{198}{11.19970}    \pgfmath@def{atan}{199}{11.25483}
\pgfmath@def{atan}{200}{11.30993}    \pgfmath@def{atan}{201}{11.36501}
\pgfmath@def{atan}{202}{11.42007}    \pgfmath@def{atan}{203}{11.47511}
\pgfmath@def{atan}{204}{11.53013}    \pgfmath@def{atan}{205}{11.58512}
\pgfmath@def{atan}{206}{11.64010}    \pgfmath@def{atan}{207}{11.69505}
\pgfmath@def{atan}{208}{11.74998}    \pgfmath@def{atan}{209}{11.80489}
\pgfmath@def{atan}{210}{11.85977}    \pgfmath@def{atan}{211}{11.91464}
\pgfmath@def{atan}{212}{11.96948}    \pgfmath@def{atan}{213}{12.02430}
\pgfmath@def{atan}{214}{12.07910}    \pgfmath@def{atan}{215}{12.13388}
\pgfmath@def{atan}{216}{12.18863}    \pgfmath@def{atan}{217}{12.24336}
\pgfmath@def{atan}{218}{12.29807}    \pgfmath@def{atan}{219}{12.35275}
\pgfmath@def{atan}{220}{12.40741}    \pgfmath@def{atan}{221}{12.46205}
\pgfmath@def{atan}{222}{12.51667}    \pgfmath@def{atan}{223}{12.57126}
\pgfmath@def{atan}{224}{12.62583}    \pgfmath@def{atan}{225}{12.68038}
\pgfmath@def{atan}{226}{12.73490}    \pgfmath@def{atan}{227}{12.78940}
\pgfmath@def{atan}{228}{12.84388}    \pgfmath@def{atan}{229}{12.89833}
\pgfmath@def{atan}{230}{12.95276}    \pgfmath@def{atan}{231}{13.00717}
\pgfmath@def{atan}{232}{13.06155}    \pgfmath@def{atan}{233}{13.11590}
\pgfmath@def{atan}{234}{13.17024}    \pgfmath@def{atan}{235}{13.22455}
\pgfmath@def{atan}{236}{13.27883}    \pgfmath@def{atan}{237}{13.33309}
\pgfmath@def{atan}{238}{13.38733}    \pgfmath@def{atan}{239}{13.44154}
\pgfmath@def{atan}{240}{13.49573}    \pgfmath@def{atan}{241}{13.54989}
\pgfmath@def{atan}{242}{13.60403}    \pgfmath@def{atan}{243}{13.65814}
\pgfmath@def{atan}{244}{13.71223}    \pgfmath@def{atan}{245}{13.76630}
\pgfmath@def{atan}{246}{13.82034}    \pgfmath@def{atan}{247}{13.87435}
\pgfmath@def{atan}{248}{13.92834}    \pgfmath@def{atan}{249}{13.98230}
\pgfmath@def{atan}{250}{14.03624}    \pgfmath@def{atan}{251}{14.09015}
\pgfmath@def{atan}{252}{14.14404}    \pgfmath@def{atan}{253}{14.19790}
\pgfmath@def{atan}{254}{14.25174}    \pgfmath@def{atan}{255}{14.30555}
\pgfmath@def{atan}{256}{14.35933}    \pgfmath@def{atan}{257}{14.41309}
\pgfmath@def{atan}{258}{14.46682}    \pgfmath@def{atan}{259}{14.52053}
\pgfmath@def{atan}{260}{14.57421}    \pgfmath@def{atan}{261}{14.62787}
\pgfmath@def{atan}{262}{14.68149}    \pgfmath@def{atan}{263}{14.73510}
\pgfmath@def{atan}{264}{14.78867}    \pgfmath@def{atan}{265}{14.84222}
\pgfmath@def{atan}{266}{14.89575}    \pgfmath@def{atan}{267}{14.94924}
\pgfmath@def{atan}{268}{15.00271}    \pgfmath@def{atan}{269}{15.05615}
\pgfmath@def{atan}{270}{15.10957}    \pgfmath@def{atan}{271}{15.16296}
\pgfmath@def{atan}{272}{15.21632}    \pgfmath@def{atan}{273}{15.26966}
\pgfmath@def{atan}{274}{15.32297}    \pgfmath@def{atan}{275}{15.37625}
\pgfmath@def{atan}{276}{15.42950}    \pgfmath@def{atan}{277}{15.48273}
\pgfmath@def{atan}{278}{15.53593}    \pgfmath@def{atan}{279}{15.58910}
\pgfmath@def{atan}{280}{15.64224}    \pgfmath@def{atan}{281}{15.69536}
\pgfmath@def{atan}{282}{15.74845}    \pgfmath@def{atan}{283}{15.80151}
\pgfmath@def{atan}{284}{15.85454}    \pgfmath@def{atan}{285}{15.90755}
\pgfmath@def{atan}{286}{15.96052}    \pgfmath@def{atan}{287}{16.01347}
\pgfmath@def{atan}{288}{16.06640}    \pgfmath@def{atan}{289}{16.11929}
\pgfmath@def{atan}{290}{16.17215}    \pgfmath@def{atan}{291}{16.22499}
\pgfmath@def{atan}{292}{16.27780}    \pgfmath@def{atan}{293}{16.33058}
\pgfmath@def{atan}{294}{16.38333}    \pgfmath@def{atan}{295}{16.43605}
\pgfmath@def{atan}{296}{16.48875}    \pgfmath@def{atan}{297}{16.54142}
\pgfmath@def{atan}{298}{16.59405}    \pgfmath@def{atan}{299}{16.64666}
\pgfmath@def{atan}{300}{16.69924}    \pgfmath@def{atan}{301}{16.75179}
\pgfmath@def{atan}{302}{16.80431}    \pgfmath@def{atan}{303}{16.85680}
\pgfmath@def{atan}{304}{16.90927}    \pgfmath@def{atan}{305}{16.96170}
\pgfmath@def{atan}{306}{17.01411}    \pgfmath@def{atan}{307}{17.06648}
\pgfmath@def{atan}{308}{17.11883}    \pgfmath@def{atan}{309}{17.17114}
\pgfmath@def{atan}{310}{17.22343}    \pgfmath@def{atan}{311}{17.27569}
\pgfmath@def{atan}{312}{17.32792}    \pgfmath@def{atan}{313}{17.38012}
\pgfmath@def{atan}{314}{17.43228}    \pgfmath@def{atan}{315}{17.48442}
\pgfmath@def{atan}{316}{17.53653}    \pgfmath@def{atan}{317}{17.58861}
\pgfmath@def{atan}{318}{17.64066}    \pgfmath@def{atan}{319}{17.69268}
\pgfmath@def{atan}{320}{17.74467}    \pgfmath@def{atan}{321}{17.79663}
\pgfmath@def{atan}{322}{17.84855}    \pgfmath@def{atan}{323}{17.90045}
\pgfmath@def{atan}{324}{17.95232}    \pgfmath@def{atan}{325}{18.00416}
\pgfmath@def{atan}{326}{18.05596}    \pgfmath@def{atan}{327}{18.10774}
\pgfmath@def{atan}{328}{18.15949}    \pgfmath@def{atan}{329}{18.21120}
\pgfmath@def{atan}{330}{18.26289}    \pgfmath@def{atan}{331}{18.31454}
\pgfmath@def{atan}{332}{18.36616}    \pgfmath@def{atan}{333}{18.41775}
\pgfmath@def{atan}{334}{18.46931}    \pgfmath@def{atan}{335}{18.52084}
\pgfmath@def{atan}{336}{18.57234}    \pgfmath@def{atan}{337}{18.62381}
\pgfmath@def{atan}{338}{18.67525}    \pgfmath@def{atan}{339}{18.72665}
\pgfmath@def{atan}{340}{18.77803}    \pgfmath@def{atan}{341}{18.82937}
\pgfmath@def{atan}{342}{18.88068}    \pgfmath@def{atan}{343}{18.93196}
\pgfmath@def{atan}{344}{18.98321}    \pgfmath@def{atan}{345}{19.03443}
\pgfmath@def{atan}{346}{19.08562}    \pgfmath@def{atan}{347}{19.13677}
\pgfmath@def{atan}{348}{19.18789}    \pgfmath@def{atan}{349}{19.23898}
\pgfmath@def{atan}{350}{19.29004}    \pgfmath@def{atan}{351}{19.34107}
\pgfmath@def{atan}{352}{19.39206}    \pgfmath@def{atan}{353}{19.44303}
\pgfmath@def{atan}{354}{19.49396}    \pgfmath@def{atan}{355}{19.54486}
\pgfmath@def{atan}{356}{19.59572}    \pgfmath@def{atan}{357}{19.64656}
\pgfmath@def{atan}{358}{19.69736}    \pgfmath@def{atan}{359}{19.74813}
\pgfmath@def{atan}{360}{19.79887}    \pgfmath@def{atan}{361}{19.84958}
\pgfmath@def{atan}{362}{19.90025}    \pgfmath@def{atan}{363}{19.95089}
\pgfmath@def{atan}{364}{20.00150}    \pgfmath@def{atan}{365}{20.05208}
\pgfmath@def{atan}{366}{20.10262}    \pgfmath@def{atan}{367}{20.15313}
\pgfmath@def{atan}{368}{20.20361}    \pgfmath@def{atan}{369}{20.25406}
\pgfmath@def{atan}{370}{20.30447}    \pgfmath@def{atan}{371}{20.35485}
\pgfmath@def{atan}{372}{20.40520}    \pgfmath@def{atan}{373}{20.45551}
\pgfmath@def{atan}{374}{20.50579}    \pgfmath@def{atan}{375}{20.55604}
\pgfmath@def{atan}{376}{20.60626}    \pgfmath@def{atan}{377}{20.65644}
\pgfmath@def{atan}{378}{20.70659}    \pgfmath@def{atan}{379}{20.75670}
\pgfmath@def{atan}{380}{20.80679}    \pgfmath@def{atan}{381}{20.85684}
\pgfmath@def{atan}{382}{20.90685}    \pgfmath@def{atan}{383}{20.95684}
\pgfmath@def{atan}{384}{21.00678}    \pgfmath@def{atan}{385}{21.05670}
\pgfmath@def{atan}{386}{21.10658}    \pgfmath@def{atan}{387}{21.15643}
\pgfmath@def{atan}{388}{21.20625}    \pgfmath@def{atan}{389}{21.25603}
\pgfmath@def{atan}{390}{21.30578}    \pgfmath@def{atan}{391}{21.35549}
\pgfmath@def{atan}{392}{21.40517}    \pgfmath@def{atan}{393}{21.45482}
\pgfmath@def{atan}{394}{21.50444}    \pgfmath@def{atan}{395}{21.55402}
\pgfmath@def{atan}{396}{21.60356}    \pgfmath@def{atan}{397}{21.65307}
\pgfmath@def{atan}{398}{21.70255}    \pgfmath@def{atan}{399}{21.75200}
\pgfmath@def{atan}{400}{21.80140}    \pgfmath@def{atan}{401}{21.85078}
\pgfmath@def{atan}{402}{21.90012}    \pgfmath@def{atan}{403}{21.94943}
\pgfmath@def{atan}{404}{21.99870}    \pgfmath@def{atan}{405}{22.04794}
\pgfmath@def{atan}{406}{22.09715}    \pgfmath@def{atan}{407}{22.14632}
\pgfmath@def{atan}{408}{22.19546}    \pgfmath@def{atan}{409}{22.24456}
\pgfmath@def{atan}{410}{22.29362}    \pgfmath@def{atan}{411}{22.34266}
\pgfmath@def{atan}{412}{22.39166}    \pgfmath@def{atan}{413}{22.44062}
\pgfmath@def{atan}{414}{22.48955}    \pgfmath@def{atan}{415}{22.53845}
\pgfmath@def{atan}{416}{22.58731}    \pgfmath@def{atan}{417}{22.63613}
\pgfmath@def{atan}{418}{22.68492}    \pgfmath@def{atan}{419}{22.73368}
\pgfmath@def{atan}{420}{22.78240}    \pgfmath@def{atan}{421}{22.83109}
\pgfmath@def{atan}{422}{22.87974}    \pgfmath@def{atan}{423}{22.92836}
\pgfmath@def{atan}{424}{22.97694}    \pgfmath@def{atan}{425}{23.02549}
\pgfmath@def{atan}{426}{23.07400}    \pgfmath@def{atan}{427}{23.12248}
\pgfmath@def{atan}{428}{23.17092}    \pgfmath@def{atan}{429}{23.21933}
\pgfmath@def{atan}{430}{23.26770}    \pgfmath@def{atan}{431}{23.31604}
\pgfmath@def{atan}{432}{23.36434}    \pgfmath@def{atan}{433}{23.41261}
\pgfmath@def{atan}{434}{23.46084}    \pgfmath@def{atan}{435}{23.50904}
\pgfmath@def{atan}{436}{23.55720}    \pgfmath@def{atan}{437}{23.60532}
\pgfmath@def{atan}{438}{23.65341}    \pgfmath@def{atan}{439}{23.70147}
\pgfmath@def{atan}{440}{23.74949}    \pgfmath@def{atan}{441}{23.79747}
\pgfmath@def{atan}{442}{23.84542}    \pgfmath@def{atan}{443}{23.89334}
\pgfmath@def{atan}{444}{23.94122}    \pgfmath@def{atan}{445}{23.98906}
\pgfmath@def{atan}{446}{24.03687}    \pgfmath@def{atan}{447}{24.08464}
\pgfmath@def{atan}{448}{24.13238}    \pgfmath@def{atan}{449}{24.18008}
\pgfmath@def{atan}{450}{24.22774}    \pgfmath@def{atan}{451}{24.27537}
\pgfmath@def{atan}{452}{24.32296}    \pgfmath@def{atan}{453}{24.37052}
\pgfmath@def{atan}{454}{24.41804}    \pgfmath@def{atan}{455}{24.46553}
\pgfmath@def{atan}{456}{24.51298}    \pgfmath@def{atan}{457}{24.56040}
\pgfmath@def{atan}{458}{24.60778}    \pgfmath@def{atan}{459}{24.65512}
\pgfmath@def{atan}{460}{24.70243}    \pgfmath@def{atan}{461}{24.74970}
\pgfmath@def{atan}{462}{24.79693}    \pgfmath@def{atan}{463}{24.84413}
\pgfmath@def{atan}{464}{24.89130}    \pgfmath@def{atan}{465}{24.93842}
\pgfmath@def{atan}{466}{24.98551}    \pgfmath@def{atan}{467}{25.03257}
\pgfmath@def{atan}{468}{25.07959}    \pgfmath@def{atan}{469}{25.12657}
\pgfmath@def{atan}{470}{25.17352}    \pgfmath@def{atan}{471}{25.22043}
\pgfmath@def{atan}{472}{25.26731}    \pgfmath@def{atan}{473}{25.31414}
\pgfmath@def{atan}{474}{25.36095}    \pgfmath@def{atan}{475}{25.40771}
\pgfmath@def{atan}{476}{25.45444}    \pgfmath@def{atan}{477}{25.50114}
\pgfmath@def{atan}{478}{25.54780}    \pgfmath@def{atan}{479}{25.59442}
\pgfmath@def{atan}{480}{25.64100}    \pgfmath@def{atan}{481}{25.68755}
\pgfmath@def{atan}{482}{25.73406}    \pgfmath@def{atan}{483}{25.78054}
\pgfmath@def{atan}{484}{25.82698}    \pgfmath@def{atan}{485}{25.87338}
\pgfmath@def{atan}{486}{25.91975}    \pgfmath@def{atan}{487}{25.96608}
\pgfmath@def{atan}{488}{26.01237}    \pgfmath@def{atan}{489}{26.05863}
\pgfmath@def{atan}{490}{26.10485}    \pgfmath@def{atan}{491}{26.15103}
\pgfmath@def{atan}{492}{26.19718}    \pgfmath@def{atan}{493}{26.24329}
\pgfmath@def{atan}{494}{26.28937}    \pgfmath@def{atan}{495}{26.33541}
\pgfmath@def{atan}{496}{26.38141}    \pgfmath@def{atan}{497}{26.42737}
\pgfmath@def{atan}{498}{26.47330}    \pgfmath@def{atan}{499}{26.51919}
\pgfmath@def{atan}{500}{26.56505}    \pgfmath@def{atan}{501}{26.61086}
\pgfmath@def{atan}{502}{26.65665}    \pgfmath@def{atan}{503}{26.70239}
\pgfmath@def{atan}{504}{26.74810}    \pgfmath@def{atan}{505}{26.79377}
\pgfmath@def{atan}{506}{26.83941}    \pgfmath@def{atan}{507}{26.88500}
\pgfmath@def{atan}{508}{26.93057}    \pgfmath@def{atan}{509}{26.97609}
\pgfmath@def{atan}{510}{27.02158}    \pgfmath@def{atan}{511}{27.06703}
\pgfmath@def{atan}{512}{27.11244}    \pgfmath@def{atan}{513}{27.15782}
\pgfmath@def{atan}{514}{27.20316}    \pgfmath@def{atan}{515}{27.24846}
\pgfmath@def{atan}{516}{27.29373}    \pgfmath@def{atan}{517}{27.33896}
\pgfmath@def{atan}{518}{27.38415}    \pgfmath@def{atan}{519}{27.42931}
\pgfmath@def{atan}{520}{27.47443}    \pgfmath@def{atan}{521}{27.51951}
\pgfmath@def{atan}{522}{27.56455}    \pgfmath@def{atan}{523}{27.60956}
\pgfmath@def{atan}{524}{27.65453}    \pgfmath@def{atan}{525}{27.69947}
\pgfmath@def{atan}{526}{27.74437}    \pgfmath@def{atan}{527}{27.78923}
\pgfmath@def{atan}{528}{27.83405}    \pgfmath@def{atan}{529}{27.87884}
\pgfmath@def{atan}{530}{27.92359}    \pgfmath@def{atan}{531}{27.96830}
\pgfmath@def{atan}{532}{28.01297}    \pgfmath@def{atan}{533}{28.05761}
\pgfmath@def{atan}{534}{28.10221}    \pgfmath@def{atan}{535}{28.14678}
\pgfmath@def{atan}{536}{28.19130}    \pgfmath@def{atan}{537}{28.23579}
\pgfmath@def{atan}{538}{28.28025}    \pgfmath@def{atan}{539}{28.32466}
\pgfmath@def{atan}{540}{28.36904}    \pgfmath@def{atan}{541}{28.41338}
\pgfmath@def{atan}{542}{28.45769}    \pgfmath@def{atan}{543}{28.50196}
\pgfmath@def{atan}{544}{28.54619}    \pgfmath@def{atan}{545}{28.59038}
\pgfmath@def{atan}{546}{28.63454}    \pgfmath@def{atan}{547}{28.67865}
\pgfmath@def{atan}{548}{28.72274}    \pgfmath@def{atan}{549}{28.76678}
\pgfmath@def{atan}{550}{28.81079}    \pgfmath@def{atan}{551}{28.85476}
\pgfmath@def{atan}{552}{28.89869}    \pgfmath@def{atan}{553}{28.94259}
\pgfmath@def{atan}{554}{28.98645}    \pgfmath@def{atan}{555}{29.03027}
\pgfmath@def{atan}{556}{29.07405}    \pgfmath@def{atan}{557}{29.11780}
\pgfmath@def{atan}{558}{29.16151}    \pgfmath@def{atan}{559}{29.20519}
\pgfmath@def{atan}{560}{29.24882}    \pgfmath@def{atan}{561}{29.29242}
\pgfmath@def{atan}{562}{29.33598}    \pgfmath@def{atan}{563}{29.37951}
\pgfmath@def{atan}{564}{29.42299}    \pgfmath@def{atan}{565}{29.46644}
\pgfmath@def{atan}{566}{29.50986}    \pgfmath@def{atan}{567}{29.55323}
\pgfmath@def{atan}{568}{29.59657}    \pgfmath@def{atan}{569}{29.63987}
\pgfmath@def{atan}{570}{29.68314}    \pgfmath@def{atan}{571}{29.72636}
\pgfmath@def{atan}{572}{29.76955}    \pgfmath@def{atan}{573}{29.81270}
\pgfmath@def{atan}{574}{29.85582}    \pgfmath@def{atan}{575}{29.89890}
\pgfmath@def{atan}{576}{29.94194}    \pgfmath@def{atan}{577}{29.98494}
\pgfmath@def{atan}{578}{30.02791}    \pgfmath@def{atan}{579}{30.07084}
\pgfmath@def{atan}{580}{30.11373}    \pgfmath@def{atan}{581}{30.15658}
\pgfmath@def{atan}{582}{30.19940}    \pgfmath@def{atan}{583}{30.24218}
\pgfmath@def{atan}{584}{30.28492}    \pgfmath@def{atan}{585}{30.32763}
\pgfmath@def{atan}{586}{30.37030}    \pgfmath@def{atan}{587}{30.41293}
\pgfmath@def{atan}{588}{30.45552}    \pgfmath@def{atan}{589}{30.49808}
\pgfmath@def{atan}{590}{30.54060}    \pgfmath@def{atan}{591}{30.58308}
\pgfmath@def{atan}{592}{30.62553}    \pgfmath@def{atan}{593}{30.66794}
\pgfmath@def{atan}{594}{30.71031}    \pgfmath@def{atan}{595}{30.75264}
\pgfmath@def{atan}{596}{30.79494}    \pgfmath@def{atan}{597}{30.83720}
\pgfmath@def{atan}{598}{30.87942}    \pgfmath@def{atan}{599}{30.92160}
\pgfmath@def{atan}{600}{30.96375}    \pgfmath@def{atan}{601}{31.00586}
\pgfmath@def{atan}{602}{31.04794}    \pgfmath@def{atan}{603}{31.08997}
\pgfmath@def{atan}{604}{31.13197}    \pgfmath@def{atan}{605}{31.17393}
\pgfmath@def{atan}{606}{31.21586}    \pgfmath@def{atan}{607}{31.25775}
\pgfmath@def{atan}{608}{31.29960}    \pgfmath@def{atan}{609}{31.34141}
\pgfmath@def{atan}{610}{31.38319}    \pgfmath@def{atan}{611}{31.42493}
\pgfmath@def{atan}{612}{31.46663}    \pgfmath@def{atan}{613}{31.50829}
\pgfmath@def{atan}{614}{31.54992}    \pgfmath@def{atan}{615}{31.59151}
\pgfmath@def{atan}{616}{31.63306}    \pgfmath@def{atan}{617}{31.67458}
\pgfmath@def{atan}{618}{31.71606}    \pgfmath@def{atan}{619}{31.75750}
\pgfmath@def{atan}{620}{31.79891}    \pgfmath@def{atan}{621}{31.84028}
\pgfmath@def{atan}{622}{31.88161}    \pgfmath@def{atan}{623}{31.92290}
\pgfmath@def{atan}{624}{31.96416}    \pgfmath@def{atan}{625}{32.00538}
\pgfmath@def{atan}{626}{32.04656}    \pgfmath@def{atan}{627}{32.08771}
\pgfmath@def{atan}{628}{32.12882}    \pgfmath@def{atan}{629}{32.16989}
\pgfmath@def{atan}{630}{32.21092}    \pgfmath@def{atan}{631}{32.25192}
\pgfmath@def{atan}{632}{32.29288}    \pgfmath@def{atan}{633}{32.33381}
\pgfmath@def{atan}{634}{32.37469}    \pgfmath@def{atan}{635}{32.41554}
\pgfmath@def{atan}{636}{32.45636}    \pgfmath@def{atan}{637}{32.49713}
\pgfmath@def{atan}{638}{32.53787}    \pgfmath@def{atan}{639}{32.57857}
\pgfmath@def{atan}{640}{32.61924}    \pgfmath@def{atan}{641}{32.65987}
\pgfmath@def{atan}{642}{32.70046}    \pgfmath@def{atan}{643}{32.74101}
\pgfmath@def{atan}{644}{32.78153}    \pgfmath@def{atan}{645}{32.82201}
\pgfmath@def{atan}{646}{32.86246}    \pgfmath@def{atan}{647}{32.90286}
\pgfmath@def{atan}{648}{32.94323}    \pgfmath@def{atan}{649}{32.98357}
\pgfmath@def{atan}{650}{33.02386}    \pgfmath@def{atan}{651}{33.06412}
\pgfmath@def{atan}{652}{33.10435}    \pgfmath@def{atan}{653}{33.14453}
\pgfmath@def{atan}{654}{33.18468}    \pgfmath@def{atan}{655}{33.22479}
\pgfmath@def{atan}{656}{33.26487}    \pgfmath@def{atan}{657}{33.30491}
\pgfmath@def{atan}{658}{33.34491}    \pgfmath@def{atan}{659}{33.38488}
\pgfmath@def{atan}{660}{33.42481}    \pgfmath@def{atan}{661}{33.46470}
\pgfmath@def{atan}{662}{33.50455}    \pgfmath@def{atan}{663}{33.54437}
\pgfmath@def{atan}{664}{33.58416}    \pgfmath@def{atan}{665}{33.62390}
\pgfmath@def{atan}{666}{33.66361}    \pgfmath@def{atan}{667}{33.70328}
\pgfmath@def{atan}{668}{33.74292}    \pgfmath@def{atan}{669}{33.78252}
\pgfmath@def{atan}{670}{33.82208}    \pgfmath@def{atan}{671}{33.86161}
\pgfmath@def{atan}{672}{33.90110}    \pgfmath@def{atan}{673}{33.94055}
\pgfmath@def{atan}{674}{33.97997}    \pgfmath@def{atan}{675}{34.01935}
\pgfmath@def{atan}{676}{34.05869}    \pgfmath@def{atan}{677}{34.09800}
\pgfmath@def{atan}{678}{34.13727}    \pgfmath@def{atan}{679}{34.17650}
\pgfmath@def{atan}{680}{34.21570}    \pgfmath@def{atan}{681}{34.25486}
\pgfmath@def{atan}{682}{34.29398}    \pgfmath@def{atan}{683}{34.33307}
\pgfmath@def{atan}{684}{34.37212}    \pgfmath@def{atan}{685}{34.41114}
\pgfmath@def{atan}{686}{34.45012}    \pgfmath@def{atan}{687}{34.48906}
\pgfmath@def{atan}{688}{34.52797}    \pgfmath@def{atan}{689}{34.56684}
\pgfmath@def{atan}{690}{34.60567}    \pgfmath@def{atan}{691}{34.64447}
\pgfmath@def{atan}{692}{34.68323}    \pgfmath@def{atan}{693}{34.72195}
\pgfmath@def{atan}{694}{34.76064}    \pgfmath@def{atan}{695}{34.79930}
\pgfmath@def{atan}{696}{34.83791}    \pgfmath@def{atan}{697}{34.87649}
\pgfmath@def{atan}{698}{34.91504}    \pgfmath@def{atan}{699}{34.95354}
\pgfmath@def{atan}{700}{34.99202}    \pgfmath@def{atan}{701}{35.03045}
\pgfmath@def{atan}{702}{35.06885}    \pgfmath@def{atan}{703}{35.10721}
\pgfmath@def{atan}{704}{35.14554}    \pgfmath@def{atan}{705}{35.18383}
\pgfmath@def{atan}{706}{35.22209}    \pgfmath@def{atan}{707}{35.26031}
\pgfmath@def{atan}{708}{35.29849}    \pgfmath@def{atan}{709}{35.33664}
\pgfmath@def{atan}{710}{35.37475}    \pgfmath@def{atan}{711}{35.41282}
\pgfmath@def{atan}{712}{35.45086}    \pgfmath@def{atan}{713}{35.48886}
\pgfmath@def{atan}{714}{35.52683}    \pgfmath@def{atan}{715}{35.56476}
\pgfmath@def{atan}{716}{35.60266}    \pgfmath@def{atan}{717}{35.64052}
\pgfmath@def{atan}{718}{35.67834}    \pgfmath@def{atan}{719}{35.71613}
\pgfmath@def{atan}{720}{35.75388}    \pgfmath@def{atan}{721}{35.79160}
\pgfmath@def{atan}{722}{35.82928}    \pgfmath@def{atan}{723}{35.86692}
\pgfmath@def{atan}{724}{35.90453}    \pgfmath@def{atan}{725}{35.94211}
\pgfmath@def{atan}{726}{35.97965}    \pgfmath@def{atan}{727}{36.01715}
\pgfmath@def{atan}{728}{36.05461}    \pgfmath@def{atan}{729}{36.09204}
\pgfmath@def{atan}{730}{36.12944}    \pgfmath@def{atan}{731}{36.16680}
\pgfmath@def{atan}{732}{36.20412}    \pgfmath@def{atan}{733}{36.24141}
\pgfmath@def{atan}{734}{36.27866}    \pgfmath@def{atan}{735}{36.31588}
\pgfmath@def{atan}{736}{36.35306}    \pgfmath@def{atan}{737}{36.39021}
\pgfmath@def{atan}{738}{36.42732}    \pgfmath@def{atan}{739}{36.46440}
\pgfmath@def{atan}{740}{36.50144}    \pgfmath@def{atan}{741}{36.53844}
\pgfmath@def{atan}{742}{36.57541}    \pgfmath@def{atan}{743}{36.61234}
\pgfmath@def{atan}{744}{36.64924}    \pgfmath@def{atan}{745}{36.68611}
\pgfmath@def{atan}{746}{36.72293}    \pgfmath@def{atan}{747}{36.75973}
\pgfmath@def{atan}{748}{36.79648}    \pgfmath@def{atan}{749}{36.83321}
\pgfmath@def{atan}{750}{36.86989}    \pgfmath@def{atan}{751}{36.90654}
\pgfmath@def{atan}{752}{36.94316}    \pgfmath@def{atan}{753}{36.97974}
\pgfmath@def{atan}{754}{37.01629}    \pgfmath@def{atan}{755}{37.05280}
\pgfmath@def{atan}{756}{37.08928}    \pgfmath@def{atan}{757}{37.12572}
\pgfmath@def{atan}{758}{37.16212}    \pgfmath@def{atan}{759}{37.19849}
\pgfmath@def{atan}{760}{37.23483}    \pgfmath@def{atan}{761}{37.27113}
\pgfmath@def{atan}{762}{37.30740}    \pgfmath@def{atan}{763}{37.34363}
\pgfmath@def{atan}{764}{37.37982}    \pgfmath@def{atan}{765}{37.41598}
\pgfmath@def{atan}{766}{37.45211}    \pgfmath@def{atan}{767}{37.48820}
\pgfmath@def{atan}{768}{37.52426}    \pgfmath@def{atan}{769}{37.56028}
\pgfmath@def{atan}{770}{37.59627}    \pgfmath@def{atan}{771}{37.63222}
\pgfmath@def{atan}{772}{37.66814}    \pgfmath@def{atan}{773}{37.70402}
\pgfmath@def{atan}{774}{37.73987}    \pgfmath@def{atan}{775}{37.77568}
\pgfmath@def{atan}{776}{37.81146}    \pgfmath@def{atan}{777}{37.84720}
\pgfmath@def{atan}{778}{37.88291}    \pgfmath@def{atan}{779}{37.91859}
\pgfmath@def{atan}{780}{37.95423}    \pgfmath@def{atan}{781}{37.98983}
\pgfmath@def{atan}{782}{38.02540}    \pgfmath@def{atan}{783}{38.06094}
\pgfmath@def{atan}{784}{38.09644}    \pgfmath@def{atan}{785}{38.13191}
\pgfmath@def{atan}{786}{38.16734}    \pgfmath@def{atan}{787}{38.20274}
\pgfmath@def{atan}{788}{38.23811}    \pgfmath@def{atan}{789}{38.27344}
\pgfmath@def{atan}{790}{38.30873}    \pgfmath@def{atan}{791}{38.34399}
\pgfmath@def{atan}{792}{38.37922}    \pgfmath@def{atan}{793}{38.41441}
\pgfmath@def{atan}{794}{38.44957}    \pgfmath@def{atan}{795}{38.48469}
\pgfmath@def{atan}{796}{38.51979}    \pgfmath@def{atan}{797}{38.55484}
\pgfmath@def{atan}{798}{38.58986}    \pgfmath@def{atan}{799}{38.62485}
\pgfmath@def{atan}{800}{38.65980}    \pgfmath@def{atan}{801}{38.69472}
\pgfmath@def{atan}{802}{38.72961}    \pgfmath@def{atan}{803}{38.76446}
\pgfmath@def{atan}{804}{38.79928}    \pgfmath@def{atan}{805}{38.83406}
\pgfmath@def{atan}{806}{38.86881}    \pgfmath@def{atan}{807}{38.90353}
\pgfmath@def{atan}{808}{38.93821}    \pgfmath@def{atan}{809}{38.97285}
\pgfmath@def{atan}{810}{39.00747}    \pgfmath@def{atan}{811}{39.04205}
\pgfmath@def{atan}{812}{39.07659}    \pgfmath@def{atan}{813}{39.11111}
\pgfmath@def{atan}{814}{39.14558}    \pgfmath@def{atan}{815}{39.18003}
\pgfmath@def{atan}{816}{39.21444}    \pgfmath@def{atan}{817}{39.24882}
\pgfmath@def{atan}{818}{39.28316}    \pgfmath@def{atan}{819}{39.31747}
\pgfmath@def{atan}{820}{39.35175}    \pgfmath@def{atan}{821}{39.38599}
\pgfmath@def{atan}{822}{39.42020}    \pgfmath@def{atan}{823}{39.45438}
\pgfmath@def{atan}{824}{39.48852}    \pgfmath@def{atan}{825}{39.52263}
\pgfmath@def{atan}{826}{39.55670}    \pgfmath@def{atan}{827}{39.59074}
\pgfmath@def{atan}{828}{39.62475}    \pgfmath@def{atan}{829}{39.65873}
\pgfmath@def{atan}{830}{39.69267}    \pgfmath@def{atan}{831}{39.72658}
\pgfmath@def{atan}{832}{39.76045}    \pgfmath@def{atan}{833}{39.79429}
\pgfmath@def{atan}{834}{39.82810}    \pgfmath@def{atan}{835}{39.86188}
\pgfmath@def{atan}{836}{39.89562}    \pgfmath@def{atan}{837}{39.92933}
\pgfmath@def{atan}{838}{39.96300}    \pgfmath@def{atan}{839}{39.99665}
\pgfmath@def{atan}{840}{40.03025}    \pgfmath@def{atan}{841}{40.06383}
\pgfmath@def{atan}{842}{40.09737}    \pgfmath@def{atan}{843}{40.13088}
\pgfmath@def{atan}{844}{40.16436}    \pgfmath@def{atan}{845}{40.19781}
\pgfmath@def{atan}{846}{40.23122}    \pgfmath@def{atan}{847}{40.26459}
\pgfmath@def{atan}{848}{40.29794}    \pgfmath@def{atan}{849}{40.33125}
\pgfmath@def{atan}{850}{40.36453}    \pgfmath@def{atan}{851}{40.39778}
\pgfmath@def{atan}{852}{40.43099}    \pgfmath@def{atan}{853}{40.46417}
\pgfmath@def{atan}{854}{40.49732}    \pgfmath@def{atan}{855}{40.53044}
\pgfmath@def{atan}{856}{40.56352}    \pgfmath@def{atan}{857}{40.59657}
\pgfmath@def{atan}{858}{40.62959}    \pgfmath@def{atan}{859}{40.66257}
\pgfmath@def{atan}{860}{40.69553}    \pgfmath@def{atan}{861}{40.72845}
\pgfmath@def{atan}{862}{40.76133}    \pgfmath@def{atan}{863}{40.79419}
\pgfmath@def{atan}{864}{40.82701}    \pgfmath@def{atan}{865}{40.85980}
\pgfmath@def{atan}{866}{40.89256}    \pgfmath@def{atan}{867}{40.92528}
\pgfmath@def{atan}{868}{40.95798}    \pgfmath@def{atan}{869}{40.99064}
\pgfmath@def{atan}{870}{41.02326}    \pgfmath@def{atan}{871}{41.05586}
\pgfmath@def{atan}{872}{41.08842}    \pgfmath@def{atan}{873}{41.12095}
\pgfmath@def{atan}{874}{41.15345}    \pgfmath@def{atan}{875}{41.18592}
\pgfmath@def{atan}{876}{41.21836}    \pgfmath@def{atan}{877}{41.25076}
\pgfmath@def{atan}{878}{41.28313}    \pgfmath@def{atan}{879}{41.31547}
\pgfmath@def{atan}{880}{41.34777}    \pgfmath@def{atan}{881}{41.38005}
\pgfmath@def{atan}{882}{41.41229}    \pgfmath@def{atan}{883}{41.44450}
\pgfmath@def{atan}{884}{41.47668}    \pgfmath@def{atan}{885}{41.50882}
\pgfmath@def{atan}{886}{41.54094}    \pgfmath@def{atan}{887}{41.57302}
\pgfmath@def{atan}{888}{41.60507}    \pgfmath@def{atan}{889}{41.63709}
\pgfmath@def{atan}{890}{41.66908}    \pgfmath@def{atan}{891}{41.70103}
\pgfmath@def{atan}{892}{41.73296}    \pgfmath@def{atan}{893}{41.76485}
\pgfmath@def{atan}{894}{41.79671}    \pgfmath@def{atan}{895}{41.82854}
\pgfmath@def{atan}{896}{41.86034}    \pgfmath@def{atan}{897}{41.89210}
\pgfmath@def{atan}{898}{41.92383}    \pgfmath@def{atan}{899}{41.95554}
\pgfmath@def{atan}{900}{41.98721}    \pgfmath@def{atan}{901}{42.01885}
\pgfmath@def{atan}{902}{42.05046}    \pgfmath@def{atan}{903}{42.08203}
\pgfmath@def{atan}{904}{42.11358}    \pgfmath@def{atan}{905}{42.14509}
\pgfmath@def{atan}{906}{42.17657}    \pgfmath@def{atan}{907}{42.20802}
\pgfmath@def{atan}{908}{42.23944}    \pgfmath@def{atan}{909}{42.27083}
\pgfmath@def{atan}{910}{42.30219}    \pgfmath@def{atan}{911}{42.33352}
\pgfmath@def{atan}{912}{42.36481}    \pgfmath@def{atan}{913}{42.39607}
\pgfmath@def{atan}{914}{42.42731}    \pgfmath@def{atan}{915}{42.45851}
\pgfmath@def{atan}{916}{42.48968}    \pgfmath@def{atan}{917}{42.52082}
\pgfmath@def{atan}{918}{42.55193}    \pgfmath@def{atan}{919}{42.58300}
\pgfmath@def{atan}{920}{42.61405}    \pgfmath@def{atan}{921}{42.64507}
\pgfmath@def{atan}{922}{42.67605}    \pgfmath@def{atan}{923}{42.70701}
\pgfmath@def{atan}{924}{42.73793}    \pgfmath@def{atan}{925}{42.76882}
\pgfmath@def{atan}{926}{42.79968}    \pgfmath@def{atan}{927}{42.83051}
\pgfmath@def{atan}{928}{42.86131}    \pgfmath@def{atan}{929}{42.89208}
\pgfmath@def{atan}{930}{42.92282}    \pgfmath@def{atan}{931}{42.95353}
\pgfmath@def{atan}{932}{42.98421}    \pgfmath@def{atan}{933}{43.01485}
\pgfmath@def{atan}{934}{43.04547}    \pgfmath@def{atan}{935}{43.07605}
\pgfmath@def{atan}{936}{43.10661}    \pgfmath@def{atan}{937}{43.13713}
\pgfmath@def{atan}{938}{43.16763}    \pgfmath@def{atan}{939}{43.19809}
\pgfmath@def{atan}{940}{43.22853}    \pgfmath@def{atan}{941}{43.25893}
\pgfmath@def{atan}{942}{43.28930}    \pgfmath@def{atan}{943}{43.31964}
\pgfmath@def{atan}{944}{43.34996}    \pgfmath@def{atan}{945}{43.38024}
\pgfmath@def{atan}{946}{43.41049}    \pgfmath@def{atan}{947}{43.44071}
\pgfmath@def{atan}{948}{43.47090}    \pgfmath@def{atan}{949}{43.50106}
\pgfmath@def{atan}{950}{43.53119}    \pgfmath@def{atan}{951}{43.56130}
\pgfmath@def{atan}{952}{43.59137}    \pgfmath@def{atan}{953}{43.62141}
\pgfmath@def{atan}{954}{43.65142}    \pgfmath@def{atan}{955}{43.68140}
\pgfmath@def{atan}{956}{43.71135}    \pgfmath@def{atan}{957}{43.74127}
\pgfmath@def{atan}{958}{43.77116}    \pgfmath@def{atan}{959}{43.80102}
\pgfmath@def{atan}{960}{43.83086}    \pgfmath@def{atan}{961}{43.86066}
\pgfmath@def{atan}{962}{43.89043}    \pgfmath@def{atan}{963}{43.92017}
\pgfmath@def{atan}{964}{43.94988}    \pgfmath@def{atan}{965}{43.97957}
\pgfmath@def{atan}{966}{44.00922}    \pgfmath@def{atan}{967}{44.03884}
\pgfmath@def{atan}{968}{44.06844}    \pgfmath@def{atan}{969}{44.09800}
\pgfmath@def{atan}{970}{44.12754}    \pgfmath@def{atan}{971}{44.15704}
\pgfmath@def{atan}{972}{44.18652}    \pgfmath@def{atan}{973}{44.21597}
\pgfmath@def{atan}{974}{44.24538}    \pgfmath@def{atan}{975}{44.27477}
\pgfmath@def{atan}{976}{44.30413}    \pgfmath@def{atan}{977}{44.33346}
\pgfmath@def{atan}{978}{44.36276}    \pgfmath@def{atan}{979}{44.39203}
\pgfmath@def{atan}{980}{44.42127}    \pgfmath@def{atan}{981}{44.45048}
\pgfmath@def{atan}{982}{44.47966}    \pgfmath@def{atan}{983}{44.50882}
\pgfmath@def{atan}{984}{44.53794}    \pgfmath@def{atan}{985}{44.56704}
\pgfmath@def{atan}{986}{44.59610}    \pgfmath@def{atan}{987}{44.62514}
\pgfmath@def{atan}{988}{44.65415}    \pgfmath@def{atan}{989}{44.68313}
\pgfmath@def{atan}{990}{44.71208}    \pgfmath@def{atan}{991}{44.74100}
\pgfmath@def{atan}{992}{44.76989}    \pgfmath@def{atan}{993}{44.79876}
\pgfmath@def{atan}{994}{44.82759}    \pgfmath@def{atan}{995}{44.85640}
\pgfmath@def{atan}{996}{44.88517}    \pgfmath@def{atan}{997}{44.91392}
\pgfmath@def{atan}{998}{44.94264}    \pgfmath@def{atan}{999}{44.97133}
\pgfmath@def{atan}{1000}{45.00000}    
  
\pgfmath@def{acos}{0}{90.00000}    \pgfmath@def{acos}{1}{89.94270}
\pgfmath@def{acos}{2}{89.88540}    \pgfmath@def{acos}{3}{89.82811}
\pgfmath@def{acos}{4}{89.77081}    \pgfmath@def{acos}{5}{89.71352}
\pgfmath@def{acos}{6}{89.65622}    \pgfmath@def{acos}{7}{89.59892}
\pgfmath@def{acos}{8}{89.54162}    \pgfmath@def{acos}{9}{89.48433}
\pgfmath@def{acos}{10}{89.42703}    \pgfmath@def{acos}{11}{89.36973}
\pgfmath@def{acos}{12}{89.31243}    \pgfmath@def{acos}{13}{89.25513}
\pgfmath@def{acos}{14}{89.19783}    \pgfmath@def{acos}{15}{89.14053}
\pgfmath@def{acos}{16}{89.08322}    \pgfmath@def{acos}{17}{89.02592}
\pgfmath@def{acos}{18}{88.96862}    \pgfmath@def{acos}{19}{88.91131}
\pgfmath@def{acos}{20}{88.85400}    \pgfmath@def{acos}{21}{88.79670}
\pgfmath@def{acos}{22}{88.73939}    \pgfmath@def{acos}{23}{88.68208}
\pgfmath@def{acos}{24}{88.62476}    \pgfmath@def{acos}{25}{88.56745}
\pgfmath@def{acos}{26}{88.51014}    \pgfmath@def{acos}{27}{88.45282}
\pgfmath@def{acos}{28}{88.39550}    \pgfmath@def{acos}{29}{88.33818}
\pgfmath@def{acos}{30}{88.28086}    \pgfmath@def{acos}{31}{88.22354}
\pgfmath@def{acos}{32}{88.16622}    \pgfmath@def{acos}{33}{88.10889}
\pgfmath@def{acos}{34}{88.05156}    \pgfmath@def{acos}{35}{87.99423}
\pgfmath@def{acos}{36}{87.93690}    \pgfmath@def{acos}{37}{87.87957}
\pgfmath@def{acos}{38}{87.82223}    \pgfmath@def{acos}{39}{87.76489}
\pgfmath@def{acos}{40}{87.70755}    \pgfmath@def{acos}{41}{87.65021}
\pgfmath@def{acos}{42}{87.59286}    \pgfmath@def{acos}{43}{87.53552}
\pgfmath@def{acos}{44}{87.47817}    \pgfmath@def{acos}{45}{87.42081}
\pgfmath@def{acos}{46}{87.36346}    \pgfmath@def{acos}{47}{87.30610}
\pgfmath@def{acos}{48}{87.24874}    \pgfmath@def{acos}{49}{87.19138}
\pgfmath@def{acos}{50}{87.13401}    \pgfmath@def{acos}{51}{87.07664}
\pgfmath@def{acos}{52}{87.01927}    \pgfmath@def{acos}{53}{86.96190}
\pgfmath@def{acos}{54}{86.90452}    \pgfmath@def{acos}{55}{86.84714}
\pgfmath@def{acos}{56}{86.78975}    \pgfmath@def{acos}{57}{86.73237}
\pgfmath@def{acos}{58}{86.67497}    \pgfmath@def{acos}{59}{86.61758}
\pgfmath@def{acos}{60}{86.56018}    \pgfmath@def{acos}{61}{86.50278}
\pgfmath@def{acos}{62}{86.44538}    \pgfmath@def{acos}{63}{86.38797}
\pgfmath@def{acos}{64}{86.33056}    \pgfmath@def{acos}{65}{86.27314}
\pgfmath@def{acos}{66}{86.21572}    \pgfmath@def{acos}{67}{86.15830}
\pgfmath@def{acos}{68}{86.10087}    \pgfmath@def{acos}{69}{86.04344}
\pgfmath@def{acos}{70}{85.98601}    \pgfmath@def{acos}{71}{85.92857}
\pgfmath@def{acos}{72}{85.87113}    \pgfmath@def{acos}{73}{85.81368}
\pgfmath@def{acos}{74}{85.75623}    \pgfmath@def{acos}{75}{85.69877}
\pgfmath@def{acos}{76}{85.64131}    \pgfmath@def{acos}{77}{85.58385}
\pgfmath@def{acos}{78}{85.52638}    \pgfmath@def{acos}{79}{85.46891}
\pgfmath@def{acos}{80}{85.41143}    \pgfmath@def{acos}{81}{85.35395}
\pgfmath@def{acos}{82}{85.29646}    \pgfmath@def{acos}{83}{85.23897}
\pgfmath@def{acos}{84}{85.18147}    \pgfmath@def{acos}{85}{85.12397}
\pgfmath@def{acos}{86}{85.06646}    \pgfmath@def{acos}{87}{85.00895}
\pgfmath@def{acos}{88}{84.95144}    \pgfmath@def{acos}{89}{84.89392}
\pgfmath@def{acos}{90}{84.83639}    \pgfmath@def{acos}{91}{84.77886}
\pgfmath@def{acos}{92}{84.72132}    \pgfmath@def{acos}{93}{84.66378}
\pgfmath@def{acos}{94}{84.60623}    \pgfmath@def{acos}{95}{84.54868}
\pgfmath@def{acos}{96}{84.49112}    \pgfmath@def{acos}{97}{84.43355}
\pgfmath@def{acos}{98}{84.37598}    \pgfmath@def{acos}{99}{84.31841}
\pgfmath@def{acos}{100}{84.26083}    \pgfmath@def{acos}{101}{84.20324}
\pgfmath@def{acos}{102}{84.14564}    \pgfmath@def{acos}{103}{84.08805}
\pgfmath@def{acos}{104}{84.03044}    \pgfmath@def{acos}{105}{83.97283}
\pgfmath@def{acos}{106}{83.91521}    \pgfmath@def{acos}{107}{83.85759}
\pgfmath@def{acos}{108}{83.79996}    \pgfmath@def{acos}{109}{83.74232}
\pgfmath@def{acos}{110}{83.68468}    \pgfmath@def{acos}{111}{83.62703}
\pgfmath@def{acos}{112}{83.56938}    \pgfmath@def{acos}{113}{83.51171}
\pgfmath@def{acos}{114}{83.45405}    \pgfmath@def{acos}{115}{83.39637}
\pgfmath@def{acos}{116}{83.33869}    \pgfmath@def{acos}{117}{83.28100}
\pgfmath@def{acos}{118}{83.22330}    \pgfmath@def{acos}{119}{83.16560}
\pgfmath@def{acos}{120}{83.10789}    \pgfmath@def{acos}{121}{83.05018}
\pgfmath@def{acos}{122}{82.99245}    \pgfmath@def{acos}{123}{82.93472}
\pgfmath@def{acos}{124}{82.87698}    \pgfmath@def{acos}{125}{82.81924}
\pgfmath@def{acos}{126}{82.76149}    \pgfmath@def{acos}{127}{82.70373}
\pgfmath@def{acos}{128}{82.64596}    \pgfmath@def{acos}{129}{82.58819}
\pgfmath@def{acos}{130}{82.53040}    \pgfmath@def{acos}{131}{82.47261}
\pgfmath@def{acos}{132}{82.41482}    \pgfmath@def{acos}{133}{82.35701}
\pgfmath@def{acos}{134}{82.29920}    \pgfmath@def{acos}{135}{82.24138}
\pgfmath@def{acos}{136}{82.18355}    \pgfmath@def{acos}{137}{82.12571}
\pgfmath@def{acos}{138}{82.06786}    \pgfmath@def{acos}{139}{82.01001}
\pgfmath@def{acos}{140}{81.95215}    \pgfmath@def{acos}{141}{81.89428}
\pgfmath@def{acos}{142}{81.83640}    \pgfmath@def{acos}{143}{81.77851}
\pgfmath@def{acos}{144}{81.72062}    \pgfmath@def{acos}{145}{81.66272}
\pgfmath@def{acos}{146}{81.60480}    \pgfmath@def{acos}{147}{81.54688}
\pgfmath@def{acos}{148}{81.48895}    \pgfmath@def{acos}{149}{81.43102}
\pgfmath@def{acos}{150}{81.37307}    \pgfmath@def{acos}{151}{81.31511}
\pgfmath@def{acos}{152}{81.25715}    \pgfmath@def{acos}{153}{81.19917}
\pgfmath@def{acos}{154}{81.14119}    \pgfmath@def{acos}{155}{81.08320}
\pgfmath@def{acos}{156}{81.02520}    \pgfmath@def{acos}{157}{80.96719}
\pgfmath@def{acos}{158}{80.90917}    \pgfmath@def{acos}{159}{80.85114}
\pgfmath@def{acos}{160}{80.79310}    \pgfmath@def{acos}{161}{80.73505}
\pgfmath@def{acos}{162}{80.67699}    \pgfmath@def{acos}{163}{80.61893}
\pgfmath@def{acos}{164}{80.56085}    \pgfmath@def{acos}{165}{80.50276}
\pgfmath@def{acos}{166}{80.44466}    \pgfmath@def{acos}{167}{80.38656}
\pgfmath@def{acos}{168}{80.32844}    \pgfmath@def{acos}{169}{80.27031}
\pgfmath@def{acos}{170}{80.21218}    \pgfmath@def{acos}{171}{80.15403}
\pgfmath@def{acos}{172}{80.09587}    \pgfmath@def{acos}{173}{80.03770}
\pgfmath@def{acos}{174}{79.97953}    \pgfmath@def{acos}{175}{79.92134}
\pgfmath@def{acos}{176}{79.86314}    \pgfmath@def{acos}{177}{79.80493}
\pgfmath@def{acos}{178}{79.74671}    \pgfmath@def{acos}{179}{79.68848}
\pgfmath@def{acos}{180}{79.63024}    \pgfmath@def{acos}{181}{79.57198}
\pgfmath@def{acos}{182}{79.51372}    \pgfmath@def{acos}{183}{79.45545}
\pgfmath@def{acos}{184}{79.39716}    \pgfmath@def{acos}{185}{79.33886}
\pgfmath@def{acos}{186}{79.28056}    \pgfmath@def{acos}{187}{79.22224}
\pgfmath@def{acos}{188}{79.16391}    \pgfmath@def{acos}{189}{79.10556}
\pgfmath@def{acos}{190}{79.04721}    \pgfmath@def{acos}{191}{78.98885}
\pgfmath@def{acos}{192}{78.93047}    \pgfmath@def{acos}{193}{78.87208}
\pgfmath@def{acos}{194}{78.81368}    \pgfmath@def{acos}{195}{78.75527}
\pgfmath@def{acos}{196}{78.69685}    \pgfmath@def{acos}{197}{78.63841}
\pgfmath@def{acos}{198}{78.57997}    \pgfmath@def{acos}{199}{78.52151}
\pgfmath@def{acos}{200}{78.46304}    \pgfmath@def{acos}{201}{78.40455}
\pgfmath@def{acos}{202}{78.34606}    \pgfmath@def{acos}{203}{78.28755}
\pgfmath@def{acos}{204}{78.22903}    \pgfmath@def{acos}{205}{78.17050}
\pgfmath@def{acos}{206}{78.11195}    \pgfmath@def{acos}{207}{78.05339}
\pgfmath@def{acos}{208}{77.99482}    \pgfmath@def{acos}{209}{77.93624}
\pgfmath@def{acos}{210}{77.87764}    \pgfmath@def{acos}{211}{77.81903}
\pgfmath@def{acos}{212}{77.76041}    \pgfmath@def{acos}{213}{77.70178}
\pgfmath@def{acos}{214}{77.64313}    \pgfmath@def{acos}{215}{77.58447}
\pgfmath@def{acos}{216}{77.52579}    \pgfmath@def{acos}{217}{77.46711}
\pgfmath@def{acos}{218}{77.40841}    \pgfmath@def{acos}{219}{77.34969}
\pgfmath@def{acos}{220}{77.29096}    \pgfmath@def{acos}{221}{77.23222}
\pgfmath@def{acos}{222}{77.17347}    \pgfmath@def{acos}{223}{77.11470}
\pgfmath@def{acos}{224}{77.05591}    \pgfmath@def{acos}{225}{76.99712}
\pgfmath@def{acos}{226}{76.93831}    \pgfmath@def{acos}{227}{76.87948}
\pgfmath@def{acos}{228}{76.82064}    \pgfmath@def{acos}{229}{76.76179}
\pgfmath@def{acos}{230}{76.70292}    \pgfmath@def{acos}{231}{76.64404}
\pgfmath@def{acos}{232}{76.58515}    \pgfmath@def{acos}{233}{76.52624}
\pgfmath@def{acos}{234}{76.46731}    \pgfmath@def{acos}{235}{76.40837}
\pgfmath@def{acos}{236}{76.34942}    \pgfmath@def{acos}{237}{76.29045}
\pgfmath@def{acos}{238}{76.23147}    \pgfmath@def{acos}{239}{76.17247}
\pgfmath@def{acos}{240}{76.11346}    \pgfmath@def{acos}{241}{76.05443}
\pgfmath@def{acos}{242}{75.99538}    \pgfmath@def{acos}{243}{75.93632}
\pgfmath@def{acos}{244}{75.87725}    \pgfmath@def{acos}{245}{75.81816}
\pgfmath@def{acos}{246}{75.75906}    \pgfmath@def{acos}{247}{75.69994}
\pgfmath@def{acos}{248}{75.64080}    \pgfmath@def{acos}{249}{75.58165}
\pgfmath@def{acos}{250}{75.52248}    \pgfmath@def{acos}{251}{75.46330}
\pgfmath@def{acos}{252}{75.40410}    \pgfmath@def{acos}{253}{75.34489}
\pgfmath@def{acos}{254}{75.28566}    \pgfmath@def{acos}{255}{75.22641}
\pgfmath@def{acos}{256}{75.16715}    \pgfmath@def{acos}{257}{75.10787}
\pgfmath@def{acos}{258}{75.04857}    \pgfmath@def{acos}{259}{74.98926}
\pgfmath@def{acos}{260}{74.92993}    \pgfmath@def{acos}{261}{74.87059}
\pgfmath@def{acos}{262}{74.81123}    \pgfmath@def{acos}{263}{74.75185}
\pgfmath@def{acos}{264}{74.69245}    \pgfmath@def{acos}{265}{74.63304}
\pgfmath@def{acos}{266}{74.57361}    \pgfmath@def{acos}{267}{74.51417}
\pgfmath@def{acos}{268}{74.45471}    \pgfmath@def{acos}{269}{74.39523}
\pgfmath@def{acos}{270}{74.33573}    \pgfmath@def{acos}{271}{74.27621}
\pgfmath@def{acos}{272}{74.21668}    \pgfmath@def{acos}{273}{74.15713}
\pgfmath@def{acos}{274}{74.09757}    \pgfmath@def{acos}{275}{74.03798}
\pgfmath@def{acos}{276}{73.97838}    \pgfmath@def{acos}{277}{73.91876}
\pgfmath@def{acos}{278}{73.85912}    \pgfmath@def{acos}{279}{73.79946}
\pgfmath@def{acos}{280}{73.73979}    \pgfmath@def{acos}{281}{73.68010}
\pgfmath@def{acos}{282}{73.62039}    \pgfmath@def{acos}{283}{73.56066}
\pgfmath@def{acos}{284}{73.50091}    \pgfmath@def{acos}{285}{73.44115}
\pgfmath@def{acos}{286}{73.38136}    \pgfmath@def{acos}{287}{73.32156}
\pgfmath@def{acos}{288}{73.26174}    \pgfmath@def{acos}{289}{73.20190}
\pgfmath@def{acos}{290}{73.14204}    \pgfmath@def{acos}{291}{73.08216}
\pgfmath@def{acos}{292}{73.02226}    \pgfmath@def{acos}{293}{72.96235}
\pgfmath@def{acos}{294}{72.90241}    \pgfmath@def{acos}{295}{72.84246}
\pgfmath@def{acos}{296}{72.78248}    \pgfmath@def{acos}{297}{72.72249}
\pgfmath@def{acos}{298}{72.66248}    \pgfmath@def{acos}{299}{72.60244}
\pgfmath@def{acos}{300}{72.54239}    \pgfmath@def{acos}{301}{72.48232}
\pgfmath@def{acos}{302}{72.42223}    \pgfmath@def{acos}{303}{72.36212}
\pgfmath@def{acos}{304}{72.30198}    \pgfmath@def{acos}{305}{72.24183}
\pgfmath@def{acos}{306}{72.18166}    \pgfmath@def{acos}{307}{72.12147}
\pgfmath@def{acos}{308}{72.06125}    \pgfmath@def{acos}{309}{72.00102}
\pgfmath@def{acos}{310}{71.94077}    \pgfmath@def{acos}{311}{71.88049}
\pgfmath@def{acos}{312}{71.82019}    \pgfmath@def{acos}{313}{71.75988}
\pgfmath@def{acos}{314}{71.69954}    \pgfmath@def{acos}{315}{71.63918}
\pgfmath@def{acos}{316}{71.57880}    \pgfmath@def{acos}{317}{71.51840}
\pgfmath@def{acos}{318}{71.45798}    \pgfmath@def{acos}{319}{71.39754}
\pgfmath@def{acos}{320}{71.33707}    \pgfmath@def{acos}{321}{71.27658}
\pgfmath@def{acos}{322}{71.21608}    \pgfmath@def{acos}{323}{71.15555}
\pgfmath@def{acos}{324}{71.09499}    \pgfmath@def{acos}{325}{71.03442}
\pgfmath@def{acos}{326}{70.97382}    \pgfmath@def{acos}{327}{70.91321}
\pgfmath@def{acos}{328}{70.85257}    \pgfmath@def{acos}{329}{70.79190}
\pgfmath@def{acos}{330}{70.73122}    \pgfmath@def{acos}{331}{70.67051}
\pgfmath@def{acos}{332}{70.60978}    \pgfmath@def{acos}{333}{70.54903}
\pgfmath@def{acos}{334}{70.48826}    \pgfmath@def{acos}{335}{70.42746}
\pgfmath@def{acos}{336}{70.36664}    \pgfmath@def{acos}{337}{70.30579}
\pgfmath@def{acos}{338}{70.24493}    \pgfmath@def{acos}{339}{70.18404}
\pgfmath@def{acos}{340}{70.12312}    \pgfmath@def{acos}{341}{70.06218}
\pgfmath@def{acos}{342}{70.00122}    \pgfmath@def{acos}{343}{69.94024}
\pgfmath@def{acos}{344}{69.87923}    \pgfmath@def{acos}{345}{69.81820}
\pgfmath@def{acos}{346}{69.75714}    \pgfmath@def{acos}{347}{69.69606}
\pgfmath@def{acos}{348}{69.63496}    \pgfmath@def{acos}{349}{69.57383}
\pgfmath@def{acos}{350}{69.51268}    \pgfmath@def{acos}{351}{69.45150}
\pgfmath@def{acos}{352}{69.39030}    \pgfmath@def{acos}{353}{69.32908}
\pgfmath@def{acos}{354}{69.26783}    \pgfmath@def{acos}{355}{69.20655}
\pgfmath@def{acos}{356}{69.14525}    \pgfmath@def{acos}{357}{69.08393}
\pgfmath@def{acos}{358}{69.02258}    \pgfmath@def{acos}{359}{68.96120}
\pgfmath@def{acos}{360}{68.89980}    \pgfmath@def{acos}{361}{68.83837}
\pgfmath@def{acos}{362}{68.77692}    \pgfmath@def{acos}{363}{68.71544}
\pgfmath@def{acos}{364}{68.65394}    \pgfmath@def{acos}{365}{68.59241}
\pgfmath@def{acos}{366}{68.53086}    \pgfmath@def{acos}{367}{68.46928}
\pgfmath@def{acos}{368}{68.40767}    \pgfmath@def{acos}{369}{68.34604}
\pgfmath@def{acos}{370}{68.28438}    \pgfmath@def{acos}{371}{68.22269}
\pgfmath@def{acos}{372}{68.16098}    \pgfmath@def{acos}{373}{68.09924}
\pgfmath@def{acos}{374}{68.03748}    \pgfmath@def{acos}{375}{67.97568}
\pgfmath@def{acos}{376}{67.91386}    \pgfmath@def{acos}{377}{67.85202}
\pgfmath@def{acos}{378}{67.79014}    \pgfmath@def{acos}{379}{67.72824}
\pgfmath@def{acos}{380}{67.66631}    \pgfmath@def{acos}{381}{67.60436}
\pgfmath@def{acos}{382}{67.54237}    \pgfmath@def{acos}{383}{67.48036}
\pgfmath@def{acos}{384}{67.41832}    \pgfmath@def{acos}{385}{67.35626}
\pgfmath@def{acos}{386}{67.29416}    \pgfmath@def{acos}{387}{67.23204}
\pgfmath@def{acos}{388}{67.16988}    \pgfmath@def{acos}{389}{67.10770}
\pgfmath@def{acos}{390}{67.04550}    \pgfmath@def{acos}{391}{66.98326}
\pgfmath@def{acos}{392}{66.92099}    \pgfmath@def{acos}{393}{66.85870}
\pgfmath@def{acos}{394}{66.79637}    \pgfmath@def{acos}{395}{66.73402}
\pgfmath@def{acos}{396}{66.67164}    \pgfmath@def{acos}{397}{66.60923}
\pgfmath@def{acos}{398}{66.54679}    \pgfmath@def{acos}{399}{66.48432}
\pgfmath@def{acos}{400}{66.42182}    \pgfmath@def{acos}{401}{66.35929}
\pgfmath@def{acos}{402}{66.29673}    \pgfmath@def{acos}{403}{66.23414}
\pgfmath@def{acos}{404}{66.17152}    \pgfmath@def{acos}{405}{66.10887}
\pgfmath@def{acos}{406}{66.04619}    \pgfmath@def{acos}{407}{65.98348}
\pgfmath@def{acos}{408}{65.92074}    \pgfmath@def{acos}{409}{65.85796}
\pgfmath@def{acos}{410}{65.79516}    \pgfmath@def{acos}{411}{65.73233}
\pgfmath@def{acos}{412}{65.66946}    \pgfmath@def{acos}{413}{65.60657}
\pgfmath@def{acos}{414}{65.54364}    \pgfmath@def{acos}{415}{65.48068}
\pgfmath@def{acos}{416}{65.41769}    \pgfmath@def{acos}{417}{65.35467}
\pgfmath@def{acos}{418}{65.29161}    \pgfmath@def{acos}{419}{65.22853}
\pgfmath@def{acos}{420}{65.16541}    \pgfmath@def{acos}{421}{65.10226}
\pgfmath@def{acos}{422}{65.03908}    \pgfmath@def{acos}{423}{64.97586}
\pgfmath@def{acos}{424}{64.91261}    \pgfmath@def{acos}{425}{64.84933}
\pgfmath@def{acos}{426}{64.78602}    \pgfmath@def{acos}{427}{64.72267}
\pgfmath@def{acos}{428}{64.65929}    \pgfmath@def{acos}{429}{64.59588}
\pgfmath@def{acos}{430}{64.53244}    \pgfmath@def{acos}{431}{64.46896}
\pgfmath@def{acos}{432}{64.40544}    \pgfmath@def{acos}{433}{64.34190}
\pgfmath@def{acos}{434}{64.27832}    \pgfmath@def{acos}{435}{64.21470}
\pgfmath@def{acos}{436}{64.15105}    \pgfmath@def{acos}{437}{64.08737}
\pgfmath@def{acos}{438}{64.02365}    \pgfmath@def{acos}{439}{63.95990}
\pgfmath@def{acos}{440}{63.89611}    \pgfmath@def{acos}{441}{63.83229}
\pgfmath@def{acos}{442}{63.76844}    \pgfmath@def{acos}{443}{63.70455}
\pgfmath@def{acos}{444}{63.64062}    \pgfmath@def{acos}{445}{63.57666}
\pgfmath@def{acos}{446}{63.51266}    \pgfmath@def{acos}{447}{63.44863}
\pgfmath@def{acos}{448}{63.38456}    \pgfmath@def{acos}{449}{63.32045}
\pgfmath@def{acos}{450}{63.25631}    \pgfmath@def{acos}{451}{63.19213}
\pgfmath@def{acos}{452}{63.12792}    \pgfmath@def{acos}{453}{63.06367}
\pgfmath@def{acos}{454}{62.99938}    \pgfmath@def{acos}{455}{62.93506}
\pgfmath@def{acos}{456}{62.87070}    \pgfmath@def{acos}{457}{62.80630}
\pgfmath@def{acos}{458}{62.74187}    \pgfmath@def{acos}{459}{62.67740}
\pgfmath@def{acos}{460}{62.61289}    \pgfmath@def{acos}{461}{62.54834}
\pgfmath@def{acos}{462}{62.48376}    \pgfmath@def{acos}{463}{62.41913}
\pgfmath@def{acos}{464}{62.35447}    \pgfmath@def{acos}{465}{62.28977}
\pgfmath@def{acos}{466}{62.22504}    \pgfmath@def{acos}{467}{62.16026}
\pgfmath@def{acos}{468}{62.09545}    \pgfmath@def{acos}{469}{62.03059}
\pgfmath@def{acos}{470}{61.96570}    \pgfmath@def{acos}{471}{61.90077}
\pgfmath@def{acos}{472}{61.83580}    \pgfmath@def{acos}{473}{61.77079}
\pgfmath@def{acos}{474}{61.70574}    \pgfmath@def{acos}{475}{61.64065}
\pgfmath@def{acos}{476}{61.57552}    \pgfmath@def{acos}{477}{61.51035}
\pgfmath@def{acos}{478}{61.44514}    \pgfmath@def{acos}{479}{61.37988}
\pgfmath@def{acos}{480}{61.31459}    \pgfmath@def{acos}{481}{61.24926}
\pgfmath@def{acos}{482}{61.18389}    \pgfmath@def{acos}{483}{61.11847}
\pgfmath@def{acos}{484}{61.05302}    \pgfmath@def{acos}{485}{60.98752}
\pgfmath@def{acos}{486}{60.92199}    \pgfmath@def{acos}{487}{60.85641}
\pgfmath@def{acos}{488}{60.79078}    \pgfmath@def{acos}{489}{60.72512}
\pgfmath@def{acos}{490}{60.65941}    \pgfmath@def{acos}{491}{60.59367}
\pgfmath@def{acos}{492}{60.52787}    \pgfmath@def{acos}{493}{60.46204}
\pgfmath@def{acos}{494}{60.39616}    \pgfmath@def{acos}{495}{60.33025}
\pgfmath@def{acos}{496}{60.26428}    \pgfmath@def{acos}{497}{60.19828}
\pgfmath@def{acos}{498}{60.13223}    \pgfmath@def{acos}{499}{60.06613}
\pgfmath@def{acos}{500}{60.00000}    \pgfmath@def{acos}{501}{59.93381}
\pgfmath@def{acos}{502}{59.86759}    \pgfmath@def{acos}{503}{59.80132}
\pgfmath@def{acos}{504}{59.73500}    \pgfmath@def{acos}{505}{59.66864}
\pgfmath@def{acos}{506}{59.60224}    \pgfmath@def{acos}{507}{59.53579}
\pgfmath@def{acos}{508}{59.46929}    \pgfmath@def{acos}{509}{59.40275}
\pgfmath@def{acos}{510}{59.33617}    \pgfmath@def{acos}{511}{59.26953}
\pgfmath@def{acos}{512}{59.20285}    \pgfmath@def{acos}{513}{59.13613}
\pgfmath@def{acos}{514}{59.06936}    \pgfmath@def{acos}{515}{59.00254}
\pgfmath@def{acos}{516}{58.93568}    \pgfmath@def{acos}{517}{58.86876}
\pgfmath@def{acos}{518}{58.80180}    \pgfmath@def{acos}{519}{58.73480}
\pgfmath@def{acos}{520}{58.66774}    \pgfmath@def{acos}{521}{58.60064}
\pgfmath@def{acos}{522}{58.53349}    \pgfmath@def{acos}{523}{58.46629}
\pgfmath@def{acos}{524}{58.39905}    \pgfmath@def{acos}{525}{58.33175}
\pgfmath@def{acos}{526}{58.26441}    \pgfmath@def{acos}{527}{58.19702}
\pgfmath@def{acos}{528}{58.12957}    \pgfmath@def{acos}{529}{58.06208}
\pgfmath@def{acos}{530}{57.99454}    \pgfmath@def{acos}{531}{57.92695}
\pgfmath@def{acos}{532}{57.85931}    \pgfmath@def{acos}{533}{57.79162}
\pgfmath@def{acos}{534}{57.72388}    \pgfmath@def{acos}{535}{57.65608}
\pgfmath@def{acos}{536}{57.58824}    \pgfmath@def{acos}{537}{57.52035}
\pgfmath@def{acos}{538}{57.45240}    \pgfmath@def{acos}{539}{57.38441}
\pgfmath@def{acos}{540}{57.31636}    \pgfmath@def{acos}{541}{57.24826}
\pgfmath@def{acos}{542}{57.18010}    \pgfmath@def{acos}{543}{57.11190}
\pgfmath@def{acos}{544}{57.04364}    \pgfmath@def{acos}{545}{56.97533}
\pgfmath@def{acos}{546}{56.90697}    \pgfmath@def{acos}{547}{56.83855}
\pgfmath@def{acos}{548}{56.77008}    \pgfmath@def{acos}{549}{56.70156}
\pgfmath@def{acos}{550}{56.63298}    \pgfmath@def{acos}{551}{56.56435}
\pgfmath@def{acos}{552}{56.49567}    \pgfmath@def{acos}{553}{56.42693}
\pgfmath@def{acos}{554}{56.35813}    \pgfmath@def{acos}{555}{56.28928}
\pgfmath@def{acos}{556}{56.22038}    \pgfmath@def{acos}{557}{56.15141}
\pgfmath@def{acos}{558}{56.08240}    \pgfmath@def{acos}{559}{56.01333}
\pgfmath@def{acos}{560}{55.94420}    \pgfmath@def{acos}{561}{55.87501}
\pgfmath@def{acos}{562}{55.80577}    \pgfmath@def{acos}{563}{55.73647}
\pgfmath@def{acos}{564}{55.66712}    \pgfmath@def{acos}{565}{55.59770}
\pgfmath@def{acos}{566}{55.52823}    \pgfmath@def{acos}{567}{55.45871}
\pgfmath@def{acos}{568}{55.38912}    \pgfmath@def{acos}{569}{55.31947}
\pgfmath@def{acos}{570}{55.24977}    \pgfmath@def{acos}{571}{55.18001}
\pgfmath@def{acos}{572}{55.11019}    \pgfmath@def{acos}{573}{55.04030}
\pgfmath@def{acos}{574}{54.97036}    \pgfmath@def{acos}{575}{54.90036}
\pgfmath@def{acos}{576}{54.83030}    \pgfmath@def{acos}{577}{54.76018}
\pgfmath@def{acos}{578}{54.69000}    \pgfmath@def{acos}{579}{54.61976}
\pgfmath@def{acos}{580}{54.54945}    \pgfmath@def{acos}{581}{54.47909}
\pgfmath@def{acos}{582}{54.40866}    \pgfmath@def{acos}{583}{54.33817}
\pgfmath@def{acos}{584}{54.26762}    \pgfmath@def{acos}{585}{54.19701}
\pgfmath@def{acos}{586}{54.12633}    \pgfmath@def{acos}{587}{54.05559}
\pgfmath@def{acos}{588}{53.98479}    \pgfmath@def{acos}{589}{53.91392}
\pgfmath@def{acos}{590}{53.84299}    \pgfmath@def{acos}{591}{53.77199}
\pgfmath@def{acos}{592}{53.70093}    \pgfmath@def{acos}{593}{53.62981}
\pgfmath@def{acos}{594}{53.55862}    \pgfmath@def{acos}{595}{53.48736}
\pgfmath@def{acos}{596}{53.41604}    \pgfmath@def{acos}{597}{53.34466}
\pgfmath@def{acos}{598}{53.27320}    \pgfmath@def{acos}{599}{53.20168}
\pgfmath@def{acos}{600}{53.13010}    \pgfmath@def{acos}{601}{53.05844}
\pgfmath@def{acos}{602}{52.98672}    \pgfmath@def{acos}{603}{52.91494}
\pgfmath@def{acos}{604}{52.84308}    \pgfmath@def{acos}{605}{52.77115}
\pgfmath@def{acos}{606}{52.69916}    \pgfmath@def{acos}{607}{52.62710}
\pgfmath@def{acos}{608}{52.55497}    \pgfmath@def{acos}{609}{52.48276}
\pgfmath@def{acos}{610}{52.41049}    \pgfmath@def{acos}{611}{52.33815}
\pgfmath@def{acos}{612}{52.26574}    \pgfmath@def{acos}{613}{52.19326}
\pgfmath@def{acos}{614}{52.12070}    \pgfmath@def{acos}{615}{52.04808}
\pgfmath@def{acos}{616}{51.97538}    \pgfmath@def{acos}{617}{51.90261}
\pgfmath@def{acos}{618}{51.82976}    \pgfmath@def{acos}{619}{51.75685}
\pgfmath@def{acos}{620}{51.68386}    \pgfmath@def{acos}{621}{51.61080}
\pgfmath@def{acos}{622}{51.53766}    \pgfmath@def{acos}{623}{51.46445}
\pgfmath@def{acos}{624}{51.39117}    \pgfmath@def{acos}{625}{51.31781}
\pgfmath@def{acos}{626}{51.24437}    \pgfmath@def{acos}{627}{51.17086}
\pgfmath@def{acos}{628}{51.09728}    \pgfmath@def{acos}{629}{51.02361}
\pgfmath@def{acos}{630}{50.94987}    \pgfmath@def{acos}{631}{50.87606}
\pgfmath@def{acos}{632}{50.80216}    \pgfmath@def{acos}{633}{50.72819}
\pgfmath@def{acos}{634}{50.65414}    \pgfmath@def{acos}{635}{50.58001}
\pgfmath@def{acos}{636}{50.50580}    \pgfmath@def{acos}{637}{50.43152}
\pgfmath@def{acos}{638}{50.35715}    \pgfmath@def{acos}{639}{50.28270}
\pgfmath@def{acos}{640}{50.20818}    \pgfmath@def{acos}{641}{50.13357}
\pgfmath@def{acos}{642}{50.05888}    \pgfmath@def{acos}{643}{49.98411}
\pgfmath@def{acos}{644}{49.90926}    \pgfmath@def{acos}{645}{49.83432}
\pgfmath@def{acos}{646}{49.75930}    \pgfmath@def{acos}{647}{49.68420}
\pgfmath@def{acos}{648}{49.60902}    \pgfmath@def{acos}{649}{49.53375}
\pgfmath@def{acos}{650}{49.45839}    \pgfmath@def{acos}{651}{49.38296}
\pgfmath@def{acos}{652}{49.30743}    \pgfmath@def{acos}{653}{49.23182}
\pgfmath@def{acos}{654}{49.15613}    \pgfmath@def{acos}{655}{49.08035}
\pgfmath@def{acos}{656}{49.00448}    \pgfmath@def{acos}{657}{48.92852}
\pgfmath@def{acos}{658}{48.85248}    \pgfmath@def{acos}{659}{48.77634}
\pgfmath@def{acos}{660}{48.70012}    \pgfmath@def{acos}{661}{48.62381}
\pgfmath@def{acos}{662}{48.54741}    \pgfmath@def{acos}{663}{48.47092}
\pgfmath@def{acos}{664}{48.39434}    \pgfmath@def{acos}{665}{48.31767}
\pgfmath@def{acos}{666}{48.24091}    \pgfmath@def{acos}{667}{48.16405}
\pgfmath@def{acos}{668}{48.08710}    \pgfmath@def{acos}{669}{48.01006}
\pgfmath@def{acos}{670}{47.93293}    \pgfmath@def{acos}{671}{47.85570}
\pgfmath@def{acos}{672}{47.77838}    \pgfmath@def{acos}{673}{47.70096}
\pgfmath@def{acos}{674}{47.62345}    \pgfmath@def{acos}{675}{47.54585}
\pgfmath@def{acos}{676}{47.46814}    \pgfmath@def{acos}{677}{47.39034}
\pgfmath@def{acos}{678}{47.31244}    \pgfmath@def{acos}{679}{47.23445}
\pgfmath@def{acos}{680}{47.15635}    \pgfmath@def{acos}{681}{47.07816}
\pgfmath@def{acos}{682}{46.99987}    \pgfmath@def{acos}{683}{46.92147}
\pgfmath@def{acos}{684}{46.84298}    \pgfmath@def{acos}{685}{46.76439}
\pgfmath@def{acos}{686}{46.68569}    \pgfmath@def{acos}{687}{46.60690}
\pgfmath@def{acos}{688}{46.52800}    \pgfmath@def{acos}{689}{46.44899}
\pgfmath@def{acos}{690}{46.36989}    \pgfmath@def{acos}{691}{46.29068}
\pgfmath@def{acos}{692}{46.21136}    \pgfmath@def{acos}{693}{46.13194}
\pgfmath@def{acos}{694}{46.05241}    \pgfmath@def{acos}{695}{45.97278}
\pgfmath@def{acos}{696}{45.89304}    \pgfmath@def{acos}{697}{45.81319}
\pgfmath@def{acos}{698}{45.73323}    \pgfmath@def{acos}{699}{45.65317}
\pgfmath@def{acos}{700}{45.57299}    \pgfmath@def{acos}{701}{45.49271}
\pgfmath@def{acos}{702}{45.41231}    \pgfmath@def{acos}{703}{45.33180}
\pgfmath@def{acos}{704}{45.25118}    \pgfmath@def{acos}{705}{45.17045}
\pgfmath@def{acos}{706}{45.08961}    \pgfmath@def{acos}{707}{45.00865}
\pgfmath@def{acos}{708}{44.92757}    \pgfmath@def{acos}{709}{44.84638}
\pgfmath@def{acos}{710}{44.76508}    \pgfmath@def{acos}{711}{44.68366}
\pgfmath@def{acos}{712}{44.60212}    \pgfmath@def{acos}{713}{44.52046}
\pgfmath@def{acos}{714}{44.43869}    \pgfmath@def{acos}{715}{44.35680}
\pgfmath@def{acos}{716}{44.27478}    \pgfmath@def{acos}{717}{44.19265}
\pgfmath@def{acos}{718}{44.11039}    \pgfmath@def{acos}{719}{44.02802}
\pgfmath@def{acos}{720}{43.94552}    \pgfmath@def{acos}{721}{43.86289}
\pgfmath@def{acos}{722}{43.78014}    \pgfmath@def{acos}{723}{43.69727}
\pgfmath@def{acos}{724}{43.61427}    \pgfmath@def{acos}{725}{43.53115}
\pgfmath@def{acos}{726}{43.44790}    \pgfmath@def{acos}{727}{43.36452}
\pgfmath@def{acos}{728}{43.28101}    \pgfmath@def{acos}{729}{43.19737}
\pgfmath@def{acos}{730}{43.11360}    \pgfmath@def{acos}{731}{43.02970}
\pgfmath@def{acos}{732}{42.94567}    \pgfmath@def{acos}{733}{42.86151}
\pgfmath@def{acos}{734}{42.77721}    \pgfmath@def{acos}{735}{42.69278}
\pgfmath@def{acos}{736}{42.60821}    \pgfmath@def{acos}{737}{42.52351}
\pgfmath@def{acos}{738}{42.43867}    \pgfmath@def{acos}{739}{42.35370}
\pgfmath@def{acos}{740}{42.26858}    \pgfmath@def{acos}{741}{42.18333}
\pgfmath@def{acos}{742}{42.09793}    \pgfmath@def{acos}{743}{42.01240}
\pgfmath@def{acos}{744}{41.92672}    \pgfmath@def{acos}{745}{41.84090}
\pgfmath@def{acos}{746}{41.75493}    \pgfmath@def{acos}{747}{41.66882}
\pgfmath@def{acos}{748}{41.58257}    \pgfmath@def{acos}{749}{41.49617}
\pgfmath@def{acos}{750}{41.40962}    \pgfmath@def{acos}{751}{41.32292}
\pgfmath@def{acos}{752}{41.23607}    \pgfmath@def{acos}{753}{41.14908}
\pgfmath@def{acos}{754}{41.06193}    \pgfmath@def{acos}{755}{40.97463}
\pgfmath@def{acos}{756}{40.88717}    \pgfmath@def{acos}{757}{40.79956}
\pgfmath@def{acos}{758}{40.71180}    \pgfmath@def{acos}{759}{40.62388}
\pgfmath@def{acos}{760}{40.53580}    \pgfmath@def{acos}{761}{40.44756}
\pgfmath@def{acos}{762}{40.35916}    \pgfmath@def{acos}{763}{40.27061}
\pgfmath@def{acos}{764}{40.18189}    \pgfmath@def{acos}{765}{40.09300}
\pgfmath@def{acos}{766}{40.00396}    \pgfmath@def{acos}{767}{39.91474}
\pgfmath@def{acos}{768}{39.82537}    \pgfmath@def{acos}{769}{39.73582}
\pgfmath@def{acos}{770}{39.64611}    \pgfmath@def{acos}{771}{39.55622}
\pgfmath@def{acos}{772}{39.46617}    \pgfmath@def{acos}{773}{39.37594}
\pgfmath@def{acos}{774}{39.28554}    \pgfmath@def{acos}{775}{39.19496}
\pgfmath@def{acos}{776}{39.10421}    \pgfmath@def{acos}{777}{39.01328}
\pgfmath@def{acos}{778}{38.92218}    \pgfmath@def{acos}{779}{38.83089}
\pgfmath@def{acos}{780}{38.73942}    \pgfmath@def{acos}{781}{38.64777}
\pgfmath@def{acos}{782}{38.55594}    \pgfmath@def{acos}{783}{38.46392}
\pgfmath@def{acos}{784}{38.37171}    \pgfmath@def{acos}{785}{38.27932}
\pgfmath@def{acos}{786}{38.18673}    \pgfmath@def{acos}{787}{38.09396}
\pgfmath@def{acos}{788}{38.00100}    \pgfmath@def{acos}{789}{37.90784}
\pgfmath@def{acos}{790}{37.81448}    \pgfmath@def{acos}{791}{37.72093}
\pgfmath@def{acos}{792}{37.62719}    \pgfmath@def{acos}{793}{37.53324}
\pgfmath@def{acos}{794}{37.43909}    \pgfmath@def{acos}{795}{37.34474}
\pgfmath@def{acos}{796}{37.25019}    \pgfmath@def{acos}{797}{37.15542}
\pgfmath@def{acos}{798}{37.06046}    \pgfmath@def{acos}{799}{36.96528}
\pgfmath@def{acos}{800}{36.86989}    \pgfmath@def{acos}{801}{36.77429}
\pgfmath@def{acos}{802}{36.67848}    \pgfmath@def{acos}{803}{36.58245}
\pgfmath@def{acos}{804}{36.48621}    \pgfmath@def{acos}{805}{36.38974}
\pgfmath@def{acos}{806}{36.29305}    \pgfmath@def{acos}{807}{36.19615}
\pgfmath@def{acos}{808}{36.09901}    \pgfmath@def{acos}{809}{36.00165}
\pgfmath@def{acos}{810}{35.90406}    \pgfmath@def{acos}{811}{35.80625}
\pgfmath@def{acos}{812}{35.70820}    \pgfmath@def{acos}{813}{35.60991}
\pgfmath@def{acos}{814}{35.51139}    \pgfmath@def{acos}{815}{35.41263}
\pgfmath@def{acos}{816}{35.31364}    \pgfmath@def{acos}{817}{35.21440}
\pgfmath@def{acos}{818}{35.11491}    \pgfmath@def{acos}{819}{35.01518}
\pgfmath@def{acos}{820}{34.91520}    \pgfmath@def{acos}{821}{34.81497}
\pgfmath@def{acos}{822}{34.71449}    \pgfmath@def{acos}{823}{34.61375}
\pgfmath@def{acos}{824}{34.51276}    \pgfmath@def{acos}{825}{34.41150}
\pgfmath@def{acos}{826}{34.30999}    \pgfmath@def{acos}{827}{34.20821}
\pgfmath@def{acos}{828}{34.10616}    \pgfmath@def{acos}{829}{34.00385}
\pgfmath@def{acos}{830}{33.90126}    \pgfmath@def{acos}{831}{33.79840}
\pgfmath@def{acos}{832}{33.69526}    \pgfmath@def{acos}{833}{33.59184}
\pgfmath@def{acos}{834}{33.48814}    \pgfmath@def{acos}{835}{33.38416}
\pgfmath@def{acos}{836}{33.27989}    \pgfmath@def{acos}{837}{33.17533}
\pgfmath@def{acos}{838}{33.07047}    \pgfmath@def{acos}{839}{32.96532}
\pgfmath@def{acos}{840}{32.85988}    \pgfmath@def{acos}{841}{32.75413}
\pgfmath@def{acos}{842}{32.64807}    \pgfmath@def{acos}{843}{32.54171}
\pgfmath@def{acos}{844}{32.43504}    \pgfmath@def{acos}{845}{32.32806}
\pgfmath@def{acos}{846}{32.22076}    \pgfmath@def{acos}{847}{32.11314}
\pgfmath@def{acos}{848}{32.00520}    \pgfmath@def{acos}{849}{31.89693}
\pgfmath@def{acos}{850}{31.78833}    \pgfmath@def{acos}{851}{31.67939}
\pgfmath@def{acos}{852}{31.57012}    \pgfmath@def{acos}{853}{31.46051}
\pgfmath@def{acos}{854}{31.35056}    \pgfmath@def{acos}{855}{31.24026}
\pgfmath@def{acos}{856}{31.12961}    \pgfmath@def{acos}{857}{31.01860}
\pgfmath@def{acos}{858}{30.90724}    \pgfmath@def{acos}{859}{30.79551}
\pgfmath@def{acos}{860}{30.68341}    \pgfmath@def{acos}{861}{30.57095}
\pgfmath@def{acos}{862}{30.45811}    \pgfmath@def{acos}{863}{30.34489}
\pgfmath@def{acos}{864}{30.23128}    \pgfmath@def{acos}{865}{30.11729}
\pgfmath@def{acos}{866}{30.00291}    \pgfmath@def{acos}{867}{29.88813}
\pgfmath@def{acos}{868}{29.77294}    \pgfmath@def{acos}{869}{29.65736}
\pgfmath@def{acos}{870}{29.54136}    \pgfmath@def{acos}{871}{29.42494}
\pgfmath@def{acos}{872}{29.30810}    \pgfmath@def{acos}{873}{29.19084}
\pgfmath@def{acos}{874}{29.07315}    \pgfmath@def{acos}{875}{28.95502}
\pgfmath@def{acos}{876}{28.83645}    \pgfmath@def{acos}{877}{28.71743}
\pgfmath@def{acos}{878}{28.59796}    \pgfmath@def{acos}{879}{28.47803}
\pgfmath@def{acos}{880}{28.35763}    \pgfmath@def{acos}{881}{28.23677}
\pgfmath@def{acos}{882}{28.11542}    \pgfmath@def{acos}{883}{27.99360}
\pgfmath@def{acos}{884}{27.87128}    \pgfmath@def{acos}{885}{27.74847}
\pgfmath@def{acos}{886}{27.62516}    \pgfmath@def{acos}{887}{27.50134}
\pgfmath@def{acos}{888}{27.37700}    \pgfmath@def{acos}{889}{27.25214}
\pgfmath@def{acos}{890}{27.12675}    \pgfmath@def{acos}{891}{27.00082}
\pgfmath@def{acos}{892}{26.87434}    \pgfmath@def{acos}{893}{26.74731}
\pgfmath@def{acos}{894}{26.61973}    \pgfmath@def{acos}{895}{26.49157}
\pgfmath@def{acos}{896}{26.36283}    \pgfmath@def{acos}{897}{26.23351}
\pgfmath@def{acos}{898}{26.10359}    \pgfmath@def{acos}{899}{25.97306}
\pgfmath@def{acos}{900}{25.84193}    \pgfmath@def{acos}{901}{25.71017}
\pgfmath@def{acos}{902}{25.57778}    \pgfmath@def{acos}{903}{25.44475}
\pgfmath@def{acos}{904}{25.31106}    \pgfmath@def{acos}{905}{25.17671}
\pgfmath@def{acos}{906}{25.04169}    \pgfmath@def{acos}{907}{24.90598}
\pgfmath@def{acos}{908}{24.76958}    \pgfmath@def{acos}{909}{24.63247}
\pgfmath@def{acos}{910}{24.49464}    \pgfmath@def{acos}{911}{24.35608}
\pgfmath@def{acos}{912}{24.21678}    \pgfmath@def{acos}{913}{24.07672}
\pgfmath@def{acos}{914}{23.93588}    \pgfmath@def{acos}{915}{23.79427}
\pgfmath@def{acos}{916}{23.65185}    \pgfmath@def{acos}{917}{23.50863}
\pgfmath@def{acos}{918}{23.36457}    \pgfmath@def{acos}{919}{23.21967}
\pgfmath@def{acos}{920}{23.07391}    \pgfmath@def{acos}{921}{22.92728}
\pgfmath@def{acos}{922}{22.77975}    \pgfmath@def{acos}{923}{22.63132}
\pgfmath@def{acos}{924}{22.48195}    \pgfmath@def{acos}{925}{22.33164}
\pgfmath@def{acos}{926}{22.18036}    \pgfmath@def{acos}{927}{22.02810}
\pgfmath@def{acos}{928}{21.87483}    \pgfmath@def{acos}{929}{21.72053}
\pgfmath@def{acos}{930}{21.56518}    \pgfmath@def{acos}{931}{21.40876}
\pgfmath@def{acos}{932}{21.25124}    \pgfmath@def{acos}{933}{21.09260}
\pgfmath@def{acos}{934}{20.93281}    \pgfmath@def{acos}{935}{20.77185}
\pgfmath@def{acos}{936}{20.60969}    \pgfmath@def{acos}{937}{20.44630}
\pgfmath@def{acos}{938}{20.28165}    \pgfmath@def{acos}{939}{20.11570}
\pgfmath@def{acos}{940}{19.94844}    \pgfmath@def{acos}{941}{19.77982}
\pgfmath@def{acos}{942}{19.60981}    \pgfmath@def{acos}{943}{19.43837}
\pgfmath@def{acos}{944}{19.26546}    \pgfmath@def{acos}{945}{19.09105}
\pgfmath@def{acos}{946}{18.91509}    \pgfmath@def{acos}{947}{18.73754}
\pgfmath@def{acos}{948}{18.55835}    \pgfmath@def{acos}{949}{18.37748}
\pgfmath@def{acos}{950}{18.19487}    \pgfmath@def{acos}{951}{18.01047}
\pgfmath@def{acos}{952}{17.82423}    \pgfmath@def{acos}{953}{17.63609}
\pgfmath@def{acos}{954}{17.44598}    \pgfmath@def{acos}{955}{17.25385}
\pgfmath@def{acos}{956}{17.05962}    \pgfmath@def{acos}{957}{16.86322}
\pgfmath@def{acos}{958}{16.66457}    \pgfmath@def{acos}{959}{16.46359}
\pgfmath@def{acos}{960}{16.26020}    \pgfmath@def{acos}{961}{16.05430}
\pgfmath@def{acos}{962}{15.84580}    \pgfmath@def{acos}{963}{15.63459}
\pgfmath@def{acos}{964}{15.42057}    \pgfmath@def{acos}{965}{15.20360}
\pgfmath@def{acos}{966}{14.98357}    \pgfmath@def{acos}{967}{14.76033}
\pgfmath@def{acos}{968}{14.53374}    \pgfmath@def{acos}{969}{14.30364}
\pgfmath@def{acos}{970}{14.06986}    \pgfmath@def{acos}{971}{13.83221}
\pgfmath@def{acos}{972}{13.59049}    \pgfmath@def{acos}{973}{13.34447}
\pgfmath@def{acos}{974}{13.09392}    \pgfmath@def{acos}{975}{12.83856}
\pgfmath@def{acos}{976}{12.57811}    \pgfmath@def{acos}{977}{12.31225}
\pgfmath@def{acos}{978}{12.04060}    \pgfmath@def{acos}{979}{11.76278}
\pgfmath@def{acos}{980}{11.47834}    \pgfmath@def{acos}{981}{11.18676}
\pgfmath@def{acos}{982}{10.88748}    \pgfmath@def{acos}{983}{10.57984}
\pgfmath@def{acos}{984}{10.26309}    \pgfmath@def{acos}{985}{9.93636}
\pgfmath@def{acos}{986}{9.59863}    \pgfmath@def{acos}{987}{9.24870}
\pgfmath@def{acos}{988}{8.88512}    \pgfmath@def{acos}{989}{8.50614}
\pgfmath@def{acos}{990}{8.10961}    \pgfmath@def{acos}{991}{7.69281}
\pgfmath@def{acos}{992}{7.25224}    \pgfmath@def{acos}{993}{6.78328}
\pgfmath@def{acos}{994}{6.27958}    \pgfmath@def{acos}{995}{5.73196}
\pgfmath@def{acos}{996}{5.12640}    \pgfmath@def{acos}{997}{4.43922}
\pgfmath@def{acos}{998}{3.62430}    \pgfmath@def{acos}{999}{2.56255}
\pgfmath@def{acos}{1000}{0.00000}



% Local Variables:
% tab-width: 2
% End:

pgfmathparser.code.tex

\newdimen\pgfmath@dimen
\newcount\pgfmath@count
\newbox\pgfmath@box
\newtoks\pgfmath@toks

\newif\ifpgfmath@quickparse
\newif\ifpgfmathfloat
\newif\ifpgfmathunitsdeclared
\newif\ifpgfmathmathunitsdeclared
\newif\ifpgfmathignoreunitscale

\def\pgfmathprint#1{\pgfmathparse{#1}\pgfmathresult}

\def\pgfmathparse{%
  \begingroup
    \pgfmath@catcodes
    \pgfmath@quickparsefalse
    % Test for the fpu library
    \ifpgfmathfloat
      \let\pgfmath@parse@next=\pgfmathfloatparsenumber
    \else
      \let\pgfmath@parse@next=\pgfmathparse@
    \fi
    \pgfmath@parse@next}

\def\pgfmath@catcodes{% Maybe unecessary.
  \catcode`\==12%
  \catcode`\,=12%
  \catcode`\|=12%
  \catcode`\&=12%
}

\def\pgfmathqparse{%
  \begingroup
    \pgfmath@catcodes
    \pgfmath@quickparsetrue
    \pgfmathparse@}
  
\def\pgfmathparse@#1{%
    % We are inside a group (opened in |\pgfmathparse| or
    % |\pgfmathqparse|). 
    % Stuff for calc compatiability.
    \let\real=\pgfmath@calc@real
    \let\minof=\pgfmath@calc@minof
    \let\maxof=\pgfmath@calc@maxof
    \let\ratio=\pgfmath@calc@ratio
    \let\widthof=\pgfmath@calc@widthof
    \let\heightof=\pgfmath@calc@heightof
    \let\depthof=\pgfmath@calc@depthof
    % Restore font (defined in pgfmathutil.code.tex)
    \pgfmath@selectfont
    % Expand expression so any reamining CSs are registers
    % or box dimensions (i.e. |\wd|, |\ht|, |\dp|).
    \edef\pgfmath@expression{#1}%
    % No (math) units yet. 
    \global\pgfmathunitsdeclaredfalse
    \global\pgfmathmathunitsdeclaredfalse
    % Set up stack.
    \pgfmath@stack@operation={{}{}{}}%
    \pgfmath@stack@operand={{}{}{}}%
    \let\pgfmath@stack@operation@top=\pgfmath@stack@empty
    \let\pgfmath@stack@operand@top=\pgfmath@stack@empty
    % An expression always begins with an operand.
    \expandafter\pgfmath@bgroup@strip\expandafter{\pgfmath@expression}%
    % |\pgfmath@bgroup@stripped| is the result of
    % |\pgfmath@bgroup@strip|
    \expandafter\pgfmath@parse@@operand\pgfmath@bgroup@stripped @@@@\pgfmath@parse@stop%
}

\def\pgfmath@parse@end#1\pgfmath@parse@stop{%
    \pgfmathpostparse
    \pgfmath@smuggleone\pgfmathresult%
  \endgroup
  \ignorespaces}

\let\pgfmathpostparse=\relax

% For compatiability with older version.
%
\def\pgfmathscaleresult{%
  \ifpgfmathunitsdeclared
  \else
    \ifpgfmathignoreunitscale
    \else
       \afterassignment\pgfmath@gobbletilpgfmath@%
      \pgfmath@x\pgfmathresultunitscale pt\relax\pgfmath@%
      \expandafter\pgfmath@x\pgfmathresult\pgfmath@x%
      \edef\pgfmathresult{\pgfmath@tonumber{\pgfmath@x}}%
    \fi
  \fi
}

\def\pgfmathsetresultunitscale#1{\def\pgfmathresultunitscale{#1}}

\def\pgfmathresultunitscale{1}

% Stuff for compatability with the calc package.
%
\def\pgfmath@calc@real#1{#1}
\def\pgfmath@calc@minof#1#2{min(#1,#2)}
\def\pgfmath@calc@maxof#1#2{max(#1,#2)}
\def\pgfmath@calc@ratio#1#2{#1/#2}
\def\pgfmath@calc@widthof#1{width("#1")}
\def\pgfmath@calc@heightof#1{height("#1")}
\def\pgfmath@calc@depthof#1{depth("#1")}

\def\pgfmath@bgroup{\string\pgfmath@bgroup}
\def\pgfmath@egroup{\string\pgfmath@egroup}
\def\pgfmath@egroup@token{\pgfmath@egroup}

\def\pgfmath@text@@{@}
\def\pgfmath@text@operator{operator}
\def\pgfmath@text@function{function}
\def\pgfmath@dots{...}
\def\pgfmath@char@zero{0}
\def\pgfmath@char@quote{"}
\def\pgfmath@char@exclamation{!}
\def\pgfmath@char@plus{+}
\def\pgfmath@char@minus{-}
\def\pgfmath@char@period{.}
\def\pgfmath@char@leftangle{<}
\def\pgfmath@char@leftbracket{[}
\pgfmath@toks={#}
\edef\pgfmath@char@hash{\the\pgfmath@toks}

\def\pgfmath@tokens@make#1#2{%
  % Defines for each token or balenced text in |#2| a control sequence
  % |\pgfmath@token@<#1>@\string<one token from #2>| and stores |#2|
  % in it.
  \def\pgfmath@prefix{#1}%
  % Note the empty group |{}| at the end that ends the loop in
  % |\pgfmath@token@@make|.
  \expandafter\pgfmath@tokens@@make#2{}}
  
\def\pgfmath@tokens@@make#1{%
  \def\pgfmath@token{#1}%
  \ifx\pgfmath@token\pgfmath@empty
    % End of loop: all tokens or balanced texts were parsed.
  \else
    \pgfmath@namedef{pgfmath@token@\pgfmath@prefix @\string#1}{#1}%
    \expandafter\pgfmath@tokens@@make%
  \fi}

\pgfmath@tokens@make{box}{\wd\ht\dp}
\ifx\dimexpr\@undefined\else % needed for classic tex
  \pgfmath@tokens@make{dimexpr}{\dimexpr\glueexpr}
\fi
\pgfmath@tokens@make{unit}{{bp}{cc}{cm}{dd}{em}{ex}{in}{mm}{pc}{pt}{sp}}
\pgfmath@tokens@make{mathunit}{{mu}}
\pgfmath@tokens@make{numeric}{.0123456789}
\pgfmath@tokens@make{number}{0123456789}
\pgfmath@tokens@make{functional}{_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ}
\pgfmath@tokens@make{exponent}{eE}
\pgfmath@tokens@make{group}{{()}{[]}{\pgfmath@bgroup\pgfmath@egroup}}
\pgfmath@tokens@make{specials}{@)]\pgfmath@egroup}
\pgfmath@tokens@make{hexadecimal}{0123456789ABCDEFabcdef}
\pgfmath@tokens@make{octal}{01234567}
\pgfmath@tokens@make{binary}{01}

\pgfmath@namedef{pgfmath@base@0x}{16}
\pgfmath@namedef{pgfmath@base@0X}{16}
\pgfmath@namedef{pgfmath@base@0b}{2}
\pgfmath@namedef{pgfmath@base@0B}{2}

% Determine if a register is a count or a dimension/skip register.
\newif\ifpgfmath@dimen@
\def\pgfmath@dimen@#1{%
  \begingroup
    \afterassignment\pgfmath@dimen@@%
    #1=0.0pt\relax\pgfmath@}
\def\pgfmath@dimen@@#1#2\pgfmath@{%
  \endgroup
  \ifx#1.%
    \pgfmath@dimen@false
  \else
    \pgfmath@dimen@true
  \fi}

\def\pgfmath@parse@ifbgroup#1#2{%
  \let\pgfmath@parse@bgroup@after=#1%
  \let\pgfmath@parse@nobgroup@after=#2%
  \futurelet\pgfmath@token@let%
  \pgfmath@parse@@ifbgroup}
  
\def\pgfmath@parse@@ifbgroup{%
  \ifx\pgfmath@token@let\bgroup
    \let\pgfmath@parse@next=\pgfmath@parse@@@ifbgroup
  \else
    % |\pgfmath@sptoken| defined in \file{pgfmathutil.code.tex}.
    \ifx\pgfmath@token@let\pgfmath@sptoken
      \let\pgfmath@parse@next=\pgfmath@parse@@@@ifbgroup
    \else
      \let\pgfmath@parse@next=\pgfmath@parse@nobgroup@after
    \fi
  \fi
  \pgfmath@parse@next}

% I (CJ) *think* it replaces |{| and |}| by |\pgfmath@bgroup| and
% |\pgfmath@egroup|?
\def\pgfmath@parse@@@ifbgroup#1{%
  \pgfmath@parse@bgroup@after\pgfmath@bgroup#1\pgfmath@egroup}

{
\def\:{\pgfmath@parse@@@@ifbgroup}
\expandafter\gdef\: {\futurelet\pgfmath@token@let\pgfmath@parse@@ifbgroup}
}

% Parse an operand.
\def\pgfmath@parse@operand{%
  \expandafter\pgfmath@parse@@operand\pgfmath@token@next}

% This is the entry point for the parser. It is called at the end of
% |\pgfmathparse@| with the following syntax
% |\expandafter\pgfmath@parse@@operand\pgfmath@bgroup@stripped
% @@@@\pgfmath@parse@stop|.
% Note: we are inside a group.
\def\pgfmath@parse@@operand{%
  \pgfmath@parse@ifbgroup{\pgfmath@parse@@operand}{\pgfmath@parse@@operand@}}

% An operand is 
% * |+| (unary plus),
% * |-| (unary minus), 
% * a prefix operator
\def\pgfmath@parse@@operand@#1{%
  \def\pgfmath@token{#1}%
  \ifx\pgfmath@token\pgfmath@char@plus
    % Unary (prefix) plus
    \let\pgfmath@parse@next=\pgfmath@parse@@operand%
  \else
    \ifx\pgfmath@token\pgfmath@char@minus
      % Unary (prefix) minus
      \pgfmath@stack@push@operation{neg}%
      \let\pgfmath@parse@next=\pgfmath@parse@@operand
    \else
      % See |\pgfmathdeclareoperator| (below). Note that |+| and |-|
      % that are also declared as operators have been tested before so
      % they should never be parsed as binary (infix) operator at this stage.
      \expandafter\ifx\csname pgfmath@operation@\expandafter\string\pgfmath@token @prefix\endcsname\pgfmath@token
        \let\pgfmath@parse@next=\pgfmath@parse@prefix@operator
      \else
        \ifpgfmath@quickparse
          \let\pgfmath@parse@next=\pgfmath@qparse@operand
        \else
          \let\pgfmath@number=\pgfmath@empty
          \expandafter\ifx\csname pgfmath@token@functional@\string#1\endcsname\relax%
            \let\pgfmath@base=\pgfmath@empty%
            \let\pgfmath@token@next=\pgfmath@token%
            \if#10% Check for octal prefix.
              \def\pgfmath@base{8}%
            \fi%
            \let\pgfmath@parse@next=\pgfmath@parse@number%
          \else%
            \let\pgfmath@function=\pgfmath@token%
            \let\pgfmath@parse@next=\pgfmath@parse@function%
          \fi%
        \fi%
      \fi%
    \fi%
  \fi%
  \pgfmath@parse@next%
}

% Parse prefix operators.
%
\def\pgfmath@parse@prefix@operator{%
  \ifx\pgfmath@token\pgfmath@char@quote% Quote character.
    \let\pgfmath@parse@next=\pgfmath@parse@operand@quote%
  \else%
    \ifx\pgfmath@token\pgfmath@char@exclamation% Prefix !.
      \pgfmath@stack@push@operation{not}%
      \let\pgfmath@parse@next=\pgfmath@parse@@operand%
    \else% Anything else, just push and hope.
      \expandafter\pgfmath@stack@push@operation\expandafter{\pgfmath@token}%
      \let\pgfmath@parse@next=\pgfmath@parse@@operand%
    \fi%
  \fi%
  \pgfmath@parse@next%
}%


% Quote part of an expression.
%
\def\pgfmath@parse@operand@quote#1"{%
  \def\pgfmathresult{#1}%
  \expandafter\pgfmath@stack@push@operand\expandafter{\pgfmathresult}%
  \pgfmath@parse@@operator%
}

% Quick operand parsing. Should always have units.
% No functions, base conversion, quoting or scientific notation
% are permitted.
\def\pgfmath@qparse@operand{%
  \afterassignment\pgfmath@qparse@@operand%
  \pgfmath@dimen\pgfmath@token}
\def\pgfmath@qparse@@operand{%
  \edef\pgfmathresult{\pgfmath@tonumber{\pgfmath@dimen}}%
  \expandafter\pgfmath@stack@push@operand\expandafter{\pgfmathresult}%
  \pgfmath@parse@@operator%
}

% Parse a number, which can take the form:
%
% 1. An integer, or a decimal, with or without units.
% 2. A dimension/skip or a count register.
% 3. A dimension register preceded by a number or count register.
% 4. A box dimension (e.g., \wd\mybox).
% 5. A box dimension preceded by a number or a count register.
% 6. Scientific notation (e.g., 1.234567e-10).
% 7. A binary, hexadeciaml, or octal number.
%  
\def\pgfmath@parse@number{\pgfmath@parse@ifbgroup{\pgfmath@parse@number}{\pgfmath@parse@number@}}
\def\pgfmath@parse@number@#1{%
  \let\pgfmath@token=\pgfmath@token@next%
  \def\pgfmath@token@next{#1}%
  \pgfmath@parse@@number}

\def\pgfmath@parse@@number{%
  \ifx\pgfmath@token\pgfmath@egroup@token%
    \expandafter\pgfmath@stack@push@operand\expandafter{\pgfmath@number}%
    \let\pgfmath@parse@next=\pgfmath@parse@@@operator%
  \else%
    \expandafter\ifcat\pgfmath@token\relax% A CS?
      \expandafter\ifx\csname pgfmath@token@dimexpr@\expandafter\string\pgfmath@token\endcsname\relax%
        \expandafter\ifx\pgfmath@token\numexpr%
          \let\pgfmath@parse@next=\pgfmath@parse@numexpr%
        \else%
          \expandafter\ifx\pgfmath@token\muexpr%
            \let\pgfmath@parse@next=\pgfmath@parse@muexpr%
          \else%
            \expandafter\ifx\csname pgfmath@token@box@\expandafter\string\pgfmath@token\endcsname\relax%
              % So, is the CS is a dimension or a count register?
              \expandafter\pgfmath@dimen@\pgfmath@token%
              \ifpgfmath@dimen@% A dimension register.
                \global\pgfmathunitsdeclaredtrue%
                \pgfmath@dimen=\pgfmath@number\pgfmath@token%
                \edef\pgfmathresult{\pgfmath@tonumber{\pgfmath@dimen}}%
                \expandafter\pgfmath@stack@push@operand\expandafter{\pgfmathresult}%
                \let\pgfmath@parse@next=\pgfmath@parse@operator%
              \else% A count register.
                \pgfmath@count=\pgfmath@token%
                \expandafter\def\expandafter\pgfmath@number\expandafter{\the\pgfmath@count}%
                \expandafter\ifcat\pgfmath@token@next\relax%
                  % A CS following a count register should be \wd, \ht or \dp. 
                  \let\pgfmath@parse@next=\pgfmath@parse@number%
                \else%
                  \let\pgfmathresult=\pgfmath@number%
                  \expandafter\pgfmath@stack@push@operand\expandafter{\pgfmathresult}%
                  \let\pgfmath@parse@next=\pgfmath@parse@operator%
                \fi%
              \fi%
            \else%
              % This should be a box specification, for example, 0.5\wd\mybox.
              \global\pgfmathunitsdeclaredtrue%
              \pgfmath@dimen=\pgfmath@number\pgfmath@token\pgfmath@token@next%
              \edef\pgfmathresult{\pgfmath@tonumber{\pgfmath@dimen}}%
              \expandafter\pgfmath@stack@push@operand\expandafter{\pgfmathresult}%
              \let\pgfmath@parse@next=\pgfmath@parse@@operator%
            \fi%
          \fi%
        \fi%
      \else%
        \global\pgfmathunitsdeclaredtrue%
        \let\pgfmath@parse@next=\pgfmath@parse@dimexpr%
      \fi%
    \else%
      \expandafter\ifx\csname pgfmath@token@numeric@\expandafter\string\pgfmath@token\endcsname\relax%
        % It isn't numeric (i.e., 012345679.), so it might be units...
        \expandafter\ifx\csname pgfmath@token@unit@\pgfmath@token\expandafter\string\pgfmath@token@next\endcsname\relax%
          % ...or the exponent characters...
          \expandafter\ifx\csname pgfmath@token@exponent@\pgfmath@token\endcsname\relax%
            % ...or a base prefix...
            \expandafter\ifx\csname pgfmath@base@\pgfmath@number\pgfmath@token\endcsname\relax%
              % ...or a math unit...
              \expandafter\ifx\csname pgfmath@token@mathunit@\pgfmath@token\expandafter\string\pgfmath@token@next\endcsname\relax%
                % ...none of the above...
                  \ifx\pgfmath@base\pgfmath@empty%
                    \let\pgfmathresult=\pgfmath@number% 
                  \else%
                    \ifx\pgfmath@number\pgfmath@char@zero%
                      \let\pgfmathresult=\pgfmath@number%
                    \else%
                      % Convert from octal.
                      \expandafter\pgfmathbasetobase\expandafter\pgfmathresult\expandafter{\pgfmath@number}{8}{10}%
                    \fi%
                  \fi%
                  \expandafter\pgfmath@stack@push@operand\expandafter{\pgfmathresult}%
                  \let\pgfmath@parse@next=\pgfmath@parse@@@operator%
              \else%
                % ...here, it is a math unit (mu). Treat it as a pt.
                \global\pgfmathunitsdeclaredtrue%
                \global\pgfmathmathunitsdeclaredtrue%
                \pgfmath@dimen=\pgfmath@number pt\relax%
                \edef\pgfmathresult{\pgfmath@tonumber{\pgfmath@dimen}}%
                \expandafter\pgfmath@stack@push@operand\expandafter{\pgfmathresult}%
                \let\pgfmath@parse@next=\pgfmath@parse@@operator%
              \fi%
            \else%
              % ...here, it is a base prefix 0x, 0X, 0b or 0B
              \expandafter\let\expandafter\pgfmath@base\expandafter=%
                \csname pgfmath@base@\pgfmath@number\pgfmath@token\endcsname%
              \let\pgfmath@parse@next=\pgfmath@parse@base%
            \fi%
          \else% ... and here, it is the exponent characters.
            \let\pgfmath@parse@next=\pgfmath@parse@exponent%          
          \fi%
        \else% ...but here it is units.
          \global\pgfmathunitsdeclaredtrue%
          \pgfmath@dimen=\pgfmath@number\pgfmath@token\pgfmath@token@next\relax%
          \edef\pgfmathresult{\pgfmath@tonumber{\pgfmath@dimen}}%
          \expandafter\pgfmath@stack@push@operand\expandafter{\pgfmathresult}%
          \let\pgfmath@parse@next=\pgfmath@parse@@operator%
        \fi%
      \else% It is numeric.
        \expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter\pgfmath@number%
          \expandafter\expandafter\expandafter{\expandafter\pgfmath@number\pgfmath@token}%
        \ifx\pgfmath@token\pgfmath@char@period%
          \let\pgfmath@base=\pgfmath@empty%
        \fi%
        \let\pgfmath@parse@next=\pgfmath@parse@number%
      \fi%
    \fi%
  \fi%
  \pgfmath@parse@next%
}


% Parse a \dimexpr
\def\pgfmath@parse@dimexpr{%
  \afterassignment\pgfmath@parse@dimexpr@%
  \expandafter\expandafter\expandafter\pgfmath@dimen\expandafter\pgfmath@token\pgfmath@token@next%
}
\def\pgfmath@parse@dimexpr@{%
  \edef\pgfmathresult{\pgfmath@tonumber{\pgfmath@dimen}}%
  \expandafter\pgfmath@stack@push@operand\expandafter{\pgfmathresult}%
  \pgfmath@parse@@operator%
}


% Parse a \muexpr
\def\pgfmath@parse@muexpr{%
  \begingroup%
    \afterassignment\pgfmath@parse@muexpr@%
    \expandafter\expandafter\expandafter\muskip\expandafter\expandafter\expandafter0\expandafter\pgfmath@token\expandafter\pgfmath@token@next%
}
\def\pgfmath@parse@muexpr@{%
  \expandafter\endgroup%
  \expandafter\edef\expandafter\pgfmathresult\expandafter{\expandafter\pgfMATH@STRIPMU\the\muskip0}%
  \expandafter\pgfmath@stack@push@operand\expandafter{\pgfmathresult}%
  \pgfmath@parse@@operator%
}

{
\catcode`\m=12
\catcode`\u=12
\gdef\pgfMATH@STRIPMU#1mu{#1}
}


% Parse a \numexpr
\def\pgfmath@parse@numexpr{%
  \afterassignment\pgfmath@parse@numexpr@%
  \expandafter\expandafter\expandafter\pgfmath@count\expandafter\pgfmath@token\pgfmath@token@next%
}
\def\pgfmath@parse@numexpr@#1{%
  \expandafter\def\expandafter\pgfmath@number\expandafter{\the\pgfmath@count}%
  \def\pgfmath@token@next{#1}%
  \expandafter\ifcat\pgfmath@token@next\relax%
    % A CS following a count register should be \wd, \ht or \dp. 
    \let\pgfmath@parse@next=\pgfmath@parse@number%
  \else%
    \let\pgfmathresult=\pgfmath@number%
    \expandafter\pgfmath@stack@push@operand\expandafter{\pgfmathresult}%
    \let\pgfmath@parse@next=\pgfmath@parse@operator%
  \fi%
  \pgfmath@parse@next%
}


% Parse the exponent of a number.
%
% REMARK: this method will be overwritten by the FPU library. Please
% keep changes consistent...
\def\pgfmath@parse@exponent{%
  \afterassignment\pgfmath@parse@@exponent%
  \pgfmath@count\pgfmath@token@next}
\def\pgfmath@parse@@exponent{%
  \pgfmathscientific{\pgfmath@number}{\the\pgfmath@count}%
  \expandafter\pgfmath@stack@push@operand\expandafter{\pgfmathresult}%
  \pgfmath@parse@@operator%
}

% Parse binary or hexadecimal numbers (octal numbers done elsehwere).
%
\def\pgfmath@parse@base{%
  \ifnum\pgfmath@base=2\relax%
    \let\pgfmath@parse@next=\pgfmath@parse@binary%
  \else%
    \ifnum\pgfmath@base=16\relax%
      \let\pgfmath@parse@next=\pgfmath@parse@hexadecimal%
    \else%
      \pgfmath@error{Unexpected numerical base `\pgfmath@base'}{}%
      \def\pgfmathresult{0}%
      \let\pgfmath@parse@next=\pgfmath@parse@end%
    \fi%
  \fi%
  \let\pgfmath@number=\pgfmath@empty%
  \expandafter\pgfmath@parse@next\pgfmath@token@next%
}
  
\def\pgfmath@parse@binary#1{%
  \expandafter\ifx\csname pgfmath@token@binary@#1\endcsname\relax%
    \expandafter\pgfmathbasetobase\expandafter\pgfmathresult\expandafter{\pgfmath@number}{2}{10}%
    \expandafter\pgfmath@stack@push@operand\expandafter{\pgfmathresult}%
    \def\pgfmath@token@next{#1}%
    \let\pgfmath@parse@next=\pgfmath@parse@operator%
  \else%
    \expandafter\def\expandafter\pgfmath@number\expandafter{\pgfmath@number#1}%
    \let\pgfmath@parse@next=\pgfmath@parse@binary%
  \fi%
  \pgfmath@parse@next%
}

\def\pgfmath@parse@hexadecimal#1{%
  \expandafter\ifx\csname pgfmath@token@hexadecimal@#1\endcsname\relax%
    \expandafter\pgfmathbasetobase\expandafter\pgfmathresult\expandafter{\pgfmath@number}{16}{10}%
    \expandafter\pgfmath@stack@push@operand\expandafter{\pgfmathresult}%
    \def\pgfmath@token@next{#1}%
    \let\pgfmath@parse@next=\pgfmath@parse@operator%
  \else%
    \expandafter\def\expandafter\pgfmath@number\expandafter{\pgfmath@number#1}%
    \let\pgfmath@parse@next=\pgfmath@parse@hexadecimal%
  \fi%
  \pgfmath@parse@next%
}
  
% Parse a function.
%
\def\pgfmath@parse@function{\pgfmath@parse@ifbgroup{\pgfmath@parse@function}{\pgfmath@parse@@function}}
\def\pgfmath@parse@function@{\futurelet\pgfmath@token@let\pgfmath@parse@@function}
\def\pgfmath@parse@@function{%
  \ifx\pgfmath@token@let\pgfmath@sptoken%
    \let\pgfmath@token=\pgfmath@empty%
    \let\pgfmath@parse@next=\pgfmath@parse@@@@function%
  \else%
    \let\pgfmath@parse@next=\pgfmath@parse@@@function%
  \fi%
  \pgfmath@parse@next}

\def\pgfmath@parse@@@function#1{%
  \expandafter\ifx\csname pgfmath@token@functional@\expandafter\string#1\endcsname\relax%
    \expandafter\ifx\csname pgfmath@token@number@\expandafter\string#1\endcsname\relax%
      \def\pgfmath@token{#1}% Not from A-Z, a-z, 0-9, or _.
      \let\pgfmath@parse@next=\pgfmath@parse@@@@function%
    \else% It is from 0-9.
      \expandafter\def\expandafter\pgfmath@function\expandafter{\pgfmath@function#1}%
      \let\pgfmath@parse@next=\pgfmath@parse@function@%
    \fi%
  \else% It is from from A-Z, a-z, or _.
    \edef\pgfmath@function{\pgfmath@function#1}%
    \let\pgfmath@parse@next=\pgfmath@parse@function@%
  \fi%
  \pgfmath@parse@next}

\def\pgfmath@parse@@@@function{%
  \expandafter\ifx\csname pgfmath@function@\pgfmath@function\endcsname\relax%
    \pgfmath@error{Unknown function `\pgfmath@function'}{}%
    \def\pgfmathresult{0}%
    \let\pgfmath@parse@next=\pgfmath@parse@end%
  \else%
    \expandafter\ifnum\csname pgfmath@operation@\pgfmath@function @arity\endcsname=0\relax%
     % Functions with zero arity are called directly.
      \csname pgfmath\pgfmath@function @\endcsname%
      \expandafter\pgfmath@stack@push@operand\expandafter{\pgfmathresult}%
      \let\pgfmath@parse@next=\pgfmath@parse@@operator%
    \else% Otherwise, they are pushed onto the operator stack
      \expandafter\pgfmath@stack@push@operation\expandafter{\pgfmath@function}%
      \let\pgfmath@parse@next=\pgfmath@parse@@operand%
    \fi%
  \fi%
  \expandafter\pgfmath@parse@next\pgfmath@token}

% Parse an operator.
%
\def\pgfmath@parse@operator{\pgfmath@parse@ifbgroup{\pgfmath@parse@operator}{\pgfmath@parse@operator@}}%
\def\pgfmath@parse@operator@#1{% Get one token.
  \let\pgfmath@token=\pgfmath@token@next%
  \def\pgfmath@token@next{#1}%
  \pgfmath@parse@@@operator}

\def\pgfmath@parse@@operator{\pgfmath@parse@ifbgroup{\pgfmath@parse@@operator}{\pgfmath@parse@@operator@}}%
\def\pgfmath@parse@@operator@#1{% Get first token...
  \def\pgfmath@token{#1}%
  \pgfmath@parse@ifbgroup{\pgfmath@parse@@operator@@}{\pgfmath@parse@@operator@@}}%
\def\pgfmath@parse@@operator@@#1{% ...and second token.
  \def\pgfmath@token@next{#1}%
  \pgfmath@parse@@@operator}  

\def\pgfmath@parse@@@operator{%
  \expandafter\ifx\csname pgfmath@operator@\pgfmath@token\expandafter\string\pgfmath@token@next\endcsname\relax%
    % Not a double character operator.
    \expandafter\ifx\csname pgfmath@operator@\pgfmath@token\endcsname\relax%
      % Not a single character operator.
      \pgfmath@error{Unknown operator `\pgfmath@token' or `\pgfmath@token\pgfmath@token@next'}{}%
      \def\pgfmathresult{0}%
    \let\pgfmath@parse@next=\pgfmath@parse@end%
    \else%
      \expandafter\pgfmath@operation@process\expandafter{\pgfmath@token}%
      \ifx\pgfmath@token\pgfmath@text@@%
        \let\pgfmath@parse@next=\pgfmath@parse@end%
      \else%
        \expandafter\ifx\csname pgfmath@operation@\pgfmath@token @postfix\endcsname\pgfmath@token%
          % Postfix operators are followed by an operator.
          \ifx\pgfmath@token@next\pgfmath@char@leftbracket% Except [.
            \let\pgfmath@parse@next=\pgfmath@parse@operand%
          \else%
            \let\pgfmath@parse@next=\pgfmath@parse@operator%
          \fi%
        \else%
          % Any other operator is followed by an operand.
          \let\pgfmath@parse@next=\pgfmath@parse@operand%
        \fi%
      \fi%
    \fi%
  \else%
    % A double character operator...
    \expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter%
      \pgfmath@token\expandafter\expandafter\expandafter%
        {\expandafter\pgfmath@token\pgfmath@token@next}%
    \expandafter\pgfmath@operation@process\expandafter{\pgfmath@token}%
    % ...is always followed by an operand.
    \let\pgfmath@parse@next=\pgfmath@parse@@operand%
  \fi%
  \pgfmath@parse@next%
}


% Process an operation.
%
\def\pgfmath@operation@process#1{%
  \def\pgfmath@operator{#1}%
  \ifx\pgfmath@stack@operation@top\pgfmath@stack@empty%
  \else%
    \pgfmath@operation@@process%
  \fi%
  \expandafter\ifx\csname pgfmath@token@specials@#1\endcsname\relax%
    \pgfmath@stack@push@operation{#1}%
  \fi%
}

% Process the operation stack.
%
\def\pgfmath@operation@@process{%
  \ifx\pgfmath@stack@operation@top\pgfmath@stack@empty%
    \let\pgfmath@parse@next=\relax%
  \else%
    \ifnum\csname pgfmath@operation@\pgfmath@operator @precedence\endcsname>%
      \csname pgfmath@operation@\pgfmath@stack@operation@top @precedence\endcsname\relax%
      % If the precedence of the scanned operator is greater than the
      % precedence of the operator at the top of the stack, do nothing.
      \let\pgfmath@parse@next=\relax%
    \else%
      \let\pgfmath@stack@operation@last=\pgfmath@stack@operation@top%
      \expandafter\ifx\csname pgfmath@operator@\pgfmath@stack@operation@top\endcsname\relax%
        \pgfmath@function@@@process%
      \else%
        \pgfmath@operator@@@process%
      \fi%
      \expandafter\pgfmath@stack@push@operand\expandafter{\pgfmathresult}%
      \expandafter\ifx\csname pgfmath@token@group@\pgfmath@stack@operation@last\pgfmath@operator\endcsname\relax%
        \let\pgfmath@parse@next=\pgfmath@operation@@process%
      \else%
        \let\pgfmath@parse@next=\relax%
      \fi%
    \fi%
  \fi%
  \pgfmath@parse@next%
}

% Process an operator.
%
\def\pgfmath@operator@@@process{% Process an operator.
  \pgfmath@stack@pop@operation\pgfmath@@operator%
  \pgfmath@stack@pop@operand\pgfmath@operand@a%  
  \ifcase\csname pgfmath@operation@\pgfmath@@operator @arity\endcsname\relax%
    % Zero arity operators (!).
  \or%    
    \pgfmath@operator@@@@process{\pgfmath@operand@a}%
  \or%
    \pgfmath@stack@pop@operand\pgfmath@operand@b%
    \pgfmath@operator@@@@process{\pgfmath@operand@b}{\pgfmath@operand@a}%
  \or%
    \pgfmath@stack@pop@operand\pgfmath@operand@b%
    \expandafter\pgfmath@operator@@@@process\expandafter%
      {\expandafter\pgfmath@operand@b\expandafter}\pgfmath@operand@a%    
  \else%
    % No operators with more than tenary arity.
  \fi%
}

\def\pgfmath@operator@@@@process{%
  \csname pgfmath%
    \csname pgfmath@operation@\pgfmath@@operator @name\endcsname%
  @\endcsname}

% Process a function.
%
\def\pgfmath@function@@@process{% Process a function.
  \ifnum\csname pgfmath@operation@\pgfmath@stack@operation@top @arity\endcsname>0\relax%
    \pgfmath@stack@pop@operation\pgfmath@@function%
    \pgfmath@stack@pop@operand\pgfmath@@operand%
    \ifnum\csname pgfmath@operation@\pgfmath@@function @arity\endcsname>1\relax%
      \ifnum\csname pgfmath@operation@\pgfmath@@function @arity\endcsname>9\relax%
        \csname pgfmath\pgfmath@@function @\endcsname{\pgfmath@@operand}%
      \else%
        \expandafter\pgfmath@function@@@@process\pgfmath@@operand%
      \fi
    \else%
      \expandafter\pgfmath@function@@@@process\expandafter{\pgfmath@@operand}%
    \fi%
  \fi%    
}

\def\pgfmath@function@@@@process{\csname pgfmath\pgfmath@@function @\endcsname}

% Stack.
%
\newtoks\pgfmath@stack@operand
\newtoks\pgfmath@stack@operation
\let\pgfmath@stack@empty=\pgfmath@empty

\def\pgfmath@stack@push#1#2{%
  \def\pgfmath@stack@top{#2}%
  \expandafter\expandafter\expandafter#1%
    \expandafter\expandafter\expandafter{\expandafter\expandafter\expandafter%
      {\expandafter\pgfmath@stack@top\expandafter}\the#1}}%

\def\pgfmath@stack@pop#1#2{\expandafter\pgfmath@stack@@pop\the#1\pgfmath@stack@stop{#1}{#2}}
\def\pgfmath@stack@@pop#1#2#3\pgfmath@stack@stop#4#5{\def#5{#1}#4={{#2}#3}\def\pgfmath@stack@top{#2}}

\def\pgfmath@stack@push@operation#1{%
  \pgfmath@stack@push\pgfmath@stack@operation{#1}%
  \let\pgfmath@stack@operation@top=\pgfmath@stack@top}

\def\pgfmath@stack@pop@operation#1{%
  \pgfmath@stack@pop\pgfmath@stack@operation{#1}%
  \let\pgfmath@stack@operation@top=\pgfmath@stack@top}
  
% REMARK: This method will be overwritten by the FPU library. Please
% keep any changes consistent.
\def\pgfmath@stack@push@operand#1{%
  \pgfmath@stack@push\pgfmath@stack@operand{#1}%
  \let\pgfmath@stack@operand@top=\pgfmath@stack@top}

\def\pgfmath@stack@pop@operand#1{%
  \pgfmath@stack@pop\pgfmath@stack@operand{#1}%
  \let\pgfmath@stack@operand@top=\pgfmath@stack@top}
  

% Declare an operator for the parser.
%
% It is not recommended that new operators be created as 
% the parser is not fully robust for arbitrary operators.
%
\def\pgfmathdeclareoperator#1#2#3#4#5{%
  \ifx\pgfmath@operatorlist\pgfutil@empty
    \edef\pgfmath@operatorlist{{\string#1}}%
  \else
    \edef\pgfmath@operatorlist{\pgfmath@operatorlist,{\string#1}}%
  \fi
  \pgfmath@namedef{pgfmath@operator@\string#1}{#1}%
  \pgfmath@namedef{pgfmath@operation@\string#1@name}{#2}%
  \pgfmath@namedef{pgfmath@operation@\string#1@arity}{#3}%
  \pgfmath@namedef{pgfmath@operation@\string#1@#4}{#1}%
  \pgfmath@namedef{pgfmath@operation@\string#1@precedence}{#5}%
}

\def\pgfmath@operatorlist{}

\pgfmathdeclareoperator{+}{add}     {2}{infix}{500}
\pgfmathdeclareoperator{-}{subtract}{2}{infix}{500}
\pgfmathdeclareoperator{*}{multiply}{2}{infix}{700}
\pgfmathdeclareoperator{/}{divide}  {2}{infix}{700}
\pgfmathdeclareoperator{^}{pow}     {2}{infix}{900}

\pgfmathdeclareoperator{<} {}       {1}{prefix} {1}

\pgfmathdeclareoperator{>} {greater}   {2}{infix} {250}
\pgfmathdeclareoperator{<} {less}      {2}{infix} {250}
\pgfmathdeclareoperator{==}{equal}     {2}{infix} {250}
\pgfmathdeclareoperator{>=}{notless}   {2}{infix} {250}
\pgfmathdeclareoperator{<=}{notgreater}{2}{infix} {250}
\pgfmathdeclareoperator{&&}{and}       {2}{infix} {200}
\pgfmathdeclareoperator{||}{or}        {2}{infix} {200}
\pgfmathdeclareoperator{!=}{notequal}  {2}{infix} {250}
\pgfmathdeclareoperator{!} {not}       {1}{prefix}{975}
\pgfmathdeclareoperator{?} {ifthenelse}{3}{infix} {100}
\pgfmathdeclareoperator{:} {@@collect}  {2}{infix}{101}

\pgfmathdeclareoperator{!}{factorial}{1}{postfix}{800}% Must be defined after prefix ! operator.
\pgfmathdeclareoperator{r}{deg}      {1}{postfix}{600}

\pgfmathdeclareoperator{,}{@collect}   {2}{infix}  {10}
\pgfmathdeclareoperator{[}{@startindex}{2}{prefix} {7}
\pgfmathdeclareoperator{]}{@endindex}  {0}{postfix}{6}
\pgfmathdeclareoperator{(}{@startgroup}{1}{prefix} {5}
\pgfmathdeclareoperator{)}{@endgroup}  {0}{postfix}{4}

\pgfmathdeclareoperator{\pgfmath@bgroup}{@startarray}{1}{prefix} {3}
\pgfmathdeclareoperator{\pgfmath@egroup}{@endarray}  {1}{postfix}{2}% 

% Special operators.
\pgfmathdeclareoperator{"}{}{1}{prefix}{1}
\pgfmathdeclareoperator{@}{}{0}{postfix}{0}

% Internal functions.

% Begin and end parenthesis ().
%
\def\pgfmath@startgroup@#1{\edef\pgfmathresult{#1}}
\def\pgfmath@endgroup@{}% Never actually called.

% Begin and end array access [].
%
\def\pgfmath@startindex@#1#2{%
  \expandafter\pgfmatharray@#1{#2}%
  \expandafter\pgfmath@bgroup@strip\expandafter{\pgfmathresult}%
  \ifx\pgfmath@token@let\bgroup%
    \expandafter\def\expandafter\pgfmathresult\expandafter{\expandafter{\pgfmathresult}}%
  \fi}
\def\pgfmath@endindex@{}% Never actually called.

% Begin and end array {}.
%
\def\pgfmath@startarray@#1{\expandafter\def\expandafter\pgfmathresult\expandafter{\expandafter{#1}}}
\def\pgfmath@endarray@#1{\expandafter\def\expandafter\pgfmathresult\expandafter{#1}}% Never actually called.


\def\pgfmath@@collect@#1#2{%
  \expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter%
    \pgfmathresult\expandafter\expandafter\expandafter{\expandafter\expandafter\expandafter%
      {\expandafter#1\expandafter}\expandafter{#2}}%
}
% Collect items separated by ,.
%
\def\pgfmath@collect@#1#2{%
  \expandafter\def\expandafter\pgfmath@collect@original\expandafter{#1}%
  \expandafter\pgfmath@bgroup@strip\expandafter{#1}%
  \ifx\pgfmath@token@let\bgroup%
    \ifx\pgfmath@collect@original\pgfmath@bgroup@stripped%
      \expandafter\def\expandafter\pgfmathresult\expandafter{\pgfmath@bgroup@stripped}%
    \else%
      \expandafter\def\expandafter\pgfmathresult\expandafter{\expandafter{\pgfmath@bgroup@stripped}}%
    \fi%
  \else%
    \expandafter\def\expandafter\pgfmathresult\expandafter{\expandafter{\pgfmath@bgroup@stripped}}%
  \fi%
  \expandafter\pgfmath@bgroup@strip\expandafter{#2}%
  \expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter%
    \pgfmathresult\expandafter\expandafter\expandafter%
      {\expandafter\pgfmathresult\expandafter{\pgfmath@bgroup@stripped}}%
}

% Strip braces from a token sequence.
%
\def\pgfmath@bgroup@strip#1{%
  \def\pgfmath@bgroup@strip@last{#1}%
  \pgfmath@bgroup@@strip{#1}\pgfmath@\pgfmath@@\pgfmath@@@}

\def\pgfmath@bgroup@strip@#1{%
  \def\pgfmath@bgroup@strip@last{#1}%
  \pgfmath@bgroup@@strip#1\pgfmath@\pgfmath@@\pgfmath@@@}

\def\pgfmath@bgroup@pgfmath@{\pgfmath@}

\def\pgfmath@bgroup@@strip{%
  \futurelet\pgfmath@token@let\pgfmath@bgroup@@@strip}

\def\pgfmath@bgroup@@@strip#1#2#3\pgfmath@@@{%
  \ifx\pgfmath@token@let\bgroup
    \def\pgfmath@bgroup@test{#2}%
    \ifx\pgfmath@bgroup@test\pgfmath@bgroup@pgfmath@
      \def\pgfmath@next{\pgfmath@bgroup@strip@{#1}}%
    \else
      \let\pgfmath@bgroup@stripped=\pgfmath@bgroup@strip@last
      \let\pgfmath@next=\relax
    \fi
  \else
    \pgfmath@bgroup@@@@strip#1#2#3%
    \let\pgfmath@next=\relax
  \fi
  \pgfmath@next}

\def\pgfmath@bgroup@@@@strip#1\pgfmath@\pgfmath@@{%
  \def\pgfmath@bgroup@stripped{#1}}

% Local Variables:
% tab-width: 2
% End:
pgfmathutil.code.tex
% Copyright 2007 Mark Wibrow
%
% but subject to the LaTeX Project Public License 
% (http://www.latex-project.org/lppl.txt)
%
% and the GNU Public License 
% (http://www.gnu.org/licenses/gpl.txt)
%

% This file defines utilities common to the \pgfmath files.
%
% Version 1.414213 29/9/2007

\def\pgfmathincluded{}

% \pgfmath@ensureregister
%
% Ensure a control sequence exists as a TeX count/dimen register.
%
% #1 - count or dimen.
% #2 - a control sequence.
%
\def\pgfmath@ensureregister#1#2{%
	\begingroup%
	\setbox0=\hbox\bgroup\begingroup% In case #2 is a defined macro. Unlikely, but you never know...
		\afterassignment\pgfmath@@ensureregister%
		\noexpand#20.0pt\let\pgfmath@temp\relax\relax\pgfmath@#2#1\pgfmath@}

\def\pgfmath@@ensureregister#1#2\pgfmath@#3#4#5\pgfmath@{%
		\endgroup\egroup%
	\endgroup%
	\ifx#4c% 
		\ifx#1.% Already a count register.
		\else%
			\csname newcount\endcsname#3% This gets round \outer in plain TeX.
		\fi%
	\else%
		\ifx#4d% 
			\ifx\let#1% Already a dimen register.
			\else%
				\csname newdimen\endcsname#3%
			\fi%
		\fi%
	\fi%
}

% Check registers exist. If not, create them. 
%
\pgfmath@ensureregister{dimen}{\pgf@x}
\pgfmath@ensureregister{dimen}{\pgf@xa}
\pgfmath@ensureregister{dimen}{\pgf@xb}
\pgfmath@ensureregister{dimen}{\pgf@xc}

\pgfmath@ensureregister{dimen}{\pgf@y}
\pgfmath@ensureregister{dimen}{\pgf@ya}
\pgfmath@ensureregister{dimen}{\pgf@yb}
\pgfmath@ensureregister{dimen}{\pgf@yc}

\pgfmath@ensureregister{dimen}{\pgfutil@tempdima}
\pgfmath@ensureregister{dimen}{\pgfutil@tempdimb}

\pgfmath@ensureregister{count}{\c@pgf@counta}
\pgfmath@ensureregister{count}{\c@pgf@countb}
\pgfmath@ensureregister{count}{\c@pgf@countc}
\pgfmath@ensureregister{count}{\c@pgf@countd}

\pgfmath@ensureregister{count}{\pgfutil@tempcnta}
\pgfmath@ensureregister{count}{\pgfutil@tempcntb}

% Alias for \pgfmath.
%
\let\pgfmath@x\pgf@x
\let\pgfmath@xa\pgf@xa
\let\pgfmath@xb\pgf@xb
\let\pgfmath@xc\pgf@xc

\let\pgfmath@y\pgf@y
\let\pgfmath@ya\pgf@ya
\let\pgfmath@yb\pgf@yb
\let\pgfmath@yc\pgf@yc

\let\pgfmath@tempdima\pgfutil@tempdima
\let\pgfmath@tempdimb\pgfutil@tempdimb

\let\c@pgfmath@counta\c@pgf@counta
\let\c@pgfmath@countb\c@pgf@countb
\let\c@pgfmath@countc\c@pgf@countc
\let\c@pgfmath@countd\c@pgf@countd

\let\pgfmath@tempcnta\pgfutil@tempcnta
\let\pgfmath@tempcntb\pgfutil@tempcntb

% Now check if pgfutil and pgf@sys stuff exists. If it does, fine.
% Just \let pgfmath versions. If not, define pgfmath versions (Arghhh). 
%

% \...ifnextchar
%
\ifx\pgfutil@ifnextchar\pgfmath@undefined%
	\long\def\pgfmath@ifnextchar#1#2#3{%
  \let\pgfmath@reserved@d#1%
  \def\pgfmath@reserved@a{#2}%
  \def\pgfmath@reserved@b{#3}%
  \futurelet\pgfmath@let@token\pgfmath@ifnch}
	\def\pgfmath@ifnch{%
	  \ifx\pgfmath@let@token\pgfmath@sptoken%
	    \let\pgfmath@reserved@c\pgfmath@xifnch%
	  \else%
	    \ifx\pgfmath@let@token\pgfmath@reserved@d%
	      \let\pgfmath@reserved@c\pgfmath@reserved@a%
	    \else%
	      \let\pgfmath@reserved@c\pgfmath@reserved@b%
	    \fi%
	  \fi%
	  \pgfmath@reserved@c}
	{%
	  \def\:{\global\let\pgfmath@sptoken= } \:
	  \def\:{\pgfmath@xifnch} \expandafter\gdef\: {\futurelet\pgfmath@let@token\pgfmath@ifnch}
	}%
\else%
	\let\pgfmath@ifnextchar\pgfutil@ifnextchar%
	% Still need to define \pgfmath@sptoken (cannot \let).
	{%
		\def\:{\global\let\pgfmath@sptoken= } \:
	}%
\fi%

% \...ifundefined
%
\ifx\pgfutil@ifundefined\pgfmath@undefined%
	\long\def\pgfmath@ifundefined#1{%
	  \expandafter\ifx\csname#1\endcsname\relax%
	    \expandafter\pgfmath@firstoftwo%
	  \else%
	    \expandafter\pgfmath@secondoftwo%
	  \fi}%
\else%
	\let\pgfmath@ifundefined\pgfutil@ifundefined%
\fi%

% \...selectfont
%
\ifx\pgfutil@selectfont\pgfmath@undefined%
	\ifx\selectfont\pgfmath@undefined%
		\let\pgfmath@selectfont\rm% Plain TeX and ConTeXt.
	\else%
		\let\pgfmath@selectfont\selectfont% LaTeX.
	\fi%
\else%
	\let\pgfmath@selectfont\pgfutil@selectfont%
\fi%

% New definition easier than fussing around with let.
%
\newif\ifpgfmath@in@
\def\pgfmath@in@#1#2{%
 \def\pgfmath@in@@##1#1##2##3\pgfmath@in@@{%
  \ifx\pgfmath@in@##2\pgfmath@in@false\else\pgfmath@in@true\fi}%
 \pgfmath@in@@#2#1\pgfmath@in@\pgfmath@in@@}


% \...tonumber
%
\ifx\pgf@sys@tonumber\pgfmath@undefined%
  {\catcode`\p=12\catcode`\t=12\gdef\Pgf@geT#1pt{#1}}
	\def\pgfmath@tonumber#1{\expandafter\Pgf@geT\the#1}
\else%
	\let\pgfmath@tonumber\pgf@sys@tonumber%
\fi%


% \PackageWarning and \PackageError
%
\ifx\PackageWarning\pgfmath@undefined
	\def\pgfmath@PackageWarning#1#2{\immediate\write-1{Package #1: Warning! #2.}}%
\else%
	\let\pgfmath@PackageWarning\PackageWarning%
\fi%
\ifx\PackageError\pgfmath@undefined
	\def\pgfmath@PackageError#1#2#3{\errmessage{Package #1 Error: #2.}}%
\else%
	\let\pgfmath@PackageError\PackageError%
\fi%

\def\pgfmath@error#1#2{%
	\pgfmath@PackageError{PGF Math}{%
		#1%
		\pgfutil@ifundefined{pgfmath@expression}{}{ (in '\pgfmath@expression')}%
	}{#2}%
}
\def\pgfmath@warning#1{%
	\pgfmath@PackageWarning{PGF Math}{%
		#1%
		\pgfutil@ifundefined{pgfmath@expression}{}{ (in '\pgfmath@expression')}%
	}%
}

% \pgfmath@pt
%
% Needed to test for 'pt' resulting from expansion using \the.
%
{\catcode`\p=12\catcode`\t=12\gdef\PgfmaTh@PT{pt}}		
\edef\pgfmath@pt{\PgfmaTh@PT}%

% \pgfmath@empty
%
% A handy macro.
%
\def\pgfmath@empty{}

\def\pgfmath@firstoftwo#1#2{#1}
\def\pgfmath@secondoftwo#1#2{#2}

% \pgfmath@gobbletilpgfmath@
%
% Gobble stream until \pgfmath@ {which is undefined}.
% 
\def\pgfmath@gobbletilpgfmath@#1\pgfmath@{}
\def\pgfmath@gobbleone#1{}%


\def\pgfmath@namedef#1{\expandafter\def\csname#1\endcsname}
\def\pgfmath@nameedef#1{\expandafter\edef\csname#1\endcsname}

% \pgfmathloop
%
% A version of the standard TeX and LaTeX
% \loop, with an additional macro \pgfmathcounter
% (which is *not* a TeX counter) which keeps
% track of the iterations.
%
\newif\ifpgfmathcontinueloop
\def\pgfmathloop#1\repeatpgfmathloop{%
	\def\pgfmathcounter{1}%
	\def\pgfmath@iterate{%
		#1\relax%
		{% Do this inside a group, just in case...
			\c@pgfmath@counta\pgfmathcounter%
			\advance\c@pgfmath@counta1\relax%
			\xdef\pgfmathloop@temp{\the\c@pgfmath@counta}%
		}%	
		\edef\pgfmathcounter{\pgfmathloop@temp}%
		\expandafter\pgfmath@iterate\fi}%
	\pgfmath@iterate\let\pgfmath@iterate\relax}
\let\repeatpgfmathloop\fi
\def\pgfmathbreakloop{\let\pgfmath@iterate\relax}%

% \pgfmath@returnone
%
% #1 - a dimension representing a number or dimension.
%
% Changed by TT: made faster and simpler since it is used
% *heavily*. #1 must be something that can be assigned to a
% dimension. 
%
\def\pgfmath@returnone#1\endgroup{%
  \pgfmath@x#1%
  \edef\pgfmath@temp{\pgfmath@tonumber{\pgfmath@x}}%
  \expandafter\endgroup\expandafter\def\expandafter\pgfmathresult\expandafter{\pgfmath@temp}%
}

\let\pgfmathreturn=\pgfmath@returnone

% \pgfmath@smuggleone
%
% Smuggle a macro outside a group.
%
% Changed by TT: Speedup by insisting, that smuggleone is directly
% followed by \endgroup
%
\def\pgfmath@smuggleone#1\endgroup{%
  \expandafter\endgroup\expandafter\def\expandafter#1\expandafter{#1}}  

\let\pgfmathsmuggle=\pgfmath@smuggleone

pgfmoduledecorations.code.tex
% Copyright 2008 by Mark Wibrow and Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.


% The following naming conventions are (more or less) observed:
%
% `decorated'  : the path that is being decorated.
% `decoration' : any path created/left by the automaton
% `decorate'   : generic use where distinction is probably unimportant
%                (e.g. internal macros).



% These should be moved.
%
\def\pgfgetpath#1{\pgfsyssoftpath@getcurrentpath{#1}}
\def\pgfsetpath#1{\pgfsyssoftpath@setcurrentpath{#1}}


% Required registers.
%
\newdimen\pgfdecoratedcompleteddistance
\newdimen\pgfdecoratedremainingdistance
\newdimen\pgfdecoratedinputsegmentcompleteddistance
\newdimen\pgfdecoratedinputsegmentremainingdistance
\newdimen\pgf@decorate@distancetomove

\newcount\pgf@decorate@repeatstate


% Extra options used in all libraries

\newdimen\pgfdecorationsegmentamplitude
\newdimen\pgfdecorationsegmentlength
\pgfdecorationsegmentamplitude2.5pt
\pgfdecorationsegmentlength10pt
\def\pgfdecorationsegmentangle{45}
\def\pgfdecorationsegmentaspect{0.5}
\def\pgfmetadecorationsegmentamplitude{2.5pt}  
\def\pgfmetadecorationsegmentlength{1cm}

\pgfkeys{%
  /pgf/decoration/.code={\pgfkeys{/pgf/decoration/.cd,#1}},
  /pgf/decoration/.cd,
  amplitude/.code={\pgfmathsetlength\pgfdecorationsegmentamplitude{#1}},
  meta-amplitude/.store in=\pgfmetadecorationsegmentamplitude,
  segment length/.code={\pgfmathsetlength\pgfdecorationsegmentlength{#1}},
  meta-segment length/.store in=\pgfmetadecorationsegmentlength,
  angle/.code={\pgfmathparse{#1}\let\pgfdecorationsegmentangle\pgfmathresult},
  aspect/.code={\pgfmathparse{#1}\let\pgfdecorationsegmentaspect\pgfmathresult},
  start radius/.initial=2.5pt,
  end radius/.initial=2.5pt,
  radius/.style={start radius=#1,end radius=#1},
  path has corners/.is if=pgfdecoratepathhascorners,
  reverse path/.is if=pgf@decorate@inputsegmentobjects@reverse
} 
\newif\ifpgfdecoratepathhascorners
\newif\ifpgf@decorate@inputsegmentobjects@reverse

% Declare a decoration
%
% #1 = name of the decoration
% #2 = initial state
% #3 = states
%
% This command declares a new decoration for later use.
% Inside the code of #3 the command \state may be used. This command
% will only be defined while #3 is executed.
%
% Example:
%
% \pgfdeclaredecoration{zigzag}{q}
% {
%   \state{q}[width=10pt]
%   {
%     \pgfpathlineto{\pgfpoint{2.5pt}{2.5pt}}
%     \pgfpathlineto{\pgfpoint{7.5pt}{-2.5pt}}
%     \pgfpathlineto{\pgfpoint{10pt}{0pt}}
%   }
%   \state{final}
%   {
%     \pgfpathlineto{\pgfpointdecoratedpathlast}
%   }
% }

\long\def\pgfdeclaredecoration#1#2#3{%
  \let\pgf@mod@dec@next=\pgf@mod@dec@firstofone%
  \pgfifmetadecoration{#1}{%
    \pgferror{You cannot declare a decoration of the same
      name as a meta-decoration}%
    \let\pgf@mod@dec@next=\pgfutil@gobble%
  }{}%
  \pgf@mod@dec@next
  {%
    \def\pgf@decorate@name{#1}%
    \pgfutil@namedef{pgf@decorate@@#1@initial}{#2}%
    \let\pgf@orig@state\state%
    \let\state\pgf@decorate@state
    #3%
    \let\state\pgf@orig@state%
  }%
}

\def\pgf@decorate@state#1{\pgfutil@ifnextchar[{\pgf@decorate@@start#1}{\pgf@decorate@@start#1[]}}%}
\def\pgf@decorate@@start#1[#2]#3{%
  \pgfutil@namedef{pgf@decorate@@\pgf@decorate@name @#1@options}{#2}%
  \pgfutil@namedef{pgf@decorate@@\pgf@decorate@name @#1@code}{#3}%
}
\long\def\pgf@mod@dec@firstofone#1{#1}


% Test whether something is a decoration
%
% #1 = name
% #2 = if-code
% #3 = else-code
%
% Example:
%
% \pgfifdecoration{zigzag}{Exists}{Does not exist}

\def\pgfifdecoration#1#2#3{\pgfutil@ifundefined{pgf@decorate@@#1@initial}{#3}{#2}}



% Declare a meta decoration
%
% #1 = name of the meta decoration
% #2 = initial state
% #3 = states
%
% This command declares a new meta decoration for later use.
% Inside the code of #3 the command \state may be used.

\long\def\pgfdeclaremetadecoration#1#2#3{%
  \let\pgf@mod@dec@next=\pgf@mod@dec@firstofone%
  \pgfifdecoration{#1}{%
    \pgferror{You cannot declare a meta-decoration of the
      same name as a decoration}%
    \let\pgf@mod@dec@next=\pgfutil@gobble%
  }{}%
  \pgf@mod@dec@next{%
    \def\pgf@metadecoration@name{#1}%
    \pgfutil@namedef{pgf@metadecoration@@#1@initial}{#2}%
    \let\pgf@orig@state\state%
    \let\state\pgf@metadecoration@state
    #3%
    \let\state\pgf@orig@state%
  }%
}

\def\pgf@metadecoration@state#1{\pgfutil@ifnextchar[{\pgf@metadecoration@@state#1}{\pgf@metadecoration@@state#1[]}}%}
\def\pgf@metadecoration@@state#1[#2]#3{%
  \pgfutil@namedef{pgf@metadecoration@@\pgf@metadecoration@name @#1@options}{#2}%
  \pgfutil@namedef{pgf@metadecoration@@\pgf@metadecoration@name @#1@code}{#3}%
}


% Test whether something is a meta-decoration
%
% #1 = name
% #2 = if-code
% #3 = else-code
%
% Example:
%
% \pgfifmetadecoration{zigzag}{Exists}{Does not exist}

\def\pgfifmetadecoration#1#2#3{\pgfutil@ifundefined{pgf@metadecoration@@#1@initial}{#3}{#2}}





\let\pgfdecoratebeforecode\pgfutil@empty
\let\pgfdecorateaftercode\pgfutil@empty

% \pgfdecoratepath
%
% Decorate a path.
%
% \pgfdecoratebeforecode and \pgfdecorateaftercode can be used to 
% execute code before and after the decoration.
% 
% #1 - the name of the decoration.
% #2 - a (non-empty) path specification.
%
% Example:
%
%  \pgfdeclaredecoration{circles}{red circles}{
%    \state{red circles}[width=10pt, repeat state=2, next state=blue circles]
%    {
%      \pgfmathparse{round(rnd*100)}
%      \pgfsetstrokecolor{red!\pgfmathresult!brown}
%      \pgfsetfillcolor{orange!\pgfmathresult!yellow}
%      \pgfpathcircle{\pgfpointorigin}{2.5pt}
%      \pgfusepath{stroke,fill}
%    }
%    \state{blue circles}[width=10pt, repeat state=1, next state=red circles]
%    {
%      \pgfmathparse{round(rnd*100)}
%      \pgfsetstrokecolor{blue!\pgfmathresult!gray}
%      \pgfsetfillcolor{blue!\pgfmathresult!white}
%      \pgfpathcircle{\pgfpointorigin}{2.5pt}
%      \pgfusepath{stroke,fill}
%    }
%    \state{final}{}
%  }  
%  
%  \pgfpicture
%    \pgfdecoratepath{circles}
%    {
%      \pgfpathmoveto{\pgfpointorigin}
%      \pgfpathcurveto{\pgfpoint{0cm}{3cm}}{\pgfpoint{4cm}{0cm}}{\pgfpoint{4cm}{3cm}}
%    }
%  \endpgfpicture
%
\long\def\pgfdecoratepath#1#2{%
  \pgfdecoration{{#1}{\pgfdecoratedpathlength}{\pgfdecoratebeforecode}{\pgfdecorateaftercode}}%
  #2%
  \endpgfdecoration}




% \pgfdecoratecurrentpath
%
% Decorate the current/existing path, but (unavoidably) destroys it.
% 
% \pgfdecoratebeforecode and \pgfdecorateaftercode can be used to 
% execute code before and after the decoration.
%
% #1 - the name of the decoration.
%
% Example:
%
%  \pgfdeclaredecoration{stars}{move}{
%    \state{move}[width=7.5pt, next state=star]{}
%    \state{star}[width=7.5pt, next state=move]
%    {
%      \pgfmathparse{round(rnd*100)}
%      \pgfsetfillcolor{yellow!\pgfmathresult!orange}
%      \pgfsetstrokecolor{yellow!\pgfmathresult!red}
%      \pgfmathparse{rnd*.75+.25}
%      \pgftransformscale{\pgfmathresult}
%      \pgfnode{star}{center}{}{}{\pgfusepath{stroke,fill}}
%    }
%    \state{final}
%    {
%      \pgfpathmoveto{\pgfpointdecoratedpathlast}
%    }
%  }
%
%  \pgfpicture
%    \pgfpathmoveto{\pgfpointorigin}
%    \pgfpathcurveto{\pgfqpoint{0cm}{2cm}}{\pgfqpoint{3cm}{2cm}}{\pgfqpoint{3cm}{0cm}}
%    \pgfpathcurveto{\pgfqpoint{3cm}{-3cm}}{\pgfqpoint{0cm}{0cm}}{\pgfqpoint{0cm}{-3cm}}
%    \pgfpathcurveto{\pgfqpoint{0cm}{-5cm}}{\pgfqpoint{3cm}{-5cm}}{\pgfqpoint{3cm}{-3cm}}
%    \pgfdecoratecurrentpath{stars}
%  \endpgfpicture
%
\def\pgfdecoratecurrentpath#1{%
  \pgfgetpath\pgf@decorate@currentpath%
  \pgfsetpath\pgfutil@empty%
  \pgfdecoration{{#1}{\pgfdecoratedpathlength}{\pgfdecoratebeforecode}{\pgfdecorateaftercode}}%
    \pgfsetpath\pgf@decorate@currentpath%
  \endpgfdecoration}




% Environment \pgfdecoration \endpgfdecoration
%
% Decorates a path with multiple decorations.
%
% Definitions:
%
% `existing path' 
%    - any unsed path exsiting prior to the environment.
%
% `decorated path'
%   - the path that is being decorated.
%
%  `decoration path'
%    - any unused path left by the decoration automaton.
%
% The action of the environment is as follows:
%
%  1. Any existing path is saved.
%  2. Construction commands are executed forming the decorated path.
%  3. If the first command in the decorated path is not a `move to',
%    the last known position from the exisiting path is inserted.
%  4. The saved existing path is reinstalled. 
%  5. The decoration automaton is executed along the decorated path.
%  
% Parameters:
%
% #1 - a comma separated list of decoration specifications.
% 
% A decoration specification takes the format:
%
% {<name>}{<distance>}{<before code>}{<after code>}
%
% The decoration <name> is applied to a section of the decorated
% path from the last point on the decorated path the decoration 
% automaton reached to <distance> from that point.
% 
% When <distance>} is parsed, the dimension 
% \pgfdecoratedreminingdistance holds the distance remaining on the
% entire decorated path, and the macro \pgfdecoratedpathlength holds
% the total length of the entire decorated path. 
% After <distance> is parsed, both are set to to the value of 
% <distance> for the automaton to decorate current section of the 
% decorated path.
%
% <before code> is executed just before the decoration automaton
% starts and <after code> is executed just after the automaton stops.
% If <before code> or <after code> are empty, they can be omitted.
%  The macros \pgfdecoratedpathfirst and \pgfdecoratedpathlast
% will be set up as the first and last points on the current section
% of the decorated path.
%
% When the environment exits, the following macros will be set up:
%
%  \pgfdecorateexistingpath
%    - the existing path.
%
%  \pgfdecoratedpath
%    - the decorated path.
%
%  \pgfdecorationpath
%    - any unused decoration path.
%
%  \pgfpointdecoratedpathlast 
%   - the last point on the decorated path.
%
% Examples (require pgfdecorations library):
%
%  \pgfpicture
%  \pgfdecoration
%    {
%      {lineto}{\pgfdecoratedpathlength/3},
%      {zigzag}{\pgfdecoratedpathlength/3},
%      {lineto}{\pgfdecoratedpathlength/3}
%    }
%    \pgfpathmoveto{\pgfpointorigin}
%    \pgfpathcurveto{\pgfpoint{0cm}{4cm}}{\pgfpoint{5cm}{0cm}}{\pgfpoint{5cm}{4cm}}
%  \endpgfdecoration
%  \pgfusepath{stroke}
%  \endpgfpicture 
%  
%  
%  \pgfpicture
%  \pgfdecoration
%    {
%      {lineto}{\pgfdecoratedpathlength/5}{}{\pgfusepath{stroke}},
%      {zigzag}{\pgfdecoratedpathlength/5}
%        {
%          \pgfpathmoveto{\pgfpointdecoratedpathfirst}
%        }
%        {
%          \pgfsetstrokecolor{red}
%          \pgfusepath{stroke}
%        },
%      {lineto}{\pgfdecoratedpathlength/5}
%        {
%          \pgfpathmoveto{\pgfpointdecoratedpathfirst}
%        }
%        {
%          \pgfsetstrokecolor{black}
%          \pgfusepath{stroke}
%        },
%      {zigzag}{\pgfdecoratedpathlength/5}
%        {
%          \pgfpathmoveto{\pgfpointdecoratedpathfirst}
%        }
%        {
%          \pgfsetstrokecolor{red}
%          \pgfusepath{stroke}
%        },
%      {lineto}{\pgfdecoratedpathlength/5}
%        {
%          \pgfpathmoveto{\pgfpointdecoratedpathfirst}
%        }
%        {
%          \pgfsetstrokecolor{black}
%          \pgfusepath{stroke}
%        }
%    }
%    \pgfpathmoveto{\pgfpointorigin}
%    \pgfpathcurveto{\pgfpoint{0cm}{4cm}}{\pgfpoint{5cm}{0cm}}{\pgfpoint{5cm}{4cm}}
%  \endpgfdecoration
%  
%  \endpgfpicture 
%  
%  
%  
%  \pgfdeclaredecoration{polygons}{move}{
%    \state{move}[width=7.5pt, next state=polygon]{}
%    \state{polygon}[width=7.5pt, next state=move]
%    {
%      \pgfmathparse{round(rnd*100)}
%      \pgfsetfillcolor{green!\pgfmathresult!yellow}
%      \pgfsetstrokecolor{green!\pgfmathresult!brown}
%      \pgfnode{regular polygon}{center}{}{}{\pgfusepath{stroke,fill}}
%    }
%    \state{final}
%    {
%      \pgfpathmoveto{\pgfpointdecoratedpathlast}
%    }
%  }
%  
%  \pgfpicture
%  \pgfdecoration
%    {
%      {polygons}{45pt},
%      {lineto}{30pt}
%        {\pgfpathmoveto{\pgfpointdecoratedpathfirst}}
%        {        
%          \pgfsetstrokecolor{yellow!50!orange}
%          \pgfusepath{stroke}  
%        },
%      {polygons}{45pt},
%      {lineto}{30pt}
%        {\pgfpathmoveto{\pgfpointdecoratedpathfirst}}
%        {        
%          \pgfsetstrokecolor{green!50!blue}
%          \pgfusepath{stroke}  
%        },
%      {polygons}{\pgfdecoratedremainingdistance}
%    }
%    \pgfpathmoveto{\pgfpointorigin}
%    \pgfpathcurveto{\pgfpoint{0cm}{4cm}}{\pgfpoint{5cm}{0cm}}{\pgfpoint{5cm}{4cm}}
%  \endpgfdecoration
%  \endpgfpicture
%  
%  
%  \pgfpicture
%    \pgfpathmoveto{\pgfpointorigin}
%    \pgfpathcurveto{\pgfpoint{0cm}{4cm}}{\pgfpoint{5cm}{0cm}}{\pgfpoint{5cm}{4cm}}
%    \pgfgetpath\temppath
%    \pgfsetstrokecolor{red}
%    \pgfusepath{stroke}
%    
%    \pgfset{decoration text={Here is some text all the way along this curve!}}
%    \pgfdecoration{{text}{\pgfdecoratedremainingdistance}}
%      \pgfsetpath\temppath
%    \endpgfdecoration
%  \endpgfpicture
%
\def\pgfdecoration#1{%
  \begingroup%
    \def\pgf@decorate@decorationlist{#1}%
    \pgf@decoration@env%    
}

\def\endpgfdecoration{%
    \pgf@decoration@endenv%
    \ifx\pgfdecoratedpath\pgfutil@empty%
    \else%
      % 
      % Perform the decoration(s).
      % 
      \pgf@decorate@for\pgf@temp:=\pgf@decorate@decorationlist\do{%
        \ifx\pgf@temp\pgfutil@empty%
        \else%
          \expandafter\pgf@decorate@invoke\expandafter{\pgf@temp}%
        \fi%
      }%
    \fi%
    \pgfgetpath\pgfdecorationpath%
    % 
    % Take stuff outside the group.
    % 
    \global\let\pgf@decorate@decorationpathtemp\pgfdecorationpath%
    \global\let\pgf@decorate@decoratedpathtemp\pgfdecoratedpath%
    \global\let\pgf@decorate@existingpathtemp\pgfdecorateexistingpath%
    \global\let\pgfpoint@decorated@pathlasttemp\pgfpoint@decorated@pathlast%
  \endgroup%
  % 
  % Are we in LaTeX?
  % 
  \pgfutil@ifnextchar\@checkend{\aftergroup\pgf@decorate@installmacrosatend}%
  {\pgf@decorate@installmacrosatend}%
}



% Enviroment \pgfmetadecoration \endpgfmetadecoration
%
% Decorate a path with decoration automatons!
%
% Example:
%
%  \pgfdeclaremetadecoration{fancy line}{line to}{
%    \state{line to}[width=1cm, next state=zigzag]
%    {
%      \decoration{lineto}
%      \beforedecoration{\pgfpathmoveto{\pgfpointdecoratedpathfirst}}  
%      \afterdecoration
%      {
%        \pgfsetstrokecolor{black}
%        \pgfusepath{stroke}      
%      }
%    }
%    \state{zigzag}[width=2cm, next state=line to]
%    {
%      \decoration{zigzag}  
%      \beforedecoration{\pgfpathmoveto{\pgfpointdecoratedpathfirst}}
%      \afterdecoration
%      {
%        \pgfsetstrokecolor{red}
%        \pgfusepath{stroke}  
%      }
%    }
%    \state{final}
%    {
%      \decoration{lineto}
%      \beforedecoration{\pgfpathmoveto{\pgfpointdecoratedpathfirst}}
%      \afterdecoration
%      {
%        \pgfsetstrokecolor{black}
%        \pgfusepath{stroke}      
%      }
%    }
%  }
%  
%  \pgfpicture
%    \pgfmetadecoration{fancy line}
%      \pgfpathmoveto{\pgfpointorigin}
%      \pgfpathcurveto{\pgfqpoint{0cm}{2cm}}{\pgfqpoint{3cm}{2cm}}{\pgfqpoint{3cm}{0cm}}
%      \pgfpathcurveto{\pgfqpoint{3cm}{-3cm}}{\pgfqpoint{0cm}{0cm}}{\pgfqpoint{0cm}{-3cm}}
%      \pgfpathcurveto{\pgfqpoint{0cm}{-5cm}}{\pgfqpoint{3cm}{-5cm}}{\pgfqpoint{3cm}{-3cm}}
%    \endpgfmetadecoration
%  \endpgfpicture
%
\def\pgfmetadecoration#1{%
  \begingroup%    
    \let\decoration\pgf@metadecoration@decoration%
    \let\beforedecoration\pgf@metadecoration@beforedecoration%
    \let\afterdecoration\pgf@metadecoration@afterdecoration%
    \def\pgf@metadecoration@name{#1}%
    \pgf@decoration@env%
}

\def\endpgfmetadecoration{%
    \pgf@decoration@endenv%
    \ifx\pgfdecoratedpath\pgfutil@empty%
    \else%
      \let\pgfmetadecoratedpathlength\pgf@decorate@totalpathlength%
      \def\pgfmetadecoratedinputsegmentremainingdistance{\pgfdecoratedremainingdistance}%
      \def\pgfmetadecoratedinputsegmentcompleteddistance{\pgfdecoratedcompleteddistance}%
      %
      % Perform the meta decoration...
      %
      \expandafter\let\expandafter\pgf@metadecoration@current@state%
      \csname pgf@metadecoration@@\pgf@metadecoration@name @initial\endcsname%
      \pgf@metadecoration@run%
      %
      % ..until the final state.
      %
      \let\pgf@decorate@tempname\pgfutil@empty%
      \let\pgf@decorate@tempbefore\pgfutil@empty%
      \let\pgf@decorate@tempafter\pgfutil@empty%
      \csname pgf@metadecoration@@\pgf@metadecoration@name @\pgf@metadecoration@current@state @code\endcsname%
      \ifx\pgf@decorate@tempname\pgfutil@empty%
        \def\pgf@decorate@tempname{moveto}
      \fi%
      \pgf@decorate@invoke{%
        {\pgf@decorate@tempname}{\pgfdecoratedremainingdistance}%
        {\pgf@decorate@tempbefore}{\pgf@decorate@tempafter}%
      }%       
    \fi%
    \pgfgetpath\pgfdecorationpath%
    %
    % Take stuff outside the group.
    %
     \global\let\pgf@decorate@decorationpathtemp\pgfdecorationpath%
    \global\let\pgf@decorate@decoratedpathtemp\pgfdecoratedpath%
    \global\let\pgf@decorate@existingpathtemp\pgfdecorateexistingpath%
    \global\let\pgfpoint@decorated@pathlasttemp\pgfpoint@decorated@pathlast%
  \endgroup%
  %
  % Are we in LaTeX?
  % 
  \pgfutil@ifnextchar\@checkend{\aftergroup\pgf@decorate@installmacrosatend}%
    {\pgf@decorate@installmacrosatend}%
}






% Internal macro for the decoration enironment.
%
\def\pgf@decoration@env{%
  \pgfgetpath\pgfdecorateexistingpath%
  \pgfsetpath\pgfutil@empty%
  \let\pgfdecorationpath\pgfutil@empty%
  \let\pgfdecoratedpath\pgfutil@empty%
  \let\pgfpoint@decorated@pathlast\pgfpointorigin%
  \edef\pgfpoint@decorate@existingpathlast{\pgf@x\the\pgf@path@lastx\pgf@y\the\pgf@path@lasty}%      
  % 
  % Begin a group so transformations don't mess things up.
  % 
  \bgroup%  
}

\def\pgf@decorate@path@check@moveto#1{%
  \expandafter\pgf@decorate@path@@check@moveto#1\pgf@decorate@stop\pgf@decorate@@stop}

\def\pgf@decorate@token@stop{\pgf@decorate@stop}%
\def\pgf@decorate@path@@check@moveto#1#2#3#4\pgf@decorate@@stop#5#6{%
  \def\pgf@decorate@temp{#4}%
  \pgf@x=#2\relax%
  \pgf@y=#3\relax%
  \ifx\pgf@decorate@temp\pgf@decorate@token@stop%
    #5%
  \else%
    #6%
  \fi%
}

\def\pgf@decoration@endenv{%
  \egroup%        
  \pgftransformreset%
  % 
  % Save the existing soft path and restore the existing path.
  % 
  \pgfgetpath\pgfdecoratedpath%
  \pgfsetpath\pgfdecorateexistingpath%
  % 
  \ifx\pgfdecoratedpath\pgfutil@empty%
    \pgferror{I cannot decorate an empty path}%
  \else%
    %
    % If the path consists of a single moveto token, make it
    % a very small horizontal line.
    %
    \pgf@decorate@path@check@moveto\pgfdecoratedpath{%  
      \advance\pgf@x by0.0001pt\relax%
      \edef\pgfdecoratedpath{%
        \expandafter\noexpand\pgfdecoratedpath%
        \noexpand\pgfsyssoftpath@linetotoken{\the\pgf@x}{\the\pgf@y}%
      }%
    }%
    {}%
    %   
    % Remove special round tokens and get points.
    % 
    \pgfprocessround{\pgfdecoratedpath}{\pgfdecoratedpath}%
    % 
    % Parse the soft path into a series of decorated input segment objects.
    % 
    \pgf@decorate@parsesoftpath{\pgfdecoratedpath}{\pgf@decorate@inputsegmentobjects}%
    %
    % Setup further options
    %
    \pgfkeys{/pgf/every decoration/.try}%
    %
    % Reverse objects if necessary.
    %
    \ifpgf@decorate@inputsegmentobjects@reverse%
      \pgf@decorate@inputsegmentobjects@reverse{\pgf@decorate@inputsegmentobjects}{\pgf@decorate@inputsegmentobjects}%
    \fi%
    % 
    \let\pgf@decorated@remainingdistance\pgf@decorate@totalpathlength%
    % 
    \let\pgfpoint@decorated@totalpathfirst\pgfpoint@decorated@firstparsed%
    \let\pgfpoint@decorated@totalpathlast\pgfpoint@decorate@lastnonmovetoparsed%
    % 
    \let\pgfpoint@decorated@pathfirst\pgfpoint@decorated@totalpathfirst
    \let\pgfpoint@decorated@pathlast\pgfpoint@decorated@totalpathlast%
    % 
    % Set up the first input segment.
    % 
    \let\pgf@decorate@currentinputsegmentobjects\pgf@decorate@inputsegmentobjects%
    \let\pgf@decorate@transformtoinputsegment\pgfutil@empty%
    \pgf@decorate@getnextinputsegmentobject\pgf@decorate@nextinputsegmentobject%
    \pgf@decorate@processnextinputsegmentobject%
    \pgf@decorate@distancetomove0pt\relax%
  \fi%
}%  




\def\pgf@decorate@installmacrosatend{%
  \let\pgfdecorationpath\pgf@decorate@decorationpathtemp%
  \let\pgfdecoratedpath\pgf@decorate@decoratedpathtemp%
  \let\pgfdecorateexistingpath\pgf@decorate@existingpathtemp%
  \let\pgfpoint@decorated@pathlast\pgfpoint@decorated@pathlasttemp%
}

\let\pgfdecorationpath\pgfutil@empty
\let\pgfdecoratedpath\pgfutil@empty
\let\pgfdecorateexisitingpath\pgfutil@empty

\let\pgfpoint@decorated@pathlast\pgfpointorigin



% A version of \pgfutil@for which doesn't expand each value in #3.
%
\def\pgf@decorate@for#1:=#2\do#3{%
  \def\pgf@decorate@for@var{#1}%
  \def\pgf@decorate@for@action{#3}%
  \expandafter\pgf@decorate@@for#2,\pgf@stop,}
  
\def\pgf@decorate@@for#1,{%
  \ifx#1\pgf@stop%
    \expandafter\let\pgf@decorate@for@var\pgfutil@empty%
  \else%
    \expandafter\def\pgf@decorate@for@var{#1}%
    \pgf@decorate@for@action%
    \expandafter\pgf@decorate@@for%
  \fi%
}


% Invoke a decoration.
%
% #1 - {<name>}{<distance>}{<before code>}{<after code>}
%
\def\pgf@decorate@invoke#1{%
  \pgf@decorate@@invoke#1\pgf@decorate@invoke\pgf@decorate@invoke\pgf@decorate@invoke\pgf@stop}
  
\def\pgf@decorate@@invoke#1#2#3#4#5\pgf@stop{%
  \pgfutil@ifundefined{pgf@decorate@@#1@initial}%
  {%
    \pgferror{Unknown decoration `#1'}%
  }%
  {%
    \def\pgf@decorate@name{#1}%
    \ifx\pgf@decorate@invoke#3%
      \let\pgf@decorate@beforecode\pgfutil@empty%
    \else%
      \def\pgf@decorate@beforecode{#3}%
    \fi%
    \ifx\pgf@decorate@invoke#4%
      \let\pgf@decorate@aftercode\pgfutil@empty%
    \else%
      \def\pgf@decorate@aftercode{#4}%
    \fi%
    %
    % Make remaining distance and the decorated path length `public'.
    %
    \pgfdecoratedremainingdistance\pgf@decorated@remainingdistance\relax%
    \let\pgfdecoratedpathlength\pgf@decorate@totalpathlength%
    %
    \pgfmathsetlength\pgf@xa{#2}%
    \ifdim\pgf@xa>\pgf@decorated@remainingdistance\relax%
      \pgf@xa\pgf@decorated@remainingdistance\relax%
    \fi%
    \edef\pgf@decorate@currentpathlength{\the\pgf@xa}%
    %
    % Calculate the distance remaining to the end of the entire path.
    %
    \pgf@xa-\pgf@decorate@currentpathlength\relax%
    \advance\pgf@xa\pgf@decorated@remainingdistance\relax%
    \edef\pgf@decorated@remainingdistance{\the\pgf@xa}%
    %
    % Set up the macros and distances for the current section
    % of the decorated path.
    %
    \let\pgfdecoratedpathlength\pgf@decorate@currentpathlength%
    \pgfdecoratedremainingdistance\pgfdecoratedpathlength\relax%
    \pgfdecoratedcompleteddistance0pt\relax%
    %
    % Execute user-defined code beore decoration.
    %
    \pgf@decorate@beforecode%
    %
    % Run the decoration...
    %
    \expandafter\let\expandafter\pgf@decorate@current@state%
      \csname pgf@decorate@@\pgf@decorate@name @initial\endcsname%
    \pgf@decorate@run%
    %
    % ...until the final state.
    %
    \ifdim\pgf@decorated@remainingdistance<1pt\relax% Should be =0pt, but need to control for inaccuracies.
      \let\pgfpoint@decorated@pathlast\pgfpoint@decorated@totalpathlast%
    \else%
      %
      % Set up \pgfpoint@decorated@pathlast if the end of
      % the total decorated path has not been reached.
      %
      {%
        \pgf@decorate@movealonginputsegment{\the\pgfdecoratedremainingdistance}%
        \pgf@decorate@transformtoinputsegment%
        \pgfpointorigin%
        \pgf@pos@transform{\pgf@x}{\pgf@y}%
        \global\pgf@x\pgf@x%
        \global\pgf@y\pgf@y%
      }%
      \edef\pgfpoint@decorated@pathlast{\pgf@x\the\pgf@x\pgf@y\the\pgf@y}%
    \fi%    
    {%
      \pgftransformreset%
      \pgf@decorate@transformtoinputsegment%
      \pgf@decorate@additionaltransform%
      \csname pgf@decorate@@\pgf@decorate@name @final@code\endcsname%
    }%
    \pgf@decorate@movealonginputsegment{\the\pgfdecoratedremainingdistance}%
    %
    % Execute user-defined code after decoration.
    %
    \pgf@decorate@aftercode%  
    %
    % Update the input segment objects.
    %
    \let\pgf@decorate@additionaltransform\pgfutil@empty%
    \let\pgf@decorate@inputsegmentobjects\pgf@decorate@inputsegmentobjects@aftersplit%
    \let\pgfpoint@decorated@pathfirst\pgfpoint@decorated@pathlast%
   }%
}



\let\pgf@decorate@transformtoinputsegment\pgfutil@empty%
\let\pgf@decorate@additionaltransform\pgfutil@empty%


% \pgfpointdecoratedpathfirst
%
\def\pgfpointdecoratedpathfirst{%
  {%
    \pgftransforminvert%
    \pgfpoint@decorated@pathfirst%
    \pgf@pos@transform{\pgf@x}{\pgf@y}%
    \global\pgf@x\pgf@x%
    \global\pgf@y\pgf@y%
  }%
}%

% \pgfpointdecoratedpathlast
%
\def\pgfpointdecoratedpathlast{%
  {%
    \pgftransforminvert%
    \pgfpoint@decorated@pathlast%
    \pgf@pos@transform{\pgf@x}{\pgf@y}%
    \global\pgf@x\pgf@x%
    \global\pgf@y\pgf@y%
  }%
}%

% \pgfpointdecoratedinputsegmentfirst
%
% The first point of the current sub-path. 
%
\def\pgfpointdecoratedinputsegmentfirst{%
  {%
    \pgftransforminvert%
    \pgf@decorate@inputsegment@first%
    \pgf@pos@transform{\pgf@x}{\pgf@y}%
    \global\pgf@x\pgf@x%
    \global\pgf@y\pgf@y%
  }%
}%  

% \pgfpointdecoratedinputsegmentlast
%
% The final point of the current sub-path. 
%
\def\pgfpointdecoratedinputsegmentlast{%
  {%
    \pgftransforminvert%
    \pgf@decorate@inputsegment@last%
    \pgf@pos@transform{\pgf@x}{\pgf@y}%
    \global\pgf@x\pgf@x%
    \global\pgf@y\pgf@y%
  }%
}%


\def\pgf@final@text{final}

% Run a normal decoration.
%
\def\pgf@decorate@run{%
  \let\pgf@decorate@next\pgf@decorate@do@state%
  \ifx\pgf@decorate@current@state\pgf@final@text%
    \let\pgf@decorate@next\relax%
  \fi%
  \pgf@decorate@next%  
}

\def\pgf@decorate@do@state{%
  \let\pgf@decorate@next\relax%
  \let\pgf@decorate@next@state\pgf@decorate@current@state%
  %
  % Get the options.
  %
  \let\pgf@decorate@persistent@pre=\relax%
  \let\pgf@decorate@persistent@post=\relax%
  \expandafter\expandafter\expandafter\pgf@decorate@setter
  \expandafter\expandafter\expandafter{\csname pgf@decorate@@\pgf@decorate@name @\pgf@decorate@current@state @options\endcsname}%
  \ifx\pgf@decorate@next\relax%
    \let\pgf@decorate@next\pgf@decorate@do@code%
  \fi%
  \pgf@decorate@next%
}

\def\pgf@decorate@setter{\pgfqkeys{/pgf/decoration automaton}}

\pgf@decorate@repeatstate-1\relax

\def\pgf@decorate@do@code{%
  %
  % Execute code.
  %
  \pgf@decorate@persistent@pre%
  {%
    \pgftransformreset%
    \pgf@decorate@transformtoinputsegment%
    \pgf@decorate@additionaltransform%
    \csname pgf@decorate@@\pgf@decorate@name @\pgf@decorate@current@state @code\endcsname%
  }%
  \pgf@decorate@persistent@post%
  \pgf@decorate@movealongpath{\pgf@decorate@width}%
  %
  % Next iteration.
  %
  \ifnum\pgf@decorate@repeatstate>0\relax%
    \advance\pgf@decorate@repeatstate-1\relax%
  \else%
    \pgf@decorate@repeatstate-1\relax%
    \let\pgf@decorate@current@state\pgf@decorate@next@state%
  \fi%
  \pgf@decorate@run%
}

\pgfkeys{
  /pgf/decoration automaton/width/.code=\def\pgf@decorate@width{#1}\pgf@decorate@switch@if#1 to final\pgf@stop,%
  /pgf/decoration automaton/switch if less than/.code=\pgf@decorate@switch@if#1\pgf@stop,%
  /pgf/decoration automaton/switch if input segment less than/.code=\pgf@decorate@switch@ifinputsegment#1\pgf@stop,%
  /pgf/decoration automaton/next state/.store in=\pgf@decorate@next@state,%
  /pgf/decoration automaton/persistent precomputation/.store in=\pgf@decorate@persistent@pre,%
  /pgf/decoration automaton/persistent postcomputation/.store in=\pgf@decorate@persistent@post,%
  /pgf/decoration automaton/repeat state/.code={%
    \ifnum\pgf@decorate@repeatstate=-1\relax%
      \pgfmathsetcount\pgf@decorate@repeatstate{#1}%
    \fi%
  },%
  /pgf/decoration automaton/if input segment is closepath/.code={%
    \ifpgf@decorate@is@closepath@%
      \pgfkeysalso{#1}%
    \fi%
  },
  /pgf/decoration automaton/auto end on length/.code=\pgf@decorate@auto@end{#1},
  /pgf/decoration automaton/auto corner on length/.code=\pgf@decorate@auto@corner{#1},
}

\def\pgf@decorate@auto@end#1{%
  \ifx\pgf@decorate@next\relax%
    \pgfmathsetlength\pgf@x{#1}%
    \ifpgf@decorate@is@closepath@%
      \ifdim\pgfdecoratedremainingdistance>\pgf@x%
        \ifdim\pgfdecoratedinputsegmentremainingdistance>\pgf@x%
        \else%
          \pgfpathclose%
          \pgf@decorate@movealongpath{\pgfdecoratedinputsegmentremainingdistance}%
          \pgf@decorate@repeatstate-1\relax%
          \let\pgf@decorate@next\pgf@decorate@run%
        \fi%
      \else%
        \pgfpathclose%
        \def\pgf@decorate@current@state{final}%
        \def\pgf@decorate@width{\pgfdecoratedremainingdistance}
        \pgf@decorate@repeatstate-1\relax%
        \let\pgf@decorate@next\pgf@decorate@run%
      \fi%
    \else%
      \ifdim\pgfdecoratedremainingdistance>\pgf@x%
      \else%
        {%
          \pgftransformreset%
          \pgf@decorate@transformtoinputsegment%
          \pgf@decorate@additionaltransform%
          \pgfpathlineto{\pgfpoint{\pgfdecoratedremainingdistance}{0pt}}
        }%
        \def\pgf@decorate@current@state{final}%
        \def\pgf@decorate@width{\pgfdecoratedremainingdistance}
        \pgf@decorate@repeatstate-1\relax%
        \let\pgf@decorate@next\pgf@decorate@run%
      \fi%
    \fi%
  \fi%
}

\def\pgf@decorate@auto@corner#1{%
  \ifpgfdecoratepathhascorners%
    \ifx\pgf@decorate@next\relax%
      \pgfmathsetlength\pgf@x{#1}%
      \ifdim\pgfdecoratedinputsegmentremainingdistance>\pgf@x%
      \else%
        {%
          \pgftransformreset%
          \pgf@decorate@transformtoinputsegment%
          \pgf@decorate@additionaltransform%
          \pgfpathlineto{\pgfqpoint{\pgfdecoratedinputsegmentremainingdistance}{0pt}}
        }%
        \pgf@decorate@movealongpath{\pgfdecoratedinputsegmentremainingdistance}%
        \pgf@decorate@repeatstate-1\relax%
        \let\pgf@decorate@next\pgf@decorate@run%
      \fi%
    \fi%
  \fi%
}

\def\pgf@decorate@switch@if#1to #2\pgf@stop{%
  \ifx\pgf@decorate@next\relax%
    \ifdim\pgfdecoratedremainingdistance=0pt\relax%
      \def\pgf@decorate@current@state{#2}%
      \pgf@decorate@repeatstate-1\relax%
      \let\pgf@decorate@next\pgf@decorate@run%
    \else%
      \pgfmathsetlength\pgf@x{#1}%
      \ifdim\pgfdecoratedremainingdistance<\pgf@x%
        \def\pgf@decorate@current@state{#2}%
        \pgf@decorate@repeatstate-1\relax%
        \let\pgf@decorate@next\pgf@decorate@run%
      \fi%
    \fi%
  \fi%
}

\def\pgf@decorate@switch@ifinputsegment#1to #2\pgf@stop{%
  \ifx\pgf@decorate@next\relax%
    \pgfmathsetlength\pgf@x{#1}%
    \ifdim\pgfdecoratedinputsegmentremainingdistance<\pgf@x%
      \def\pgf@decorate@current@state{#2}%
      \pgf@decorate@repeatstate-1\relax%
      \let\pgf@decorate@next\pgf@decorate@run%
    \fi%
  \fi%
}




% \pgfsetdecorationsegmenttransformation
%
% Set the additional transform for each decoration state.
%
% Example:
%
% \pgfsetdecorationsegmenttransformation{\pgftransformyshift{5pt}}
%
\def\pgfsetdecorationsegmenttransformation#1{\def\pgf@decorate@additionaltransform{#1}}
\let\pgf@decorate@additionaltransform\pgfutil@empty%




\def\pgf@metadecoration@decoration#1{%
  \edef\pgf@decorate@tempname{#1}%
}
\def\pgf@metadecoration@beforedecoration#1{%
  \def\pgf@decorate@tempbefore{#1}%
}
\def\pgf@metadecoration@afterdecoration#1{%
  \def\pgf@decorate@tempafter{#1}%
}


\def\pgf@final@text{final}

% Run a meta decoration.
%
\def\pgf@metadecoration@run{%
  \let\pgf@metadecoration@next\pgf@metadecoration@do@state%
  \ifx\pgf@metadecoration@current@state\pgf@final@text%
    \let\pgf@metadecoration@next\relax%
  \fi%
  \pgf@metadecoration@next%  
}

\def\pgf@metadecoration@do@state{%
  \let\pgf@metadecoration@next\relax%
  \let\pgf@metadecoration@next@state\pgf@metadecoration@current@state%
  %
  % Set up some macros.
  %
  \let\pgfmetadecoratedremainingdistance\pgf@decorated@remainingdistance%
  \pgf@x-\pgfmetadecoratedremainingdistance\relax%
  \advance\pgf@x\pgf@decorate@totalpathlength\relax%
  \edef\pgfmetadecoratedcompleteddistance{\the\pgf@x}%
  %
  % Get the options.
  %
  \expandafter\expandafter\expandafter\pgf@metadecoration@setter
  \expandafter\expandafter\expandafter{\csname pgf@metadecoration@@\pgf@metadecoration@name @\pgf@metadecoration@current@state @options\endcsname}%
  \ifx\pgf@metadecoration@next\relax%
    \let\pgf@metadecoration@next\pgf@metadecoration@do@code%
  \fi%
  \pgf@metadecoration@next%
}

\def\pgf@metadecoration@do@code{%
  %
  % Execute code.
  %
  \let\pgf@decorate@tempname\pgfutil@empty%
  \let\pgf@decorate@tempbefore\pgfutil@empty%
  \let\pgf@decorate@tempafter\pgfutil@empty%
  \let\pgfpointmetadecoratedpathfirst\pgfpointdecoratedpathfirst%
  \let\pgfpointmetadecoratedpathlast\pgfpointdecoratedpathlast%
  \csname pgf@metadecoration@@\pgf@metadecoration@name @\pgf@metadecoration@current@state @code\endcsname%
  \ifx\pgf@decorate@tempname\pgfutil@empty%
    \def\pgf@decorate@tempname{moveto}
  \fi%
  \pgf@decorate@invoke{%
    {\pgf@decorate@tempname}{\pgf@metadecoration@width}%
    {\pgf@decorate@tempbefore}{\pgf@decorate@tempafter}%
  }%
  %
  % Next iteration.
  %
  \let\pgf@metadecoration@current@state\pgf@metadecoration@next@state%
  \pgf@metadecoration@run%
}

\def\pgf@metadecoration@setter{\pgfqkeys{/pgf/meta-decoration automaton}}

\pgfkeys{
  /pgf/meta-decoration automaton/width/.code=\def\pgf@metadecoration@width{#1}\pgf@metadecoration@switch@if#1 to final\pgf@stop,%
  /pgf/meta-decoration automaton/switch if less than/.code=\pgf@metadecoration@switch@if#1\pgf@stop,%
  /pgf/meta-decoration automaton/switch if input segment less than/.code=\pgf@metadecoration@switch@ifinputsegment#1\pgf@stop,%
  /pgf/meta-decoration automaton/next state/.store in=\pgf@metadecoration@next@state,%
}

\def\pgf@metadecoration@switch@if#1to #2\pgf@stop{%
  \ifx\pgf@metadecoration@next\relax%
    \pgfmathsetlength\pgf@x{#1}%
    \ifdim\pgf@decorated@remainingdistance<\pgf@x%
      \def\pgf@metadecoration@current@state{#2}%
      \let\pgf@metadecoration@next\pgf@metadecoration@run%
    \fi%
  \fi%
}

\def\pgf@metadecoration@switch@ifinputsegment#1to #2\pgf@stop{%
  \ifx\pgf@metadecoration@next\relax%
    \pgfmathsetlength\pgf@x{#1}%
    \ifdim\pgfdecoratedinputsegmentremainingdistance<\pgf@x%
      \def\pgf@metadecoration@current@state{#2}%
      \let\pgf@metadecoration@next\pgf@metadecoration@run%
    \fi%
  \fi%
}



% Move along the path by a specified distance.
%
\def\pgf@decorate@movealongpath#1{%
  \pgfmathsetlength\pgf@decorate@distancetomove{#1}%
  \advance\pgfdecoratedcompleteddistance\pgf@decorate@distancetomove%
  \advance\pgfdecoratedremainingdistance-\pgf@decorate@distancetomove%
  \pgf@decorate@@movealongpath%
}
\def\pgf@decorate@@movealongpath{%
  \advance\pgfdecoratedinputsegmentcompleteddistance\pgf@decorate@distancetomove%
  \advance\pgfdecoratedinputsegmentremainingdistance-\pgf@decorate@distancetomove%
  \ifdim\pgfdecoratedinputsegmentremainingdistance>0pt\relax%
    \let\pgf@next\pgf@decorate@@@movealongpath%
  \else%
    \pgf@decorate@distancetomove-\pgfdecoratedinputsegmentremainingdistance%
    \pgf@decorate@processnextinputsegmentobject%
    \ifx\pgf@decorate@currentinputsegmentobjects\pgfutil@empty%
      \pgfdecoratedremainingdistance0pt\relax%
      \let\pgf@next\relax%
    \else%
      \let\pgf@next\pgf@decorate@@movealongpath%
    \fi%
  \fi%
  \pgf@next%
}

\def\pgf@decorate@@@movealongpath{%
  %
  % Move along input segment for real.
  %
  \pgf@decorate@movealonginputsegment{\the\pgf@decorate@distancetomove}%
  \pgf@decorate@distancetomove0pt\relax%
  %
  % Grrr. Hacking to control some inaccuracies.
  %
  \ifdim\pgf@decorate@inputsegmenttime pt>1pt\relax%
    \let\pgf@decorate@inputsegmenttimetemp\pgf@decorate@inputsegmenttime%
    \pgf@decorate@processnextinputsegmentobject%
    \pgf@x\pgf@decorate@inputsegmenttimetemp pt\relax%
    \advance\pgf@x-1pt\relax%
    \edef\pgf@decorate@inputsegmenttime{\pgfmath@tonumber{\pgf@x}}%
    \ifx\pgf@decorate@currentinputsegmentobjects\pgfutil@empty%
      \pgfdecoratedremainingdistance0pt\relax%
    \fi%
  \fi%
}

% Return the next input segment object in a macro 
%
\def\pgf@decorate@getnextinputsegmentobject#1{%
  \ifx\pgf@decorate@currentinputsegmentobjects\pgfutil@empty%
    \let\pgf@next\relax%
  \else%
    \def\pgf@decorate@temp{#1}%
    \let\pgf@next\pgf@decorate@@getnextinputsegmentobject%
  \fi%
  \pgf@next%
}
\def\pgf@decorate@@getnextinputsegmentobject{%
  \expandafter\pgf@decorate@@@getnextinputsegmentobject\pgf@decorate@currentinputsegmentobjects\pgf@stop}
\def\pgf@decorate@@@getnextinputsegmentobject#1#2\pgf@stop{%
  \expandafter\def\pgf@decorate@temp{#1}%
  \def\pgf@decorate@currentinputsegmentobjects{#2}}

% Process the next input segment object.
%
\def\pgf@decorate@processnextinputsegmentobject{%
  \let\pgfdecorationpreviousinputsegment\pgfdecoratecurrentinputsegment%
  \let\pgf@decorate@currentinputsegmentobject\pgf@decorate@nextinputsegmentobject%
  \pgf@decorate@getnextinputsegmentobject\pgf@decorate@nextinputsegmentobject%
  %
  % If the current input segment object is a moveto, execute the 
  % object macro and get the next input segment object.
  %
  \pgf@decorate@is@closepath@false%
  \pgf@decorate@currentinputsegmentobject%
  \ifx\pgfdecorationcurrentinputsegment\pgfdecorationinputsegmentmoveto%
    \pgfpathmoveto{\pgf@decorate@inputsegment@first}%
    \let\pgfdecorationpreviousinputsegment\pgfdecorationcurrentinputsegment%
    \let\pgf@decorate@currentinputsegmentobject\pgf@decorate@nextinputsegmentobject%
    \pgf@decorate@getnextinputsegmentobject\pgf@decorate@nextinputsegmentobject%
    \pgf@decorate@is@closepath@false%
    \pgf@decorate@currentinputsegmentobject%
  \fi%
  %
  % Teensy hack in case a path goes nowhere.
  %
  \ifdim\pgfdecoratedinputsegmentlength=0pt\relax%
    \def\pgfdecoratedinputsegmentlength{0.05pt}% Arbitrary choice >0pt.
  \fi%
  \pgfdecoratedinputsegmentremainingdistance\pgfdecoratedinputsegmentlength\relax%
  \pgfdecoratedinputsegmentcompleteddistance0pt\relax%
  \def\pgf@decorate@inputsegmenttime{0}%
  %
  % Get the angle at the start of the input segment.
  %
  \ifx\pgfdecorationcurrentinputsegment\pgfdecorationinputsegmentcurveto%
    \pgfmathanglebetweenpoints{\pgf@decorate@inputsegment@first}{\pgf@decorate@inputsegment@supporta}%
    \let\pgfdecoratedangle\pgfmathresult%
    \let\pgfdecoratedinputsegmentstartangle\pgfmathresult%
    \pgfmathanglebetweenpoints{\pgf@decorate@inputsegment@supportb}{\pgf@decorate@inputsegment@last}%
    \let\pgfdecoratedinputsegmentendangle\pgfmathresult%
  \else%
    \pgfmathanglebetweenpoints{\pgf@decorate@inputsegment@first}{\pgf@decorate@inputsegment@last}%
    \let\pgfdecoratedangle\pgfmathresult%
    \let\pgfdecoratedinputsegmentstartangle\pgfmathresult%
    \let\pgfdecoratedinputsegmentendangle\pgfmathresult%
  \fi%
  %
  % Get the angle to the next input segment.
  %
  \begingroup%
    \pgf@decorate@nextinputsegmentobject%
    \global\let\pgf@decorate@temp\pgfdecorationcurrentinputsegment%
    \ifx\pgfdecorationcurrentinputsegment\pgfdecorationinputsegmentmoveto%
      \expandafter\pgf@decorate@currentinputsegmentobject%
    \fi%
    \ifx\pgfdecorationcurrentinputsegment\pgfdecorationinputsegmentcurveto%
      \pgfmathanglebetweenpoints{\pgf@decorate@inputsegment@first}{\pgf@decorate@inputsegment@supporta}%
    \else%
      \pgfmathanglebetweenpoints{\pgf@decorate@inputsegment@first}{\pgf@decorate@inputsegment@last}%
    \fi%
    \pgf@x-\pgfdecoratedangle pt\relax%
    \advance\pgf@x\pgfmathresult pt\relax%
    \edef\pgfdecoratedangletonextinputsegment{\the\pgf@x}%
    \pgfmath@smuggleone\pgfdecoratedangletonextinputsegment%
  \endgroup%
  \let\pgfdecorationnextinputsegmentobject\pgf@decorate@temp%
}


%
% Input segment objects
%

\newif\ifpgf@decorate@is@closepath@%

% Input segment types.
%
% These allow comparison with \ifx using
%
% \pgfdecorationcurrentinputsegment 
% \pgfdecorationnextinputsegment
% \pgfdecorationcurrentprevioussegment
%
\def\pgfdecorationinputsegmentmoveto{moveto}
\def\pgfdecorationinputsegmentlineto{lineto}
\def\pgfdecorationinputsegmentcurveto{curveto}
\def\pgfdecorationinputsegmentclosepath{closepath}
\def\pgfdecorationinputsegmentlast{last}

% Input segment object moveto.
%
\def\pgf@decorate@inputsegmentobject@moveto#1{%
  \def\pgf@decorate@inputsegment@first{#1}%
  \def\pgf@decorate@inputsegment@supporta{#1}%
  \def\pgf@decorate@inputsegment@supportb{#1}%
  \def\pgf@decorate@inputsegment@last{#1}%
  \edef\pgf@decorate@lastmoveto{#1}%
  \def\pgfdecoratedinputsegmentlength{0pt}%
  \let\pgfdecorationcurrentinputsegment\pgfdecorationinputsegmentmoveto%
}

% Input segment object lineto.
%
\def\pgf@decorate@inputsegmentobject@lineto#1#2#3{%
  \def\pgfdecoratedinputsegmentlength{#1}%
  \def\pgf@decorate@inputsegment@first{#2}%
  \def\pgf@decorate@inputsegment@last{#3}%
  %
  % Supports should be defined like this, so if treated as a curve, 
  % equal time steps will correspond to equal distances. 
  %
  \pgfpointdiff{#2}{#3}%
  \pgf@xa\pgf@x%
  \pgf@ya\pgf@y%
  \pgfextract@process\pgf@decorate@inputsegment@supporta{%
    \pgf@process{#2}%
    \advance\pgf@x0.333333\pgf@xa%
    \advance\pgf@y0.333333\pgf@ya%
  }%
  \pgfextract@process\pgf@decorate@inputsegment@supportb{%
    \pgf@process{#2}%
    \advance\pgf@x0.666666\pgf@xa%
    \advance\pgf@y0.666666\pgf@ya%
  }%  
  \let\pgf@decorate@movealonginputsegment\pgf@decorate@movealonginputsegment@line%
  \let\pgf@decorate@transformtoinputsegment\pgf@decorate@transformtoinputsegment@line%
  \let\pgfdecorationcurrentinputsegment\pgfdecorationinputsegmentlineto%
}

% Input segment object curveto.
%
\def\pgf@decorate@inputsegmentobject@curveto#1#2#3#4#5{%
  \def\pgfdecoratedinputsegmentlength{#1}%
  \def\pgf@decorate@inputsegment@first{#2}%
  \def\pgf@decorate@inputsegment@supporta{#3}%
  \def\pgf@decorate@inputsegment@supportb{#4}%
  \def\pgf@decorate@inputsegment@last{#5}%  
  %
  \let\pgf@decorate@movealonginputsegment\pgf@decorate@movealonginputsegment@curve%
  \let\pgf@decorate@transformtoinputsegment\pgf@decorate@transformtoinputsegment@curve%
  \let\pgfdecorationcurrentinputsegment\pgfdecorationinputsegmentcurveto%
}

% Input segment object closepath.
%
% Treated like a lineto, but flag that it is a closepath.
%
\def\pgf@decorate@inputsegmentobject@closepath#1#2#3{%
  \pgf@decorate@is@closepath@true%
  %
  \def\pgfdecoratedinputsegmentlength{#1}%
  \def\pgf@decorate@inputsegment@first{#2}%
  \def\pgf@decorate@inputsegment@last{#3}%
  %  
  \pgfpointdiff{#2}{#3}%
  \pgf@xa\pgf@x%
  \pgf@ya\pgf@y%
  \pgfextract@process\pgf@decorate@inputsegment@supporta{%
    \pgf@process{#2}%
    \advance\pgf@x0.333333\pgf@xa%
    \advance\pgf@y0.333333\pgf@ya%
  }%
  \pgfextract@process\pgf@decorate@inputsegment@supportb{%
    \pgf@process{#2}%
    \advance\pgf@x0.666666\pgf@xa%
    \advance\pgf@y0.666666\pgf@ya%
  }%  
  % 
  \let\pgf@decorate@movealonginputsegment\pgf@decorate@movealonginputsegment@line%
  \let\pgf@decorate@transformtoinputsegment\pgf@decorate@transformtoinputsegment@line%
  \let\pgfdecorationcurrentinputsegment\pgfdecorationinputsegmentclosepath%
}


% Input segment object endofinputsegments.
%
\def\pgf@decorate@inputsegmentobject@endofinputsegments{%
  \let\pgfdecorationcurrentinputsegment\pgfdecorationinputsegmentlast%
}




% This macro controls how the automaton moves along a line sub-path
%
\def\pgf@decorate@movealonginputsegment@line#1{}% Nothing special needed.

% This macro controls how the automaton moves along a curve sub-path.
%
\def\pgf@decorate@movealonginputsegment@curve#1{%
  \ifdim#1=0pt\relax%
  \else%
    \pgfpointcurveattime{\pgf@decorate@inputsegmenttime}%
      {\pgf@decorate@inputsegment@first}{\pgf@decorate@inputsegment@supporta}%
      {\pgf@decorate@inputsegment@supportb}{\pgf@decorate@inputsegment@last}%
    \pgf@xa\pgf@x%
    \pgf@ya\pgf@y%
    \pgf@xb\pgf@decorate@inputsegmenttime pt\relax%
    %
    % Reduce the initial time step, depending on the length 
    % of the path. To do: Optimise this step (should also depend on #1).
    %
    \ifdim\pgf@decorate@currentpathlength<128pt\relax%
      \pgf@yb.03125pt\relax%
    \else%
      \ifdim\pgf@decorate@currentpathlength<512pt\relax%
        \pgf@yb.015625pt\relax%
      \else%
        \ifdim\pgf@decorate@currentpathlength<2048pt\relax%
          \pgf@yb.00390625pt\relax%
        \else%
          \pgf@yb.0009765625pt\relax%
        \fi%
      \fi%
    \fi%
    \c@pgf@counta1\relax%
    \pgfutil@tempdima0pt\relax%
    \pgfmathloop%
      \advance\pgf@xb\c@pgf@counta\pgf@yb%
      %
      % We would like to use \pgfpointcurveattime. However, we must not
      % overuse \pgf@process or \pgfmath stuff within this loop,
      % otherwise we increase the chances of save stack overflow. 
      %
      \edef\pgf@decorate@temp{%
        \pgf@xa\the\pgf@xa%
        \pgf@xb\the\pgf@xb%
        \pgf@ya\the\pgf@ya%
        \pgf@yb\the\pgf@yb%
      }%
      %
      \pgfpoint@decorate@curveattime{\pgfmath@tonumber{\pgf@xb}}%
        {\pgf@decorate@inputsegment@first}{\pgf@decorate@inputsegment@supporta}%
        {\pgf@decorate@inputsegment@supportb}{\pgf@decorate@inputsegment@last}%
      \pgf@decorate@temp%
      %
      \pgf@xc\pgf@xa%
      \pgf@yc\pgf@ya%
      \pgf@xa\pgf@x%
      \pgf@ya\pgf@y%
      \advance\pgf@x-\pgf@xc%
      \advance\pgf@y-\pgf@yc%
      \pgfmathveclen@{\pgfmath@tonumber{\pgf@x}}{\pgfmath@tonumber{\pgf@y}}%
      \pgfutil@tempdimb\pgfmathresult pt\relax%
      \advance\pgfutil@tempdima\c@pgf@counta\pgfutil@tempdimb%
      \ifnum\c@pgf@counta>0\relax%
        \ifdim\pgfutil@tempdima>#1\relax%
          \c@pgf@counta-\c@pgf@counta%
          \pgf@yb.5\pgf@yb%
        \fi%
      \else%
        \ifdim\pgfutil@tempdima<#1\relax%
          \c@pgf@counta-\c@pgf@counta%
          \pgf@yb.5\pgf@yb%
        \fi%
      \fi%
      \ifdim\pgf@yb=0pt\relax% *Should* be OK.
      \else%
    \repeatpgfmathloop%
    \edef\pgf@decorate@inputsegmenttime{\pgfmath@tonumber{\pgf@xb}}%
    %
    % Now calculate the angle at the new time on the curve.
    %
    % We can use \pgfpointcurveattime safely here.
    %
    \pgfpointcurveattime{\pgf@decorate@inputsegmenttime}%
      {\pgf@decorate@inputsegment@first}{\pgf@decorate@inputsegment@supporta}%
      {\pgf@decorate@inputsegment@supportb}{\pgf@decorate@inputsegment@last}%
    \edef\pgf@marshal{%
      \noexpand\pgfmathanglebetweenpoints%
        {\pgf@x\the\pgf@xb\pgf@y\the\pgf@yb}%
        {\pgf@x\the\pgf@xa\pgf@y\the\pgf@ya}%
    }%
    \pgf@marshal%
    \let\pgfdecoratedangle\pgfmathresult%
  \fi%
}

% \pgfpoint@decorate@curveattime
%
% A `quick' version of \pgfpointcurveattime
%
% No parsing and no use of \pgf@process. 
% This prevents save stack build up when used inside a loop.
%
\def\pgfpoint@decorate@curveattime#1#2#3#4#5{%
  \edef\pgf@time@s{#1}%
  \pgf@x-\pgf@time@s pt\relax%
  \advance\pgf@x1pt\relax%
  \edef\pgf@time@t{\pgf@sys@tonumber{\pgf@x}}%
  #5\relax%
  \pgf@xc=\pgf@x%
  \pgf@yc=\pgf@y%
  #4\relax%
  \pgf@xb=\pgf@x%
  \pgf@yb=\pgf@y%
  #3\relax%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  #2\relax%
  % First iteration:
  \pgf@x=\pgf@time@t\pgf@x\advance\pgf@x by\pgf@time@s\pgf@xa%
  \pgf@y=\pgf@time@t\pgf@y\advance\pgf@y by\pgf@time@s\pgf@ya%
  \pgf@xa=\pgf@time@t\pgf@xa\advance\pgf@xa by\pgf@time@s\pgf@xb%
  \pgf@ya=\pgf@time@t\pgf@ya\advance\pgf@ya by\pgf@time@s\pgf@yb%
  \pgf@xb=\pgf@time@t\pgf@xb\advance\pgf@xb by\pgf@time@s\pgf@xc%
  \pgf@yb=\pgf@time@t\pgf@yb\advance\pgf@yb by\pgf@time@s\pgf@yc%
  % Second iteration:
  \pgf@x=\pgf@time@t\pgf@x\advance\pgf@x by\pgf@time@s\pgf@xa%
  \pgf@y=\pgf@time@t\pgf@y\advance\pgf@y by\pgf@time@s\pgf@ya%
  \pgf@xa=\pgf@time@t\pgf@xa\advance\pgf@xa by\pgf@time@s\pgf@xb%
  \pgf@ya=\pgf@time@t\pgf@ya\advance\pgf@ya by\pgf@time@s\pgf@yb%
  % Save x/y
  \pgf@xb=\pgf@x%
  \pgf@yb=\pgf@y%
  % Third iteration:
  \pgf@x=\pgf@time@t\pgf@x\advance\pgf@x by\pgf@time@s\pgf@xa%
  \pgf@y=\pgf@time@t\pgf@y\advance\pgf@y by\pgf@time@s\pgf@ya%
}


% Applies the necessary transform for a line sub-path.
%
\def\pgf@decorate@transformtoinputsegment@line{%
  \pgftransformshift{%
    \pgfpointlineatdistance{\pgfdecoratedinputsegmentcompleteddistance}{\pgf@decorate@inputsegment@first}{\pgf@decorate@inputsegment@last}
  }%
  \pgftransformrotate{\pgfdecoratedangle}%
}

% Applies the necessary transform for a curve sub-path.
%
\def\pgf@decorate@transformtoinputsegment@curve{%
  \pgfslopedattimetrue%
  \pgfallowupsidedownattimetrue%
  \pgftransformcurveattime{\pgf@decorate@inputsegmenttime}%
    {\pgf@decorate@inputsegment@first}{\pgf@decorate@inputsegment@supporta}%
    {\pgf@decorate@inputsegment@supportb}{\pgf@decorate@inputsegment@last}%
}





%  \pgf@decorate@parsesoftpath
%  
%  Parses an instance of a soft path into intermediate line and curve
%  sub-path objects which the decoration automaton can use to traverse 
% the decorated path. 
%  
%  The soft path should be well formed and only contain `primative' 
%  soft path tokens, that is: moveto, lineto, curvetosupporta, 
%  curvetosupportb, curveto, rectcorner, rectsize, and closepath.
%  (i.e., all specialround tokens should have removed using 
%  \pgfprocessround)
%  
%  The overall length of the path is also calculated and returned
%  in the macro \pgfdecoratedpathlength. 
%  
%  Parameters:
%  
%  #1 - a macro containing a well formed soft path.
%  #2 - a macro to store the intermediate sub-path representations.
%
%  Example:
%  
%  \pgfpathmoveto{\pgfpointorigin}
%  \pgfpathlineto{\pgfpoint{0pt}{12pt}}
%  \pgfpathlineto{\pgfpoint{12pt}{0pt}}
%  \pgfgetpath\softpath
%  
%  \pgf@decorate@parsesoftpath{\softpath}{\parsedsoftpath}
%  
%  results in:
%  
%  \parsedsoftpath ->
%    {\pgf@decorate@inputsegmentobject@lineto{12pt}{\pgf@x 0pt\pgf@y 0pt}{\pgf@x 0pt\pgf@y 12pt}}
%    {\pgf@decorate@inputsegmentobject@lineto{12pt}{\pgf@x 0pt\pgf@y 12pt}{\pgf@x 12pt\pgf@y 12pt}}
%  
%  \pgfdecoratedpathlength ->
%    24pt
%

\def\pgf@decorate@parsesoftpath#1#2{%
  \def\pgf@decorate@inputsegmentobjectsmacro{#2}%
  \let\pgf@decorate@inputsegmentobjects\pgfutil@empty%
  \pgfutil@tempdima0pt\relax%
  \let\pgfpoint@decorate@lastparsed\pgfpoint@decorate@existingpathlast%
  \let\pgfpoint@decorate@lastnonmovetoparsed\pgfpoint@origin%
  \let\pgf@decorate@queueinputsegmentobject\pgfutil@empty%
  \let\pgfpoint@decorated@firstparsed\pgfutil@empty%
  \expandafter\pgf@decorate@@parsesoftpath#1\pgf@stop%
}

\def\pgf@decorate@@parsesoftpath#1{%
  \ifx#1\pgf@stop%
    \let\pgf@decorate@queueinputsegmentobject\pgfutil@empty% <- removes final moveto (may not be desirable).
    \pgf@decorate@addtoinputsegmentobjects{\pgf@decorate@inputsegmentobject@endofinputsegments}%
    \pgf@decorate@addtoinputsegmentobjects{\pgf@decorate@inputsegmentobject@endofinputsegments}%
    \expandafter\let\pgf@decorate@inputsegmentobjectsmacro\pgf@decorate@inputsegmentobjects%
    \edef\pgf@decorate@totalpathlength{\the\pgfutil@tempdima}%
    \let\pgf@next\relax%
  \else%
    \ifx#1\pgfsyssoftpath@movetotoken%
      \let\pgf@next\pgf@decorate@parsemoveto%
    \else%
      \ifx#1\pgfsyssoftpath@linetotoken%
        \let\pgf@next\pgf@decorate@parselineto%
      \else%
        \ifx#1\pgfsyssoftpath@curvetosupportatoken%
          \let\pgf@next\pgf@decorate@parsecurveto%
        \else%
          \ifx#1\pgfsyssoftpath@closepathtoken%
            \let\pgf@next\pgf@decorate@parseclosepath%
          \else%
            \ifx#1\pgfsyssoftpath@rectcornertoken%
              \let\pgf@next\pgf@decorate@parserect%
            \else%
              \pgferror{Unrecognised soft path token `#1'}%
            \fi%
          \fi%
        \fi%
      \fi%
    \fi%
  \fi%
  \pgf@next}


\def\pgf@decorate@addtoinputsegmentobjects#1{%
  %
  % If there is an input segment object waiting (i.e. a moveto), insert it here.
  %
  \ifx\pgf@decorate@queueinputsegmentobject\pgfutil@empty%
  \else%
    \let\pgf@decorate@temp\pgf@decorate@queueinputsegmentobject%
    \let\pgf@decorate@queueinputsegmentobject\pgfutil@empty%
    \expandafter\pgf@decorate@addtoinputsegmentobjects\expandafter{\pgf@decorate@temp}%
  \fi%
  \ifx\pgfpoint@decorated@firstparsed\pgfutil@empty%
    #1%
    \let\pgfpoint@decorated@firstparsed\pgf@decorate@inputsegment@first%
  \fi%
  \expandafter\def\expandafter\pgf@decorate@inputsegmentobjects\expandafter%
    {\pgf@decorate@inputsegmentobjects{#1}}%
}

%  Convert \pgfsyssoftpath@movetotoken{<X>}{<Y>} into the following
% representation:
%  
%  \pgf@decorate@inputsegmentobject@moveto{\pgf@x X\pgf@y Y}
%
%  The moveto input segment object is not added immediately, so that
%  only the last of multiple movetos is inserted.
%  
\def\pgf@decorate@parsemoveto#1#2{%
  \def\pgf@decorate@queueinputsegmentobject{\pgf@decorate@inputsegmentobject@moveto{\pgf@x#1\pgf@y#2}}%
  \def\pgfpoint@decorate@lastparsed{\pgf@x#1\pgf@y#2}%
  \pgf@decorate@@parsesoftpath%
}

% Convert \pgfsyssoftpath@linetotoken{<X>}{<Y>} into the following
% representation:
%
% \pgf@decorate@inputsegmentobject@lineto{<length>}{\pgf@x <Last X> \pgf@y <Last Y}{\pgf@x <X> \pgf@y <Y>}
%
\def\pgf@decorate@parselineto#1#2{%
  \pgf@decorate@linelength{\pgfpoint@decorate@lastparsed}{\pgf@x#1\pgf@y#2}%
  \advance\pgfutil@tempdima\pgfmathresult pt\relax%
  \edef\pgf@decorate@temp{%
    \noexpand\pgf@decorate@inputsegmentobject@lineto{\pgfmathresult pt}{\pgfpoint@decorate@lastparsed}{\pgf@x#1\pgf@y#2}%
  }%
  \edef\pgfpoint@decorate@lastparsed{\pgf@x#1\pgf@y#2}%
  \let\pgfpoint@decorate@lastnonmovetoparsed\pgfpoint@decorate@lastparsed%
  \expandafter\pgf@decorate@addtoinputsegmentobjects\expandafter{\pgf@decorate@temp}%
  \pgf@decorate@@parsesoftpath%
}
  
% Convert \pgfsyssoftpath@curvetosupportatoken{<Xa>}{<Ya>}...etc
% into the following representation:
%
% \pgf@decorate@inputsegmentobject@curveto{<length>}{\pgf@x <Last X> \pgf@y <Last Y}
%    {\pgf@x <Xa> \pgf@y <Ya>}{\pgf@x <Xb> \pgf@y <Yb>}{\pgf@x <X> \pgf@y <Y>}
%
\def\pgf@decorate@parsecurveto#1#2\pgfsyssoftpath@curvetosupportbtoken#3#4\pgfsyssoftpath@curvetotoken#5#6{%
  \pgf@decorate@curvelength{\pgfpoint@decorate@lastparsed}{\pgf@x#1\pgf@y#2}{\pgf@x#3\pgf@y#4}{\pgf@x#5\pgf@y#6}%
  \advance\pgfutil@tempdima\pgfmathresult pt\relax%
  \edef\pgf@decorate@temp{%
    \noexpand\pgf@decorate@inputsegmentobject@curveto{\pgfmathresult pt}{\pgfpoint@decorate@lastparsed}%
      {\pgf@x#1\pgf@y#2}{\pgf@x#3\pgf@y#4}{\pgf@x#5\pgf@y#6}%
  }%
  \expandafter\pgf@decorate@addtoinputsegmentobjects\expandafter{\pgf@decorate@temp}%
  \edef\pgfpoint@decorate@lastparsed{\pgf@x#5\pgf@y#6}%
  \let\pgfpoint@decorate@lastnonmovetoparsed\pgfpoint@decorate@lastparsed%
  \pgf@decorate@@parsesoftpath%
}


\def\pgf@decorate@parseclosepath#1#2{%
  \pgf@decorate@linelength{\pgfpoint@decorate@lastparsed}{\pgf@x#1\pgf@y#2}%
  \advance\pgfutil@tempdima\pgfmathresult pt\relax%
  \edef\pgf@decorate@temp{%
    \noexpand\pgf@decorate@inputsegmentobject@closepath{\pgfmathresult pt}{\pgfpoint@decorate@lastparsed}{\pgf@x#1\pgf@y#2}%
  }%
  \expandafter\pgf@decorate@addtoinputsegmentobjects\expandafter{\pgf@decorate@temp}%
  \edef\pgfpoint@decorate@lastparsed{\pgf@x#1\pgf@y#2}%
  \let\pgfpoint@decorate@lastnonmovetoparsed\pgfpoint@decorate@lastparsed%
  \pgf@decorate@@parsesoftpath%
}

% Convert \pgfsyssoftpath@rectcornertoken{<X>}{<Y>}\pgfsyssoftpath@rectsizetoken{<Xa>}{<Ya>}
% into either (clockwise)
%
% \pgf@decorate@inputsegmentobject@moveto{<X>}{<Y>}
% \pgf@decorate@inputsegmentobject@lineto{<length 1>}{\pgf@x <X> \pgf@y <Y>}{\pgf@x <X> \pgf@y <Ya+Y>}
% \pgf@decorate@inputsegmentobject@lineto{<length 2>}{\pgf@x <X> \pgf@y <Ya+Y>}{\pgf@x <Xa+X> \pgf@y <Ya+Y>}
% \pgf@decorate@inputsegmentobject@lineto{<length 1>}{\pgf@x <Xa+X> \pgf@y <Ya+X>}{\pgf@x <Xa+X> \pgf@y <Y>}
% \pgf@decorate@inputsegmentobject@lineto{<length 2>}{\pgf@x <Xa+X> \pgf@y <Y>}{\pgf@x <X> \pgf@y <Y>}
% \pgf@decorate@inputsegmentobject@moveto{<Xa>}{<Ya>}
%
% ...or (anti-clockwise)
%
% \pgf@decorate@inputsegmentobject@moveto{<X>}{<Y>}
% \pgf@decorate@inputsegmentobject@lineto{<length 2>}{\pgf@x <X> \pgf@y <Y>}{\pgf@x <Xa+X> \pgf@y <Y>}
% \pgf@decorate@inputsegmentobject@lineto{<length 1>}{\pgf@x <Xa+X> \pgf@y <Y>}{\pgf@x <Xa+X> \pgf@y <Ya+Y>}
% \pgf@decorate@inputsegmentobject@lineto{<length 2>}{\pgf@x <Xa+X> \pgf@y <Ya+Y>}{\pgf@x <X> \pgf@y <Ya+Y>}
% \pgf@decorate@inputsegmentobject@lineto{<length 1>}{\pgf@x <X> \pgf@y <Ya+Y>}{\pgf@x <X> \pgf@y <Y>}
% \pgf@decorate@inputsegmentobject@moveto{<Xa>}{<Ya>}
%
\newif\ifpgfdecoraterectangleclockwise
\def\pgf@decorate@parserect#1#2\pgfsyssoftpath@rectsizetoken#3#4{%
  %
  % Subvert \pgf@decorate@parsesoftpath so parsing macros will
  % return here instead of continuing to parse the soft path.
  %
  \let\pgf@decorate@orig@@parsesoftpath\pgf@decorate@@parsesoftpath%
  \let\pgf@decorate@@parsesoftpath\relax%
  \pgf@decorate@parsemoveto{#1}{#2}%
  \pgf@xa#1\relax%
  \pgf@ya#2\relax%
  \ifpgfdecoraterectangleclockwise%  
    \advance\pgf@ya#4%
    \pgf@yb\pgf@ya%
    \edef\pgf@temp{{\the\pgf@xa}{\the\pgf@ya}}%
    \expandafter\pgf@decorate@parselineto\pgf@temp%
    \advance\pgf@xa#3%
    \pgf@xb\pgf@xa%
    \edef\pgf@temp{{\the\pgf@xa}{\the\pgf@ya}}%
    \expandafter\pgf@decorate@parselineto\pgf@temp%
    \advance\pgf@ya-#4%
    \edef\pgf@temp{{\the\pgf@xa}{\the\pgf@ya}}%
    \expandafter\pgf@decorate@parselineto\pgf@temp%
    \advance\pgf@xa-#3%
    \edef\pgf@temp{{\the\pgf@xa}{\the\pgf@ya}}%
    \expandafter\pgf@decorate@parseclosepath\pgf@temp%
  \else%
    \advance\pgf@xa#3%
    \edef\pgf@temp{{\the\pgf@xa}{\the\pgf@ya}}%
    \pgf@xb\pgf@xa%
    \expandafter\pgf@decorate@parselineto\pgf@temp%
    \advance\pgf@ya#4%
    \pgf@yb\pgf@ya%
    \edef\pgf@temp{{\the\pgf@xa}{\the\pgf@ya}}%
    \expandafter\pgf@decorate@parselineto\pgf@temp%
    \advance\pgf@xa-#3%
    \edef\pgf@temp{{\the\pgf@xa}{\the\pgf@ya}}%
    \expandafter\pgf@decorate@parselineto\pgf@temp%
    \advance\pgf@ya-#4%
    \edef\pgf@temp{{\the\pgf@xa}{\the\pgf@ya}}%
    \expandafter\pgf@decorate@parseclosepath\pgf@temp%
  \fi%  
  %
  % Restore the parsing.
  %
  \let\pgf@decorate@@parsesoftpath\pgf@decorate@orig@@parsesoftpath%
  \edef\pgf@marshal{\noexpand\pgf@decorate@parsemoveto{\the\pgf@xb}{\the\pgf@yb}}%
  \pgf@marshal%
}




% \pgf@decorate@linelength
%
% Define \pgfmathresult as the distance between #1 and #2 (without units).
%
\def\pgf@decorate@linelength#1#2{%
  \pgf@process{\pgfpointdiff{#1}{#2}}%
  \pgfmathveclen@{\pgfmath@tonumber{\pgf@x}}{\pgfmath@tonumber{\pgf@y}}%
}

% \pgf@decorate@curvelength
%
% Define \pgfmathresult as the length (without units) of the cubic 
% bezier described by #1,#2,#3 and #4.
%
% To approximate the length of the curve P (sort of) use:
% 
% curveLength(P,q)
%   Q = subdivideLeft(P);
%    R = subdivideRight(P);
%   return curveLength'(Q,q) + curveLength'(R,q);
%
% curveLength'(P,q)
%    <P1,P2,P3,P4> <- P;
%   P' = P4 - P1;
%   x = P'.x();
%    y = P'.y();
%   if (x < q) && (y < q)
%      return |P'|;
%    else%
%      Q = subdivideLeft(P);
%      R = subdivideRight(P);
%     return curveLength'(Q,q) + curveLength'(R,q);
%  
% Where q is some small value (`tolerance').
% 
\newif\ifpgf@decorate@subdivide
\def\pgf@decorate@curvelength#1#2#3#4{%
  %
  % Always begin with a subdivision in case #1 = #4.
  %
  \begingroup%
    \pgf@decorate@recursive@subdividecurve@left{#1}{#2}{#3}{#4}%
    \pgfutil@tempdimb\pgfmathresult pt\relax%
    \pgf@decorate@recursive@subdividecurve@right{#1}{#2}{#3}{#4}%
    \advance\pgfutil@tempdimb\pgfmathresult pt\relax%
    \pgfmath@returnone\pgfutil@tempdimb%
  \endgroup%
}
  
\def\pgf@decorate@@curvelength#1#2#3#4{%
  \begingroup%
    \pgf@decorate@curvecordlength{#1}{#2}{#3}{#4}%
    \ifpgf@decorate@subdivide%
      \pgf@decorate@recursive@subdividecurve@left{#1}{#2}{#3}{#4}%
      \pgfutil@tempdimb\pgfmathresult pt\relax%
      \pgf@decorate@recursive@subdividecurve@right{#1}{#2}{#3}{#4}%
      \advance\pgfutil@tempdimb\pgfmathresult pt\relax%
      \expandafter\pgfmath@returnone\expandafter\pgfutil@tempdimb%
    \else%
      \expandafter\pgfmath@returnone\expandafter\pgfmathresult\expandafter p\expandafter t\expandafter%
    \fi%
  \endgroup%
}

\def\pgf@decorate@curvelength@tolerance{1pt}

\def\pgf@decorate@curvecordlength#1#2#3#4{%
  % 
  % Calculate the curve cord vector.
  %
  #4\relax%
  \pgf@xa\pgf@x\pgf@ya\pgf@y%
  #1\relax%
  \advance\pgf@xa-\pgf@x%
  \advance\pgf@ya-\pgf@y%
  \ifdim\pgf@xa<0pt\relax\pgf@xa-\pgf@xa\fi%
  \ifdim\pgf@ya<0pt\relax\pgf@ya-\pgf@ya\fi%
  %
  % Always subdivide, unless...
  %
  \pgf@decorate@subdividetrue%
  %
  % The cord vector is small.
  %
  \ifdim\pgf@xa<\pgf@decorate@curvelength@tolerance\relax%
    \ifdim\pgf@ya<\pgf@decorate@curvelength@tolerance\relax%
      \pgfmathveclen@{\pgfmath@tonumber{\pgf@xa}}{\pgfmath@tonumber{\pgf@ya}}%
      \pgf@decorate@subdividefalse%
    \fi%    
  \fi%
}

\def\pgf@decorate@recursive@subdividecurve@left#1#2#3#4{%
  {%
    %
    % The left curve (from t=0 to t=.5) 
    %
    #1\relax%
    \pgfutil@tempdima\pgf@x%
    \pgfutil@tempdimb\pgf@y%
    \pgf@xa.5\pgf@x\pgf@ya.5\pgf@y%
    \pgf@xb.25\pgf@x\pgf@yb.25\pgf@y%
    \pgf@xc.125\pgf@x\pgf@yc.125\pgf@y%
    #2\relax%
    \advance\pgf@xa.5\pgf@x\advance\pgf@ya.5\pgf@y%
    \advance\pgf@xb.5\pgf@x\advance\pgf@yb.5\pgf@y%
    \advance\pgf@xc.375\pgf@x\advance\pgf@yc.375\pgf@y%
    #3\relax%
    \advance\pgf@xb.25\pgf@x\advance\pgf@yb.25\pgf@y%
    \advance\pgf@xc.375\pgf@x\advance\pgf@yc.375\pgf@y%
    #4\relax%
    \advance\pgf@xc.125\pgf@x\advance\pgf@yc.125\pgf@y%
    \xdef\pgf@marshal{%
      \noexpand\pgf@decorate@@curvelength%
        {\pgf@x\the\pgfutil@tempdima\pgf@y\the\pgfutil@tempdimb}%
        {\pgf@x\the\pgf@xa\pgf@y\the\pgf@ya}{\pgf@x\the\pgf@xb\pgf@y\the\pgf@yb}
          {\pgf@x\the\pgf@xc\pgf@y\the\pgf@yc}%
    }%
  }%
  \pgf@marshal%
}

\def\pgf@decorate@recursive@subdividecurve@right#1#2#3#4{%
  {%
    %
    % The right curve (from t=0.5 to t=1) 
    %
    #1\relax%
    \pgfutil@tempdima.125\pgf@x\pgfutil@tempdimb.125\pgf@y%
    #2\relax%
    \advance\pgfutil@tempdima.375\pgf@x\advance\pgfutil@tempdimb.375\pgf@y%
    \pgf@xa.25\pgf@x\pgf@ya.25\pgf@y%
    #3\relax%
    \advance\pgfutil@tempdima.375\pgf@x\advance\pgfutil@tempdimb.375\pgf@y%
    \advance\pgf@xa.5\pgf@x\advance\pgf@ya.5\pgf@y%
    \pgf@xb.5\pgf@x\pgf@yb.5\pgf@y%
    #4\relax%
    \advance\pgfutil@tempdima.125\pgf@x\advance\pgfutil@tempdimb.125\pgf@y%
    \advance\pgf@xa.25\pgf@x\advance\pgf@ya.25\pgf@y%
    \advance\pgf@xb.5\pgf@x\advance\pgf@yb.5\pgf@y%
    \pgf@xc\pgf@x\pgf@yc\pgf@y%
    \xdef\pgf@marshal{%
      \noexpand\pgf@decorate@@curvelength%
        {\pgf@x\the\pgfutil@tempdima\pgf@y\the\pgfutil@tempdimb}%
        {\pgf@x\the\pgf@xa\pgf@y\the\pgf@ya}{\pgf@x\the\pgf@xb\pgf@y\the\pgf@yb}
          {\pgf@x\the\pgf@xc\pgf@y\the\pgf@yc}%
    }%
  }%
  \pgf@marshal%
}


% Macro to reverse a set of input segment objects.
%
% #1 - a macro holding the input segment objects.
% #2 - a macro holding the reversed input segment objects.
%
\def\pgf@decorate@inputsegmentobjects@reverse#1#2{%
  \def\pgf@decorate@path@storein{#2}%
  \def\pgf@decorate@inputsegments@@temp{}%
  \expandafter\pgf@decorate@inputsegments@@reverse@pass@first#1\pgf@stop}

\def\pgf@decorate@inputsegments@@reverse@pass@first#1#2\pgf@stop{%
  \def\pgf@decorate@temp{#1}%
  \expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter%
    \pgf@decorate@inputsegments@@temp\expandafter\expandafter\expandafter%
      {\expandafter\pgf@decorate@temp\pgf@decorate@inputsegments@@temp}%
  \def\pgf@decorate@test{#2}
  \ifx\pgf@decorate@test\pgfutil@empty%
    \def\pgf@decorate@next{%
      \expandafter\pgf@decorate@inputsegmentobjects@reverse@pass@second\pgf@decorate@inputsegments@@temp\pgf@stop%
    }%
  \else%
    \def\pgf@decorate@next{\pgf@decorate@inputsegments@@reverse@pass@first#2\pgf@stop}%
  \fi%
  \pgf@decorate@next%
}  
\def\pgf@decorate@inputsegmentobjects@reverse@pass@second#1#2#3\pgf@stop{%
  \def\pgf@decorate@inputsegments@temp{#3}%
  \def\pgf@decorate@inputsegments@@temp{}%
  \let\pgf@decorate@current@inputsegmentobject=\pgfutil@empty
  \let\pgf@decorate@last@object=\pgfutil@empty
  \pgf@decorate@inputsegmentobjects@reverse@moveto@waitingtrue%
  \pgf@decorate@inputsegmentobjects@reverse@closepath@waitingfalse%
  \expandafter\pgf@decorate@path@@reverse@pass@second\pgf@decorate@inputsegments@temp\pgf@stop}%


\def\pgf@decorate@path@@reverse@pass@second#1{%
  \ifx#1\pgf@stop%
    \expandafter\def\expandafter\pgf@decorate@inputsegments@@temp\expandafter{%
      \pgf@decorate@inputsegments@@temp%
      {\pgf@decorate@inputsegmentobject@endofinputsegments}%
      {\pgf@decorate@inputsegmentobject@endofinputsegments}
    }%
    \expandafter\let\pgf@decorate@path@storein=\pgf@decorate@inputsegments@@temp%
    \let\pgf@decorate@next=\relax%
  \else%
    \ifx#1\pgf@decorate@inputsegmentobject@moveto%
      \let\pgf@decorate@next=\pgf@decorate@inputsegmentobjects@reverse@moveto%
    \else%
      \ifx#1\pgf@decorate@inputsegmentobject@lineto%
        \let\pgf@decorate@next=\pgf@decorate@inputsegmentobjects@reverse@lineto%
      \else%
        \ifx#1\pgf@decorate@inputsegmentobject@curveto%
          \let\pgf@decorate@next=\pgf@decorate@inputsegmentobjects@reverse@curveto%
        \else%
          \ifx#1\pgf@decorate@inputsegmentobject@closepath%  
            \let\pgf@decorate@next=\pgf@decorate@inputsegmentobjects@reverse@closepath%
          \else%
          \fi%
        \fi%
      \fi%
    \fi%
  \fi%
  \pgf@decorate@next%      
}

\newif\ifpgf@decorate@inputsegmentobjects@reverse@moveto@waiting

\def\pgf@decorate@inputsegmentobjects@reverse@moveto#1{%
  \ifpgf@decorate@inputsegmentobjects@reverse@closepath@waiting%
    \edef\pgf@decorate@current@inputsegmentobject{%
      {\noexpand\pgf@decorate@inputsegmentobject@closepath%
        {\pgf@decorate@reverse@closepath@length}%
        {\pgf@decorate@last}%
        {#1}%
      }%
    }%
    \pgf@decorate@inputsegmentobjects@reverse@closepath@waitingfalse%
  \else%
    \let\pgf@decorate@current@inputsegmentobject=\pgfutil@empty%
  \fi%
  \pgf@decorate@inputsegmentobjects@reverse@moveto@waitingtrue%
  \pgf@decorate@path@@@reverse@pass@second%
}

\newif\ifpgf@decorate@inputsegmentobjects@reverse@closepath@waiting

\def\pgf@decorate@inputsegmentobjects@reverse@closepath#1#2#3{%
  \pgf@decorate@inputsegmentobjects@reverse@closepath@waitingtrue%
  \def\pgf@decorate@reverse@closepath@length{#1}%
  \def\pgf@decorate@current@inputsegmentobject{}%
  \pgf@decorate@inputsegmentobjects@reverse@lineto{#1}{#2}{#3}%
}

\def\pgf@decorate@inputsegmentobjects@reverse@lineto#1#2#3#4{%
  \ifpgf@decorate@inputsegmentobjects@reverse@moveto@waiting%
    \def\pgf@decorate@current@inputsegmentobject{{\pgf@decorate@inputsegmentobject@moveto{#3}}}%
    \pgf@decorate@inputsegmentobjects@reverse@moveto@waitingfalse%
  \else%
    \let\pgf@decorate@current@inputsegmentobject=\pgfutil@empty%
  \fi%
  \def\pgf@decorate@append@inputsegmentobject{{\pgf@decorate@inputsegmentobject@lineto{#1}{#3}{#2}}}%
  \ifx#4\pgf@decorate@inputsegmentobject@moveto%
    \ifpgf@decorate@inputsegmentobjects@reverse@closepath@waiting%
      \def\pgf@decorate@append@inputsegmentobject{{\pgf@decorate@inputsegmentobject@closepath{#1}{#3}{#2}}}%
      \pgf@decorate@inputsegmentobjects@reverse@closepath@waitingfalse%
    \else%
      \def\pgf@decorate@append@inputsegmentobject{{\pgf@decorate@inputsegmentobject@lineto{#1}{#3}{#2}}}%
    \fi%
  \fi%
  \expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter%
    \pgf@decorate@current@inputsegmentobject\expandafter\expandafter\expandafter%
      {\expandafter\pgf@decorate@current@inputsegmentobject\pgf@decorate@append@inputsegmentobject}
  \def\pgf@decorate@last{#2}%
  \pgf@decorate@path@@@reverse@pass@second#4%
}

\def\pgf@decorate@inputsegmentobjects@reverse@curveto#1#2#3#4#5{%
  \ifpgf@decorate@inputsegmentobjects@reverse@moveto@waiting%
    \def\pgf@decorate@current@inputsegmentobject{%
      {\pgf@decorate@inputsegmentobject@moveto{#5}}%
      {\pgf@decorate@inputsegmentobject@curveto{#1}{#5}{#4}{#3}{#2}}%
    }%
    \pgf@decorate@inputsegmentobjects@reverse@moveto@waitingfalse%
  \else%
    \def\pgf@decorate@current@inputsegmentobject{{\pgf@decorate@inputsegmentobject@curveto{#1}{#5}{#4}{#3}{#2}}}%
  \fi%
  \def\pgf@decorate@last{#2}%
  \pgf@decorate@path@@@reverse@pass@second%
}

\def\pgf@decorate@path@@@reverse@pass@second{%
  \ifx\pgf@decorate@current@inputsegmentobject\pgfutil@empty%
  \else%
    \expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter%
      \pgf@decorate@inputsegments@@temp\expandafter\expandafter\expandafter%
        {\expandafter\pgf@decorate@inputsegments@@temp\pgf@decorate@current@inputsegmentobject}%
  \fi%  
  \pgf@decorate@path@@reverse@pass@second%
}%





\let\startpgfdecoration=\pgfdecoration
\let\stoppgfdecoration=\endpgfdecoration

\let\startpgfmetadecoration=\pgfmetadecoration
\let\stoppgfmetadecoration=\endpgfmetadecoration



%
% Predefined decorations
%


% Simple decorations. 

\pgfdeclaredecoration{lineto}{initial}{
  \state{initial}[switch if input segment less than=\pgfdecoratedremainingdistance to input segment,
                  width=\pgfdecoratedremainingdistance]
  {
  }
  \state{input segment}[width=\pgfdecoratedinputsegmentlength,next state=initial]
  {
    \pgfpathlineto{\pgfpointdecoratedinputsegmentlast}
  }
  
  \state{final}{\pgfpathlineto{\pgfpointdecoratedpathlast}}
}

\pgfdeclaredecoration{moveto}{initial}{
  \state{initial}[width=\pgfdecoratedremainingdistance]{}
  \state{final}{\pgfpathmoveto{\pgfpointdecoratedpathlast}}
}

% This decorations curves to the end along the line.

\pgfdeclaredecoration{curveto}{initial}{
  \state{initial}[width=\pgfdecoratedinputsegmentlength/100]
  {
    \pgfpathlineto{\pgfpointorigin}
  }
  \state{final}{\pgfpathlineto{\pgfpointdecoratedpathlast}}
}




% Compatibility with old "snakes":

\let\pgfsnakeremainingdistance=\pgfdecoratedremainingdistance
\let\pgfsnakecompleteddistance=\pgfdecoratedcompleteddistance
\def\pgfsnakeangle{\pgfdecoratedangle}
\let\pgfdeclaresnake=\pgfdeclaredecoration
\let\pgfsetsnakesegmenttransformation=\pgfsetdecorationsegmenttransformation
\def\pgfpathsnakesto#1#2{%
  \edef\pgf@temp{#1}%
  \expandafter\pgfdecoration\expandafter{\pgf@temp}%
    \pgfpathlineto{#2}%
  \endpgfdecoration%
}
\def\pgfpathsnaketo#1#2{\pgfpathsnakesto{{#1}{\pgfsnakeremainingdistance}}{#2}}
\def\pgfpathsnakealongvector#1#2#3{%
  \pgf@process{#3}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \pgfmathparse{#2}%
  \pgf@xa=\pgfmathresult\pgf@xa%
  \pgf@ya=\pgfmathresult\pgf@ya%
  \advance\pgf@xa by\pgf@path@lastx%
  \advance\pgf@ya by\pgf@path@lasty%
  \edef\pgf@snake@lib@temp{\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}%
  \pgfpathsnaketo{#1}{\pgf@snake@lib@temp}%
}

\let\pgfsnakesegmentamplitude=\pgfdecorationsegmentamplitude
\let\pgfsnakesegmentlength=\pgfdecorationsegmentlength
\def\pgfsnakesegmentangle{\pgfdecorationsegmentangle}
\def\pgfsnakesegmentobjectlength{\pgfkeysvalueof{/pgf/decoration/shape start width}}
\def\pgfsnakesegmentaspect{\pgfdecorationsegmentaspect}

\pgfset{%
  /pgf/segment amplitude/.style={/pgf/decoration={amplitude=#1,shape height=2*#1}},
  /pgf/segment length/.style={/pgf/decoration={segment length=#1}},
  /pgf/segment angle/.style={/pgf/decoration={angle=#1}},
  /pgf/segment aspect/.style={/pgf/decoration={aspect=#1}},
  /pgf/segment object length/.style={/pgf/decoration={shape width=#1,radius=#1}}}



\endinput
pgfmodulematrix.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/modules/pgfmodulematrix.code.tex,v 1.8 2013/09/17 17:34:00 tantau Exp $

\usepgfmodule{shapes}

\newif\ifpgfmatrix
\newif\ifpgf@matrix@correct@call

\newif\ifpgf@matrix@fixed

\newcount\pgfmatrixcurrentrow

\newcount\pgfmatrixcurrentcolumn
\newcount\pgf@matrix@numberofcolumns

\let\pgf@matrix@cell=\pgfnodeparttextbox % alias
\let\pgf@matrix@box=\pgf@matrix@cell % alias


% Sets the default row or column sep
%
% #1 = default row or column sep list
%
% Description:
%
% Sets the macro \pgfmatrixrowsep or \pgfmatrixcolumnsep to #1.
%
% Example:
%
% \pgfsetmatrixrowsep{5pt}

\def\pgfsetmatrixrowsep#1{\def\pgfmatrixrowsep{#1}}
\def\pgfsetmatrixcolumnsep#1{\def\pgfmatrixcolumnsep{#1}}

\def\pgfmatrixrowsep{0pt}
\def\pgfmatrixcolumnsep{0pt}



% The pgfmatrix command creates a node that contains a matrix. Like
% the \pgfnode command, it is to be used inside a pgfpicture
% environment. 
%
% #1 = shape type
% #2 = anchor
% #3 = name for later reference
% #4 = path usage command
% #5 = inner shift
% #6 = startup code
% #7 = the matrix code (may contain verbatim stuff)
%
% Description:
%
% This command creates a node that contains a matrix. For 
% each cell of the matrix, drawing commands may be given. These
% commands will create a cell picture and a bounding box is computed
% for each cell picture. The cell picture is then placed inside the
% cell. The position inside the cell is computed according to the
% following rules: 
%
% 1. In each column, the origins of the cell pictures are all on a
%    vertical line.
% 2. In each row, the origins of the cell pictures are all on a
%    horizontal line.
% 3. All cells in the same row have the same height and depth.
% 4. All cells in the same column have the same width.
% 5. The size of cells are chosen minimal such that the boxes fit into
%    the cells and still meet the above requirement.
%
% Next, the whole resulting matrix, which is given as #7, is placed
% inside a node whose name is given as #3, whose shape is #1, and
% whose anchor is #2. This means that the resulting node is shifted
% such that the given anchor lies at the origin. Then, as for a normal
% node, the #4 path usage command is used for the node. 
%
% The parameter #5 is an additional negative shift for the node. Normally, such
% a shift could be given beforehand (that is, the shift could be
% preapplied to the current transformation matrix). However, when #5
% is evaluated, you can refer to temporary positions of nodes inside
% the matrix. In detail, the following happens: When the matrix has
% been typeset, all nodes in the matrix temporarily get assigned their
% positions in the matrix box. The origin of this coordinate system is
% at the left baseline end of the matrix box, which corresponds to the
% text anchor. The position #5 is then interpreted inside this
% coordinate system and then used for shifting. 
%
% The idea behind using the parameter #5 is the following: If you
% specify "text" as anchor #2 and specify \pgfpointanchor{inner
% node}{some anchor} for parameter #5, where inner node is a node that
% is created in the matrix, then the whole matrix will be shifted such
% that inner node.some anchor lies at the origin of the whole picture.
%
% At the beginning and at the end of each cell, the macros
% \pgfmatrixbegincode and \pgfmatrixendcode are called. Inside these
% macros you can use \pgfmatrixcurrentcolumn and \pgfmatrixcurrentrow
% to access the current row and column.
%
% Before each column except for the first, an extra space given by the
% macro \pgfmatrixcolumnsep is added. Additionally, an extra space
% given by the optional argument of the \pgfmatrixnextcell commands in
% the first line are added, which may vary between columns. Between
% rows, an extra space given by the macro \pgfmatrixrowsep is
% added. You can also change this value for each row by using a \gdef.
%
%
% Lines are ended using the command \pgfmatrixendrow. The command \\
% is \let to be the same, but \\ is sometimes overridden by, say,
% minipage, so it's good to have \pgfmatrixendrow as a "fallback". 
%
% Inside the matrix, \\ must be used to end every line ***including
% the last***. You can pass an optional parameter to \\ as in \\[2pt]
% to give an additional space after this particular line.
%
% The usage of \\ at the end of the matrix is imporant since this
% command is used to find the end of the matrix. What happens is that
% \\ followed by a closing brace ends the matrix. 
%
% Inside the matrix, you must use \pgfmatrixnextcell to separate
% columns. The reason is that two columns are used internally for
% every single column shown. The macro \pgfmatrixnextcell is yields
% (more or less) two && (and some further trickery).
%
% The parameter #6 is executed at the beginning of the matrix
% group. It is inside the protecting group of the matrix, but outside
% the matrix itself. It can be used for different purposes: 1) It can be
% used to simplify the next cell macro. 2) It can be used to issue an
% \aftergroup command. 3) It can be used to setup local settings. For
% example, by setting #6 to \let\&=\pgfmatrixnextcell you can use \&
% instead of \pgfmatrixnextcell. You can also set the catcode of & to
% active.
%
%
% Example:
%
% \begin{tikzpicture}
%
%   \draw (0,0) circle (1mm);  % b.north will lie on the center of this circle
%
%   \pgfmatrix{rectangle}{text}{mymatrix}{\pgfusepath{}}{\pgfpointanchor{b}{north}}{\let\&=\pgfmatrixnextcell}
%   {
%     \draw (0,0) circle (1cm); \& \node (a) [draw] {Hallo}; \\
%     \node (b) [draw] {Welt};  \& \draw (0,0) circle (5mm); \\
%   }
%
%   \draw [->] (a) -- (b);
%
% \end{tikzpicture}

\def\pgfmatrix#1#2#3#4#5#6{%
  \ifpgfmatrix%
    \pgferror{You cannot nest pgfmatrix environments, yet}
  \fi%
  \bgroup%  
    \everycr{}%
    #6%
    \def\pgf@matrix@par@shape{#1}%
    \def\pgf@matrix@par@anchor{#2}%
    \def\pgf@matrix@par@name{#3}%
    \def\pgf@matrix@par@usage{#4}%
    \def\pgf@matrix@par@shift{#5}%
    % the matrix must have a name:
    \ifx\pgf@matrix@par@name\pgfutil@empty%
      \def\pgf@matrix@par@name{pgf@matrix@internal}%
    \fi%
    \pgfmatrixcurrentrow=0\relax%
    \pgfmatrixcurrentcolumn=0\relax%
    \pgf@matrix@numberofcolumns=0\relax%
    \let\\=\pgfmatrixendrow%
    \tabskip=0pt%
    \offinterlineskip%
    \pgfmatrixtrue%
    \let\pgf@matrix@node@list=\pgfutil@empty%
    \expandafter\let\csname pgf@matrix@column@finish@1\endcsname=\pgfutil@empty%
    \let\pgf@matrix@row@finish=\pgfutil@empty%
    % 
    % Get rid of bgroup
    %
    \afterassignment\pgf@matrix@cont\let\pgf@next=%
}
\def\pgf@matrix@cont{%  
    \setbox\pgf@matrix@box=\hbox\bgroup\vbox\bgroup%
    \halign\bgroup%
    \pgf@matrix@init@row%
    \pgf@matrix@step@column%
    {%
      \pgf@matrix@startcell%
      ##%
      \pgf@matrix@endcell%
    }%
    &%
    ##\pgf@matrix@padding&&%
    \pgf@matrix@step@column%
    {%
      \pgf@matrix@startcell%
      ##%
      \pgf@matrix@endcell%
    }&%
    ##\pgf@matrix@padding%
    \cr%
}

\def\pgf@end@matrix{%
      \egroup\egroup%
    \egroup%
    %
    % If there are named nodes, we must adjust their coordinates.
    %
    \ifx\pgf@matrix@node@list\pgfutil@empty%
    \else%
      % Ok, this means we got a lot of work to do...
      \pgf@matrix@compute@origin%
      \pgf@matrix@shift@nodes@initial%
    \fi%
    %
    % Compute additional shift
    %
    \pgftransformresetnontranslations%
    \pgftransformshift{\pgf@process{\pgftransformreset\pgf@matrix@par@shift\pgf@x=-\pgf@x\pgf@y=-\pgf@y}}%
    %
    % Create node
    %
    \pgfmultipartnode{\pgf@matrix@par@shape}{\pgf@matrix@par@anchor}{\pgf@matrix@par@name}{\pgf@matrix@par@usage}%
    %
    % If there are named nodes, we must adjust their coordinates, again.
    %
    \ifx\pgf@matrix@node@list\pgfutil@empty%
    \else%
      {%
        \pgftransformreset%
        \pgf@process{\pgfpointanchor{\pgf@matrix@par@name}{text}}%
        \xdef\pgf@matrix@offset{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
        \pgf@matrix@shift@nodes@secondary{\pgf@matrix@offset}%
      }%
    \fi%
}




% Ending a cell
%
% #1 = (optional) spacing between previous and next column. This
%      parameter only has an effect in the first row.
%
% Description:
%
% This command ends a cell of a matrix.
%
% Example:
%
% \pgfmatrix{rectangle}{text}{mymatrix}{\pgfusepath{}}{\pgfpointanchor{b}{north}}{}
% {
%   \draw (0,0) circle (1cm); \pgfmatrixnextcell[1cm] \node (a) [draw] {Hallo}; \\
%   \node (b) [draw] {Welt};  \pgfmatrixnextcell \draw (0,0) circle (5mm); \\
% }

\def\pgfmatrixnextcell{%
  % if the cell contains nothing, the following \let will be at the
  % beginning (macro expansion has stopped here since neither \omit
  % nor \span was found)
  \let\pgf@matrix@signal@cell@end=\pgf@matrix@signal@cell@end%
  \pgfutil@ifnextchar[{\pgf@matrix@cell@cont}{\pgf@matrix@cell@cont[0pt]}}%}

\def\pgf@matrix@cell@cont[#1]{%
  \xdef\pgf@matrix@last@nextcell@options{#1}%
  &\pgf@matrix@correct@calltrue&%
}%


\def\pgf@matrix@fixed@text{between origins}
\def\pgf@matrix@natural@text{between borders}

\def\pgf@matrix@addtolength#1#2{\edef\pgf@temp{#2}\expandafter\pgf@matrix@addtolength@\expandafter#1#2,\pgf@stop}
\def\pgf@matrix@addtolength@#1#2,#3\pgf@stop{%
  \def\pgf@temp{#2}%
  \ifx\pgf@temp\pgfutil@empty%
  \else%
    \ifx\pgf@temp\pgf@matrix@fixed@text%
      \global\pgf@matrix@fixedtrue%
    \else%
      \ifx\pgf@temp\pgf@matrix@natural@text%
        \global\pgf@matrix@fixedfalse%
      \else%
        \pgfmathaddtolength{#1}{#2}%
      \fi%
    \fi%
  \fi%
  \def\pgf@temp{#3}%
  \ifx\pgf@temp\pgfutil@empty%
  \else%
    \pgf@matrix@addtolength@#1#3\pgf@stop%
  \fi%
}



% Init a line

\def\pgf@matrix@init@row{%
  \relax%
  \global\advance\pgfmatrixcurrentrow by 1\relax%
  \global\pgfmatrixcurrentcolumn=0\relax%
  \expandafter\gdef\csname pgf@matrix@maxy\the\pgfmatrixcurrentrow\endcsname{0pt}%
  \expandafter\gdef\csname pgf@matrix@miny\the\pgfmatrixcurrentrow\endcsname{0pt}%
}



% Step the row column number

\def\pgf@matrix@step@column{%
  \relax%
  \global\advance\pgfmatrixcurrentcolumn by1\relax%
}



% Start a cell

\def\pgf@matrix@startcell{%
  %
  % Step 1: Init the list of nodes for this cell
  %
  \let\pgf@nodecallback=\pgf@matrix@nodecallback%
  %
  % Step 2: Setup the bounding box
  %
  \pgfinterruptboundingbox%
  %
  % Step 3: Reset the transformation matrix
  %
  \pgftransformreset%
  %
  % Step 4: Collect everything in a cell box
  %
  \setbox\pgf@matrix@cell=\hbox\bgroup\bgroup%
	% make sure that cell pictures are not affected if matrizes have
	% 'overlay' option on:
	\pgf@relevantforpicturesizetrue
    \pgfsys@beginpicture%
    \normalbaselines%
    % Find out whether the cell is empty:
    \pgfutil@ifnextchar\let%
    {% ok, candidate, check following symbol
      \afterassignment\pgf@matrix@empty@check\let\pgf@matrix@temp=% get rid of \let
    }%
    {% no, not empty
      \pgf@matrix@empty@cell@false%
      \pgfmatrixbegincode%
    }%
}

\def\pgf@matrix@empty@check{\futurelet\pgf@matrix@check@token\pgf@matrix@empty@check@cont}
\def\pgf@matrix@empty@check@cont{%
  \ifx\pgf@matrix@check@token\pgf@matrix@signal@cell@end%
    \pgf@matrix@empty@cell@true%
    \expandafter%
    \pgfmatrixemptycode%
    \expandafter%
    \let% reinserted
  \else%
    \pgf@matrix@empty@cell@false%
    \expandafter%
    \pgfmatrixbegincode%
    \expandafter
    \let% reinserted
  \fi%
}   

\newif\ifpgf@matrix@empty@cell@


% End a  cell

\def\pgf@matrix@endcell{%
    \ifpgf@matrix@empty@cell@%
    \else%
      \expandafter\expandafter\expandafter\pgfmatrixendcode%
      \expandafter\ifpgf@matrix@last@cell@in@row\expandafter\pgf@matrix@last@cell@in@rowtrue\expandafter\fi%
    \fi%
    \pgfsys@endpicture%
    \ifnum\pgfmatrixcurrentcolumn<\pgf@matrix@numberofcolumns%
    \else%
    \ifpgf@matrix@last@cell@in@row\else%
    {%
      \global\pgf@matrix@fixedfalse%
      \pgf@x=0pt%
      \pgf@matrix@addtolength{\pgf@x}{\pgfmatrixcolumnsep}%
      \pgf@matrix@addtolength{\pgf@x}{\pgf@matrix@last@nextcell@options}%
      \ifpgf@matrix@fixed%
        \expandafter\pgfutil@g@addto@macro\csname pgf@matrix@column@finish@\the\pgfmatrixcurrentcolumn\endcsname%
          {\global\pgf@picmaxx=0pt}%
      \fi%
      \advance\pgfmatrixcurrentcolumn by1\relax % only temporary for the following:
      \expandafter\xdef\csname pgf@matrix@column@sep@\the\pgfmatrixcurrentcolumn\endcsname{\the\pgf@x}%
      \ifpgf@matrix@fixed%
        \expandafter\gdef\csname pgf@matrix@column@finish@\the\pgfmatrixcurrentcolumn\endcsname{\global\pgf@picminx=0pt}%
      \else%
        \expandafter\global\expandafter\let\csname pgf@matrix@column@finish@\the\pgfmatrixcurrentcolumn\endcsname=\pgfutil@empty%
      \fi%
    }%
    \fi\fi%  
    % Special case of the empty picture
    \ifdim\pgf@picmaxx=-16000pt\relax%
      \global\pgf@picmaxx=0pt\relax%
      \global\pgf@picminx=0pt\relax%
      \global\pgf@picmaxy=0pt\relax%
      \global\pgf@picminy=0pt\relax%
    \fi%
    \csname pgf@matrix@column@finish@\the\pgfmatrixcurrentcolumn\endcsname%
    \pgf@matrix@row@finish%
  \egroup\egroup%
  %
  % Step 5: Horizontal gap
  %
  \ifnum\pgfmatrixcurrentcolumn>1\relax%
    \pgf@y=\csname pgf@matrix@column@sep@\the\pgfmatrixcurrentcolumn\endcsname\relax%
    \advance\pgf@picminx by-\pgf@y%
  \fi%
  % 
  % Step 6: Protocol and adjust height and depth
  %
  % Step 6.1: Protocol...
  %
  \ifdim\pgf@picmaxy>\csname pgf@matrix@maxy\the\pgfmatrixcurrentrow\endcsname%
    \expandafter\xdef\csname pgf@matrix@maxy\the\pgfmatrixcurrentrow\endcsname{\the\pgf@picmaxy}%
  \fi%  
  \ifdim\pgf@picminy<\csname pgf@matrix@miny\the\pgfmatrixcurrentrow\endcsname%
    \expandafter\xdef\csname pgf@matrix@miny\the\pgfmatrixcurrentrow\endcsname{\the\pgf@picminy}%
  \fi%  
  %
  % Step 6.2: and setup.
  %  
  \ht\pgf@matrix@cell=\pgf@picmaxy%
  \dp\pgf@matrix@cell=-\pgf@picminy%
  %
  % Step 7: Protocol and adjust left and right width
  %
  % Step 7.1: Protocol...
  %
  \ifnum\pgfmatrixcurrentcolumn>\pgf@matrix@numberofcolumns\relax%
    \expandafter\xdef\csname pgf@matrix@maxx\the\pgfmatrixcurrentcolumn\endcsname{\the\pgf@picmaxx}%
    \expandafter\xdef\csname pgf@matrix@minx\the\pgfmatrixcurrentcolumn\endcsname{\the\pgf@picminx}%
    \global\pgf@matrix@numberofcolumns=\pgfmatrixcurrentcolumn\relax%
  \else%
    \ifdim\pgf@picmaxx>\csname pgf@matrix@maxx\the\pgfmatrixcurrentcolumn\endcsname%
      \expandafter\xdef\csname pgf@matrix@maxx\the\pgfmatrixcurrentcolumn\endcsname{\the\pgf@picmaxx}%
    \fi%  
    \ifdim\pgf@picminx<\csname pgf@matrix@minx\the\pgfmatrixcurrentcolumn\endcsname%
      \expandafter\xdef\csname pgf@matrix@minx\the\pgfmatrixcurrentcolumn\endcsname{\the\pgf@picminx}%
    \fi%  
  \fi%
  %
  % Step 7.2: and setup.
  %  
  \xdef\pgf@matrix@paddingskip{\the\pgf@picmaxx}%
  % 
  % Step 8: Put in the box now
  %
  \hfil\hskip-\pgf@picminx%
  \wd\pgf@matrix@cell=0pt%
  \box\pgf@matrix@cell%
  %
  % Step 9: End bounding box
  \endpgfinterruptboundingbox%
}

% Default code for the start and end code
\let\pgfmatrixbegincode=\relax
\let\pgfmatrixendcode=\relax
\let\pgfmatrixemptycode=\relax


% The following callback is called for every node that is produced
% inside a cell

\def\pgf@matrix@nodecallback#1{%
  \def\pgf@temp{#1}%
  \ifx\pgf@temp\pgfutil@empty%
  \else%
    \xdef\pgf@matrix@node@list{\pgf@matrix@node@list,{#1}}%
    \expandafter\xdef\csname pgf@matrix@node@location@#1\endcsname{{\the\pgfmatrixcurrentrow}{\the\pgfmatrixcurrentcolumn}}%
  \fi%
}



% Padding code

\def\pgf@matrix@padding{%
  \ifpgf@matrix@correct@call%
  \else%
    \pgferror{Single ampersand used with wrong catcode}%
  \fi%
  \hskip\pgf@matrix@paddingskip\hfil%
}


% Compute the real positions of the origins

% We must now compute the real positions of the origins of all the
% small pictures. To this end, we need to compute prefix sums. After
% the procedure is done, the minx and the maxy will contain the origin
% positions. 

\def\pgf@matrix@compute@origin{%
  %
  % Inverse prefix sum on the vertical positions
  %
  {%
    \ifnum\pgfmatrixcurrentrow>0\relax%
      \expandafter\gdef\csname pgf@matrix@miny\the\pgfmatrixcurrentrow\endcsname{0pt}%
    \fi
    \c@pgf@counta=\pgfmatrixcurrentrow\relax%
    \loop%
    \ifnum\c@pgf@counta>1\relax%
      \pgf@y=\csname pgf@matrix@miny\the\c@pgf@counta\endcsname\relax%
      \advance\pgf@y by\csname pgf@matrix@maxy\the\c@pgf@counta\endcsname\relax
      \advance\c@pgf@counta by-1\relax%
      \pgf@ya=\csname pgf@matrix@miny\the\c@pgf@counta\endcsname\relax%
      \advance\pgf@y by-\pgf@ya\relax%
      \expandafter\xdef\csname pgf@matrix@miny\the\c@pgf@counta\endcsname{\the\pgf@y}%
    \repeat%
  }%
  %
  % Prefix sum on the horizontal positions
  %
  {%
    \ifnum\pgf@matrix@numberofcolumns>0\relax%
      \pgf@x=\csname pgf@matrix@minx1\endcsname\relax%
      \pgf@x=-\pgf@x%
      \expandafter\xdef\csname pgf@matrix@minx1\endcsname{\the\pgf@x}%
    \fi
    \c@pgf@counta=1\relax%
    \loop%
    \ifnum\c@pgf@counta<\pgf@matrix@numberofcolumns\relax%
      \pgf@x=\csname pgf@matrix@minx\the\c@pgf@counta\endcsname\relax%
      \advance\pgf@x by\csname pgf@matrix@maxx\the\c@pgf@counta\endcsname\relax%
      \advance\c@pgf@counta by1\relax%
      \pgf@xa=\csname pgf@matrix@minx\the\c@pgf@counta\endcsname\relax%
      \advance\pgf@x by-\pgf@xa\relax%
      \expandafter\xdef\csname pgf@matrix@minx\the\c@pgf@counta\endcsname{\the\pgf@x}%
    \repeat%
  }%
}


% Shift the nodes to their origins

% The following procedure shifts all nodes in
% \pgf@matrix@node@list to their location inside a temporary
% picture. This picture will later be shifted again to its final
% position in the real picture.

\def\pgf@matrix@shift@nodes@initial{%
  {%
  \pgfutil@for\pgf@matrix@node@name:=\pgf@matrix@node@list\do{%
    \ifx\pgf@matrix@node@name\pgfutil@empty%
    \else%
      \expandafter\ifx\csname pgf@matrix@node@visited@\pgf@matrix@node@name\endcsname\relax%
        \pgf@shift@node{\pgf@matrix@node@name}{%
          \pgf@x=\csname pgf@matrix@minx%
            \expandafter\expandafter\expandafter\pgfutil@secondoftwo\csname pgf@matrix@node@location@\pgf@matrix@node@name\endcsname\endcsname%
          \pgf@y=\csname pgf@matrix@miny%
            \expandafter\expandafter\expandafter\pgfutil@firstoftwo\csname pgf@matrix@node@location@\pgf@matrix@node@name\endcsname\endcsname%
          }%
        \expandafter\let\csname pgf@matrix@node@visited@\pgf@matrix@node@name\endcsname=\pgfutil@empty%
      \fi%
    \fi%
  }%
  }%
}


% The second shifting, done in the following procedure, shifts all
% nodes to their real positions inside the real picture.

\def\pgf@matrix@shift@nodes@secondary#1{%
  \pgfutil@for\pgf@matrix@node@name:=\pgf@matrix@node@list\do{%
    \ifx\pgf@matrix@node@name\pgfutil@empty%
    \else%
      \expandafter\ifx\csname pgf@matrix@node@visited@\pgf@matrix@node@name\endcsname\relax%
        \pgf@shift@node{\pgf@matrix@node@name}{#1}%
        \expandafter\let\csname pgf@matrix@node@visited@\pgf@matrix@node@name\endcsname=\pgfutil@empty%
      \fi%
    \fi%
  }%
}


% End of line
\def\pgfmatrixendrow{%
  % if the cell contains nothing, the following \let will be at the
  % beginning (macro expansion has stopped here since neither \omit
  % nor \span was found)
  \let\pgf@matrix@signal@cell@end=\pgf@matrix@signal@cell@end
  \pgf@matrix@last@cell@in@rowtrue%
  &\pgf@matrix@correct@calltrue%
  \global\pgf@matrix@fixedfalse%
  \pgf@y=0pt%
  \pgf@matrix@addtolength\pgf@y{\pgfmatrixrowsep}%
  \pgfutil@ifnextchar[{\pgfmatrixendrow@skip}{\pgf@matrix@finish@line}%
}
\newif\ifpgf@matrix@last@cell@in@row

\def\pgf@matrix@signal@cell@end{\pgf@matrix@signal@cell@end}
% exact definition does not matter, only needs to be unique.

\def\pgfmatrixendrow@skip[#1]{%
  \pgf@matrix@addtolength\pgf@y{#1}%
  \pgf@matrix@finish@line%
}

\def\pgf@matrix@finish@line{%
  \global\pgf@y=\pgf@y%
  \pgf@ya=-\pgf@y%
  \global\advance\pgf@ya by\csname pgf@matrix@miny\the\pgfmatrixcurrentrow\endcsname%
  \expandafter\xdef\csname pgf@matrix@miny\the\pgfmatrixcurrentrow\endcsname{\the\pgf@ya}%
  \pgfutil@ifnextchar\egroup{\cr\pgf@end@matrix}{\pgf@matrix@no@eom@found}%
}

\def\pgf@matrix@eom@found{%
  \cr%
  \pgf@end@matrix%
}

\def\pgf@matrix@no@eom@found{%
  \cr%
  \noalign{\vskip\pgf@y%
  \ifpgf@matrix@fixed%
    \vskip\csname pgf@matrix@miny\the\pgfmatrixcurrentrow\endcsname% unskip
    \vskip\pgf@y%
    \pgf@y=-\pgf@y%
    \expandafter\xdef\csname pgf@matrix@miny\the\pgfmatrixcurrentrow\endcsname{\the\pgf@y}%
    \gdef\pgf@matrix@row@finish{\global\pgf@picmaxy=0pt}%
  \else%
    \global\let\pgf@matrix@row@finish=\pgfutil@empty%
  \fi%
  }%
}


\endinput

pgfmoduleplot.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/modules/pgfmoduleplot.code.tex,v 1.12 2013/07/31 16:22:24 tantau Exp $


% PGF's plotting interface works as follows:
%
% In order to plot something, two things need to be done. First, you
% need to provide the coordinates (obviously) of the points that
% should be plotted. The coordinates are given via a long stream of
% commands. These commands are \pgfplotstreamstart, which is
% given exactly once at the beginning, the commands
% \pgfplotstreampoint, \pgfplotstreampointoutlier,
% \pgfplotstreampointundefined, \pgfplotstreamnewdataset, of which
% there are numerous in the middle, the special \pgfplotstreamspecial,
% of which there may be numerous in the middle, and \pgfplotstreamend,
% which must be given at the end. Between these commands arbitrary
% other commands may be given. Here is an example:
%
% ...
% \pgfplotstreamstart
% \pgfplotstreampoint{\pgfpointxy{0}{0}}
% \pgfplotstreampoint{\pgfpointxy{1}{1}}
% \pgfplotstreamnewdataset
% \pgfplotstreampoint{\pgfpointxy{2}{4}}
% \relax
% \pgfplotstreampointoutlier{\pgfpointxy{3}{9}}
% \pgfplotstreamspecial{some handler-dependent special stuff}
% \pgfplotstreamend
%
% By themselves, the \pgfplotstreamxxxx commands do not do anything by
% default. Rather, to ``use'' such a stream, you must first install a
% stream handler. For example, the ``lineto'' handler will simply
% basically every \pgfplotstreampoint into a \pgfpathlineto.
% 
% One special things is the handling of "jumps" in a stream. For
% instance, when a lineto handler encounters an "outlier" or a new
% data set, the current line should end and a new subpath should start
% (unless configured otherwise). For this, the special jump handler is
% important. 
%
% Example:
%
% \pgfpathmoveto{\pgfpointorigin}
%
% \pgfplothandlerlineto
% \pgfplotstreamstart
% \pgfplotstreampoint{\pgfpointxy{0}{0}}
% \pgfplotstreampoint{\pgfpointxy{1}{1}}
% \pgfplotstreampoint{\pgfpointxy{2}{4}}
% \relax
% \pgfplotstreampoint{\pgfpointxy{3}{9}}
% \pgfplotstreamend


% The stream commands actually call their ``internal'' versions, which
% are set by the handlers:
\def\pgfplotstreamstart{\pgf@plotstreamstart}
\def\pgfplotstreampoint#1{\gdef\pgfplotlastpoint{#1}\pgf@plotstreampoint{#1}}
\def\pgfplotstreampointoutlier#1{\pgfplot@outliers{}{\pgf@plotstreamjump}{\pgfplotstreampoint{#1}}}%  
\def\pgfplotstreampointundefined{\pgfplot@outliers{}{\pgf@plotstreamjump}{}}%  
\def\pgfplotstreamnewdataset{\pgfplot@outliers{}{\pgf@plotstreamjump}{}}%  
\def\pgfplotstreamspecial{\pgf@plotstreamspecial}
\def\pgfplotstreamend{\pgf@plotstreamend}

\def\pgfplot@ignorer#1#2#3{#1}
\def\pgfplot@jumper#1#2#3{#2}
\def\pgfplot@plotter#1#2#3{#3}

\let\pgfplot@outliers\pgfplot@jumper
\let\pgfplot@undefined\pgfplot@jumper
\let\pgfplot@newdata\pgfplot@jumper

\pgfset{
  handle outlier points in plots/.is choice,
  handle outlier points in plots/ignore/.code=\let\pgfplot@outliers\pgfplot@ignorer,
  handle outlier points in plots/jump/.code=\let\pgfplot@outliers\pgfplot@jumper,
  handle outlier points in plots/plot/.code=\let\pgfplot@outliers\pgfplot@plotter,
  handle undefined points in plots/.is choice,
  handle undefined points in plots/ignore/.code=\let\pgfplot@undefined\pgfplot@ignorer,
  handle undefined points in plots/jump/.code=\let\pgfplot@undefined\pgfplot@jumper,
  handle new data sets in plots/.is choice,
  handle new data sets in plots/ignore/.code=\let\pgfplot@newdata\pgfplot@ignorer,
  handle new data sets in plots/jump/.code=\let\pgfplot@newdata\pgfplot@jumper,
}


% Declares a new plot handler
%
% #1 = macro that should install the stream handler subsequently
% #2 = parameter list of said macro.
% #3 = keys as described below
%
% Description:
% 
% When you declare a new plot handler, you provide, through keys,
% different "actions" that should be taken when the different stream
% commands are used:
% 
% start       = some code to be executed when \pgfplotstreamstart is called
%               for this plothandler
% end         = same for the end of the stream
% point       = code to be executed for a point of the stream
% jump        = code to be executed for a "jump" in the stream
% special     = code to be executed for \pgfplotstreamspecial
% start macro   = here and for the following keys, the to-be-executed
%                 code is stored in the given macro
% end macro     = see above
% jump macro    = see above
% point macro   = see above
% special macro = see above
%
% Example:
% 
% \pgfdeclareplothandler{\ultrasimplehandler}{}{
%   point=\pgfpathlineto{##1}
% }

\def\pgfdeclareplothandler#1#2#3{%
  \def#1#2{%
    \pgfkeys{%
      /pgf/plots/@handler options/.cd,
      start=\relax,
      end macro=\relax,
      point macro=\pgfutil@gobble,
      jump macro=\relax,
      special macro=\pgfutil@gobble,%
      #3%
    }%
  }%
}

\pgfkeys{%
  /pgf/plots/@handler options/.cd,
  start/.code=%
    \gdef\pgf@plotstreamstart{%
      \global\pgf@plot@startedfalse%
      \global\let\pgf@plotstreamend\pgf@plotstreamend@init%
      \global\let\pgf@plotstreampoint\pgf@plotstreampoint@init%
      \global\let\pgf@plotstreamjump\pgf@plotstreamjump@init%
      \global\let\pgf@plotstreamspecial\pgf@plotstreamspecial@init%
      #1%
    },%
  start macro/.code=%
    \gdef\pgf@plotstreamstart{%
      \global\pgf@plot@startedfalse%
      \global\let\pgf@plotstreamend\pgf@plotstreamend@init%
      \global\let\pgf@plotstreampoint\pgf@plotstreampoint@init%
      \global\let\pgf@plotstreamjump\pgf@plotstreamjump@init%
      \global\let\pgf@plotstreamspecial\pgf@plotstreamspecial@init%
      #1%
    },%
  end/.code=\gdef\pgf@plotstreamend@init{#1},
  end macro/.code=\global\let\pgf@plotstreamend@init#1,
  point/.code=\gdef\pgf@plotstreampoint@init##1{#1},
  point macro/.code=\global\let\pgf@plotstreampoint@init#1,
  jump/.code=\gdef\pgf@plotstreamjump@init{#1},
  jump macro/.code=\global\let\pgf@plotstreamjump@init#1,
  special/.code=\gdef\pgf@plotstreamspecial@init##1{#1},
  special macro/.code=\global\let\pgf@plotstreamspecial@init#1,
}

\newif\ifpgf@plot@started




% Sets the action taken for the first point of a plot to a lineto.
%
% Description:
%
% For certain handlers it makes sense either the start a plot by
% moving to the first point of the plot or to do a lineto to that
% first point. Using this command this action can be set to a lineto. 
%
% Example:
%
% \pgfsetlinetofirstplotpoint

\def\pgfsetlinetofirstplotpoint{\let\pgf@plot@first@action=\pgfpathlineto}


% Sets the action taken for the first point of a plot to a moveto.
%
% Example:
%
% \pgfsetmovetofirstplotpoint

\def\pgfsetmovetofirstplotpoint{\let\pgf@plot@first@action=\pgfpathmoveto}

\let\pgf@plot@first@action=\pgfpathmoveto




%
% Handlers
%


% This handler converts each plot stream command into a lineto
% command, except for the first, which is converted to the action that
% has previously been specified using \pgfsetlinetofirstplotpoint or
% \pgfsetmovetofirstplotpoint. 
%
% Example:
%
% \pgfplothandlerlineto
% \pgfplotxyfile{mytable}

\pgfdeclareplothandler{\pgfplothandlerlineto}{}{
  point macro=\pgf@plot@line@handler,
  jump=\global\let\pgf@plotstreampoint\pgf@plot@line@handler@move%
}

\def\pgf@plot@line@handler#1{%
  \pgf@plot@first@action{#1}%
  \global\let\pgf@plotstreampoint=\pgfpathlineto%
}

\def\pgf@plot@line@handler@move#1{%
  \pgfpathmoveto{#1}%
  \global\let\pgf@plotstreampoint=\pgfpathlineto%
}



% This handler turns creates a series of lineto commands, with the
% last command being a closepath, resulting in a closed path. If a
% jump is encountered, the current subpath is closed and a new subpath
% is started.
%
% Example:
%
% \pgfplothandlerpolygon
% \pgfplotxyfile{mytable}

\pgfdeclareplothandler{\pgfplothandlerpolygon}{}{%
  point macro=\pgf@plot@line@handler@close,
  jump macro=\pgf@plot@next@close@and@moveto,
  end macro=\pgf@plot@polygon@stop
}%

\def\pgf@plot@line@handler@close#1{%
  \pgfpathmoveto{#1}%
  \global\pgf@plot@startedtrue%
  \global\let\pgf@plotstreampoint=\pgfpathlineto%
}

\def\pgf@plot@polygon@stop{%
  \ifpgf@plot@started%
    \pgfpathclose%
  \fi%
  \global\pgf@plot@startedfalse%
}

\def\pgf@plot@next@close@and@moveto{%
  \ifpgf@plot@started%
    \pgfpathclose%
  \fi%
  \global\let\pgf@plotstreampoint\pgf@plot@line@handler@close%
}


% More handlers are defined in pgflibraryplothandlers





% This handler discards the plot.
%
% Example:
%
% \pgfplothandlerdiscard
% \pgfplotxyfile{mytable}

\pgfdeclareplothandler{\pgfplothandlerdiscard}{}{}



% This handler records each plot stream command to a macro. This is
% useful if plot commands are difficult to generate and need to be
% ``recylced'' later on.
%
% Example:
%
% \pgfplothandlerrecord{\myplot}
% \pgfplotxyfile{mytable}  % stored in \myplot now
% \pgfplothandlerline
% \myplot
% \pgftransformxshift{1cm}
% \myplot

\pgfdeclareplothandler{\pgfplothandlerrecord}{#1}{%
  start=\gdef#1{\pgfplotstreamstart},
  point=\expandafter\gdef\expandafter#1\expandafter{#1\pgfplotstreampoint{##1}},
  jump=\expandafter\gdef\expandafter#1\expandafter{#1\pgf@plotstreamjump},
  special=\expandafter\gdef\expandafter#1\expandafter{#1\pgfplotstreamspecial{##1}},
  end=\expandafter\gdef\expandafter#1\expandafter{#1\pgfplotstreamend},
}



% Read a plot stream from a file and plot it.
%
% #1 = file from which to read things
%
% File format:
%
% Each line of the file should begin with two numbers separated by a
% space. Such a line with number #1 and #2 is converted to a
% \pgfplotstreampoint{\pgfpointxy{#1}{#2}}. Extra characters following
% on the line are ignored.
%
% Lines starting with ``%'' and ``#'' are ignored.
%
% Example:
%
% \pgfplotxyfile{tableformgnuplot.dat}

\def\pgfplotxyfile#1{%
  \begingroup%
    \pgfplotstreamstart%
    \openin\r@pgf@reada=#1
    \ifeof\r@pgf@reada
      \pgfwarning{Plot data file `#1' not found.}
     \else
      \catcode`\#=14
      \catcode`\^^M=5
      \pgf@readxyfile%
    \fi
    \pgfplotstreamend%    
  \endgroup%
}

\let\pgf@savedpar=\par%
\def\pgf@partext{\par}
\def\pgf@readxyfile{%
  \pgfutil@read\r@pgf@reada to \pgf@temp%
  \let\par=\pgf@savedpar%
  \edef\pgf@temp{\pgf@temp}%
  \ifx\pgf@temp\pgfutil@empty%
    \ifeof\r@pgf@reada\else\pgfplotstreamnewdataset\fi%
  \else\ifx\pgf@temp\pgf@partext%
    \ifeof\r@pgf@reada\else\pgfplotstreamnewdataset\fi%
  \else%
    \expandafter\pgf@parsexyline\pgf@temp\pgf@stop%
  \fi\fi%
  \ifeof\r@pgf@reada\else\expandafter\pgf@readxyfile\fi%
}

\def\pgf@parsexyline#1 #2 #3\pgf@stop{%
  \edef\pgf@xyline@flag@val{#3}%
  \ifx\pgf@xyline@flag@val\pgf@xyline@flag@undef%
    \pgfplotstreampointundefined%
  \else\ifx\pgf@xyline@flag@val\pgf@xyline@flag@out%
    \pgfplotstreampointoutlier{\pgfpointxy{#1}{#2}}%
  \else%
    \pgfplotstreampoint{\pgfpointxy{#1}{#2}}%
  \fi\fi%
}

\edef\pgf@xyline@flag@out{o\space}%
\edef\pgf@xyline@flag@undef{u\space}%




% Read a plot stream from a file and plot it.
%
% #1 = file from which to read things
%
% File format:
%
% Like xy, except that each line contains three numbers, which are
% converted to xyz coordiantes.
%
% Example:
%
% \pgfplotxyfile{tableformgnuplot.dat}

\def\pgfplotxyzfile#1{%
  \begingroup%
    \pgfplotstreamstart%
    \openin\r@pgf@reada=#1
    \ifeof\r@pgf@reada
      \pgfwarning{Plot data file `#1' not found.}
    \else
      \catcode`\#=14
      \catcode`\^^M=5
      \pgf@readxyzfile%
    \fi
    \pgfplotstreamend%    
  \endgroup%
}

\def\pgf@readxyzfile{%
  \pgfutil@read\r@pgf@reada to \pgf@temp%
  \ifx\pgf@temp\pgfutil@empty%
    \ifeof\r@pgf@reada\else\pgfplotstreamnewdataset\fi%
  \else\ifx\pgf@temp\pgf@partext%
    \ifeof\r@pgf@reada\else\pgfplotstreamnewdataset\fi%
  \else%
    \expandafter\pgf@parsexyzline\pgf@temp\pgf@stop%
  \fi\fi%
  \ifeof\r@pgf@reada\else\expandafter\pgf@readxyzfile\fi%
}

\def\pgf@parsexyzline#1 #2 #3 #4\pgf@stop{%
  \edef\pgf@xyline@flag@val{#4}%
  \ifx\pgf@xyline@flag@val\pgf@xyline@flag@undef%
    \pgfplotstreampointundefined%
  \else\ifx\pgf@xyline@flag@val\pgf@xyline@flag@out%
    \pgfplotstreampointoutlier{\pgfpointxyz{#1}{#2}{#3}}%
  \else%
    \pgfplotstreampoint{\pgfpointxyz{#1}{#2}{#3}}%
  \fi\fi%
}




% Render a function using gnuplot.
%
% #1 = filename prefix for .gnuplot and .table files (optional,
%      default is \jobname)
% #2 = gnuplot function text
%
% Description:
%
% This command will write a file called #1.gnuplot that sets up
% some gnuplot commands to write output to a file called
% #1.table. Then it calls gnuplot (using the \write18 mechanism)
% to execute the file. Then it reads #2.table using \pgfplotxyfile.
%
% Example:
%
% \pgfplothandlerlineto
% \pgfplotgnuplot[\jobname]{plot [x=0:5] x*sin(x)}

{
  \catcode`\%=12
  \catcode`\"=12
  \xdef\pgf@gnuplot@head{set table \noexpand\pgf@plottablefile@quoted; set format "%.5f"}
}

\let\pgf@plotwrite=\w@pgf@writea
\newif\ifpgf@resample@plot

\pgfkeys{%
  /pgf/plot/gnuplot call/.initial={gnuplot}}

\def\pgfplotgnuplot{\pgfutil@ifnextchar[{\pgf@plotgnuplot}{\pgf@plotgnuplot[\jobname]}}%}
\def\pgf@plotgnuplot[#1]#2{%
  \pgf@resample@plottrue%
  \pgfutilpreparefilename{#1.gnuplot}%
  \let\pgf@plotgnuplotfile=\pgfretval
  \pgfutilpreparefilename{#1.table}%
  \let\pgf@plottablefile=\pgfretval
  \let\pgf@plottablefile@quoted=\pgfretvalquoted
  % Check, whether it is up-to-date
  \openin\pgfutil@inputcheck=\pgf@plotgnuplotfile\relax
  \ifeof\pgfutil@inputcheck%
  \else%
    \pgfutil@read\pgfutil@inputcheck to\pgf@temp% ignored
    \pgfutil@read\pgfutil@inputcheck to\pgf@plot@line%
	\closein\pgfutil@inputcheck
    \edef\pgf@plot@code{#2\space}%
    \ifx\pgf@plot@code\pgf@plot@line%
      \openin\pgfutil@inputcheck=\pgfretval\relax
      \ifeof\pgfutil@inputcheck%
      \else%
	    \closein\pgfutil@inputcheck
        \pgf@resample@plotfalse%
      \fi%
    \fi%
  \fi
  \ifpgf@resample@plot%  
    \immediate\openout\pgf@plotwrite=\pgf@plotgnuplotfile\relax
    \immediate\pgfutil@write\pgf@plotwrite{\pgf@gnuplot@head}%
    \immediate\pgfutil@write\pgf@plotwrite{#2}%
    \immediate\closeout\pgf@plotwrite%
    \immediate\pgfutil@write18{%
      \pgfkeysvalueof{/pgf/plot/gnuplot call} \pgf@plotgnuplotfile}%
  \fi%
%  \let\pgf@savedparsexyline=\pgf@parsexyline%
%  \let\pgf@parsexyline=\pgf@parsegnuplotxyline%
  \pgfplotxyfile{\pgf@plottablefile}%
%  \let\pgf@parsexyline=\pgf@savedparsexyline%
}

% \def\pgf@parsegnuplotxyline#1 #2 #3\pgf@stop{%
%   \edef\pgf@xyline@flag@val{#3}%
%   \edef\pgf@xyline@flag@out{o\space}%
%   \edef\pgf@xyline@flag@undef{u\space}%
%   \ifx\pgf@xyline@flag@val\pgf@xyline@flag@undef%
%     \pgfplotstreampointundefined%
%   \else\ifx\pgf@xyline@flag@val\pgf@xyline@flag@out%
%     \pgfplotstreampointoutlier{\pgfpointxy{#1}{#2}}%
%   \else%
%     \pgfplotstreampoint{\pgfpointxy{#1}{#2}}%
%   \fi\fi%
% }

% This producer handler plots a function using pgf's mathematical engine.
%
% #1 = variable
% #2 = domain for the variable
% #3 = point, typically defined in terms of the value of the variable
%
% Description:
%
% This producer will iterate the variable #1 over all variables in #2
% (using the \foreach statement). For each value, a plot coordinate
% #3  is created.
%
% Note that this command is pretty slow.
%
% Example:
%
% \pgfplothandlerlineto
% \pgfplotfunction{\x}{0,0.1,...,3.141}{\pgfpointxy{\x}{sin(\x)}}

\def\pgfplotfunction#1#2#3{%
  \pgfplotstreamstart%
  \foreach#1in{#2}%
  {%
    \pgf@process{#3}%
    \edef\pgf@marshal{\noexpand\pgfplotstreampoint{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}}%
    \pgf@marshal%
  }
  \pgfplotstreamend%
}




\endinput

pgfmoduleshapes.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/modules/pgfmoduleshapes.code.tex,v 1.34 2013/10/31 15:44:19 tantau Exp $



\newbox\pgfnodeparttextbox


% Creates a node
%
% #1 = shape type
% #2 = anchor
% #3 = name for later reference
% #4 = path usage command
%
% Description:
%
% This command draws a shape that has previously been defined using
% \pgfdeclareshape. The shape is shifted such that the anchor is at
% the origin. In order to transform the whole shape, you should setup
% pgf's transformation matrix prior to calling this command.
%
% When this command is called, the shape-specific TeX boxes of the
% node must have been setup correctly.
%
% Example:
%
% \pgftransformshift{\pgfpoint{1cm}{1cm}}
% \pgfmultipartnode{rectangle}{center}{hellonode}{\pgfusepath{stroke}}

\def\pgfmultipartnode#1#2#3#4{%
  \pgfutil@ifundefined{pgf@sh@s@#1}%
  {\pgferror{Unknown shape ``#1''}}%
  {%
    {%
      \let\pgf@sh@savedmacros=\pgfutil@empty% MW
      \let\pgf@sh@savedpoints=\pgfutil@empty%
      \def\pgf@sm@shape@name{#1}% CJ % TT added prefix!
      \csname pgf@sh@s@#1\endcsname%
      \pgf@sh@savedpoints%
      \pgf@sh@savedmacros% MW
      \pgftransformshift{%
        \pgf@sh@reanchor{#1}{#2}%
        \pgf@x=-\pgf@x%
        \pgf@y=-\pgf@y%
      }%
      \expandafter\pgfsavepgf@process\csname pgf@sh@sa@#3\endcsname{%
      	\pgf@sh@reanchor{#1}{#2}% FIXME : this is double work!
      }%
      % Save the saved points and the transformation matrix
      \edef\pgf@node@name{#3}%
      \ifpgflatenodepositioning
        \pgf@shapes@late@pos@begin%
      \fi%
      \ifx\pgf@node@name\pgfutil@empty%
      \else%
        \expandafter\xdef\csname pgf@sh@ns@\pgf@node@name\endcsname{#1}%
        \edef\pgf@sh@@temp{\noexpand\gdef\expandafter\noexpand\csname pgf@sh@np@\pgf@node@name\endcsname}%
        \expandafter\pgf@sh@@temp\expandafter{\pgf@sh@savedpoints}%
        \edef\pgf@sh@@temp{\noexpand\gdef\expandafter\noexpand\csname pgf@sh@ma@\pgf@node@name\endcsname}% MW
        \expandafter\pgf@sh@@temp\expandafter{\pgf@sh@savedmacros}% MW
        \pgfgettransform\pgf@temp%
        \expandafter\xdef\csname pgf@sh@nt@\pgf@node@name\endcsname{\pgf@temp}%
        \expandafter\xdef\csname pgf@sh@pi@\pgf@node@name\endcsname{\pgfpictureid}%
      \fi%
      \pgfutil@ifundefined{pgf@sh@bbg@#1}{}
      {{\pgfscope\csname pgf@sh@bbg@#1\endcsname\endpgfscope}}%
      \pgfutil@ifundefined{pgf@sh@bg@#1}{%
        \global\let\pgfpositionnodelaterpath\pgfutil@empty%
      }%
      {\csname pgf@sh@bg@#1\endcsname%
        \ifpgflatenodepositioning%
          \pgfsyssoftpath@getcurrentpath\pgfpositionnodelaterpath%
          \pgfprocessround{\pgfpositionnodelaterpath}{\pgfpositionnodelaterpath}%
          \global\let\pgfpositionnodelaterpath\pgfpositionnodelaterpath%
        \fi%
        #4}%
      \pgfutil@ifundefined{pgf@sh@fbg@#1}{}
      {{\pgfscope\csname pgf@sh@fbg@#1\endcsname\endpgfscope}}%
      {%
        \expandafter\pgfutil@for\expandafter\pgf@shape@com\expandafter:\expandafter=\csname pgf@sh@boxes@#1\endcsname\do{%
          {%
            \pgftransformshift{\pgf@sh@reanchor{#1}{\pgf@shape@com}}%
              \pgfapproximatenonlineartransformation%
            \expandafter\pgfqboxsynced\expandafter{\csname pgfnodepart\pgf@shape@com box\endcsname}%
          }%
        }%
      }%
      \pgfutil@ifundefined{pgf@sh@bfg@#1}{}%
      {{\pgfscope\csname pgf@sh@bfg@#1\endcsname\endpgfscope}}%
      \pgfutil@ifundefined{pgf@sh@fg@#1}{}%
      {\csname pgf@sh@fg@#1\endcsname#4}%
      \pgfutil@ifundefined{pgf@sh@ffg@#1}{}%
      {{\pgfscope\csname pgf@sh@ffg@#1\endcsname\endpgfscope}}%
      \ifpgflatenodepositioning%
        \pgf@shapes@late@pos@end%
      \else%
        \expandafter\pgf@nodecallback\expandafter{\pgf@node@name}%
      \fi%
    }%
  }%
}

\def\pgf@shapes@late@pos@begin{%
  % Rename node
  \edef\pgf@node@name{not yet positionedPGFINTERNAL\pgf@node@name}%
  % Interrupt bounding box!
  \pgfinterruptboundingbox%
    % Put everything in our box:
    \pgf@relevantforpicturesizetrue%
    \setbox\pgfpositionnodelaterbox=\hbox%
      \bgroup%
}
  
\def\pgf@shapes@late@pos@end{%
      \egroup% Close box
    \ifdim\pgf@picminx>\pgf@picmaxx\relax% happens for empty nodes
      \def\pgfpositionnodelaterminx{0.0pt}%
      \let\pgfpositionnodelaterminy\pgfpositionnodelaterminx%
      \let\pgfpositionnodelatermaxx\pgfpositionnodelaterminx%
      \let\pgfpositionnodelatermaxy\pgfpositionnodelaterminx%
    \else%
      \edef\pgfpositionnodelaterminx{\the\pgf@picminx}%
      \edef\pgfpositionnodelaterminy{\the\pgf@picminy}%
      \edef\pgfpositionnodelatermaxx{\the\pgf@picmaxx}%
      \edef\pgfpositionnodelatermaxy{\the\pgf@picmaxy}%
    \fi%
    \let\pgfpositionnodelatername=\pgf@node@name%
    \pgf@positionnodelater@macro%
  \endpgfinterruptboundingbox%
}
      
\def\pgf@shift@node#1#2{%
  % This internal command shifts the recorded coordinates for node #1
  % by the vector #2. It is used to
  % correct the position of the node if the recorded coordinate
  % happens to be wrong
  {%
    \pgfsettransform{\csname pgf@sh@nt@#1\endcsname}%
    \pgf@process{#2}%
    \advance\pgf@pt@x by\pgf@x%
    \advance\pgf@pt@y by\pgf@y%
    \pgfgettransform{\pgf@temp}%
    \expandafter\xdef\csname pgf@sh@nt@#1\endcsname{\pgf@temp}%
  }%
}

\let\pgf@nodecallback=\pgfutil@gobble



% Creates a node
%
% #1 = shape type
% #2 = anchor
% #3 = normal TeX text
% #4 = name for later reference
% #5 = path usage command
%
% Description:
%
% This command draws a shape that has previously been defined using
% \pgfdeclareshape. The shape is shifted such that the anchor is at
% the origin. In order to transform the whole shape, you should setup
% pgf's transformation matrix prior to calling this command.
%
% Example:
%
% \pgftransformshift{\pgfpoint{1cm}{1cm}}
% \pgfnode{rectangle}{center}{Hello}{hellonode}{\pgfusepath{stroke}}

\def\pgfnode#1#2#3#4#5{%
  {%
    \setbox\pgfnodeparttextbox=\hbox%
    {%
      \pgfinterruptpicture%
        {#3}%
      \endpgfinterruptpicture%
    }%
    \pgfmultipartnode{#1}{#2}{#4}{#5}%
  }
}  



% Create a node that is positioned later
%
% #1 = macro to be called after the next node has been created
%
% Description:
%
% You can use this command to create a node that is "positioned
% later". The idea is the following: Normally, when a node is created
% using a command like \pgfnode, the node is immediately inserted into
% the current picture. In particular, you have no chance to change the
% position of a created node after it has been create.
%
% Using \pgfpositionnodelater, you can change the default
% behaviour. This command is not a replacement for \pgfnode, but is
% called before such a command and will cause the following to happen:
% The node is created, but not inserted into the picture. Instead, it
% is stored in the box \pgfpositionnodelaterbox. Furthermore, the node
% is not relevant for the picture's bounding box, but a bounding box
% for the node is computed and stored in the macros
% \pgfpositionnodelaterboundboxminx to
% \pgfpositionnodelaterboundboxmaxy. Finally, the 
% macro #1 is called with the following macros setup:
% 
%   \pgfpositionnodelaterbox
%   A box register (box 0 by default) that stores the node's paths and
%   texts. You should move the contents of this box to a box of your
%   choice. 
%
%   \pgfpositionnodelatername
%   The name of the just-created-node. This name will be the
%   originally "desired" name of the box plus the prefix "not yet
%   positioned boxPGFINTERNAL".
%
%   \pgfpositionnodelaterminx
%   \pgfpositionnodelatermaxx
%   \pgfpositionnodelaterminy
%   \pgfpositionnodelatermaxy
%   These four macros store the bounding box as dimensions that are
%   guarenteed to end with "pt".
%   
% By setting #1 to \relax (which is the default), you can switch off
% the whole mechanism
% 
% Once a late node has been created, you can add arbitrary code in the
% same picture. Then, at some later point, you call
% \pgfpositionnodenow to finally position the node at a given position.
% 
% When \pgfpositionnodenow is called, the macros mentioned above
% should have the exact same values they had when #1 is called.

\def\pgfpositionnodelater#1{%
  \let\pgf@positionnodelater@macro=#1%
  \ifx\pgf@positionnodelater@macro\relax%
    \pgflatenodepositioningfalse%
  \else%
    \pgflatenodepositioningtrue%
  \fi%
}
\newif\ifpgflatenodepositioning
\pgfpositionnodelater{\relax}
\def\pgfpositionnodelaterbox{0}




% Position a node that has been scheduled for later insertion
%
% #1 = position in the picture, where the original anchor should go,
%      now 
%
% Description:
%
% This command works in concert with \pgfpositionnodelater, see the
% description there. When \pgfpositionnodenow is called, the macros
% \pgfpositionnodelaterbox and so on should be set to the values they
% had when the macro given to \pgfpositionnodelater was called. Then,
% the box described by these macros will be inserted into the picture
% at the position given #1. More precisely, the original node will
% have been positioned such that the anchor given upon invocation is
% at (0,0) and the node is now shifted by #1 before being inserted
% into the actual picture.

\def\pgfpositionnodenow#1{%
  \pgfinterruptpath%
  {%
    \pgfpointtransformed{#1}%
    \edef\pgf@temp@shift{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}
    \pgftransformreset%
    \pgftransformshift{\pgf@temp@shift}%
    \pgfsys@pictureboxsynced\pgfpositionnodelaterbox%
    \pgf@shift@node{\pgfpositionnodelatername}{\pgf@temp@shift}%
    % Bounding box update...
    \pgfpointtransformed{\pgfqpoint{\pgfpositionnodelaterminx}{\pgfpositionnodelaterminy}}%
    \pgf@protocolsizes{\pgf@x}{\pgf@y}
    \pgfpointtransformed{\pgfqpoint{\pgfpositionnodelatermaxx}{\pgfpositionnodelatermaxy}}%
    \pgf@protocolsizes{\pgf@x}{\pgf@y}
    % Naming and callbacks
    \expandafter\pgfpositionnodenow@rename\pgfpositionnodelatername\relax%
  }%
  % Late setup%
  {%
    \csname pgf@lns@\pgfpositionnodelatername\endcsname%  
    \expandafter\global\expandafter\let\csname pgf@lns@\pgfpositionnodelatername\endcsname\relax%  
  }%
  \endpgfinterruptpath%
}

\def\pgfpositionnodenow@rename not yet positionedPGFINTERNAL#1\relax{%
  \pgfnoderename{#1}{not yet positionedPGFINTERNAL#1}
  \pgf@nodecallback{#1}%
}



% "Fake" a node 
% 
% #1 = node name
% 
% Description:
% 
% This command will setup things so that it "looks like" a node named
% #1 has been created, but, in reality, no node is created. The idea
% is that a node created in this way can be referenced by systems
% using the late positioning, which will only create the node later
% on.
%
\def\pgffakenode#1{%
  \edef\pgf@temp{\ifpgflatenodepositioning not yet positionedPGFINTERNAL\fi#1}%
  \expandafter\gdef\csname pgf@sh@ns@\pgf@temp\endcsname{coordinate}%
  \expandafter\gdef\csname pgf@sh@np@\pgf@temp\endcsname{\def\centerpoint{\pgfpointorigin}}%
  \expandafter\gdef\csname pgf@sh@nt@\pgf@temp\endcsname{{1}{0}{0}{1}{0pt}{0pt}}%
  \expandafter\global\expandafter\let\csname pgf@sh@ma@\pgf@temp\endcsname\pgfutil@empty%
  \expandafter\xdef\csname pgf@sh@pi@\pgf@temp\endcsname{\pgfpictureid}%
}



% Specify code that should be executed after a node has been created
%
% #1 = node name
% #2 = later code
%
% Description:
%
% This macro allows you to provide some code #2 that will be executed
% right after a node has been positioned using \pgfpositionnodenow. If
% the node has already been positioned (if the late positioning is not
% switched on), nothing happens.

\def\pgfnodepostsetupcode#1#2{%
  \ifpgflatenodepositioning%
    \expandafter\ifx\csname pgf@lns@not yet positionedPGFINTERNAL#1\endcsname\relax%
      \expandafter\gdef\csname pgf@lns@not yet positionedPGFINTERNAL#1\endcsname{#2}%
    \else%
      \expandafter\pgfutil@g@addto@macro\csname pgf@lns@not yet positionedPGFINTERNAL#1\endcsname{#2}%
    \fi%
  \fi%
}



% Alias a node
%
% #1 = new node name
% #2 = existing node name
%
% Description:
%
% This command allows you to subsequently access the node #2 using the
% name #1.
%
% Example:
%
% \pgfnode{rectangle}{center}{Hallo}{hellonode}{}
% \pgfnodealias{mynode}{hellonode}

\def\pgfnodealias#1#2{%
  \pgf@node@gnamelet{pgf@sh@ns@#1}{pgf@sh@ns@#2}%
  \pgf@node@gnamelet{pgf@sh@np@#1}{pgf@sh@np@#2}%
  \pgf@node@gnamelet{pgf@sh@nt@#1}{pgf@sh@nt@#2}%
  \pgf@node@gnamelet{pgf@sh@pi@#1}{pgf@sh@pi@#2}%
  \pgf@node@gnamelet{pgf@sh@ma@#1}{pgf@sh@ma@#2}%
  \pgf@nodecallback{#1}%
}
\def\pgf@node@gnamelet#1#2{%
  \expandafter\let\expandafter\pgf@temp\csname #2\endcsname%
  \expandafter\global\expandafter\let\csname #1\endcsname=\pgf@temp%
}

% Rename a node
% 
% #1 = new name
% #2 = old name
% 
% Description:
% 
% Renames a node. This is like an alias, only the memory used for the
% old name is freed.

\def\pgfnoderename#1#2{%
  \pgfnodealias{#1}{#2}%
  \expandafter\global\expandafter\let\csname pgf@sh@ns@#2\endcsname\relax
  \expandafter\global\expandafter\let\csname pgf@sh@np@#2\endcsname\relax
  \expandafter\global\expandafter\let\csname pgf@sh@nt@#2\endcsname\relax
  \expandafter\global\expandafter\let\csname pgf@sh@pi@#2\endcsname\relax
  \expandafter\global\expandafter\let\csname pgf@sh@ma@#2\endcsname\relax
}


% Quickly create a coordinate node
%
% #1 = name
% #2 = coordinate
%
% Description:
%
% Creates a node of shape coordinate. The following have the same
% effect, only the second is much faster:
%
% { \pgftransformshift{\pgfpoint{1cm}{2cm} \pgfnode{coordinate}{center}{}{foo}{} }
% \pgfcoordinate{foo}{\pgfpoint{1cm}{2cm}}

\def\pgfcoordinate#1#2{%
  \edef\pgf@temp{#1}%
  \ifx\pgf@temp\pgfutil@empty% do nothing
  \else%
    \ifpgflatenodepositioning%
      {\pgftransformshift{#2}\pgfnode{coordinate}{center}{}{#1}{}}%
    \else%
      \pgf@process{\pgfpointtransformed{#2}}%
      \expandafter\gdef\csname pgf@sh@ns@#1\endcsname{coordinate}%
      \expandafter\xdef\csname pgf@sh@np@#1\endcsname{%
        \noexpand\def\noexpand\centerpoint{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
      }
      \expandafter\gdef\csname pgf@sh@nt@#1\endcsname{{1}{0}{0}{1}{0pt}{0pt}}%
      \expandafter\global\expandafter\let\csname pgf@sh@ma@#1\endcsname\pgfutil@empty%
      \expandafter\xdef\csname pgf@sh@pi@#1\endcsname{\pgfpictureid}%
    \fi%
  \fi%
}

\def\pgf@sh@redeferredanchor#1#2{% CJ
  \expandafter\gdef\csname pgf@anchor@\pgf@sm@shape@name @#1\endcsname{#2}}% CJ






\def\pgf@sh@resavedanchor#1#2{%
  \pgf@process{#2}%
  \edef\pgf@sh@marshal{%
    \noexpand\pgfutil@g@addto@macro\noexpand\pgf@sh@savedpoints{%
      \noexpand\def\noexpand#1{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
    }}%
  \pgf@sh@marshal%
}


\def\pgf@sh@resaveddimen#1#2{%
  {#2\global\pgf@x=\pgf@x}%
  \edef\pgf@sh@marshal{%
    \noexpand\pgfutil@g@addto@macro\noexpand\pgf@sh@savedpoints{%
      \noexpand\def\noexpand#1{\the\pgf@x}%
    }}%
  \pgf@sh@marshal%
}

\def\pgf@sh@resavedmacro#1#2{%
	\let#1\pgfutil@empty%
	\def\addtosavedmacro##1{%
		\expandafter\def\expandafter\pgf@sh@addtomacro@temp\expandafter{#1\noexpand\def\noexpand##1{##1}}%
		{\expandafter\pgfutil@toks@\expandafter{\pgf@sh@addtomacro@temp}\expandafter}%
		\expandafter\def\expandafter#1\expandafter{\the\pgfutil@toks@}%
	}%
  #2\relax%
  \edef\pgf@sh@marshal{%
    \noexpand\pgfutil@g@addto@macro\noexpand\pgf@sh@savedmacros{%
      \noexpand\def\noexpand#1{#1}%
    }}%
  \pgf@sh@marshal%
}

% Invoke an anchor
\def\pgf@sh@reanchor#1#2{%
  \pgfutil@ifundefined{pgf@anchor@#1@#2}%
  {%
    \pgfutil@ifundefined{pgf@anchor@generic@#2}{%
	    \pgfmathsetcounter{pgf@counta}{#2}%
	    \csname pgf@anchor@#1@border\endcsname{\pgfqpointpolar{\the\c@pgf@counta}{1pt}}%
    }{%
        \csname pgf@anchor@generic@#2\endcsname{#1}%
    }%
  }%
  {\csname pgf@anchor@#1@#2\endcsname}%
}

% Defines a generic anchor, i.e. one which gets the associated shape
% as first argument.
%
% #1: the anchor name.
% #2: the code of the anchor. It may depend upon '##1', the shape's
% name.
%
% The anchor will be defined locally in the current TeX scope.
%
% If the anchor will be referenced later by \pgfpointanchor, the macro \pgfreferencednodename
% can be used to query the referenced node's name.
% This macro is not defined during node creation.
\def\pgfdeclaregenericanchor#1#2{%
  \expandafter\def\csname pgf@anchor@generic@#1\endcsname##1{#2}%
}%


% Retrieves an anchor of a shape
%
% #1 = name
% #2 = anchor or a number (corresponding to a degree)
%
% Description:
%
% This command yields a point at the anchor of the given named shape.
%
% Example:
%
% \pgfshape{rectangle}{center}{Hello}{hellonode}{\pgfusepath[stroke]}
% \pgfpathmoveto{\pgfpointanchor{hellonode}{center}}

\def\pgfpointanchor#1#2{%
  % Ok, check whether #1 is known!
  \pgfutil@ifundefined{pgf@sh@ns@#1}
  {\pgfutil@ifundefined{pgf@sh@ns@not yet positionedPGFINTERNAL#1}{%
      \pgferror{No shape named #1 is known}}{
      % else, fail silently
    }%
    \pgfpointorigin}%
  {%
    \pgf@process{%
      \edef\pgfreferencednodename{#1}% for use inside of anchors.
      % MW install special macros
      \csname pgf@sh@ma@#1\endcsname% MW
      % install special coordinates
      \csname pgf@sh@np@#1\endcsname
      \pgf@sh@reanchor{\csname pgf@sh@ns@#1\endcsname}{#2}%
      {%
        \pgfsettransform{\csname pgf@sh@nt@#1\endcsname}%
        \pgf@pos@transform{\pgf@x}{\pgf@y}%
        \global\pgf@x=\pgf@x%
        \global\pgf@y=\pgf@y%
      }%
      % Add inter picture transformation
      \pgf@shape@interpictureshift{#1}%
      % Undo current transformation
      \pgftransforminvert%
      \pgf@pos@transform{\pgf@x}{\pgf@y}%
    }%
  }%
}

\def\pgf@shape@interpictureshift#1{%
  \expandafter\ifx\csname pgf@sh@pi@#1\endcsname\pgfpictureid%
  \else%
    \pgfsys@getposition{\csname pgf@sh@pi@#1\endcsname}\pgf@shape@original@pos%
    \pgfsys@getposition{\pgfpictureid}\pgf@shape@current@pos%
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgf@process{\pgfpointorigin\pgf@shape@current@pos}%
    \advance\pgf@xa by-\pgf@x%
    \advance\pgf@ya by-\pgf@y%
    \pgf@process{\pgfpointorigin\pgf@shape@original@pos}%
    \advance\pgf@xa by\pgf@x%
    \advance\pgf@ya by\pgf@y%
    \pgf@x=\pgf@xa%
    \pgf@y=\pgf@ya%
  \fi%
}



% Retrieves a border point of a shape
%
% #1 = name
% #2 = another point
%
% Description:
%
% This command yields a point on the border of the shape that is on a
% straight line from the center to the point #2.
%
% Example:
%
% \pgfshape{rectangle}{center}{Hello}{hellonode}{\pgfusepath[stroke]}
% \pgfpathmoveto{\pgfpointshapeborder{hellonode}{\pgfpoint{2cm}{1cm}}
% \pgfpathlineto{\pgfpoint{2cm}{1cm}}
% \pgfusepath{stroke}

\def\pgfpointshapeborder#1#2{%
  % Ok, check whether #1 is known!
  \pgfutil@ifundefined{pgf@sh@ns@#1}
  {\pgferror{No shape named #1 is known}%
    \pgfpointorigin}%
  {%
    \pgf@process{%
      \edef\pgfreferencednodename{#1}% for use inside of anchors.
      % MW install special macros
      \csname pgf@sh@ma@#1\endcsname% MW
      % install special coordinates
      \csname pgf@sh@np@#1\endcsname%
      {%
        \pgf@process{\pgfpointtransformed{#2}}%
        \pgfsettransform{\csname pgf@sh@nt@#1\endcsname}%
        \pgftransforminvert%
        \pgf@pos@transform{\pgf@x}{\pgf@y}%
        \pgf@xa=\pgf@x%
        \pgf@ya=\pgf@y%
        \pgf@process{\csname pgf@anchor@\csname pgf@sh@ns@#1\endcsname @center\endcsname}%
        \pgf@process{\pgf@shape@interpictureshift{#1}}%%
        \advance\pgf@xa by-\pgf@x%
        \advance\pgf@ya by-\pgf@y%
        \csname pgf@anchor@\csname pgf@sh@ns@#1\endcsname @border\endcsname{\pgfqpoint{\pgf@xa}{\pgf@ya}}%
        \pgfsettransform{\csname pgf@sh@nt@#1\endcsname}%
        \pgf@pos@transform{\pgf@x}{\pgf@y}%
        \global\pgf@x=\pgf@x%
        \global\pgf@y=\pgf@y%
      }%
      % Add inter picture transformation
      \pgf@shape@interpictureshift{#1}%
      % Undo current transformation
      \pgftransforminvert%
      \pgf@pos@transform{\pgf@x}{\pgf@y}%
    }%
  }%
}


% Retrieve the list of node parts of a shape
%
% #1 = a macro
% #2 = a shape name
%
% Description:
%
% Stores the list of node parts of a shape #2 in the macro #1.
%
% Example:
%
% \pgfgetnodeparts\mylist{circle split}
%
% This will set \mylist\ to "text,lower"

\def\pgfgetnodeparts#1#2{%
  \expandafter\let\expandafter#1\csname pgf@sh@boxes@#2\endcsname%
}


% Declares a shape type
%
% #1 = shape type
% #2 = shape specification
%
% Description:
%
% This command declares a new shape type. The shape specification
% should contain the following commands:
%
% - \savedanchor
%   This command takes two arguments: a name and some code. The point
%   specified by the code (the \pgf@x and \pgf@y values resulting from
%   executing the code, to be precise), will be stored under the given
%   name. Whenever, later on, an anchor is invoked these stored points
%   will be available. The \saveddimen works like \savedanchor, only a
%   single dimension is stored (taken from \pgf@x).
%   When a savedanchor is calculated, the height/width/depth of the
%   boxes mentioned in \nodeparts can be used.
%
% - \anchor
%   Specifies an anchor. This command takes two arguments: an anchor
%   name and some code for computing the anchor. When the anchor
%   computation starts, all shape points and shape dimension will be
%   setup.
%
% - \anchorborder
%   This command should compute a point on the border of the
%   shape. When the code is called, \pgf@x and \pgf@y will have been
%   preinitialised with a direction.
%
% - \behindbackgroundpath
%   Some things to be draw behind everything.
%
% - \backgroundpath
%   A path that is drawn behind the main box. How this path is used
%   depends on how \pgfshape is called.
%
% - \beforebackgroundpath
%   Some things to be draw before the background path, but behind the
%   main box.
%
% - \behindforegroundpath
%   Some things to be draw on top of the main box.
%
% - \foregroundpath
%   A path that is drawn on top of all of the above. How this path is
%   used depends on how \pgfshape is called.
%
% - \beforeforegroundpath
%   Some things to be draw before everything.
%
% - \nodeparts
%   List of node parts that make up the shape. For each entry XYZ in
%   the list there must be a box named \pgfnodepartXYZbox (possibly
%   ``redirected'' to some different box using \let). Each such box
%   will be placed at the anchor XYZ.
%   By default, \nodeparts is just {text}. Thus, there will be one
%   node part box named \pgfnodeparttextbox and this node will be
%   placed at the anchor text. 
%   
%
% Example:
%
% See the definition of rectangle, below.

\long\def\pgfdeclareshape#1#2{%
  {
    \def\pgf@sm@shape@name{#1}
    \let\savedanchor=\pgf@sh@savedanchor
    \let\saveddimen=\pgf@sh@saveddimen
    \let\savedmacro=\pgf@sh@savedmacro% MW
    \let\deferredanchor=\pgf@sh@deferredanchor% CJ
    \let\anchor=\pgf@sh@anchor
    \let\anchorborder=\pgf@sh@anchorborder
    \let\behindbackgroundpath=\pgf@sh@behindbgpath
    \let\backgroundpath=\pgf@sh@bgpath
    \let\beforebackgroundpath=\pgf@sh@beforebgpath
    \let\behindforegroundpath=\pgf@sh@behindfgpath
    \let\foregroundpath=\pgf@sh@fgpath
    \let\beforeforegroundpath=\pgf@sh@beforefgpath
    \let\nodeparts=\pgf@sh@boxes
    \let\inheritsavedanchors=\pgf@sh@inheritsavedanchors
    \let\inheritanchor=\pgf@sh@inheritanchor
    \let\inheritanchorborder=\pgf@sh@inheritanchorborder
    \let\inheritbehindbackgroundpath=\pgf@sh@inheritbehindbgpath
    \let\inheritbackgroundpath=\pgf@sh@inheritbgpath
    \let\inheritbeforebackgroundpath=\pgf@sh@inheritbeforebgpath
    \let\inheritbehindforegroundpath=\pgf@sh@inheritbehindfgpath
    \let\inheritforegroundpath=\pgf@sh@inheritfgpath
    \let\inheritbeforeforegroundpath=\pgf@sh@inheritbeforefgpath
    \let\inheritnodeparts=\pgf@sh@inheritboxes
    \anchorborder{\csname pgf@anchor@#1@center\endcsname}%
    \anchor{text}{\pgfpointorigin}%
    \nodeparts{text}%
    \expandafter\global\expandafter\let\csname pgf@sh@s@\pgf@sm@shape@name\endcsname=\pgfutil@empty%
    #2
  }
}

\def\pgf@sh@savedanchor#1#2{%
  \expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@\pgf@sm@shape@name\endcsname{\pgf@sh@resavedanchor{#1}{#2}}}
\def\pgf@sh@saveddimen#1#2{%
  \expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@\pgf@sm@shape@name\endcsname{\pgf@sh@resaveddimen{#1}{#2}}}
 \def\pgf@sh@savedmacro#1#2{% MW
  \expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@\pgf@sm@shape@name\endcsname{\pgf@sh@resavedmacro{#1}{#2}}}% MW
\def\pgf@sh@anchor#1#2{\expandafter\gdef\csname pgf@anchor@\pgf@sm@shape@name @#1\endcsname{#2}}
\def\pgf@sh@deferredanchor#1#2{% CJ
  \expandafter\pgfutil@g@addto@macro
    \csname pgf@sh@s@\pgf@sm@shape@name\endcsname{\pgf@sh@redeferredanchor{#1}{#2}}}% CJ
\def\pgf@sh@anchorborder#1{\expandafter\gdef\csname pgf@anchor@\pgf@sm@shape@name @border\endcsname##1{\pgf@process{##1}#1}}
\long\def\pgf@sh@behindbgpath#1{\expandafter\gdef\csname pgf@sh@bbg@\pgf@sm@shape@name\endcsname{#1}}
\long\def\pgf@sh@bgpath#1{\expandafter\gdef\csname pgf@sh@bg@\pgf@sm@shape@name\endcsname{#1}}
\long\def\pgf@sh@beforebgpath#1{\expandafter\gdef\csname pgf@sh@fbg@\pgf@sm@shape@name\endcsname{#1}}
\long\def\pgf@sh@behindfgpath#1{\expandafter\gdef\csname pgf@sh@bfg@\pgf@sm@shape@name\endcsname{#1}}
\long\def\pgf@sh@fgpath#1{\expandafter\gdef\csname pgf@sh@fg@\pgf@sm@shape@name\endcsname{#1}}
\long\def\pgf@sh@beforefgpath#1{\expandafter\gdef\csname pgf@sh@ffg@\pgf@sm@shape@name\endcsname{#1}}
\def\pgf@sh@boxes#1{\expandafter\gdef\csname pgf@sh@boxes@\pgf@sm@shape@name\endcsname{#1}}

\def\pgf@sh@inheritsavedanchors[from=#1]{%
  \expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@\pgf@sm@shape@name\endcsname{\csname pgf@sh@s@#1\endcsname}}
  
 \def\pgf@sh@inheritanchor[from=#1]#2{%
  \edef\pgf@marshal{\global\let\expandafter\noexpand\csname
    pgf@anchor@\pgf@sm@shape@name @#2\endcsname=\expandafter\noexpand\csname
    pgf@anchor@#1@#2\endcsname}%
  \pgf@marshal%
}
\def\pgf@sh@inheritanchorborder[from=#1]{%
  \edef\pgf@marshal{\global\let\expandafter\noexpand\csname
    pgf@anchor@\pgf@sm@shape@name @border\endcsname=\expandafter\noexpand\csname
    pgf@anchor@#1@border\endcsname}%
  \pgf@marshal%
}
\def\pgf@sh@inheritor#1#2{%
  \edef\pgf@marshal{\global\let\expandafter\noexpand\csname
    pgf@sh@#1@\pgf@sm@shape@name\endcsname=\expandafter\noexpand\csname
    pgf@sh@#1@#2\endcsname}%
  \pgf@marshal%
}
\def\pgf@sh@inheritbehindbgpath[from=#1]{\pgf@sh@inheritor{bbg}{#1}}
\def\pgf@sh@inheritbgpath[from=#1]{\pgf@sh@inheritor{bg}{#1}}
\def\pgf@sh@inheritbeforebgpath[from=#1]{\pgf@sh@inheritor{fbg}{#1}}
\def\pgf@sh@inheritbehindfgpath[from=#1]{\pgf@sh@inheritor{bfg}{#1}}
\def\pgf@sh@inheritfgpath[from=#1]{\pgf@sh@inheritor{fg}{#1}}
\def\pgf@sh@inheritbeforefgpath[from=#1]{\pgf@sh@inheritor{ffg}{#1}}
\def\pgf@sh@inheritboxes[from=#1]{\pgf@sh@inheritor{boxes}{#1}}



% 
% Coordinate. This shape is special: It is only used to reference a
% point for later usage. Nothing is drawn, all anchors are identical
% to the center. 
%

\pgfdeclareshape{coordinate}
{
  \savedanchor\centerpoint{%
    % x
    \pgf@x=.5\wd\pgfnodeparttextbox%
    % y
    \pgf@y=.5\ht\pgfnodeparttextbox%
    \advance\pgf@y by -.5\dp\pgfnodeparttextbox%
  }
  
  \anchor{center}{\centerpoint}
  \anchor{north}{\centerpoint}
  \anchor{north west}{\centerpoint}
  \anchor{north east}{\centerpoint}
  \anchor{center}{\centerpoint}
  \anchor{west}{\centerpoint}
  \anchor{east}{\centerpoint}
  \anchor{mid}{\centerpoint}
  \anchor{mid west}{\centerpoint}
  \anchor{mid east}{\centerpoint}
  \anchor{base}{\centerpoint}
  \anchor{base west}{\centerpoint}
  \anchor{base east}{\centerpoint}
  \anchor{south}{\centerpoint}
  \anchor{south west}{\centerpoint}
  \anchor{south east}{\centerpoint}
  \anchorborder{\centerpoint}

  \nodeparts{}% no text
}


% Value keys for shapes:
%
% /pgf/inner xsep     : recommended inner x separation
% /pgf/inner ysep     : recommended inner y separation
% /pgf/outer xsep     : recommended outer x separation
% /pgf/outer ysep     : recommended outer y separation
% /pgf/minimum width  : recommended minimum width
% /pgf/minimum height : recommended minimum height

\pgfset{
  inner xsep/.initial     =.3333em,
  inner ysep/.initial     =.3333em,
  inner sep/.style        ={/pgf/inner xsep=#1,/pgf/inner ysep=#1},
  outer xsep/.initial     =.5\pgflinewidth,
  outer ysep/.initial     =.5\pgflinewidth,
  outer sep/.style        ={/pgf/outer xsep=#1,/pgf/outer ysep=#1},
  minimum width/.initial  =1pt,
  minimum height/.initial =1pt,
  minimum size/.style     ={/pgf/minimum width=#1,/pgf/minimum height=#1},
}

% Keys for rotating the shape border.
% (may not be supported by all shapes)
%
% /pgf/shape border uses incircle : Calculate the shape border using the incircle 
%                                   around the node contents (+inner sep).
%						
% /pgf/shape border rotate        : Angle of independent border rotation.

\newif\ifpgfshapeborderusesincircle
\pgfkeys{/pgf/shape border uses incircle/.is if=pgfshapeborderusesincircle}
\pgfkeys{/pgf/shape border rotate/.initial=0}

% 
% Rectangle
%

\pgfdeclareshape{rectangle}
{
  \savedanchor\northeast{%
    % Calculate x
    %
    % First, is width < minimum width?
    \pgf@x=\the\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@xc{\pgfkeysvalueof{/pgf/inner xsep}}%
    \advance\pgf@x by 2\pgf@xc%
    \pgfmathsetlength\pgf@xb{\pgfkeysvalueof{/pgf/minimum width}}%
    \ifdim\pgf@x<\pgf@xb%
      % yes, too small. Enlarge...
      \pgf@x=\pgf@xb%
    \fi%
    % Now, calculate right border: .5\wd\pgfnodeparttextbox + .5 \pgf@x + outer sep
    \pgf@x=.5\pgf@x%
    \advance\pgf@x by.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/outer xsep}}%
    \advance\pgf@x by\pgf@xa%
    % Calculate y
    %
    % First, is height+depth < minimum height?
    \pgf@y=\ht\pgfnodeparttextbox%
    \advance\pgf@y by\dp\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@yc{\pgfkeysvalueof{/pgf/inner ysep}}%
    \advance\pgf@y by 2\pgf@yc%
    \pgfmathsetlength\pgf@yb{\pgfkeysvalueof{/pgf/minimum height}}%
    \ifdim\pgf@y<\pgf@yb%
      % yes, too small. Enlarge...
      \pgf@y=\pgf@yb%
    \fi%
    % Now, calculate upper border: .5\ht-.5\dp + .5 \pgf@y + outer sep
    \pgf@y=.5\pgf@y%
    \advance\pgf@y by-.5\dp\pgfnodeparttextbox%
    \advance\pgf@y by.5\ht\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/outer ysep}}%
    \advance\pgf@y by\pgf@ya%
  }
    
  \savedanchor\southwest{%
      % Calculate x
      %
      % First, is width < minimum width?
      \pgf@x=\wd\pgfnodeparttextbox%
      \pgfmathsetlength\pgf@xc{\pgfkeysvalueof{/pgf/inner xsep}}%
      \advance\pgf@x by 2\pgf@xc%
      \pgfmathsetlength\pgf@xb{\pgfkeysvalueof{/pgf/minimum width}}%
      \ifdim\pgf@x<\pgf@xb%
        % yes, too small. Enlarge...
        \pgf@x=\pgf@xb%
      \fi%
      % Now, calculate left border: .5\wd\pgfnodeparttextbox - .5 \pgf@x - outer sep
      \pgf@x=-.5\pgf@x%
      \advance\pgf@x by.5\wd\pgfnodeparttextbox%
      \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/outer xsep}}%
      \advance\pgf@x by-\pgf@xa%
      % Calculate y
      %
      % First, is height+depth < minimum height?
      \pgf@y=\ht\pgfnodeparttextbox%
      \advance\pgf@y by\dp\pgfnodeparttextbox%
      \pgfmathsetlength\pgf@yc{\pgfkeysvalueof{/pgf/inner ysep}}%
      \advance\pgf@y by 2\pgf@yc%
      \pgfmathsetlength\pgf@yb{\pgfkeysvalueof{/pgf/minimum height}}%
      \ifdim\pgf@y<\pgf@yb%
        % yes, too small. Enlarge...
        \pgf@y=\pgf@yb%
      \fi%
       % Now, calculate upper border: .5\ht-.5\dp - .5 \pgf@y - outer sep
      \pgf@y=-.5\pgf@y%
      \advance\pgf@y by-.5\dp\pgfnodeparttextbox%
      \advance\pgf@y by.5\ht\pgfnodeparttextbox%
      \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/outer ysep}}%
      \advance\pgf@y by-\pgf@ya%
  }

  %
  % Anchors
  % 
  \anchor{center}{
    \pgf@process{\northeast}%
    \pgf@xa=.5\pgf@x%
    \pgf@ya=.5\pgf@y%
    \pgf@process{\southwest}%
    \pgf@x=.5\pgf@x%
    \pgf@y=.5\pgf@y%
    \advance\pgf@x by \pgf@xa%
    \advance\pgf@y by \pgf@ya%
  }
  \anchor{mid}{\pgf@anchor@rectangle@center\pgfmathsetlength\pgf@y{.5ex}}
  \anchor{base}{\pgf@anchor@rectangle@center\pgf@y=0pt}
  \anchor{north}{
    \pgf@process{\southwest}%
    \pgf@xa=.5\pgf@x%
    \pgf@process{\northeast}%
    \pgf@x=.5\pgf@x%
    \advance\pgf@x by \pgf@xa%
  }
  \anchor{south}{
    \pgf@process{\northeast}%
    \pgf@xa=.5\pgf@x%
    \pgf@process{\southwest}%
    \pgf@x=.5\pgf@x%
    \advance\pgf@x by \pgf@xa%
  }
  \anchor{west}{
    \pgf@process{\northeast}%
    \pgf@ya=.5\pgf@y%
    \pgf@process{\southwest}%
    \pgf@y=.5\pgf@y%
    \advance\pgf@y by \pgf@ya%
  }
  \anchor{mid west}{\southwest\pgfmathsetlength\pgf@y{.5ex}}
  \anchor{base west}{\southwest\pgf@y=0pt}
  \anchor{north west}{
    \southwest
    \pgf@xa=\pgf@x
    \northeast
    \pgf@x=\pgf@xa}
  \anchor{south west}{\southwest}
  \anchor{east}{%
    \pgf@process{\southwest}%
    \pgf@ya=.5\pgf@y%
    \pgf@process{\northeast}%
    \pgf@y=.5\pgf@y%
    \advance\pgf@y by \pgf@ya%
  }
  \anchor{mid east}{\northeast\pgfmathsetlength\pgf@y{.5ex}}
  \anchor{base east}{\northeast\pgf@y=0pt}
  \anchor{north east}{\northeast}
  \anchor{south east}{
    \northeast
    \pgf@xa=\pgf@x
    \southwest
    \pgf@x=\pgf@xa
  }
  \anchorborder{%
    \pgf@xb=\pgf@x% xb/yb is target
    \pgf@yb=\pgf@y%
    \southwest%
    \pgf@xa=\pgf@x% xa/ya is se
    \pgf@ya=\pgf@y%
    \northeast%
    \advance\pgf@x by-\pgf@xa%
    \advance\pgf@y by-\pgf@ya%
    \pgf@xc=.5\pgf@x% x/y is half width/height
    \pgf@yc=.5\pgf@y%
    \advance\pgf@xa by\pgf@xc% xa/ya becomes center
    \advance\pgf@ya by\pgf@yc%
    \edef\pgf@marshal{%
      \noexpand\pgfpointborderrectangle
      {\noexpand\pgfqpoint{\the\pgf@xb}{\the\pgf@yb}}
      {\noexpand\pgfqpoint{\the\pgf@xc}{\the\pgf@yc}}%
    }%
    \pgf@process{\pgf@marshal}%
    \advance\pgf@x by\pgf@xa%
    \advance\pgf@y by\pgf@ya%
  }

  %
  % Background path
  %
  \backgroundpath{
    \pgfpathrectanglecorners
    {\pgfpointadd{\southwest}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}
    {\pgfpointadd{\northeast}{\pgfpointscale{-1}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}}
  }
}


% Special current path start coordinate:
\expandafter\def\csname pgf@sh@ns@current subpath start\endcsname{coordinate}
\expandafter\def\csname pgf@sh@np@current subpath start\endcsname{%
  \def\centerpoint{\expandafter\pgfqpoint\pgfsyssoftpath@lastmoveto}%
}
\expandafter\def\csname pgf@sh@nt@current subpath start\endcsname{{1}{0}{0}{1}{0pt}{0pt}}
\expandafter\def\csname pgf@sh@pi@current subpath start\endcsname{\pgfpictureid}



% Special  current bounding box  rectangle:
\expandafter\def\csname pgf@sh@ns@current bounding box\endcsname{rectangle}
\expandafter\def\csname pgf@sh@np@current bounding box\endcsname{%
  \def\southwest{\pgfqpoint{\pgf@picminx}{\pgf@picminy}}%
  \def\northeast{\pgfqpoint{\pgf@picmaxx}{\pgf@picmaxy}}%
}
\expandafter\def\csname pgf@sh@nt@current bounding box\endcsname{{1}{0}{0}{1}{0pt}{0pt}}
\expandafter\def\csname pgf@sh@pi@current bounding box\endcsname{\pgfpictureid}


% Special  current path bounding box  rectangle:
\expandafter\def\csname pgf@sh@ns@current path bounding box\endcsname{rectangle}
\expandafter\def\csname pgf@sh@np@current path bounding box\endcsname{%
  \def\southwest{\pgfqpoint{\pgf@pathminx}{\pgf@pathminy}}%
  \def\northeast{\pgfqpoint{\pgf@pathmaxx}{\pgf@pathmaxy}}%
}
\expandafter\def\csname pgf@sh@nt@current path bounding box\endcsname{{1}{0}{0}{1}{0pt}{0pt}}
\expandafter\def\csname pgf@sh@pi@current path bounding box\endcsname{\pgfpictureid}


% Special  current page bounding box rectangle:
\expandafter\def\csname pgf@sh@ns@current page\endcsname{rectangle}
\expandafter\def\csname pgf@sh@np@current page\endcsname{%
  \def\southwest{\pgfpointorigin}%
  \def\northeast{\pgfpoint{\pgfsys@thepagewidth}{\pgfsys@thepageheight}}%
}
\expandafter\def\csname pgf@sh@nt@current page\endcsname{{1}{0}{0}{1}{0pt}{0pt}}
\expandafter\def\csname pgf@sh@pi@current page\endcsname{pgfpageorigin}


% Special scope bounding box rectangle:
\pgfkeys{/pgf/local bounding box/.code={%
    \expandafter\gdef\csname pgf@sh@ns@#1\endcsname{rectangle}
    \expandafter\gdef\csname pgf@sh@np@#1\endcsname{%
      \def\southwest{\pgfqpoint{\csname pgf@lbb@minx@#1\endcsname}{\csname pgf@lbb@miny@#1\endcsname}}%
      \def\northeast{\pgfqpoint{\csname pgf@lbb@maxx@#1\endcsname}{\csname pgf@lbb@maxy@#1\endcsname}}%
    }
    \expandafter\gdef\csname pgf@sh@nt@#1\endcsname{{1}{0}{0}{1}{0pt}{0pt}}
    \expandafter\gdef\csname pgf@sh@pi@#1\endcsname{\pgfpictureid}
    \expandafter\gdef\csname pgf@lbb@maxx@#1\endcsname{-16000pt}%
    \expandafter\gdef\csname pgf@lbb@minx@#1\endcsname{16000pt}%
    \expandafter\gdef\csname pgf@lbb@maxy@#1\endcsname{-16000pt}%
    \expandafter\gdef\csname pgf@lbb@miny@#1\endcsname{16000pt}%
    \pgf@size@hookedtrue%
    \expandafter\def\expandafter\pgf@path@size@hook\expandafter{\pgf@path@size@hook\pgf@lbb@do{#1}}
  },
  /pgf/freeze local bounding box/.code={%
    {%
      \csname pgf@sh@np@#1\endcsname%
      \southwest%
      \pgf@xa=\pgf@x%
      \pgf@ya=\pgf@y%
      \northeast%
      \expandafter\xdef\csname pgf@sh@np@#1\endcsname{%
        \noexpand\def\noexpand\southwest{\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}%
        \noexpand\def\noexpand\northeast{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
      }%
    }%  
  }
}
\def\pgf@lbb@do#1{%
  \ifdim\pgf@size@hook@x<\csname pgf@lbb@minx@#1\endcsname\expandafter\xdef\csname pgf@lbb@minx@#1\endcsname{\the\pgf@size@hook@x}\fi%
  \ifdim\pgf@size@hook@x>\csname pgf@lbb@maxx@#1\endcsname\expandafter\xdef\csname pgf@lbb@maxx@#1\endcsname{\the\pgf@size@hook@x}\fi%
  \ifdim\pgf@size@hook@y<\csname pgf@lbb@miny@#1\endcsname\expandafter\xdef\csname pgf@lbb@miny@#1\endcsname{\the\pgf@size@hook@y}\fi%
  \ifdim\pgf@size@hook@y>\csname pgf@lbb@maxy@#1\endcsname\expandafter\xdef\csname pgf@lbb@maxy@#1\endcsname{\the\pgf@size@hook@y}\fi%
}

%
% Circle
%

\pgfdeclareshape{circle}
%
% Draws a circle around the text
%
{
  \savedanchor\centerpoint{%
    \pgf@x=.5\wd\pgfnodeparttextbox%
    \pgf@y=.5\ht\pgfnodeparttextbox%
    \advance\pgf@y by-.5\dp\pgfnodeparttextbox%
  }
    
  \saveddimen\radius{%
    % 
    % Caculate ``height radius''
    % 
    \pgf@ya=.5\ht\pgfnodeparttextbox%
    \advance\pgf@ya by.5\dp\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@yb{\pgfkeysvalueof{/pgf/inner ysep}}%
    \advance\pgf@ya by\pgf@yb%
    % 
    % Caculate ``width radius''
    % 
    \pgf@xa=.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@xb{\pgfkeysvalueof{/pgf/inner xsep}}%
    \advance\pgf@xa by\pgf@xb%
    % 
    % Calculate length of radius vector:
    % 
    \pgf@process{\pgfpointnormalised{\pgfqpoint{\pgf@xa}{\pgf@ya}}}%
    \ifdim\pgf@x>\pgf@y%
        \c@pgf@counta=\pgf@x%
        \ifnum\c@pgf@counta=0\relax%
        \else%
          \divide\c@pgf@counta by 255\relax%
          \pgf@xa=16\pgf@xa\relax%
          \divide\pgf@xa by\c@pgf@counta%
          \pgf@xa=16\pgf@xa\relax%
        \fi%
      \else%
        \c@pgf@counta=\pgf@y%
        \ifnum\c@pgf@counta=0\relax%
        \else%
          \divide\c@pgf@counta by 255\relax%
          \pgf@ya=16\pgf@ya\relax%
          \divide\pgf@ya by\c@pgf@counta%
          \pgf@xa=16\pgf@ya\relax%
        \fi%
    \fi%
    \pgf@x=\pgf@xa%
    % 
    % If necessary, adjust radius so that the size requirements are
    % met: 
    % 
    \pgfmathsetlength{\pgf@xb}{\pgfkeysvalueof{/pgf/minimum width}}%  
    \pgfmathsetlength{\pgf@yb}{\pgfkeysvalueof{/pgf/minimum height}}%  
    \ifdim\pgf@x<.5\pgf@xb%
        \pgf@x=.5\pgf@xb%
    \fi%
    \ifdim\pgf@x<.5\pgf@yb%
        \pgf@x=.5\pgf@yb%
    \fi%
    % 
    % Now, add larger of outer sepearations.
    % 
    \pgfmathsetlength{\pgf@xb}{\pgfkeysvalueof{/pgf/outer xsep}}%  
    \pgfmathsetlength{\pgf@yb}{\pgfkeysvalueof{/pgf/outer ysep}}%  
    \ifdim\pgf@xb<\pgf@yb%
      \advance\pgf@x by\pgf@yb%
    \else%
      \advance\pgf@x by\pgf@xb%
    \fi%
  }

  %
  % Anchors
  % 
  \anchor{center}{\centerpoint}
  \anchor{mid}{\centerpoint\pgfmathsetlength\pgf@y{.5ex}}
  \anchor{base}{\centerpoint\pgf@y=0pt}
  \anchor{north}{\centerpoint\advance\pgf@y by\radius}
  \anchor{south}{\centerpoint\advance\pgf@y by-\radius}
  \anchor{west}{\centerpoint\advance\pgf@x by-\radius}
  \anchor{east}{\centerpoint\advance\pgf@x by\radius}
  \anchor{mid west}{\centerpoint\advance\pgf@x by-\radius\pgfmathsetlength\pgf@y{.5ex}}
  \anchor{mid east}{\centerpoint\advance\pgf@x by\radius\pgfmathsetlength\pgf@y{.5ex}}
  \anchor{base west}{\centerpoint\advance\pgf@x by-\radius\pgf@y=0pt}
  \anchor{base east}{\centerpoint\advance\pgf@x by\radius\pgf@y=0pt}
  \anchor{north west}{
    \centerpoint
    \pgf@xa=\radius
    \advance\pgf@x by-0.707107\pgf@xa
    \advance\pgf@y by0.707107\pgf@xa
  }
  \anchor{south west}{
    \centerpoint
    \pgf@xa=\radius
    \advance\pgf@x by-0.707107\pgf@xa
    \advance\pgf@y by-0.707107\pgf@xa
  }
  \anchor{north east}{
    \centerpoint
    \pgf@xa=\radius
    \advance\pgf@x by0.707107\pgf@xa
    \advance\pgf@y by0.707107\pgf@xa
  }
  \anchor{south east}{
    \centerpoint
    \pgf@xa=\radius
    \advance\pgf@x by0.707107\pgf@xa
    \advance\pgf@y by-0.707107\pgf@xa
  }
  \anchorborder{
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \edef\pgf@marshal{%
      \noexpand\pgfpointborderellipse
      {\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}
      {\noexpand\pgfqpoint{\radius}{\radius}}%
    }%
    \pgf@marshal%
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \centerpoint%
    \advance\pgf@x by\pgf@xa%
    \advance\pgf@y by\pgf@ya%
  }

  %
  % Background path
  %
  \backgroundpath{%
    \pgfutil@tempdima=\radius%
    \pgfmathsetlength{\pgf@xb}{\pgfkeysvalueof{/pgf/outer xsep}}%  
    \pgfmathsetlength{\pgf@yb}{\pgfkeysvalueof{/pgf/outer ysep}}%  
    \ifdim\pgf@xb<\pgf@yb%
      \advance\pgfutil@tempdima by-\pgf@yb%
    \else%
      \advance\pgfutil@tempdima by-\pgf@xb%
    \fi%
    \pgfpathcircle{\centerpoint}{\pgfutil@tempdima}%
  }
}





\endinput

pgfplotsarray.code.tex
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% This is a helper package with an elementary array datastructure,
% featuring O(1) index access and O(N) creation, deletion, copy.
%
% The following macros are supplied:
%
% \pgfplotsarraynewempty
% \pgfplotsarraynew
% \pgfplotsarrayresize
% \pgfplotsarraycopy
% \pgfplotsarraypushback
% \pgfplotsarraysize
% \pgfplotsarrayselect
% \pgfplotsarrayset
% \pgfplotsarrayletentry
% \pgfplotsarraycheckempty
% \pgfplotsarrayforeach
% \pgfplotsarraysort
%
% and a subset also for global arrays:
% \pgfplotsarraynewemptyglobal
% \pgfplotsarrayresizeglobal
% \pgfplotsarraysetglobal
% \pgfplotsarrayletentryglobal
%
% Copyright 2007/2008 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\newcount\c@pgfplotsarray@tmp
\newif\ifpgfplotsarrayempty

% Creates a new, empty array.
\def\pgfplotsarraynewempty#1{%
	\pgfplotsarray@@def{#1@size}{0}%
}
\def\pgfplotsarraynewemptyglobal#1{%
	\expandafter\gdef\csname\string#1@size\endcsname{0}%
}

% resizes (truncates) array #1 to size #2
%
% the elements won't be initialised. Use 'set' for each element.
\def\pgfplotsarrayresize#1#2{%
	\c@pgfplotsarray@tmp=#2
	\pgfplotsarray@@edef{#1@size}{\the\c@pgfplotsarray@tmp}%
}
\def\pgfplotsarrayresizeglobal#1#2{%
	\c@pgfplotsarray@tmp=#2
	\expandafter\xdef\csname\string#1@size\endcsname{\the\c@pgfplotsarray@tmp}%
}

% Invokes code '#2' if the array named '#1' exists and '#3' if it does
% not exist.
\def\pgfplotsarrayifdefined#1#2#3{%
	\pgfutil@ifundefined{#1@size}{#3}{#2}%
}%

% Creates a new array with an abirtrary number of elements.
% Arguments:
% #1: the array's name (a macro name)
% #2: the elements in one of the following forms
% 	a) a '\\' terminated list:
%     first\\second\\third\\ ...\\
%     like in tabular with one column. The final '\\' necessary!
%   b) a comma-separated list:
%     first,second,third,5,10,last
%     ATTENTION: arrays do not support the '...' syntax of tikz!
%
% Example:
% \pgfplotsarraynew\fooarray{First Element\\Second Element\\Third Element\\}
% \pgfplotsarraynew\fooarray{First Element,Second Element,Third Element}
% \pgfplotsarraynew\fooarray{0,1,2,...,10}
%
%
\long\def\pgfplotsarraynew#1#2{%
	\pgfplots@check@backwards@compatible@list@format #2\\\pgfplots@EOI
	\ifpgfplots@is@old@list@format
		\pgfplotsarraynew@backslash{#1}{#2}%
	\else
		\pgfplotsarraynew@commasep{#1}{#2}%
	\fi
}

% #1 the array's name (a macro name
% #2 a list created by \pgfplotslistnew 
\def\pgfplotsarrayfrompgfplotslist#1#2{%
	\pgfplotsarraynewempty#1%
	\pgfplotslistforeachungrouped#2\as\pgfplotsarray@TMPa{%
		\expandafter\pgfplotsarraypushback\expandafter{\pgfplotsarray@TMPa}\to#1%
	}%
}%

\def\pgfplotsarraynew@backslash#1#2{%
	\pgfplotsarraynewempty{#1}%
	\long\def\pgfplotsarraynew@impl@rest{#2}%
	\pgfutil@loop
	\ifx\pgfplotsarraynew@impl@rest\pgfutil@empty
		\pgfplots@loop@CONTINUEfalse
	\else
		\pgfplots@loop@CONTINUEtrue
	\fi
	\ifpgfplots@loop@CONTINUE
		\expandafter\pgfplotsarraynew@impl\pgfplotsarraynew@impl@rest\toarray#1\relax
	\pgfutil@repeat
}%

% converts a comma-separated list (PGF foreach)  to my internal list
% structure.
\long\def\pgfplotsarraynew@commasep#1#2{%
	\pgfplotsarraynewempty{#1}%
	\pgfplotsutilforeachcommasep{#2}\as\pgfplotsarraynew@elem{%
		\expandafter\pgfplotsarraypushback\expandafter{\pgfplotsarraynew@elem}\to#1%
	}%
}
% helper macro for \pgfplotsarraynew
\long\def\pgfplotsarraynew@impl#1\\#2\toarray#3{%
	\pgfplotsarraypushback#1\to#3\relax%
	\def\pgfplotsarraynew@impl@rest{#2}%
}


\def\pgfplotsarray@@let#1=#2{%
	\def\pgfplotsarray@TMP@@{\expandafter\let\csname\string#1\endcsname}%
	\expandafter\pgfplotsarray@TMP@@\csname\string#2\endcsname
}%

\def\pgfplotsarray@@#1#2{%
	\expandafter#1\csname\string#2\endcsname
}%
\def\pgfplotsarray@@def#1{%
	\expandafter\def\csname\string#1\endcsname
}%
\def\pgfplotsarray@@edef#1{%
	\expandafter\edef\csname\string#1\endcsname
}%

\def\pgfplotsarray@@getsizeto#1#2{%
	\pgfplotsarraysize{#1}\to\c@pgfplotsarray@tmp
	\edef#2{\the\c@pgfplotsarray@tmp}%
}%

% Copies array #1 to array #2.
\def\pgfplotsarraycopy#1\to#2{%
	\pgfplotsarray@@let{#2@size}={#1@size}%
	\pgfplotsarray@@getsizeto{#1}{\pgfplotsarray@TMP}%
	\c@pgfplotsarray@tmp=0
	\pgfutil@loop
	\ifnum\c@pgfplotsarray@tmp<\pgfplotsarray@TMP
	\pgfplotsarray@@let{#2@\the\c@pgfplotsarray@tmp}={#1@\the\c@pgfplotsarray@tmp}%
	\advance\c@pgfplotsarray@tmp by1
	\pgfutil@repeat
}



% #1: the item to append
% #2: the array as macro name
% Example:
% \pgfplotsarraypushback Next last element\to\fooarray
\long\def\pgfplotsarraypushback#1\to#2{%
	\pgfplotsarraysize{#2}\to\c@pgfplotsarray@tmp
	\pgfplotsarray@@def{#2@\the\c@pgfplotsarray@tmp}{#1}%
	\advance\c@pgfplotsarray@tmp by1
	\pgfplotsarray@@edef{#2@size}{\the\c@pgfplotsarray@tmp}%
}
\long\def\pgfplotsarraypushbackglobal#1\to#2{%
	\pgfplotsarraysize{#2}\to\c@pgfplotsarray@tmp
	\pgfplotsarray@@\gdef{#2@\the\c@pgfplotsarray@tmp}{#1}%
	\advance\c@pgfplotsarray@tmp by1
	\pgfplotsarray@@\xdef{#2@size}{\the\c@pgfplotsarray@tmp}%
}

\long\def\pgfplotsarraypushbackglobal#1\to#2{%
	\pgfplotsarraysize{#2}\to\c@pgfplotsarray@tmp
	\pgfplotsarray@@\gdef{#2@\the\c@pgfplotsarray@tmp}{#1}%
	\advance\c@pgfplotsarray@tmp by1
	\pgfplotsarray@@\xdef{#2@size}{\the\c@pgfplotsarray@tmp}%
}

% Counts the number of elements in array #1, storing it into the count
% register #2.
% Example:
% \pgfplotsarraysize\foo\to{\count0}%
% \the\count0
\long\def\pgfplotsarraysize#1\to#2{%
	#2=\csname\string#1@size\endcsname\relax
}
\long\def\pgfplotsarraysizetomacro#1\to#2{%
	\expandafter\let\expandafter#2\csname\string#1@size\endcsname
}

% expands to the size of array #1.
\def\pgfplotsarraysizeof#1{\csname\string#1@size\endcsname}%


% Returns the #1th element of array #2 into macro #3
% Arguments:
% #1: a count 0,...,N-1 where N is the array size.
%     You may specify a number of a count.
% #2: a array
% #3: a macro name
% Example:
%   Element 0:
%   \pgfplotsarrayselect0\of\foo\to\elem
%   \elem
%   Element \count1:
%   \pgfplotsarrayselect\count1\of\foo\to\elem
\def\pgfplotsarrayselect#1\of#2\to#3{%
	\c@pgfplotsarray@tmp=#1\relax
	\expandafter\let\expandafter#3\csname\string#2@\the\c@pgfplotsarray@tmp\endcsname%
	\ifx#3\relax
		\pgfplotsthrow{no such element}{#1}{No such element: \string\pgfplotsarrayselect\the\c@pgfplotsarray@tmp\string\of{\string#2}}\pgfeov%
	\fi
}

% Expands to the value at index #1 of array #2.
% #1: a number (not a register)
% #2: an array
\def\pgfplotsarrayvalueofelem#1\of#2{\csname\string#2@#1\endcsname}%

% Sets element '#1' of array '#2' to '#3'.
\def\pgfplotsarrayset#1\of#2\to#3{%
	\c@pgfplotsarray@tmp=#1\relax
	\pgfutil@namedef{\string#2@\the\c@pgfplotsarray@tmp}{#3}%
}
\def\pgfplotsarraysetglobal#1\of#2\to#3{%
	\c@pgfplotsarray@tmp=#1\relax
	\expandafter\gdef\csname\string#2@\the\c@pgfplotsarray@tmp\endcsname{#3}%
}
\long\def\pgfplotsarrayletentry#1\of#2=#3{%
	\c@pgfplotsarray@tmp=#1\relax
	\expandafter\let\csname\string#2@\the\c@pgfplotsarray@tmp\endcsname=#3\relax
}
\long\def\pgfplotsarrayletentryglobal#1\of#2=#3{%
	\c@pgfplotsarray@tmp=#1\relax
	\expandafter\global\expandafter\let\csname\string#2@\the\c@pgfplotsarray@tmp\endcsname=#3\relax
}

% Defines \pgfplotsretval to be a text-representation of the array.
% It will contain \t to separate cells.
%
\def\pgfplotsarraytotext#1{%
	\begingroup
	\pgfplotsapplistXnewempty\pgfplotsretval@
	\pgfplotsarrayforeachungrouped#1\as\entry{%
		\pgfmathfloatparsenumber\entry
		\pgfmathfloattosci\pgfmathresult
		\edef\entry{\pgfmathresult\noexpand\t}%
		\expandafter\pgfplotsapplistXpushback\entry\to\pgfplotsretval@
	}%
	\pgfplotsapplistXlet\pgfplotsretval=\pgfplotsretval@
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}

% Sets the boolean \ifpgfplotsarrayempty depending on whether array #1 is empty
% or not.
% Example:
%
% \pgfplotsarraycheckempty\fooarray
% \ifpgfplotsarrayempty
%    List fooarray is empty!
% \else
%    List is not empty.
% \fi
\def\pgfplotsarraycheckempty#1{%
	\ifnum\csname\string#1@size\endcsname=0
		\pgfplotsarrayemptytrue
	\else
		\pgfplotsarrayemptyfalse
	\fi
}


% Iterates through each array element, names it #2 and calls code #3.
% Example:
% \pgfplotsarraynew\fooarray{Eins\\Zwei\\Drei\\}%
% \pgfplotsarrayforeach\fooarray\as\foo{Element \foo\par}%
% results in
%  Element Eins
%  Element Zwei
%  Element Drei
% Each single element will be grouped with TeX groups.
%
% During the loop, \pgfplotsarrayforeachindex expands to the current index.
\long\def\pgfplotsarrayforeach#1\as#2#3{%
	\pgfplotsarray@@getsizeto{#1}{\pgfplotsarray@TMP}%
	\c@pgfplotsarray@tmp=0\relax
	\def\pgfplotsarrayforeachindex{\the\c@pgfplotsarray@tmp}%
	\long\def\pgfplotsarray@TMPb{#3}%
	\pgfutil@loop
		\ifnum\c@pgfplotsarray@tmp<\pgfplotsarray@TMP\relax
		\begingroup
		\expandafter\let\expandafter#2\expandafter=\csname\string#1@\the\c@pgfplotsarray@tmp\endcsname%
		\pgfplotsarray@TMPb
		\endgroup
		\advance\c@pgfplotsarray@tmp by1
	\pgfutil@repeat
	\let\pgfplotsarrayforeachindex=\relax%
}

% The same but without groups around #3.
\long\def\pgfplotsarrayforeachungrouped#1\as#2#3{%
	\pgfplotsarray@@getsizeto{#1}{\pgfplotsarray@TMP}%
	\c@pgfplotsarray@tmp=0\relax
	\def\pgfplotsarrayforeachindex{\the\c@pgfplotsarray@tmp}%
	\pgfutil@loop
		\ifnum\c@pgfplotsarray@tmp<\pgfplotsarray@TMP\relax
		\expandafter\let\expandafter#2\expandafter=\csname\string#1@\the\c@pgfplotsarray@tmp\endcsname%
		\begingroup
		\toks0={#3}%
		\xdef\pgfplotsarray@glob@TMP{%
			\the\toks0 %
			% restore loop state:
			\c@pgfplotsarray@tmp=\the\c@pgfplotsarray@tmp\space
			\noexpand\def\noexpand\pgfplotsarray@TMP{\pgfplotsarray@TMP}%
		}%
		\endgroup
		\pgfplotsarray@glob@TMP
		\advance\c@pgfplotsarray@tmp by1
	\pgfutil@repeat
	\let\pgfplotsarrayforeachindex=\relax%
}

\long\def\pgfplotsarrayforeachreversed#1\as#2#3{%
	\pgfplotsarray@@getsizeto{#1}{\pgfplotsarray@TMP}%
	\c@pgfplotsarray@tmp=\pgfplotsarray@TMP\relax
	\def\pgfplotsarrayforeachindex{\the\c@pgfplotsarray@tmp}%
	\long\def\pgfplotsarray@TMPb{#3}%
	\pgfutil@loop
		\ifnum\c@pgfplotsarray@tmp>0 %
		\advance\c@pgfplotsarray@tmp by-1
		\begingroup
		\expandafter\let\expandafter#2\expandafter=\csname\string#1@\the\c@pgfplotsarray@tmp\endcsname%
		\pgfplotsarray@TMPb
		\endgroup
	\pgfutil@repeat
	\let\pgfplotsarrayforeachindex=\relax%
}

\long\def\pgfplotsarrayforeachreversedungrouped#1\as#2#3{%
	\pgfplotsarray@@getsizeto{#1}{\pgfplotsarray@TMP}%
	\c@pgfplotsarray@tmp=\pgfplotsarray@TMP\relax
	\def\pgfplotsarrayforeachindex{\the\c@pgfplotsarray@tmp}%
	\long\def\pgfplotsarray@TMPb{#3}%
	\pgfutil@loop
		\ifnum\c@pgfplotsarray@tmp>0 %
		\advance\c@pgfplotsarray@tmp by-1
		\expandafter\let\expandafter#2\expandafter=\csname\string#1@\the\c@pgfplotsarray@tmp\endcsname%
		\pgfplotsarray@TMPb
	\pgfutil@repeat
	\let\pgfplotsarrayforeachindex=\relax%
}

\pgfkeys{%
	/pgfplots/array/unscope pre/.code={%
		% That's more or less efficient (although some runtime factors
		% could be saved).
		\c@pgfplotsarraysort@i=0
		\c@pgfplotsarray@tmp=\pgfplotsarraysizeof{#1}\relax
		\pgfutil@loop
		\ifnum\c@pgfplotsarraysort@i<\c@pgfplotsarray@tmp
			\pgfplotsarrayselect{\c@pgfplotsarraysort@i}\of{#1}\to\pgfplots@loc@TMPa
			\pgfplotsarrayletentryglobal\c@pgfplotsarraysort@i\of{pgfparraytmp}=\pgfplots@loc@TMPa
			\advance\c@pgfplotsarraysort@i by1
		\pgfutil@repeat
	},%
	/pgfplots/array/unscope post/.code={%
		% copy from global temp -> #1
		\c@pgfplotsarray@tmp=0
		\pgfplotsarraysizetomacro{#1}\to\pgfplots@loc@TMPb
		\pgfutil@loop
		\ifnum\c@pgfplotsarray@tmp<\pgfplots@loc@TMPb
			\pgfplotsarrayselect{\c@pgfplotsarray@tmp}\of{pgfparraytmp}\to\pgfplots@loc@TMPa
			\pgfplotsarrayletentry\c@pgfplotsarray@tmp\of{#1}=\pgfplots@loc@TMPa
			\advance\c@pgfplotsarray@tmp by1
		\pgfutil@repeat
	},%
}%

% Sorts array '#1' using N log N time.
% 
% The sort key is provided as argument in
% /pgfplots/iflessthan/.code args={#1#2#3#4}, see docs in
% pgfplotsutil.code.tex.
%
% Remarks:
% - the sorting algorithm is a sub-optimal mergesort currently -
% but it has runtime N log N. 
% - As usual, it is very difficult to move the final result out of the
%   current scope. The initial configuration allocates a *global* copy of #1 
%   to carry results out of one TeX group. This means that memory will NEVER be freed.
%   I don't see a general N log N alternative for doing so (short of discarding
%   the scopes for local groups).
%   BUT:
%   you can redefine the code key pair 
%     |/pgfplots/array/unscope pre|
%   and
%     |/pgfplots/array/unscope post|
%   to define your own routine which may benefit from special needs of
%   your application. The |... pre| command is invoked JUST before the
%   \endgroup and the |... post| JUST after the |\endgroup|.
%
%
% EXAMPLE:
%--------------------------------------------------
% \pgfplotsarraynewempty\testarray
% \pgfplotsarraypushback503\to\testarray
% \pgfplotsarraypushback087\to\testarray
% \pgfplotsarraypushback512\to\testarray
% \pgfplotsarraypushback061\to\testarray
% \pgfplotsarraypushback908\to\testarray
% \pgfplotsarraypushback170\to\testarray
% \pgfplotsarraypushback897\to\testarray
% \pgfplotsarraypushback275\to\testarray
% \pgfplotsarraypushback653\to\testarray
% \pgfplotsarraypushback426\to\testarray
% \pgfplotsarraypushback154\to\testarray
% \pgfplotsarraypushback509\to\testarray
% \pgfplotsarraypushback612\to\testarray
% \pgfplotsarraypushback677\to\testarray
% \pgfplotsarraypushback765\to\testarray
% \pgfplotsarraypushback703\to\testarray
% 
% Unsorted: 
% 
% [\pgfplotsarrayforeach\testarray\as\elem{\elem\space}]
% 
% \pgfplotsarraysort\testarray
% 
% sorted: 
% 
% [\pgfplotsarrayforeach\testarray\as\elem{\elem\space}]
% 
%-------------------------------------------------- 
%
% @see \pgfplotsutilsortthree
% @see \pgfplotsutilsortfour
\def\pgfplotsarraysort{%
	\pgfutil@ifnextchar[{\pgfplotsarraysort@opt}{\pgfplotsarraysort@opt[]}%
}%
\def\pgfplotsarraysort@opt[#1]#2{%
	% I admit, the implementation is more-or less copy-paste of an
	% experiment I had done at university. It does its job, but it is
	% certainly not optimal (that means: it is slow).
	\begingroup
	\pgfqkeys{/pgfplots/array}{#1}%
	\pgfkeysifdefined{/pgfplots/array/iflessthan/.@cmd}{%
		\pgfplots@warning{Warning: /pgfplots/array/iflessthan/.@cmd is deprecated. Please use /pgfplots/iflessthan/.@cmd instead.}%
		\pgfkeysgetvalue{/pgfplots/array/iflessthan/.@cmd}\pgfplotsarraysort@iflt
	}{%
		\pgfkeysgetvalue{/pgfplots/iflessthan/.@cmd}\pgfplotsarraysort@iflt
	}%
	\pgfplotsarraysize{#2}\to\c@pgfplotsarray@tmp
	\pgfplotsarrayresizeglobal{pgfparraytmp}{\the\c@pgfplotsarray@tmp}%
	\countdef\c@pgfplotsarraysort@m=0
	\countdef\c@pgfplotsarraysort@k=1
	\countdef\c@pgfplotsarraysort@i=2
	\countdef\c@pgfplotsarraysort@l=3
	\countdef\c@pgfplotsarraysort@j=4
	\countdef\c@pgfplotsarraysort@q=5
	\def\pgfplotsarray@mergesort@{\pgfplotsarray@mergesort{#2}}%
	\def\pgfplotsarray@mergesort@recurse@{\pgfplotsarray@mergesort@recurse{#2}}%
	\edef\pgfplotsarray@mergesort@@{{0}{\the\c@pgfplotsarray@tmp}}%
	\expandafter\pgfplotsarray@mergesort@\pgfplotsarray@mergesort@@
	%
	% copy the complete, sorted result outside of the current scope.
	\pgfkeysvalueof{/pgfplots/array/unscope pre/.@cmd}#2\pgfeov
	\endgroup
	\pgfkeysvalueof{/pgfplots/array/unscope post/.@cmd}#2\pgfeov
}%

% #1: array name,
% #2: start offset (as string number)
% #3: number of elems (as string number)
\def\pgfplotsarray@mergesort#1#2#3{%
	\ifnum#3<2
		% ready!
	\else
		\c@pgfplotsarraysort@m=#3\relax
		\divide\c@pgfplotsarraysort@m by2
		\c@pgfplotsarraysort@q=#3\relax
		\advance\c@pgfplotsarraysort@q by-\c@pgfplotsarraysort@m
		\c@pgfplotsarraysort@i=\c@pgfplotsarraysort@m
		\advance\c@pgfplotsarraysort@i by#2\relax
		\edef\pgfplotsarray@mergesort@@{%
			{#2}{\the\c@pgfplotsarraysort@m}% start1, N_1
			{\the\c@pgfplotsarraysort@i}{\the\c@pgfplotsarraysort@q}% start2, N_2
		}%
		\expandafter\pgfplotsarray@mergesort@recurse@\pgfplotsarray@mergesort@@
		%
		% Merge:
		% restore 'm':
		\c@pgfplotsarraysort@m=#3\relax
		\divide\c@pgfplotsarraysort@m by2
		\c@pgfplotsarraysort@q=#3
		\advance\c@pgfplotsarraysort@q by-\c@pgfplotsarraysort@m
		\c@pgfplotsarraysort@k=0
		\c@pgfplotsarraysort@l=0
		\c@pgfplotsarraysort@i=0
		%
		% direct comparisons for merge:
		\pgfutil@loop
		\pgfplots@loop@CONTINUEtrue
		\ifnum\c@pgfplotsarraysort@k<\c@pgfplotsarraysort@m
			\ifnum\c@pgfplotsarraysort@l<\c@pgfplotsarraysort@q
			\else
				\pgfplots@loop@CONTINUEfalse
			\fi
		\else
			\pgfplots@loop@CONTINUEfalse
		\fi
		\ifpgfplots@loop@CONTINUE
			\c@pgfplotsarraysort@j=\c@pgfplotsarraysort@m
			\advance\c@pgfplotsarraysort@j by\c@pgfplotsarraysort@l
			\advance\c@pgfplotsarraysort@j by#2
			\pgfplotsarrayselect{\c@pgfplotsarraysort@j}\of{#1}\to\pgfplotsarray@x@mpl
			\c@pgfplotsarraysort@j=\c@pgfplotsarraysort@k
			\advance\c@pgfplotsarraysort@j by#2
			\pgfplotsarrayselect{\c@pgfplotsarraysort@j}\of{#1}\to\pgfplotsarray@x@k
			\begingroup
			\pgfplotsarraysort@iflt
				{\pgfplotsarray@x@mpl}%
				{\pgfplotsarray@x@k}%
				{% x[m+l] < x[k]
					\aftergroup\pgfplots@loc@tmptrue
				}%
				{% x[k] <= x[m+l]
					\aftergroup\pgfplots@loc@tmpfalse
				}%
				\pgfeov
			\endgroup
			\ifpgfplots@loc@tmp
				\pgfplotsarrayletentryglobal\c@pgfplotsarraysort@i\of{pgfparraytmp}=\pgfplotsarray@x@mpl
				\advance\c@pgfplotsarraysort@i by1
				\advance\c@pgfplotsarraysort@l by1
			\else
				\pgfplotsarrayletentryglobal\c@pgfplotsarraysort@i\of{pgfparraytmp}=\pgfplotsarray@x@k
				\advance\c@pgfplotsarraysort@i by1
				\advance\c@pgfplotsarraysort@k by1
			\fi
		\pgfutil@repeat
		%
		% append:
		\pgfutil@loop
		\ifnum\c@pgfplotsarraysort@k<\c@pgfplotsarraysort@m
			\c@pgfplotsarraysort@j=\c@pgfplotsarraysort@k
			\advance\c@pgfplotsarraysort@j by#2
			\pgfplotsarrayselect{\c@pgfplotsarraysort@j}\of{#1}\to\pgfplots@loc@TMPa
			\pgfplotsarrayletentryglobal\c@pgfplotsarraysort@i\of{pgfparraytmp}=\pgfplots@loc@TMPa
			\advance\c@pgfplotsarraysort@i by1
			\advance\c@pgfplotsarraysort@k by1
		\pgfutil@repeat
		\pgfutil@loop
		\ifnum\c@pgfplotsarraysort@l<\c@pgfplotsarraysort@q
			\c@pgfplotsarraysort@j=\c@pgfplotsarraysort@m
			\advance\c@pgfplotsarraysort@j by\c@pgfplotsarraysort@l
			\advance\c@pgfplotsarraysort@j by#2
			\pgfplotsarrayselect{\c@pgfplotsarraysort@j}\of{#1}\to\pgfplots@loc@TMPa
			\pgfplotsarrayletentryglobal\c@pgfplotsarraysort@i\of{pgfparraytmp}=\pgfplots@loc@TMPa
			\advance\c@pgfplotsarraysort@i by1
			\advance\c@pgfplotsarraysort@l by1
		\pgfutil@repeat
		%
		% copy back from temporary to '#1'
		\c@pgfplotsarraysort@i=0
		\c@pgfplotsarraysort@k=#3
		\pgfutil@loop
		\ifnum\c@pgfplotsarraysort@i<\c@pgfplotsarraysort@k
			\c@pgfplotsarraysort@j=\c@pgfplotsarraysort@i
			\advance\c@pgfplotsarraysort@j by#2
			\pgfplotsarrayselect{\c@pgfplotsarraysort@i}\of{pgfparraytmp}\to\pgfplots@loc@TMPa
			\pgfplotsarrayletentry\c@pgfplotsarraysort@j\of{#1}=\pgfplots@loc@TMPa
			\advance\c@pgfplotsarraysort@i by1
		\pgfutil@repeat
%\pgfplotsarraysort@DEBUGTEST{#1}{after mergesort(start=#2,n=#3):}%
	\fi
}%
\long\def\pgfplotsarraysort@DEBUGTEST#1#2{%
	\par#2\par
	[\pgfplotsarrayforeach{#1}\as\elem{\elem\space}]\par%
}
% #1: array name
% #2: start1
% #3: N1
% #4: start2
% #5: N2
\def\pgfplotsarray@mergesort@recurse#1#2#3#4#5{%
	\pgfplotsarray@mergesort{#1}{#2}{#3}%
	\pgfplotsarray@mergesort{#1}{#4}{#5}%
}

	
% A simple, ungrouped insert sort algorithm for small arrays.
%
%	for i := 1; i < N; ++i do
%    begin
%        value := A[i];
%        j := i - 1;
%        done := false;
%        repeat
%            if A[j] > value then
%            begin
%                A[j + 1] := A[j];
%                j := j - 1;
%                if j < 0 then
%                    done := true;
%            end
%            else
%                done := true;
%        until done;
%        A[j + 1] := value;
%    end;
\def\pgfplotsarrayinsertionsort#1{%
	\pgfkeysgetvalue{/pgfplots/iflessthan/.@cmd}\pgfplotsarraysort@iflt
	\pgfplotsarraysizetomacro#1\to\pgfplotsarrayinsertionsort@N
	\c@pgf@countd=1
	\pgfplotsarrayinsertionsort@{#1}%
}%
\def\pgfplotsarrayinsertionsort@#1{%
	\ifnum\c@pgf@countd<\pgfplotsarrayinsertionsort@N\relax
		\pgfplotsarrayselect\c@pgf@countd\of#1\to\pgfplotsarrayinsertionsort@v
		%
		\c@pgf@countb=\c@pgf@countd
		\advance\c@pgf@countb by-1
		%
		\pgfplotsarrayinsertionsort@@{#1}%
		\advance\c@pgf@countb by1
		\pgfplotsarrayletentry\c@pgf@countb\of#1=\pgfplotsarrayinsertionsort@v
		%
		\advance\c@pgf@countd by1
		\expandafter\pgfplotsarrayinsertionsort@\expandafter#1%
	\fi
}
\def\pgfplotsarrayinsertionsort@@#1{%
	\pgfplotsarrayselect\c@pgf@countb\of#1\to\pgfplotsarrayinsertionsort@j
	\pgfplotsarraysort@iflt{\pgfplotsarrayinsertionsort@v}{\pgfplotsarrayinsertionsort@j}
	{%
		\advance\c@pgf@countb by1
		\pgfplotsarrayletentry\c@pgf@countb\of#1=\pgfplotsarrayinsertionsort@j
		\advance\c@pgf@countb by-2
		\ifnum\c@pgf@countb<0
			\let\pgfplotsarrayinsertionsort@@next\relax%
		\else
			\def\pgfplotsarrayinsertionsort@@next{\pgfplotsarrayinsertionsort@@#1}%
		\fi
	}{%
		\let\pgfplotsarrayinsertionsort@@next\relax%
	}\pgfeov%
	\pgfplotsarrayinsertionsort@@next
}%


pgfplotsbinary.code.tex
%--------------------------------------------
% $Header: /cvsroot/pgfplots/pgfplots/generic/pgfplots/util/pgfplotsbinary.code.tex,v 1.13 2009/07/21 18:18:48 ludewich Exp $
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2007/2008 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------

% This file provides a self-contained package which does only need
% pgfkeys.
%
% It provides a method to convert TeX numbers (integers and
% dimensions) into binary format (macros with catcode 11 or 12).
%

\edef\pgfplotsbinaryatcode{\the\catcode`\@ }
\catcode`\@=11


% Returns a single character, which has the
% binary ASCII code '#1', with catcode 11.
%
% #1 (expands to) a number between 0 and 255 (inclusive).
%
% @see \pgfplotsgetchar Note that \pgfplotsgetchar is more powerful,
% but can't be used inside of \edef (it is not expandable) whereas
% \pgfplotscharno is.
\def\pgfplotscharno#1{\csname pgfp@bin@#1\endcsname}%
\let\pgfplotscharno@bincatcode=\pgfplotscharno

\def\pgfplotscharno@lualatex#1{#1,}

\input pgfplotsbinary.data.code.tex

% Defines the LUA (!) value pgfplotsretval to be a binary string
% containing the pgfplots binary value #1.
%
% #1 a pgfplots binary value collected with \pgfplotscharno.
% More precisely, it should be a comma-separated sequence of numbers
% of the form '0,255,2,128,' (can be terminated by comma). It will be
% converted to the respective binary numbers 0x0, 0xff, 0x02,..
% 
% example:
%  \pgfplotsbinarytoluabinary{0, 255,2,128}
%  \directlua{
%  		pdf.immediateobj{"stream", pgfplotsretval,"/DataWithBinaryStream"}
%  }
\def\pgfplotsbinarytoluabinary#1{%
	% lualatex does not support binary chars as pdftex does - so we have to resort to LUA
	% methods. The idea is to use
	% string.char(1,2,3) which results in a binary string with chars 0x01, 0x02, 0x03 etc.
	% I only need to get the integer numbers. To this end, I patch \pgfplotscharno 
	% and create the binary string here:
	\directlua{%
		pgfplotsretval = pgfplotsGetLuaBinaryStringFromCharIndices({#1});
	}%
}%

% Defines \pgfplotsretval to be the ASCII character for #1, with
% catcode 11.
%
% #1: either a number between 0 and 255 (inclusive) or a description
% of the character.
%
% Examples:
% \pgfplotsgetchar{35}
% \pgfplotsgetchar{`\#}   % code for '#'
% \pgfplotsgetchar{`\^^M} % Newline
% \pgfplotsgetchar{`\^^ff}% 255
%
% @see \pgfplotscharno
\def\pgfplotsgetchar#1{%
	\begingroup
	\count0=#1\relax
	\edef\pgfplotsretval{\pgfplotscharno{\the\count0 }}%
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%

\def\pgfplotsbinary@apphighorderbytes@BIGENDIAN#1{\xdef\pgfplotsbinaryresult{#1\pgfplotsbinaryresult}}%
\def\pgfplotsbinary@apphighorderbytes@LITTLEENDIAN#1{\xdef\pgfplotsbinaryresult{\pgfplotsbinaryresult#1}}%

\def\pgfplotsbinaryencode@badic@unsigned@PAD@LITTLEENDIAN{%
	% pad with zeros:
	\ifcase\c@pgfplotsbin@byteno
		% ok.
	\or
		% one byte missing.
		\pgfplotsbinary@apphighorderbytes{\pgfplotsbinary@ZERO@HIGHEST}%
	\or
		% two bytes missing.
		\pgfplotsbinary@apphighorderbytes{\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO@HIGHEST}%
	\or
		\pgfplotsbinary@apphighorderbytes{\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO@HIGHEST}%
	\or
		\pgfplotsbinary@apphighorderbytes{\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO@HIGHEST}%
	\or
		\pgfplotsbinary@apphighorderbytes{\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO@HIGHEST}%
	\or
		\pgfplotsbinary@apphighorderbytes{\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO@HIGHEST}%
	\or
		\pgfplotsbinary@apphighorderbytes{\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO@HIGHEST}%
	\or
		\pgfplotsbinary@apphighorderbytes{\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO@HIGHEST}%
	\else
		\pgfplots@error{Sorry, I can't process byte no \the\c@pgfplotsbin@byteno... you may need to change bytes=\pgfplotsbinary@bytes.}%
	\fi
}%
\def\pgfplotsbinaryencode@badic@unsigned@PAD@BIGENDIAN{%
	% pad with zeros:
	\ifcase\c@pgfplotsbin@byteno
		% ok.
	\or
		% one byte missing.
		\pgfplotsbinary@apphighorderbytes{\pgfplotsbinary@ZERO@HIGHEST}%
	\or
		% two bytes missing.
		\pgfplotsbinary@apphighorderbytes{\pgfplotsbinary@ZERO@HIGHEST\pgfplotsbinary@ZERO}%
	\or
		\pgfplotsbinary@apphighorderbytes{\pgfplotsbinary@ZERO@HIGHEST\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO}%
	\or
		\pgfplotsbinary@apphighorderbytes{\pgfplotsbinary@ZERO@HIGHEST\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO}%
	\or
		\pgfplotsbinary@apphighorderbytes{\pgfplotsbinary@ZERO@HIGHEST\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO}%
	\or
		\pgfplotsbinary@apphighorderbytes{\pgfplotsbinary@ZERO@HIGHEST\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO}%
	\or
		\pgfplotsbinary@apphighorderbytes{\pgfplotsbinary@ZERO@HIGHEST\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO}%
	\or
		\pgfplotsbinary@apphighorderbytes{\pgfplotsbinary@ZERO@HIGHEST\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO}%
	\else
		\pgfplots@error{Sorry, I can't process byte no \the\c@pgfplotsbin@byteno... you may need to change bytes=\pgfplotsbinary@bytes.}%
	\fi
}%

\expandafter\def\csname pgfplotsbinarysetbytes@1\endcsname{%
	\def\pgfplotsbinary@add@signed@largest@absolute{\advance\c@pgfplotsbin@input by 127 }%
	\def\pgfplotsbinaryencodesignedmaplinearly@prepare{%
		% warning: \pgfplotsbinary@bytes is NOT necessarily 1 (ASCII
		% encoding features)
		\c@pgfplotsbin@byteno=\pgfplotsbinary@bytes\relax
		\c@pgfplotsbin@basis=\pgfplotsbinary@basis\relax
		\divide\c@pgfplotsbin@input by16909320 % ~= (2^31-1) /  (2^(8*1-1) -1)
	}%
}%
\expandafter\def\csname pgfplotsbinarysetbytes@2\endcsname{%
	\def\pgfplotsbinary@add@signed@largest@absolute{\advance\c@pgfplotsbin@input by 32767 }%
	\def\pgfplotsbinaryencodesignedmaplinearly@prepare{%
		\c@pgfplotsbin@byteno=\pgfplotsbinary@bytes\relax
		\c@pgfplotsbin@basis=\pgfplotsbinary@basis\relax
		\divide\c@pgfplotsbin@input by65538 % ~= (2^31-1) /  (2^(8*2-1) -1)
	}%
}%
\expandafter\def\csname pgfplotsbinarysetbytes@3\endcsname{%
	\def\pgfplotsbinary@add@signed@largest@absolute{\advance\c@pgfplotsbin@input by 8388607 }%
	\def\pgfplotsbinaryencodesignedmaplinearly@prepare{%
		\c@pgfplotsbin@byteno=\pgfplotsbinary@bytes\relax
		\c@pgfplotsbin@basis=\pgfplotsbinary@basis\relax
		\divide\c@pgfplotsbin@input by256 % ~= (2^31-1) /  (2^(8*3-1) -1)
	}%
}%
\expandafter\def\csname pgfplotsbinarysetbytes@4\endcsname{%
	\def\pgfplotsbinary@add@signed@largest@absolute{%
		\advance\c@pgfplotsbin@input by 2147483647 % this is the *absolute* largest int that TeX can handle.
	}%
	\def\pgfplotsbinaryencodesignedmaplinearly@prepare{%
		\c@pgfplotsbin@byteno=\pgfplotsbinary@bytes\relax
		\c@pgfplotsbin@basis=\pgfplotsbinary@basis\relax
	}%
}%
\def\pgfplotsbinarysetbytes@@{%
	\def\pgfplotsbinaryencodesignedmaplinearly@prepare{%
		\c@pgfplotsbin@byteno=\pgfplotsbinary@bytes\relax
		\c@pgfplotsbin@basis=\pgfplotsbinary@basis\relax
		\pgfplots@error{Sorry, but I can't perform \string\pgfplotsbinaryencodesignedmaplinearly\space for bytes=\pgfplotsbinary@bytes\space yet... bytes=4 is the maximum.}%
	}%
	\def\pgfplotsbinary@add@signed@largest@absolute{
		\advance\c@pgfplotsbin@input by 2147483647 
	}%
}%
\expandafter\let\csname pgfplotsbinary@bytes@5\endcsname=\pgfplotsbinarysetbytes@@
\expandafter\let\csname pgfplotsbinary@bytes@6\endcsname=\pgfplotsbinarysetbytes@@
\expandafter\let\csname pgfplotsbinary@bytes@7\endcsname=\pgfplotsbinarysetbytes@@
\expandafter\let\csname pgfplotsbinary@bytes@8\endcsname=\pgfplotsbinarysetbytes@@

\pgfqkeys{/pgfplots/bin}{%
	% ordering not yet implemented; uses always BIG ENDIAN.
	ordering/.is choice,%
	ordering/big endian/.code={%
		\def\pgfplotsbinary@byteorder{0}%
		\let\pgfplotsbinary@apphighorderbytes=\pgfplotsbinary@apphighorderbytes@BIGENDIAN
		\let\pgfplotsbinaryencode@badic@unsigned@PAD=\pgfplotsbinaryencode@badic@unsigned@PAD@BIGENDIAN
	},%
	ordering/net/.style={/pgfplots/bin/ordering/big endian},%
	ordering/little endian/.code={%
		\def\pgfplotsbinary@byteorder{1}%
		\let\pgfplotsbinary@apphighorderbytes=\pgfplotsbinary@apphighorderbytes@LITTLEENDIAN
		\let\pgfplotsbinaryencode@badic@unsigned@PAD=\pgfplotsbinaryencode@badic@unsigned@PAD@LITTLEENDIAN
	},
	ordering/big endian,%
	%
	% The standard method - it results in binary encoded numbers.
	binary encoding/.code={%
		\pgfutil@IfUndefined{directlua}{%
			\let\pgfplotscharno=\pgfplotscharno@bincatcode
		}{%
			% Ah - we use LuaTeX!
			% At the time of this writing, LUA does not allow binary output which has been
			% created by means of catcode modifications & TeX string concatenation.
			% binary output in LUA needs to be (re)implemented in LUA (see inline code 
			% comments below).
			%
			% There are two possible work-arounds: 
			% (a) Base64 encoding
			% (b) binary encoding using special LUA handling. 
			% This is what I do. Set the 'encode filter' such that it reinitializes the encoder:
			% we patch \pgfplotscharno with a special routine which collects
			% only the integer indices:
			\let\pgfplotscharno=\pgfplotscharno@lualatex
			% later, the user has to convert this list into a binary lua
			% string before he can use it. See \pgfplotsbinarytoluabinary
		}%
		\edef\pgfplotsbinary@ZERO{\pgfplotscharno0}%
		\edef\pgfplotsbinary@ZERO@LINEARMAP{\pgfplotscharno{128}}%
		\let\pgfplotsbinary@ZERO@HIGHEST=\pgfplotsbinary@ZERO
		\def\pgfplotsbinary@basis{256}%
		\let\pgfplotsbinary@hook=\relax
		\def\pgfplotsbinary@hook@signed@linearmap{%
			\ifnum\c@pgfplotsbin@byteno=0
				\advance\c@pgfplotsbin@input by128
				\ifnum\c@pgfplotsbin@input>255
					\pgfplotsbinary@hook@signed@linearmap@error
				\fi
			\fi
		}%
		\def\pgfplotsbinarysetbytes##1{%
			\pgfutil@ifundefined{pgfplotsbinarysetbytes@##1}{%
				\pgfplots@error{Sorry, I can't write binary output with '##1' bytes yet...}%
			}{%
				\edef\pgfplotsbinary@bytes{##1}%
				\csname pgfplotsbinarysetbytes@##1\endcsname
			}%
		}%
	},%
	%
	% This applies 'binary encoding' and encodes the resulting bytes
	% in Hex. It corresponds to the ASCIIHexEncode in postscript or
	% pdf.
	% Please note that 'bytes' sets the number of binary bytes - the
	% actual encoding length is exactly twice as large.
	ASCIIHexEncode/.code={%
		\let\pgfplotscharno=\pgfplotscharno@bincatcode
		\edef\pgfplotsbinary@ZERO{\pgfplotscharno{48}}%
		\edef\pgfplotsbinary@ZERO@LINEARMAP{\pgfplotscharno{56}}%
		\let\pgfplotsbinary@ZERO@HIGHEST=\pgfplotsbinary@ZERO
		\pgfkeysalso{/pgfplots/bin/ordering/big endian}%
		\def\pgfplotsbinary@basis{16}%
		\def\pgfplotsbinary@hook@hex{%
			\ifnum\c@pgfplotsbin@input<10
				\advance\c@pgfplotsbin@input by48
			\else
				\advance\c@pgfplotsbin@input by55
			\fi
		}%
		\let\pgfplotsbinary@hook=\pgfplotsbinary@hook@hex
		\def\pgfplotsbinary@hook@signed@linearmap{%
			\ifnum\c@pgfplotsbin@byteno=0
				\advance\c@pgfplotsbin@input by8
				\ifnum\c@pgfplotsbin@input>16
					\pgfplotsbinary@hook@signed@linearmap@error
				\fi
			\fi
			\pgfplotsbinary@hook@hex
		}%
		\def\pgfplotsbinarysetbytes##1{%
			\pgfutil@ifundefined{pgfplotsbinarysetbytes@##1}{%
				\pgfplots@error{Sorry, I can't write binary output with '##1' bytes yet...}%
			}{%
				\csname pgfplotsbinarysetbytes@##1\endcsname
				\begingroup
					\count0=##1\relax
					\multiply\count0 by2
					\xdef\pgfplotsbinary@glob@TMP{\the\count0 }%
				\endgroup
				\let\pgfplotsbinary@bytes=\pgfplotsbinary@glob@TMP
			}%
		}%
	},%
	%
	% 
	% This applies 'binary encoding' and encodes the resulting bytes
	% using a base 85 encoding. It corresponds to the ASCII85Encode in postscript or
	% pdf.
	% Handle this method with care - it works just for ONE number, not for a stream of
	% numbers as in pdf. Therefore, it might not be useful at all.
	% Please note that 'bytes' will be ignored; ASCII85Encode assumes
	% 4 binary bytes and uses 5 bytes to encode them.
	%
	% @ATTENTION bytes is ALWAYS 4, regardless of the setting of
	% 'bytes'!
	ASCII85Encode/.code={%
		\let\pgfplotscharno=\pgfplotscharno@bincatcode
		\edef\pgfplotsbinary@ZERO{\pgfplotscharno{33}}%
		\edef\pgfplotsbinary@ZERO@LINEARMAP{\pgfplotscharno{42}}%
		\let\pgfplotsbinary@ZERO@HIGHEST=\pgfplotsbinary@ZERO
		\pgfkeysalso{/pgfplots/bin/ordering/big endian}%
		\edef\pgfplotsbinary@ASCII@specialzero{\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO\pgfplotsbinary@ZERO}%
		\expandafter\def\expandafter\pgfplotsbinaryencode@badic@unsigned@PAD\expandafter{%
			\pgfplotsbinaryencode@badic@unsigned@PAD
			\ifx\pgfplotsbinaryresult\pgfplotsbinary@ASCII@specialzero
				% PDF standard: 0 is encoded as 'z':
				\gdef\pgfplotsbinaryresult{z}%
			\fi
		}%
		\def\pgfplotsbinary@basis{85}%
		\def\pgfplotsbinary@hook{%
			\advance\c@pgfplotsbin@input by33
		}%
		\def\pgfplotsbinary@hook@signed@linearmap{%
			\advance\c@pgfplotsbin@input by33
			\ifnum\c@pgfplotsbin@byteno=0
				\advance\c@pgfplotsbin@input by42
				\ifnum\c@pgfplotsbin@input>85
					\pgfplotsbinary@hook@signed@linearmap@error
				\fi
			\fi
		}%
		% I know, that does only work efficiently if bytes=4 for every
		% encoded number.
		\def\pgfplotsbinarysetbytes##1{%
			\def\pgfplotsbinary@bytes{5}%
			\csname pgfplotsbinarysetbytes@4\endcsname
		}%
		\pgfplotsbinarysetbytes4%
	},%
	binary encoding,%
	%
	bytes/.code={\pgfplotsbinarysetbytes{#1}},%
	bytes=4,
	%
	% Irreversibly change to VERBATIM output for debugging:
	debug mode/.code={%
		\let\pgfplotsbinary@apphighorderbytes@ORIG=\pgfplotsbinary@apphighorderbytes
		\def\pgfplotsbinary@ZERO{[Pad-0]}%
		\let\pgfplotsbinary@ZERO@HIGHEST=\pgfplotsbinary@ZERO
		\def\pgfplotsbinary@ZERO@LINEARMAP{[Pad-128]}%
		\def\pgfplotsbinary@apphighorderbytes##1{%
			\pgfutil@ifnextchar\pgfplotscharno{%
				\pgfplotsbinary@apphighorderbytes@DEBUG@csname
			}{%
				\pgfplotsbinary@apphighorderbytes@DEBUG@normal
			}%
			##1\relax
		}%
	},%
	% Write pdf objects in binary form. This does only work with
	% pdftex, and its output is only useful in conjunction with
	% \pdfcompresslevel=0
	% and a text editor.
	% Usage:
	% \pgfkeys{/pgfplots/bin/debug to pdf={\pgfplotsbinaryencodeunsigned}{1,2,3,...,16}}
	%
	% works only with pdftex
	debug to pdf/.code 2 args={%
		\foreach \num in {#2} {%
			#1{\num}%
			\immediate \pdfobj stream attr {
				/Decimal \num\space
				/Routine (\string#1)
			} {%
				\pgfplotsbinaryresult
			}%
		}%
	},%
}


\def\pgfplotsbinary@hook@signed@linearmap@error{%
	\pgfplots@error{Sorry, there are not enough bytes to store the current number. I tried to write \the\c@pgfplotsbin@input...}%
}%

\def\pgfplotsbinary@apphighorderbytes@DEBUG@csname\pgfplotscharno#1\relax{%
	\pgfplotsbinary@apphighorderbytes@ORIG{[#1]}%
}%
\def\pgfplotsbinary@apphighorderbytes@DEBUG@normal#1\relax{%
	\pgfplotsbinary@apphighorderbytes@ORIG{#1}%
}%

%\pgfkeys{/pgfplots/bin/debug mode}


\countdef\c@pgfplotsbin@input=0
\countdef\c@pgfplotsbin@tmpa=1
\countdef\c@pgfplotsbin@tmpb=2
\countdef\c@pgfplotsbin@byteno=3
\countdef\c@pgfplotsbin@basis=4
\def\pgfplotsbinaryempty{}

%--------------------------------------------------
% input:    unsigned int x, b, n;
% output:   unsigned int y[n];
% for (i=0; i<n; i++) y[i] = 0;
% i=0;
% while (x > 0)
% { y[i] = x % b; /* entspricht x mod b   */
%  x = x / b;    /* ganzzahlige Division */
%  i++;
%  }
%-------------------------------------------------- 
% with x = #1
% b = basis
% will store stuff into \pgfplotsbinaryresult in binary format
%
% PRECONDITION:
% - \pgfplotsbinaryresult= empty!
% - \c@pgfplotsbin@byteno=\pgfplotsbinary@bytes
\def\pgfplotsbinaryencode@badic@unsigned@{%
	\ifnum\c@pgfplotsbin@input>0
		\c@pgfplotsbin@tmpa=\c@pgfplotsbin@input
		\divide\c@pgfplotsbin@tmpa by\c@pgfplotsbin@basis\relax
		\c@pgfplotsbin@tmpb=\c@pgfplotsbin@tmpa\relax
		\multiply\c@pgfplotsbin@tmpa by\c@pgfplotsbin@basis\relax
		\advance\c@pgfplotsbin@input by -\c@pgfplotsbin@tmpa\relax
		\advance\c@pgfplotsbin@byteno by-1
		\pgfplotsbinary@hook% hooks for modifications.
		\pgfplotsbinary@apphighorderbytes{\pgfplotscharno{\the\c@pgfplotsbin@input}}%
		\c@pgfplotsbin@input=\c@pgfplotsbin@tmpb
%\message{RESULT SO FAR byte no \the\c@pgfplotsbin@byteno: \pgfplotsbinaryresult}%
		\expandafter\pgfplotsbinaryencode@badic@unsigned@
	\else
		\pgfplotsbinaryencode@badic@unsigned@PAD
%\message{RESULT SO FAR byte no \the\c@pgfplotsbin@byteno: \pgfplotsbinaryresult}%
	\fi
}%


% Defines \pgfplotsbinaryresult to be the binary representation of an
% unsigned integer.
%
% The representation will use unsigned dual number representation.
%
% The assignment to \pgfplotsbinaryresult will be globally.
% #1: an unsigned integer. It won't be transformed in any way, so make
% sure it fits into the configured number of bytes. It is an error if
% the number is too large or too small. Please note that only unsigned
% numbers are supported with this method.
%
% FIXME : fix  > 2^30
\def\pgfplotsbinaryencodeunsigned#1{%
	\begingroup
	\global\let\pgfplotsbinaryresult=\pgfplotsbinaryempty
	\c@pgfplotsbin@input=#1 %
	\c@pgfplotsbin@byteno=\pgfplotsbinary@bytes\relax
	\c@pgfplotsbin@basis=\pgfplotsbinary@basis\relax
	\pgfplotsbinaryencode@badic@unsigned@%
	\endgroup
}%

% An implementation for signed integers which maps the signed integer linearly into 
% the unsigned data range before it proceeds.
%
% The idea is thus, to first introduce a linear mapping
%
% phi : [- smallest_possible, +largest_possible ] -> [0, 256^bytes-1 ]
%
% A signed integer in TeX is in [ - (2^31-1), 2^31-1 ].
% Thus, we should map
%
% phi : [  -(2^31-1), 2^31-1 ] -> [ 0, 2^32-1 ].
%
% A simpler case is to employ the symmetry in TeX's registers and
% leave one out, i.e. to map to 2^32-2:
%
% phi : [  -(2^31-1), 2^31-1 ] -> [ 0, 2^32-2 ].
%
% Then,
%
% phi(x) = ( x + 2^31 -1 ) / (2^31-1 + 2^31-1) * (2^32-2) = x+ 2^31-1.
%
% The same map phi(x) = x + 2^31 -1 with target space  [0, 2^32-1 ]
% could be realized with the input space [- (2^31-1), 2^31 ].
%
% I am using this encoding procedure, phi(x) = x + 2^31 -1.
%
% As a consequence, the binary pattern FF FF FF FF does never occur as
% result of the mapping.
%
% To invert the mapping (i.e. to decode the result), set up the unique
% linear map
%
% psi : [ 0, 2^32-1 ] -> [ -(2^31-1), 2^31 ].
%
% Then, psi( phi(x) ) = x and the decoding procedure is correct.
%
% This doesn't need TeX register arithmetics on the whole range.
%
% REMARK: the whole operation does also work if bytes<4 (i.e. we have
% less than 32 bits in the target range). In this case, the mapping is
% phi : [  -(2^31-1), 2^31-1 ] -> [ 0, 2^{8*bytes}-1 ]
% and a further, *lossy* quantization still will be applied. The
% quantization step is an integer division performed in signed number
% arithmetics (i.e. it is symmetric around 0). 
\def\pgfplotsbinaryencodesignedmaplinearly#1{%
	\begingroup
	\global\let\pgfplotsbinaryresult=\pgfplotsbinaryempty
	\c@pgfplotsbin@input=#1\relax%
	\pgfplotsbinaryencodesignedmaplinearly@prepare
	\ifnum\c@pgfplotsbin@input<0 %
		% compute + 2^31 - 1
		\pgfplotsbinary@add@signed@largest@absolute
	\else
		% change zero padding such that positive numbers
		% get the EFFECT of + 2^31.
		\let\pgfplotsbinary@ZERO@HIGHEST=\pgfplotsbinary@ZERO@LINEARMAP
		\let\pgfplotsbinary@hook=\pgfplotsbinary@hook@signed@linearmap
		% and compute the -1 explicitly here:
		\advance\c@pgfplotsbin@input by-1 %
	\fi
	\pgfplotsbinaryencode@badic@unsigned@%
	\endgroup
}%

% Encodes a dimen (like 1pt or \dimen0) in binary form.
%
% The encoding works by mapping #1 linearly into the allowed integer
% range using a quantization technique to respect the (possibly)
% restricted number of bytes.
%
% The implementation is fast and uses only integer arithmetics.
% It relies on \pgfplotsbinaryencodesignedmaplinearly and a scale.
%
% So, what we do is to setup a linear map into binary range with k
% bytes. The range of a TeX dimen is precisely (in units of pt)
%  [ -(2^30-1) / 2^16, (2^30 -1) / 2^16 ] = [-16383.99998, 16383.99998]
%
% Thus, for an input dimen x, we set up the mapping
% 	phi(x) = 2^16 * x * 2
% which maps 
%  phi: [ -(2^30-1) / 2^16, (2^30-1) / 2^16 ] -> [-(2^31 -2), 2^31-2].
%
% I simply use the \pgfplotsbinaryencodesignedmaplinearly to process
% this further. To simplify the computation, I simply compute
%   phi_signed( phi(x) ), 
% where phi_signed denotes an application of
% \pgfplotsbinaryencodesignedmaplinearly:
%   phi_signed( y ) = y +2^31 -1,
%   phi_signed( phi(x) ) = 2^16 * 2 * x + 2^31 - 1.
% This is NOT a linear map to [0,2^32-1] as promised. 
% But, we can setup an inverse transformation PHI (which is linear) anyway
% such that
%   PHI( phi_signed(phi(x)) ) = x
% and that's all I want. Do do that, we use the unique linear decoder map 
%   PHI : [ 0,2^32-1 ] -> [ -16383.999992, 16384 ].
%
% This is not exacty the input range of before, but using it results
% in a proper decoder. The difference is due to the non-unique zero
% representation in TeX's arithmetics.
% 
%
% REMARK: the whole operation does also work if bytes<4 (i.e. we have
% less than 32 bits in the target range). In this case, a further
% *lossy* quantization step is applied in phi_signed. The inverse
% transformations are the same, however. See
% \pgfplotsbinaryencodesignedmaplinearly for details about the
% quantization step (or try it out).
%
	%
	%% DEBUG NOTE: This mapping appears to work correctly according to
	%% my tests.
	%% For bc -l test codes: 
	%% ibase=16; 
	%% -4000 +  809658FA. / (2^20) * 8000
\def\pgfplotsbinaryencodedimenmaplinearly#1{%
	\begingroup
	\dimen0=#1\relax
	\c@pgfplotsbin@input=\dimen0
	\multiply\c@pgfplotsbin@input by2
%\message{LOWLEVEL ENCODING '\the\c@pgfplotsbin@input' with linear map}%
	\pgfplotsbinaryencodesignedmaplinearly\c@pgfplotsbin@input
	\endgroup
}%

\catcode`\@=\pgfplotsbinaryatcode
\endinput

pgfplotsbinary.data.code.tex
\begingroup
% prepare ONE-BYTE conversion [0-255] -> binary character:
\count0=0
\countdef\counter=0
\catcode`\^^00=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^00}\advance\counter by1
\catcode`\^^01=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^01}\advance\counter by1
\catcode`\^^02=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^02}\advance\counter by1
\catcode`\^^03=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^03}\advance\counter by1
\catcode`\^^04=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^04}\advance\counter by1
\catcode`\^^05=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^05}\advance\counter by1
\catcode`\^^06=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^06}\advance\counter by1
\catcode`\^^07=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^07}\advance\counter by1
\catcode`\^^08=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^08}\advance\counter by1
\begingroup
\catcode`\^^09=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^09}\endgroup\advance\counter by1
\begingroup
\catcode`\^^0a=11\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^0a}\endgroup\advance\counter by1
\begingroup
\catcode`\^^0b=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^0b}\endgroup\advance\counter by1
\catcode`\^^0c=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^0c}\advance\counter by1
\begingroup
\catcode`\^^0d=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^0d}\endgroup\advance\counter by1
\catcode`\^^0e=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^0e}\advance\counter by1
\catcode`\^^0f=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^0f}\advance\counter by1
\catcode`\^^10=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^10}\advance\counter by1
\catcode`\^^11=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^11}\advance\counter by1
\catcode`\^^12=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^12}\advance\counter by1
\catcode`\^^13=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^13}\advance\counter by1
\catcode`\^^14=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^14}\advance\counter by1
\catcode`\^^15=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^15}\advance\counter by1
\catcode`\^^16=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^16}\advance\counter by1
\catcode`\^^17=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^17}\advance\counter by1
\catcode`\^^18=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^18}\advance\counter by1
\catcode`\^^19=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^19}\advance\counter by1
\catcode`\^^1a=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^1a}\advance\counter by1
\catcode`\^^1b=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^1b}\advance\counter by1
\catcode`\^^1c=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^1c}\advance\counter by1
\catcode`\^^1d=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^1d}\advance\counter by1
\catcode`\^^1e=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^1e}\advance\counter by1
\catcode`\^^1f=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^1f}\advance\counter by1
\begingroup
\catcode`\^^20=11^^I\expandafter\xdef\csname^^Ipgfp@bin@\the\counter^^I\endcsname{^^20}\endgroup\advance\counter by1
\catcode`\^^21=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^21}\advance\counter by1
\catcode`\^^22=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^22}\advance\counter by1
\catcode`\^^23=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^23}\advance\counter by1
\catcode`\^^24=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^24}\advance\counter by1
\catcode`\^^25=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^25}\advance\counter by1
\catcode`\^^26=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^26}\advance\counter by1
\catcode`\^^27=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^27}\advance\counter by1
\catcode`\^^28=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^28}\advance\counter by1
\catcode`\^^29=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^29}\advance\counter by1
\catcode`\^^2a=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^2a}\advance\counter by1
\catcode`\^^2b=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^2b}\advance\counter by1
\catcode`\^^2c=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^2c}\advance\counter by1
\catcode`\^^2d=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^2d}\advance\counter by1
\catcode`\^^2e=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^2e}\advance\counter by1
\catcode`\^^2f=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^2f}\advance\counter by1
\begingroup
\catcode`\^^30=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^30}\endgroup\advance\counter by1
\begingroup
\catcode`\^^31=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^31}\endgroup\advance\counter by1
\begingroup
\catcode`\^^32=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^32}\endgroup\advance\counter by1
\begingroup
\catcode`\^^33=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^33}\endgroup\advance\counter by1
\begingroup
\catcode`\^^34=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^34}\endgroup\advance\counter by1
\begingroup
\catcode`\^^35=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^35}\endgroup\advance\counter by1
\begingroup
\catcode`\^^36=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^36}\endgroup\advance\counter by1
\begingroup
\catcode`\^^37=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^37}\endgroup\advance\counter by1
\begingroup
\catcode`\^^38=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^38}\endgroup\advance\counter by1
\begingroup
\catcode`\^^39=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^39}\endgroup\advance\counter by1
\catcode`\^^3a=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^3a}\advance\counter by1
\catcode`\^^3b=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^3b}\advance\counter by1
\catcode`\^^3c=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^3c}\advance\counter by1
\begingroup
\catcode`\^^3d=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^3d}\endgroup\advance\counter by1
\catcode`\^^3e=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^3e}\advance\counter by1
\catcode`\^^3f=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^3f}\advance\counter by1
\catcode`\^^40=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^40}\advance\counter by1
\catcode`\^^41=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^41}\advance\counter by1
\catcode`\^^42=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^42}\advance\counter by1
\catcode`\^^43=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^43}\advance\counter by1
\catcode`\^^44=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^44}\advance\counter by1
\catcode`\^^45=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^45}\advance\counter by1
\catcode`\^^46=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^46}\advance\counter by1
\catcode`\^^47=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^47}\advance\counter by1
\catcode`\^^48=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^48}\advance\counter by1
\catcode`\^^49=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^49}\advance\counter by1
\catcode`\^^4a=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^4a}\advance\counter by1
\catcode`\^^4b=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^4b}\advance\counter by1
\catcode`\^^4c=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^4c}\advance\counter by1
\catcode`\^^4d=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^4d}\advance\counter by1
\catcode`\^^4e=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^4e}\advance\counter by1
\catcode`\^^4f=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^4f}\advance\counter by1
\catcode`\^^50=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^50}\advance\counter by1
\catcode`\^^51=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^51}\advance\counter by1
\catcode`\^^52=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^52}\advance\counter by1
\catcode`\^^53=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^53}\advance\counter by1
\catcode`\^^54=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^54}\advance\counter by1
\catcode`\^^55=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^55}\advance\counter by1
\catcode`\^^56=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^56}\advance\counter by1
\catcode`\^^57=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^57}\advance\counter by1
\catcode`\^^58=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^58}\advance\counter by1
\catcode`\^^59=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^59}\advance\counter by1
\catcode`\^^5a=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^5a}\advance\counter by1
\catcode`\^^5b=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^5b}\advance\counter by1
\begingroup
\catcode`\|=0
\catcode`\\=11	|expandafter|xdef|csname pgfp@bin@|the|counter|endcsname{^^5c}|endgroup \advance\counter by1
\catcode`\^^5d=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^5d}\advance\counter by1
\begingroup
\catcode`\^^5e=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^}\endgroup\advance\counter by1
\catcode`\^^5f=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^5f}\advance\counter by1
\begingroup
\catcode`\^^60=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^60}\endgroup\advance\counter by1
\catcode`\^^61=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^61}\advance\counter by1
\catcode`\^^62=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^62}\advance\counter by1
\catcode`\^^63=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^63}\advance\counter by1
\catcode`\^^64=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^64}\advance\counter by1
\catcode`\^^65=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^65}\advance\counter by1
\catcode`\^^66=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^66}\advance\counter by1
\catcode`\^^67=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^67}\advance\counter by1
\catcode`\^^68=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^68}\advance\counter by1
\catcode`\^^69=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^69}\advance\counter by1
\catcode`\^^6a=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^6a}\advance\counter by1
\catcode`\^^6b=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^6b}\advance\counter by1
\catcode`\^^6c=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^6c}\advance\counter by1
\catcode`\^^6d=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^6d}\advance\counter by1
\catcode`\^^6e=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^6e}\advance\counter by1
\catcode`\^^6f=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^6f}\advance\counter by1
\catcode`\^^70=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^70}\advance\counter by1
\catcode`\^^71=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^71}\advance\counter by1
\catcode`\^^72=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^72}\advance\counter by1
\catcode`\^^73=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^73}\advance\counter by1
\catcode`\^^74=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^74}\advance\counter by1
\catcode`\^^75=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^75}\advance\counter by1
\catcode`\^^76=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^76}\advance\counter by1
\catcode`\^^77=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^77}\advance\counter by1
\catcode`\^^78=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^78}\advance\counter by1
\catcode`\^^79=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^79}\advance\counter by1
\catcode`\^^7a=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^7a}\advance\counter by1
\begingroup
\catcode`\q=1
\catcode`\^^7b=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname q^^7b}\endgroup\advance\counter by1
\catcode`\^^7c=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^7c}\advance\counter by1
\begingroup
\catcode`\q=2
\catcode`\^^7d=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^7dq\endgroup\advance\counter by1
\catcode`\^^7e=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^7e}\advance\counter by1
\catcode`\^^7f=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^7f}\advance\counter by1
\catcode`\^^80=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^80}\advance\counter by1
\catcode`\^^81=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^81}\advance\counter by1
\catcode`\^^82=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^82}\advance\counter by1
\catcode`\^^83=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^83}\advance\counter by1
\catcode`\^^84=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^84}\advance\counter by1
\catcode`\^^85=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^85}\advance\counter by1
\catcode`\^^86=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^86}\advance\counter by1
\catcode`\^^87=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^87}\advance\counter by1
\catcode`\^^88=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^88}\advance\counter by1
\catcode`\^^89=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^89}\advance\counter by1
\catcode`\^^8a=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^8a}\advance\counter by1
\catcode`\^^8b=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^8b}\advance\counter by1
\catcode`\^^8c=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^8c}\advance\counter by1
\catcode`\^^8d=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^8d}\advance\counter by1
\catcode`\^^8e=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^8e}\advance\counter by1
\catcode`\^^8f=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^8f}\advance\counter by1
\catcode`\^^90=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^90}\advance\counter by1
\catcode`\^^91=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^91}\advance\counter by1
\catcode`\^^92=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^92}\advance\counter by1
\catcode`\^^93=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^93}\advance\counter by1
\catcode`\^^94=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^94}\advance\counter by1
\catcode`\^^95=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^95}\advance\counter by1
\catcode`\^^96=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^96}\advance\counter by1
\catcode`\^^97=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^97}\advance\counter by1
\catcode`\^^98=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^98}\advance\counter by1
\catcode`\^^99=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^99}\advance\counter by1
\catcode`\^^9a=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^9a}\advance\counter by1
\catcode`\^^9b=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^9b}\advance\counter by1
\catcode`\^^9c=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^9c}\advance\counter by1
\catcode`\^^9d=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^9d}\advance\counter by1
\catcode`\^^9e=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^9e}\advance\counter by1
\catcode`\^^9f=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^9f}\advance\counter by1
\catcode`\^^a0=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^a0}\advance\counter by1
\catcode`\^^a1=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^a1}\advance\counter by1
\catcode`\^^a2=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^a2}\advance\counter by1
\catcode`\^^a3=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^a3}\advance\counter by1
\catcode`\^^a4=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^a4}\advance\counter by1
\catcode`\^^a5=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^a5}\advance\counter by1
\catcode`\^^a6=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^a6}\advance\counter by1
\catcode`\^^a7=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^a7}\advance\counter by1
\catcode`\^^a8=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^a8}\advance\counter by1
\catcode`\^^a9=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^a9}\advance\counter by1
\catcode`\^^aa=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^aa}\advance\counter by1
\catcode`\^^ab=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^ab}\advance\counter by1
\catcode`\^^ac=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^ac}\advance\counter by1
\catcode`\^^ad=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^ad}\advance\counter by1
\catcode`\^^ae=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^ae}\advance\counter by1
\catcode`\^^af=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^af}\advance\counter by1
\catcode`\^^b0=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^b0}\advance\counter by1
\catcode`\^^b1=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^b1}\advance\counter by1
\catcode`\^^b2=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^b2}\advance\counter by1
\catcode`\^^b3=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^b3}\advance\counter by1
\catcode`\^^b4=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^b4}\advance\counter by1
\catcode`\^^b5=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^b5}\advance\counter by1
\catcode`\^^b6=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^b6}\advance\counter by1
\catcode`\^^b7=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^b7}\advance\counter by1
\catcode`\^^b8=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^b8}\advance\counter by1
\catcode`\^^b9=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^b9}\advance\counter by1
\catcode`\^^ba=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^ba}\advance\counter by1
\catcode`\^^bb=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^bb}\advance\counter by1
\catcode`\^^bc=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^bc}\advance\counter by1
\catcode`\^^bd=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^bd}\advance\counter by1
\catcode`\^^be=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^be}\advance\counter by1
\catcode`\^^bf=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^bf}\advance\counter by1
\catcode`\^^c0=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^c0}\advance\counter by1
\catcode`\^^c1=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^c1}\advance\counter by1
\catcode`\^^c2=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^c2}\advance\counter by1
\catcode`\^^c3=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^c3}\advance\counter by1
\catcode`\^^c4=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^c4}\advance\counter by1
\catcode`\^^c5=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^c5}\advance\counter by1
\catcode`\^^c6=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^c6}\advance\counter by1
\catcode`\^^c7=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^c7}\advance\counter by1
\catcode`\^^c8=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^c8}\advance\counter by1
\catcode`\^^c9=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^c9}\advance\counter by1
\catcode`\^^ca=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^ca}\advance\counter by1
\catcode`\^^cb=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^cb}\advance\counter by1
\catcode`\^^cc=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^cc}\advance\counter by1
\catcode`\^^cd=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^cd}\advance\counter by1
\catcode`\^^ce=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^ce}\advance\counter by1
\catcode`\^^cf=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^cf}\advance\counter by1
\catcode`\^^d0=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^d0}\advance\counter by1
\catcode`\^^d1=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^d1}\advance\counter by1
\catcode`\^^d2=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^d2}\advance\counter by1
\catcode`\^^d3=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^d3}\advance\counter by1
\catcode`\^^d4=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^d4}\advance\counter by1
\catcode`\^^d5=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^d5}\advance\counter by1
\catcode`\^^d6=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^d6}\advance\counter by1
\catcode`\^^d7=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^d7}\advance\counter by1
\catcode`\^^d8=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^d8}\advance\counter by1
\catcode`\^^d9=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^d9}\advance\counter by1
\catcode`\^^da=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^da}\advance\counter by1
\catcode`\^^db=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^db}\advance\counter by1
\catcode`\^^dc=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^dc}\advance\counter by1
\catcode`\^^dd=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^dd}\advance\counter by1
\catcode`\^^de=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^de}\advance\counter by1
\catcode`\^^df=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^df}\advance\counter by1
\catcode`\^^e0=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^e0}\advance\counter by1
\catcode`\^^e1=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^e1}\advance\counter by1
\catcode`\^^e2=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^e2}\advance\counter by1
\catcode`\^^e3=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^e3}\advance\counter by1
\catcode`\^^e4=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^e4}\advance\counter by1
\catcode`\^^e5=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^e5}\advance\counter by1
\catcode`\^^e6=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^e6}\advance\counter by1
\catcode`\^^e7=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^e7}\advance\counter by1
\catcode`\^^e8=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^e8}\advance\counter by1
\catcode`\^^e9=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^e9}\advance\counter by1
\catcode`\^^ea=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^ea}\advance\counter by1
\catcode`\^^eb=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^eb}\advance\counter by1
\catcode`\^^ec=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^ec}\advance\counter by1
\catcode`\^^ed=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^ed}\advance\counter by1
\catcode`\^^ee=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^ee}\advance\counter by1
\catcode`\^^ef=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^ef}\advance\counter by1
\catcode`\^^f0=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^f0}\advance\counter by1
\catcode`\^^f1=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^f1}\advance\counter by1
\catcode`\^^f2=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^f2}\advance\counter by1
\catcode`\^^f3=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^f3}\advance\counter by1
\catcode`\^^f4=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^f4}\advance\counter by1
\catcode`\^^f5=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^f5}\advance\counter by1
\catcode`\^^f6=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^f6}\advance\counter by1
\catcode`\^^f7=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^f7}\advance\counter by1
\catcode`\^^f8=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^f8}\advance\counter by1
\catcode`\^^f9=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^f9}\advance\counter by1
\catcode`\^^fa=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^fa}\advance\counter by1
\catcode`\^^fb=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^fb}\advance\counter by1
\catcode`\^^fc=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^fc}\advance\counter by1
\catcode`\^^fd=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^fd}\advance\counter by1
\catcode`\^^fe=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^fe}\advance\counter by1
\catcode`\^^ff=11	\expandafter\xdef\csname pgfp@bin@\the\counter \endcsname{^^ff}\advance\counter by1
\ifnum\counter=256
\else
	\pgfplots@error{Internal logic Error: initialisation failed. I have only \the\counter\space bytes initialised.}
\fi
\endgroup

\endinput

pgfplots.code.tex
%--------------------------------------------
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2007-2013 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------

\edef\pgfplots@oldcatcodesemicolon{\the\catcode`\;}%
\catcode`\;=12

\input pgfplotscore.code.tex
\input pgfplotslibrary.code.tex
\input pgfplotsoldpgfsupp_loader.code.tex
\input pgfplotsutil.code.tex
\input pgfplotscolormap.code.tex
\input pgfplotsstackedplots.code.tex
\input pgfplotsplothandlers.code.tex
\input pgfplots.scaling.code.tex
\input pgfplotscoordprocessing.code.tex
\input pgfplots.errorbars.code.tex
\input pgfplots.markers.code.tex
\input pgfplotsticks.code.tex
\input pgfplots.paths.code.tex



\usetikzlibrary{decorations,decorations.pathmorphing,decorations.pathreplacing}

% FIXME: reduce number of variables!

\newif\ifpgfplots@bb@isactive
\newif\ifpgfplots@xislinear
\newif\ifpgfplots@has@label@information
\newif\ifpgfplots@yislinear
\newif\ifpgfplots@zislinear
\newif\ifpgfplots@reverse@legend
\newif\ifpgfplots@transpose@legend
\newif\ifpgfplots@allow@reversal@of@rel@axis@cs
\newif\ifpgfplots@scanline@verbose
\newif\ifpgfplots@plot@graphics@autoadjustaxis
\newif\ifpgfplots@scaleuniformly@warning
\newif\ifpgfplots@hide@obscured@xtick
\newif\ifpgfplots@hide@obscured@ytick
\newif\ifpgfplots@hide@obscured@ztick
\newif\ifpgfplots@enable@tick@line@clipping
\newcount\pgfplots@numplots
\newdimen\pgfplots@xmin@reg
\newdimen\pgfplots@xmax@reg
\newdimen\pgfplots@ymin@reg
\newdimen\pgfplots@ymax@reg
\newdimen\pgfplots@zmin@reg
\newdimen\pgfplots@zmax@reg
\newif\ifpgfplots@warn@for@filter@discards
\newif\ifpgfplots@isuniformtick
\newif\ifpgfplotsplothandlermesh@patch@type@sampling
\newif\ifpgfplots@clip@limits
\newif\ifpgfplots@clip
\newif\ifpgfplots@plot@coords@mathparser
\pgfplots@plot@coords@mathparsertrue
\newif\ifpgfplots@enlargelimits
\newif\ifpgfplots@enlargelimits@respect@figure@size
\pgfplots@enlargelimits@respect@figure@sizetrue
\newif\ifpgfplots@enlargelimits@rel@thresh
\newif\ifpgfplots@enlargelimits@auto
\newif\ifpgfplots@tickshow
\newif\ifpgfplots@scatterplotenabled
\newif\ifpgfplots@xminorticks
\newif\ifpgfplots@xmajorticks
\newif\ifpgfplots@yminorticks
\newif\ifpgfplots@ymajorticks
\newif\ifpgfplots@zminorticks
\newif\ifpgfplots@zmajorticks
\newif\ifpgfplots@xminorgrids
\newif\ifpgfplots@xmajorgrids
\newif\ifpgfplots@yminorgrids
\newif\ifpgfplots@ymajorgrids
\newif\ifpgfplots@zminorgrids
\newif\ifpgfplots@zmajorgrids
\newif\ifpgfplots@clip@marker@paths
\newif\ifpgfplots@axis@on@top
\newif\ifpgfplots@separate@axis@lines
\newif\ifpgfplots@identify@log@minor@tick@pos
\newif\ifpgfplots@disablelogfilter@x
\newif\ifpgfplots@disablelogfilter@y
\newif\ifpgfplots@disablelogfilter@z
\newif\ifpgfplots@disabledatascaling
\newif\ifpgfplots@hide@x
\newif\ifpgfplots@hide@y
\newif\ifpgfplots@hide@z
\newif\ifpgfplots@shownothingof@x
\newif\ifpgfplots@shownothingof@y
\newif\ifpgfplots@shownothingof@z
\newif\ifpgfplots@is@old@list@format
\newif\ifpgfplots@errorbars@enabled
\newif\ifpgfplots@scale@only@axis
\newif\ifpgfplots@xticklabel@interval
\newif\ifpgfplots@yticklabel@interval
\newif\ifpgfplots@zticklabel@interval
\newif\ifpgfplots@stacked@reverse
\newif\ifpgfplots@stacked@plus
\newif\ifpgfplots@stacked@ignores@zero
\newif\ifpgfplots@plot@file@skipfirst
\newif\ifpgfplots@threedim
\newif\ifpgfplots@curplot@threedim
\newif\ifpgfplotsthreedim
\newif\ifpgfplots@curplot@isirrelevant
\newif\ifpgfplots@colorbar
\newif\ifpgfplots@deprecated@anchors
\newif\ifpgfplots@translategnuplot
\pgfplots@translategnuplottrue
\let\pgfnodepartimagebox=\pgfnodeparttextbox
\newif\ifpgfplotsplothandlermesh@internaldepth
\newif\ifpgfplotsplothandlermesh@hide@refined@edges
\newif\ifpgfplots@has@cell@picture
\newif\ifpgfplots@substitute@pgfpoint

\newif\ifpgfplots@collect@firstplot@astick
\newif\ifpgfplots@units@use

\def\pgfplots@errorbars@xdirection{0}% pre-init, see below
\def\pgfplots@errorbars@ydirection{0}%
\def\pgfplots@errorbars@zdirection{0}%

\def\axisdefaultwidth{240pt}
\def\axisdefaultheight{207pt}

\def\pgfplotsifaxisthreedim#1#2{\ifpgfplots@threedim #1\else #2\fi}%
\def\pgfplotsifcurplotthreedim#1#2{\ifpgfplots@curplot@threedim #1\else #2\fi}%

% Invokes '#2' if a cycle list named '#1' exists and '#3' if not.
\long\def\pgfplotsifcyclelistexists#1#2#3{%
	\pgfutil@IfUndefined{pgfp@cyclist@\string#1@}{#3}{#2}%
}%

\def\pgfplots@label@upgrade@warning{%
	\ifpgfplots@threedim
		\pgfplotswarning{center lines upgrade required}\pgfeov% 
		\global\let\pgfplots@label@upgrade@warning=\relax
	\fi
}%

% Creates a named plot cycle list.
%
% #1:  the name of the final list. Can be used in 'cycle list name'
% #2:  the list entries. You can use either a comma-separated list or
%      a '\\'-terminated list. The latter case also requires '\\'
%      AFTER the last entry.
\def\pgfplotscreateplotcyclelist#1#2{\expandafter\pgfplots@assign@list\csname pgfp@cyclist@\string#1@\endcsname{#2}}

\pgfplotscreateplotcyclelist{black white}{%
	every mark/.append style={fill=gray},mark=*\\%
	every mark/.append style={fill=gray},mark=square*\\%
	every mark/.append style={fill=gray},mark=otimes*\\%
	mark=star\\%
	every mark/.append style={fill=gray},mark=diamond*\\%
	densely dashed,every mark/.append style={solid,fill=gray},mark=*\\%
	densely dashed,every mark/.append style={solid,fill=gray},mark=square*\\%
	densely dashed,every mark/.append style={solid,fill=gray},mark=otimes*\\%
	densely dashed,every mark/.append style={solid},mark=star\\%
	densely dashed,every mark/.append style={solid,fill=gray},mark=diamond*\\%
}

\pgfplotscreateplotcyclelist{color}{%
	blue,every mark/.append style={fill=blue!80!black},mark=*\\%
	red,every mark/.append style={fill=red!80!black},mark=square*\\%
	brown!60!black,every mark/.append style={fill=brown!80!black},mark=otimes*\\%
	black,mark=star\\%
	blue,every mark/.append style={fill=blue!80!black},mark=diamond*\\%
	red,densely dashed,every mark/.append style={solid,fill=red!80!black},mark=*\\%
	brown!60!black,densely dashed,every mark/.append style={solid,fill=brown!80!black},mark=square*\\%
	black,densely dashed,every mark/.append style={solid,fill=gray},mark=otimes*\\%
	blue,densely dashed,mark=star,every mark/.append style=solid\\%
	red,densely dashed,every mark/.append style={solid,fill=red!80!black},mark=diamond*\\%
}
\pgfplotscreateplotcyclelist{linestyles}{solid,dashed,dotted}
\pgfplotscreateplotcyclelist{linestyles*}{solid,dashed,dotted,dashdotted,dashdotdotted}
\pgfplotscreateplotcyclelist{color list}{red,blue,black,yellow,brown,teal,orange,violet,cyan,green!70!black,magenta,gray}
\pgfplotscreateplotcyclelist{mark list}{%
	every mark/.append style={solid,fill=\pgfplots@mark@list@fill},mark=*\\%
	every mark/.append style={solid,fill=\pgfplots@mark@list@fill},mark=square*\\%
	every mark/.append style={solid,fill=\pgfplots@mark@list@fill},mark=triangle*\\%
	every mark/.append style={solid},mark=star\\%
	every mark/.append style={solid,fill=\pgfplots@mark@list@fill},mark=diamond*\\%
	every mark/.append style={solid,fill=\pgfplots@mark@list@fill!40},mark=otimes*\\%
	every mark/.append style={solid},mark=|\\%
	every mark/.append style={solid,fill=\pgfplots@mark@list@fill},mark=pentagon*\\%
	every mark/.append style={solid},mark=text,text mark=p\\%
	every mark/.append style={solid},mark=text,text mark=a\\%
}
\pgfplotscreateplotcyclelist{mark list*}{%
	every mark/.append style={solid,fill=\pgfplots@mark@list@fill},mark=*\\%
	every mark/.append style={solid,fill=\pgfplots@mark@list@fill},mark=square*\\%
	every mark/.append style={solid,fill=\pgfplots@mark@list@fill},mark=triangle*\\%
	every mark/.append style={solid,fill=\pgfplots@mark@list@fill},mark=halfsquare*\\%
	every mark/.append style={solid,fill=\pgfplots@mark@list@fill},mark=pentagon*\\%
	every mark/.append style={solid,fill=\pgfplots@mark@list@fill},mark=halfcircle*\\%
	every mark/.append style={solid,fill=\pgfplots@mark@list@fill,rotate=180},mark=halfdiamond*\\%
	every mark/.append style={solid,fill=\pgfplots@mark@list@fill!40},mark=otimes*\\%
	every mark/.append style={solid,fill=\pgfplots@mark@list@fill},mark=diamond*\\%
	every mark/.append style={solid,fill=\pgfplots@mark@list@fill},mark=halfsquare right*\\%
	every mark/.append style={solid,fill=\pgfplots@mark@list@fill},mark=halfsquare left*\\%
}
\def\pgfplots@mark@list@fill{\pgfkeysvalueof{/pgfplots/mark list fill}}
\pgfplotscreateplotcyclelist{exotic}{%
	teal,every mark/.append style={fill=teal!80!black},mark=*\\%
	orange,every mark/.append style={fill=orange!80!black},mark=square*\\%
	cyan!60!black,every mark/.append style={fill=cyan!80!black},mark=otimes*\\%
	red!70!white,mark=star\\%
	lime!80!black,every mark/.append style={fill=lime},mark=diamond*\\%
	red,densely dashed,every mark/.append style={solid,fill=red!80!black},mark=*\\%
	yellow!60!black,densely dashed,every mark/.append style={solid,fill=yellow!80!black},mark=square*\\%
	black,every mark/.append style={solid,fill=gray},mark=otimes*\\%
	blue,densely dashed,mark=star,every mark/.append style=solid\\%
	red,densely dashed,every mark/.append style={solid,fill=red!80!black},mark=diamond*\\%
}


% backwards compatibility:
\let\pgfcreateplotcyclelist=\pgfplotscreateplotcyclelist
\pgfplots@letcsname{pgfp@cyclist@\string\blackwhiteplotspeclist @}={pgfp@cyclist@black white@}%
\pgfplots@letcsname{pgfp@cyclist@\string\coloredplotspeclist @}={pgfp@cyclist@color@}%
%%%%

\def\pgfplotsdeprecatedstylecheck#1{%
	\pgfkeysifdefined{#1/.@cmd}{%
		\begingroup
		\edef\pgfkeyscurrentkey{#1}%
		\pgfkeyssplitpath
		\pgfplots@warning{Loading deprecated style option 
			\pgfkeyscurrentpath/\pgfkeyscurrentname.  
			Please replace '\string\tikzstyle{\pgfkeyscurrentname}' 
			with '\string\pgfplotsset{\pgfkeyscurrentname/.style={}}'
			(or '\string\pgfplotsset{\pgfkeyscurrentname/.append style={}}').}%
		\endgroup
		\pgfkeysvalueof{#1/.@cmd}\pgfeov
	}{}%
}%

\def\pgfplots@scaled@ticks@setargs#1#2{%
	\pgfutil@in@{:}{#2}%
	\ifpgfutil@in@
		\pgfplots@scaled@ticks@setargs@{#1}#2\pgfplots@EOI
	\else
		\expandafter\pgfutil@in@\expandafter{\pgfplots@activecolon}{#2}%
		\ifpgfutil@in@
			\pgfplots@scaled@ticks@setargs@active{#1}#2\pgfplots@EOI
		\else
			\pgfkeysalso{/pgfplots/scaled #1 ticks/#2}%
		\fi
	\fi
}%
\def\pgfplots@scaled@ticks@setargs@#1#2:#3\pgfplots@EOI{%
	\pgfkeysalso{/pgfplots/scaled #1 ticks/#2=#3}%
}

{
	\catcode`\:=\active
	\gdef\pgfplots@scaled@ticks@setargs@active#1#2:#3\pgfplots@EOI{%
		\pgfkeysalso{/pgfplots/scaled #1 ticks/#2=#3}%
	}
}

\expandafter\def\csname pgfplots@nodesnearcoordsalign@isanchor@center\endcsname{1}
\expandafter\def\csname pgfplots@nodesnearcoordsalign@isanchor@south west\endcsname{1}
\expandafter\def\csname pgfplots@nodesnearcoordsalign@isanchor@south\endcsname{1}
\expandafter\def\csname pgfplots@nodesnearcoordsalign@isanchor@south east\endcsname{1}
\expandafter\def\csname pgfplots@nodesnearcoordsalign@isanchor@east\endcsname{1}
\expandafter\def\csname pgfplots@nodesnearcoordsalign@isanchor@north east\endcsname{1}
\expandafter\def\csname pgfplots@nodesnearcoordsalign@isanchor@north\endcsname{1}
\expandafter\def\csname pgfplots@nodesnearcoordsalign@isanchor@north west\endcsname{1}
\expandafter\def\csname pgfplots@nodesnearcoordsalign@isanchor@west\endcsname{1}
\expandafter\def\csname pgfplots@nodesnearcoordsalign@isanchor@baseline\endcsname{1}

% Sets the keys for /pgfplots/[xyz]ticklabel anchor.
% #1: one of [xyz]
% #2: the value
\def\pgfplots@setticklabel@anchor@for#1#2{%
	\def\pgfplots@loc@TMPa{#2}%
	\def\pgfplots@loc@TMPb{auto}%
	\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
		\expandafter\def\csname pgfplots@ticklabel@anchor@#1\endcsname{0}%
	\else
		\def\pgfplots@loc@TMPb{near ticklabel}%
		\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
			\expandafter\def\csname pgfplots@ticklabel@anchor@#1\endcsname{1}%
		\else
			\def\pgfplots@loc@TMPb{tikz}%
			\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
				\expandafter\def\csname pgfplots@ticklabel@anchor@#1\endcsname{2}%
			\else
				\pgfplots@error{Sorry, I got an unexpected value for '#1ticklabel anchor': '#2'. Expected one of 'auto', 'near ticklabel' or 'tikz'.}%
			\fi
		\fi
	\fi
}%

% Does the work for '[xyz]ticklabel pos'.
%
% #1: the axis (x,y or z).
% #2: the key argument. Accepts 
% 	'lower',
% 	'upper',
% 	'default' -> depends on 'tick pos'
% 	'left' = 'lower',
% 	'bottom' = 'lower',
% 	'right' = 'upper'
% 	'top' = 'upper'.
%
\def\pgfplots@setkey@ticklabelpos#1#2{%
	\def\pgfplots@loc@TMPa{#2}%
	\def\pgfplots@loc@TMPb{lower}%
	\expandafter\def\csname pgfplots@#1ticklabel@pos\endcsname{l}%
	\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
	\else
		\def\pgfplots@loc@TMPb{upper}%
		\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
			\expandafter\def\csname pgfplots@#1ticklabel@pos\endcsname{u}%
		\else
			\def\pgfplots@loc@TMPb{default}%
			\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
				\expandafter\def\csname pgfplots@#1ticklabel@pos\endcsname{}%
			\else
				\def\pgfplots@loc@TMPb{left}%
				\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
				\else
					\def\pgfplots@loc@TMPb{right}%
					\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
						\expandafter\def\csname pgfplots@#1ticklabel@pos\endcsname{u}%
					\else
						\expandafter\def\csname pgfplots@#1ticklabel@pos\endcsname{}%
						\pgfplots@error{Sorry, the key '#1ticklabel pos' does not know what to do with '#2'... accepted values are 'default, 'lower', 'upper' and some aliases. Maybe you misspelled it?}%
					\fi
				\fi
			\fi
		\fi
	\fi
}%

% Sets 'x dir={normal,reverse}'
% #1: an axis
% #2: the key's value to apply
\def\pgfplots@setkey@axisdir@for#1#2{%
	\def\pgfplots@loc@TMPa{#2}%
	\def\pgfplots@loc@TMPb{normal}%
	\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
		\pgfkeyssetvalue{/pgfplots/#1 dir/value}{n}%
	\else
		\def\pgfplots@loc@TMPb{reverse}%
		\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
			\pgfkeyssetvalue{/pgfplots/#1 dir/value}{r}%
		\else
			\pgfkeyssetvalue{/pgfplots/#1 dir/value}{n}%
			\pgfplots@error{Sorry, the key '#1 dir' does not know what to do with '#2'... accepted values are 'normal' or 'reverse'.}%
		\fi
	\fi
}%


\def\pgfplots@meshmode{n}% none
\def\pgfplotsplothandlermesh@flatmode{m}% mean

\def\pgfplots@cycle@multi@list@EOI{\pgfplots@cycle@multi@list@EOI}%
\def\pgfplots@cycle@multi@list#1{%
	\def\pgfplots@loc@TMPb{0}%
	\gdef\pgfplots@cycle@multi@list@finalize@{}%
	\pgfplots@cycle@multi@list@#1\nextlist\pgfplots@cycle@multi@list@EOI
}%
\def\pgfplots@cycle@multi@list@#1\nextlist{%
	\def\pgfplots@loc@TMPa{#1}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		% ignore it if someone provided too many \nextlist commands.
	\else
		% parse and store list:
		\begingroup
			\def\pgfplots@as@string{#1}% this deals with control sequences inside of #1.
			\pgfplots@command@to@string\pgfplots@as@string\pgfplots@as@string
			\expandafter\pgfplots@cycle@multi@list@findnamed\pgfplots@as@string\pgfplots@EOI
			\global\let\pgfplots@glob@TMPa=\pgfplots@loc@TMPa
		\endgroup
		\ifx\pgfplots@glob@TMPa\pgfutil@empty
			% create it:
			\pgfplotscreateplotcyclelist{/pgfplots/cycle multi list/@list\pgfplots@loc@TMPb}{#1}%
		\else
			% ok, take an existing one
			\expandafter\let\csname pgfp@cyclist@/pgfplots/cycle multi list/@list\pgfplots@loc@TMPb @\endcsname=\pgfplots@glob@TMPa
		\fi
		\begingroup
			\expandafter\pgfplotslistsize\csname pgfp@cyclist@/pgfplots/cycle multi list/@list\pgfplots@loc@TMPb @\endcsname\to\c@pgf@counta
			\edef\pgfmathresult{\the\c@pgf@counta}%
			\pgfmath@smuggleone\pgfmathresult
		\endgroup
		\pgfkeyslet{/pgfplots/cycle multi list/@totalN\pgfplots@loc@TMPb}\pgfmathresult
		\pgfkeyslet{/pgfplots/cycle multi list/@N\pgfplots@loc@TMPb}\pgfmathresult
%\def\temp{#1}\message{cycle multi list/@list={\meaning\temp};   /@N\pgfplots@loc@TMPb = \pgfkeysvalueof{/pgfplots/cycle multi list/@N\pgfplots@loc@TMPb}.}%
		\pgfplotsutil@advancestringcounter\pgfplots@loc@TMPb
	\fi
	%
	\pgfutil@ifnextchar{\pgfplots@cycle@multi@list@EOI}{%
		\pgfplots@cycle@multi@list@finalize
	}{%
		\pgfplots@cycle@multi@list@
	}%
}%

% checks for 
% - <known list>
% - [<elements> of]<known list>
% POSTCONDITION:
% 	1. pgfplots@loc@TMPa will be \pgfutil@empty if there is no such
% 	list.
% 	2. \pgfplots@loc@TMPa will be \let to the list if there is one.
% 	3. \pgfplots@cycle@multi@list@finalize@ will contain any 'partial sublist'
% 	commands.
\def\pgfplots@cycle@multi@list@findnamed{\pgfutil@ifnextchar[{\pgfplots@cycle@multi@list@findnamed@}{\pgfplots@cycle@multi@list@findnamed@[]}}%
\def\pgfplots@cycle@multi@list@findnamed@[#1]#2\pgfplots@EOI{%
	\def\pgfplots@loc@TMPa{#1}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
	\else
		\pgfplots@cycle@multi@list@findnamed@@#1 \pgfplots@EOI
	\fi
	\pgfplotsifcyclelistexists{#2}{%
		\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfp@cyclist@\string#2@\endcsname%
	}{%
		\let\pgfplots@loc@TMPa=\pgfutil@empty
	}%
}
\def\pgfplots@cycle@multi@list@findnamed@@#1 {\pgfutil@ifnextchar o{\pgfplots@cycle@multi@list@findnamed@@@{#1}}{\pgfplots@cycle@multi@list@findnamed@@@{#1}of}}%
\def\pgfplots@cycle@multi@list@findnamed@@@#1of#2\pgfplots@EOI{%
	\begingroup
		\t@pgfplots@toka=\expandafter{\pgfplots@cycle@multi@list@finalize@}%
		\t@pgfplots@tokb={#1}%
		\xdef\pgfplots@cycle@multi@list@finalize@{\the\t@pgfplots@toka
			\noexpand\pgfkeys{/pgfplots/cycle multi list/partial sublist={\pgfplots@loc@TMPb}{\the\t@pgfplots@tokb}}%
		}%
	\endgroup
}

\def\pgfplots@cycle@multi@list@finalize\pgfplots@cycle@multi@list@EOI{%
	\pgfkeyslet{/pgfplots/cycle multi list/@dim}\pgfplots@loc@TMPb
	\pgfplots@cycle@multi@list@finalize@
}%

\def\pgfplots@pgfkeys@set@point@meta@value#1{%
	%
	\pgfutil@in@{=}{#1}%
	\ifpgfutil@in@
		\def\pgfplots@loc@TMPa##1=##2\pgfplots@EOI{%
			% remove spaces from ##1 and ##2:
			\pgfkeys@spdef\pgfplots@loc@TMPa{##1}%
			\pgfkeys@spdef\pgfplots@loc@TMPb{##2}%
			% 
			% check if the argument is known:
			\pgfkeysifdefined{/pgfplots/point meta/\pgfplots@loc@TMPa/.@cmd}{%
				\def\pgfplots@loc@TMPc{%
					\pgfplots@invoke@pgfkeyscode{/pgfplots/point meta/\pgfplots@loc@TMPa/.@cmd}%
				}%
				\expandafter\pgfplots@loc@TMPc\expandafter{\pgfplots@loc@TMPb}%
			}{%
				\pgfplotsthrow{invalid argument}
					{\pgfplots@loc@TMPa}%
					{Sorry, `##1' is no valid choice for `point meta'. Maybe you misspelled it?}%
					\pgfeov
			}%
		}%
		% disassemble key'='value:
		\pgfplots@loc@TMPa#1\pgfplots@EOI
	\else
		% the following code allows
		% 'point meta=\thisrow{xcol}' even though
		% \thisrow might be undefined in the context where keys are set.
		% I convert the argument to a string.
		\def\pgfplots@loc@TMPa{#1}%
		\pgfplots@command@to@string\pgfplots@loc@TMPa\pgfplots@loc@TMPb
		%
		\pgfkeysifdefined{/pgfplots/point meta/\pgfplots@loc@TMPb/.@cmd}{%
			% ok, use it!
			\pgfplots@invoke@pgfkeyscode{/pgfplots/point meta/\pgfplots@loc@TMPb/.@cmd}{}%
		}{%
			% oh, then it will be a math expression.
			\pgfplots@invoke@pgfkeyscode{/pgfplots/point meta/expr/.@cmd}{#1}%
		}%
	\fi
	%
	%
}%

\newif\ifpgfplots@stackedmode

\newif\ifpgfplotsplothandlermesh@shownormals

\pgfkeys{%
	% <key name>/.define layer set={<layer list>}{<style definition>}
	/handlers/.define layer set/.code 2 args={%
		\pgfkeyssetvalue{\pgfkeyscurrentpath/list}{#1}%
		\pgfkeysdef{\pgfkeyscurrentpath}{\pgfkeysalso{#2}}%
	}%
}

\pgfkeys{%
	/pgfplots/search path for tikz/.search also={/tikz,/pgfplots},
	/pgfplots/.is family,
	/pgfplots/scale/.is family,
	/pgfplots/legend/.is family,
	/pgfplots/tick/.is family,
	/pgfplots/axis/.is family,
	/pgfplots/descriptions/.is family,
	/pgfplots/style commands/.is family,
	/pgfplots/naming commands/.is family,
	/pgfplots/shared with tikz/.is family,
	/pgfplots/error bars/.is family,
	%
	% pgfplots uses the following (implicit) layers:
	% context:			   & associated layer name: \\
	% background path      & axis background   \\
	% grid lines           & axis grid         \\
	% tick lines		   & axis ticks        \\
	% axis lines		   & axis lines        \\
	% tick labels		   & axis tick labels  \\
	% plots				   & main              \\
	% axis descriptions	   & axis descriptions \\
	% plot marks		   & (see 'mark layer')\\
	% the 'axis on top' key will change that order by moving all plot- and mark-related paths upwards (they are drawn earlier).
	% None of these layers is mandatory; each can be omitted.
	% The magic layer name 'discard' can be used as /dev/null layer.
	%
	% the <layer set name> must be defined
	% set layers={<layer set name>}
	/pgfplots/set layers/.code={%
		\def\pgfplots@loc@TMPa{#1}%
		\def\pgfplots@loc@TMPb{none}%
		\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
			\pgfkeysalso{%
				/pgfplots/activate layers=false,
				/pgfplots/set layers*={},
			}%
		\else
			\pgfkeysalso{%
				/pgfplots/activate layers=true,
				/pgfplots/set layers*={#1},
			}%
			\pgfplotsifinaxis{%
				\pgfkeysalso{/pgfplots/cell picture=if necessary}%
			}{%
				% we wrote it outside of an axis. In this case, we can
				% assume that it prepares multiple axis - which
				% REQUIRES to disable cell pictures.
				\pgfkeysalso{/pgfplots/cell picture=false}%
			}%
		\fi
	},
	% 'activate layers=false' is the same as 'set layers=none'.
	% However, 'activate layers=true' does not work unless a 'set layers' 
	% has been installed as well.
	/pgfplots/activate layers/.is if=pgfplots@layered@graphics,
	/pgfplots/activate layers/.default=true,
	/pgfplots/set layers*/.code=\pgfplots@key@set@layers{#1},
	/pgfplots/set layers*/.default={/pgfplots/layers/standard},
	/pgfplots/@set layers arg/.initial=,
	/pgfplots/layers/.search also=/pgfplots,
	/pgfplots/layers/standard/.define layer set={axis background,axis grid,axis ticks,axis lines,axis tick labels,pre main,main,axis descriptions,axis foreground}{
		grid style=			{/pgfplots/on layer=axis grid},
		tick style=			{/pgfplots/on layer=axis ticks},
		axis line style=	{/pgfplots/on layer=axis lines},
		label style=		{/pgfplots/on layer=axis descriptions},
		legend style=		{/pgfplots/on layer=axis descriptions},
		title style=		{/pgfplots/on layer=axis descriptions},
		colorbar style=		{/pgfplots/on layer=axis descriptions},
		ticklabel style=	{/pgfplots/on layer=axis tick labels},
		axis background@ style={/pgfplots/on layer=axis background},
		3d box foreground style={/pgfplots/on layer=axis foreground},
	},
	/pgfplots/layers/axis on top/.define layer set={axis background,pre main,main,axis grid,axis ticks,axis lines,axis tick labels,axis descriptions,axis foreground}{
		/pgfplots/layers/standard
	},
	/pgfplots/on layer/.initial=,
	% mark layer can be 'auto', 'like plot', or a layer name.
	/pgfplots/mark layer/.initial=,
	/pgfplots/every axis/.style={},
	/pgfplots/every axis/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every axis}},
	/pgfplots/every axis/.belongs to family=/pgfplots/style commands,
	/pgfplots/every axis post/.style={},
	/pgfplots/every axis post/.belongs to family=/pgfplots/scale,
	/pgfplots/every semilogx axis/.style={},
	/pgfplots/every semilogx axis/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every semilogx axis}},
	/pgfplots/every semilogx axis/.belongs to family=/pgfplots/style commands,
	/pgfplots/every semilogy axis/.style={},
	/pgfplots/every semilogy axis/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every semilogy axis}},
	/pgfplots/every semilogy axis/.belongs to family=/pgfplots/style commands,
	/pgfplots/every loglog axis/.style={},
	/pgfplots/every loglog axis/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every loglog axis}},
	/pgfplots/every loglog axis/.belongs to family=/pgfplots/style commands,
	/pgfplots/every linear axis/.style={},
	/pgfplots/every linear axis/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every linear axis}},
	/pgfplots/every linear axis/.belongs to family=/pgfplots/style commands,
	/pgfplots/every axis plot/.style={},
	/pgfplots/every axis plot/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every axis plot}},
	/pgfplots/every axis plot/.belongs to family=/pgfplots/style commands,
	/pgfplots/every axis plot post/.style={},
	/pgfplots/every axis plot post/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every axis plot}},
	/pgfplots/trig format plots/.is choice,
	/pgfplots/trig format plots/deg/.code={\def\pgfplots@set@trig@format@plots{\pgfkeys{/pgf/trig format=deg}}},%
	/pgfplots/trig format plots/rad/.code={\def\pgfplots@set@trig@format@plots{\pgfkeys{/pgf/trig format=rad}}},%
	/pgfplots/trig format plots/default/.code={\let\pgfplots@set@trig@format@plots=\relax},%
	/pgfplots/trig format plots/default,
	/pgfplots/no marks/.style={/pgfplots/no markers},
	/pgfplots/no markers/.style={/pgfplots/every axis plot post/.append style={mark=none}},
	/pgfplots/every axis label/.style={},
	/pgfplots/every axis label/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every axis label}},
	/pgfplots/every axis label/.belongs to family=/pgfplots/descriptions,
	/pgfplots/xlabel near ticks/.style={%
		/pgfplots/every axis x label/.style={at={(ticklabel cs:0.5)},anchor=near ticklabel},%
		/pgfplots/every x tick scale label/.style={at={(xticklabel cs:0.9,5pt)},anchor=near xticklabel,inner sep=0pt},
	},%
	/pgfplots/xlabel absolute/.style={%
		/pgfplots/every axis x label/.style={at={(0.5,0)},below,yshift=-15pt},%
		/pgfplots/every x tick scale label/.style={at={(1,0)},yshift=-2em,left,inner sep=0pt},
	},%
	/pgfplots/every axis x label/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every axis x label}},
	/pgfplots/every axis x label/.belongs to family=/pgfplots/descriptions,
	%
	/pgfplots/ylabel near ticks/.style={%
		/pgfplots/every axis y label/.style={at={(ticklabel cs:0.5)},rotate=90,anchor=near ticklabel},%
		/pgfplots/every y tick scale label/.style={at={(yticklabel* cs:1.03,-0.3em)},/pgfplots/near ticklabel align=outside,anchor=near yticklabel opposite,inner sep=0pt},
	},%
	/pgfplots/ylabel absolute/.style={%
		/pgfplots/every axis y label/.style={at={(0,0.5)},xshift=-35pt,rotate=90},
		/pgfplots/every y tick scale label/.style={at={(0,1)},above right,inner sep=0pt,yshift=0.3em},
	},%
	/pgfplots/every axis y label/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every axis y label}},
	/pgfplots/every axis y label/.belongs to family=/pgfplots/descriptions,
	/pgfplots/every axis z label/.style={at={(ticklabel cs:0.5)},rotate=90, anchor=near ticklabel},
	/pgfplots/every axis z label/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every axis z label}},
	/pgfplots/every axis z label/.belongs to family=/pgfplots/descriptions,
	/pgfplots/every 3d description/.style={%
		/pgfplots/every axis x label/.style={at={(ticklabel cs:0.5)},anchor=near ticklabel},%
		/pgfplots/every axis y label/.style={at={(ticklabel cs:0.5)},anchor=near ticklabel},%
		/pgfplots/every x tick scale label/.style={at={(xticklabel cs:0.95,5pt)},anchor=near xticklabel,inner sep=0pt},
		/pgfplots/every y tick scale label/.style={at={(yticklabel cs:0.95,5pt)},anchor=near yticklabel,inner sep=0pt},
		/pgfplots/try min ticks=3,%
	},%
	/pgfplots/every 3d view {0}{90}/.style={%
		/pgfplots/xlabel near ticks,%
		/pgfplots/ylabel near ticks,%
		/pgfplots/axis on top=true,%
	},%
	% will be defined in \pgfplotspoint@initialisation:
	%/tikz/sloped like x axis/.code={...},%
	/pgfplots/title shift/.code={\pgfplots@error{Sorry, there is no 'title shift' option. Consider using 'title style={yshift=...}' (or the low level 'every axis title shift' which works only together with the initial 'every axis title' style)}},%
	/pgfplots/every axis title shift/.initial=6pt,
	/pgfplots/every axis title/.style={at={(0.5,1)},above,yshift=\pgfkeysvalueof{/pgfplots/every axis title shift}},
	/pgfplots/every axis title/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every axis title}},
	/pgfplots/every axis title/.belongs to family=/pgfplots/descriptions,
	/pgfplots/every tick/.style={very thin,gray},
	/pgfplots/every tick/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every tick}},
	/pgfplots/every tick/.belongs to family=/pgfplots/style commands,
	/pgfplots/every inner x axis line/.style={},
	/pgfplots/every inner y axis line/.style={},
	/pgfplots/every inner z axis line/.style={},
	/pgfplots/every outer x axis line/.style={},
	/pgfplots/every outer y axis line/.style={},
	/pgfplots/every outer z axis line/.style={},
	/pgfplots/x axis line style/.style={
		/pgfplots/every outer x axis line/.append style={#1},
		/pgfplots/every inner x axis line/.append style={#1},
	},
	/pgfplots/y axis line style/.style={
		/pgfplots/every outer y axis line/.append style={#1},
		/pgfplots/every inner y axis line/.append style={#1},
	},
	/pgfplots/z axis line style/.style={
		/pgfplots/every outer z axis line/.append style={#1},
		/pgfplots/every inner z axis line/.append style={#1},
	},
	/pgfplots/outer axis line style/.style={
		/pgfplots/every outer x axis line/.append style={#1},
		/pgfplots/every outer y axis line/.append style={#1},%
		/pgfplots/every outer z axis line/.append style={#1}%
	},
	/pgfplots/inner axis line style/.style={
		/pgfplots/every inner x axis line/.append style={#1},
		/pgfplots/every inner y axis line/.append style={#1},%
		/pgfplots/every inner z axis line/.append style={#1}%
	},
	/pgfplots/axis line style/.style={
		/pgfplots/inner axis line style={#1},
		/pgfplots/outer axis line style={#1}%
	},
	/pgfplots/separate axis lines/.is if=pgfplots@separate@axis@lines,
	/pgfplots/separate axis lines/.default=true,
	/pgfplots/every minor tick/.style={},
	/pgfplots/every minor tick/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every minor tick}},
	/pgfplots/every minor tick/.belongs to family=/pgfplots/style commands,
	/pgfplots/every major tick/.style={},
	/pgfplots/every major tick/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every major tick}},
	/pgfplots/every major tick/.belongs to family=/pgfplots/style commands,
	/pgfplots/every x tick/.style={},
	/pgfplots/every x tick/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every x tick}},
	/pgfplots/every x tick/.belongs to family=/pgfplots/style commands,
	/pgfplots/every minor x tick/.style={},
	/pgfplots/every minor x tick/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every minor x tick}},
	/pgfplots/every minor x tick/.belongs to family=/pgfplots/style commands,
	/pgfplots/every major x tick/.style={},
	/pgfplots/every major x tick/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every major x tick}},
	/pgfplots/every major x tick/.belongs to family=/pgfplots/style commands,
	/pgfplots/every y tick/.style={},
	/pgfplots/every y tick/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every y tick}},
	/pgfplots/every y tick/.belongs to family=/pgfplots/style commands,
	/pgfplots/every minor y tick/.style={},
	/pgfplots/every minor y tick/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every minor y tick}},
	/pgfplots/every minor y tick/.belongs to family=/pgfplots/style commands,
	/pgfplots/every major y tick/.style={},
	/pgfplots/every major y tick/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every major y tick}},
	/pgfplots/every major y tick/.belongs to family=/pgfplots/style commands,
	/pgfplots/every z tick/.style={},
	/pgfplots/every z tick/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every z tick}},
	/pgfplots/every z tick/.belongs to family=/pgfplots/style commands,
	/pgfplots/every minor z tick/.style={},
	/pgfplots/every minor z tick/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every minor z tick}},
	/pgfplots/every minor z tick/.belongs to family=/pgfplots/style commands,
	/pgfplots/every major z tick/.style={},
	/pgfplots/every major z tick/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every major z tick}},
	/pgfplots/every major z tick/.belongs to family=/pgfplots/style commands,
	%/pgfplots/every axis grid/.style={help lines},
	/pgfplots/every axis grid/.style={thin,black!25},
	/pgfplots/every axis grid/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every axis grid}},
	/pgfplots/every axis grid/.belongs to family=/pgfplots/style commands,
	/pgfplots/every minor grid/.style={},
	/pgfplots/every minor grid/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every minor grid}},
	/pgfplots/every minor grid/.belongs to family=/pgfplots/style commands,
	/pgfplots/every major grid/.style={},
	/pgfplots/every major grid/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every major grid}},
	/pgfplots/every major grid/.belongs to family=/pgfplots/style commands,
	/pgfplots/every axis x grid/.style={},
	/pgfplots/every axis x grid/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every axis x grid}},
	/pgfplots/every axis x grid/.belongs to family=/pgfplots/style commands,
	/pgfplots/every minor x grid/.style={},
	/pgfplots/every minor x grid/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every minor x grid}},
	/pgfplots/every minor x grid/.belongs to family=/pgfplots/style commands,
	/pgfplots/every major x grid/.style={},
	/pgfplots/every major x grid/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every major x grid}},
	/pgfplots/every major x grid/.belongs to family=/pgfplots/style commands,
	/pgfplots/every axis y grid/.style={},
	/pgfplots/every axis y grid/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every axis y grid}},
	/pgfplots/every axis y grid/.belongs to family=/pgfplots/style commands,
	/pgfplots/every minor y grid/.style={},
	/pgfplots/every minor y grid/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every minor y grid}},
	/pgfplots/every minor y grid/.belongs to family=/pgfplots/style commands,
	/pgfplots/every major y grid/.style={},
	/pgfplots/every major y grid/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every major y grid}},
	/pgfplots/every major y grid/.belongs to family=/pgfplots/style commands,
	/pgfplots/every axis z grid/.style={},
	/pgfplots/every axis z grid/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every axis z grid}},
	/pgfplots/every axis z grid/.belongs to family=/pgfplots/style commands,
	/pgfplots/every minor z grid/.style={},
	/pgfplots/every minor z grid/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every minor z grid}},
	/pgfplots/every minor z grid/.belongs to family=/pgfplots/style commands,
	/pgfplots/every major z grid/.style={},
	/pgfplots/every major z grid/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every major z grid}},
	/pgfplots/every major z grid/.belongs to family=/pgfplots/style commands,
	/pgfplots/every tick label/.style={},
	/pgfplots/every tick label/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every tick label}},
	/pgfplots/every tick label/.belongs to family=/pgfplots/style commands,
	/pgfplots/every x tick label/.style={},
	/pgfplots/every x tick label/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every x tick label}},
	/pgfplots/every x tick label/.belongs to family=/pgfplots/style commands,
	/pgfplots/every extra x tick/.style={
		/pgfplots/log identify minor tick positions=true,
		/pgfplots/hide obscured x ticks=false,
	},
	/pgfplots/every extra x tick/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every extra x tick}},
	/pgfplots/every extra x tick/.belongs to family=/pgfplots/style commands,
	/pgfplots/extra x tick style/.belongs to family=/pgfplots/style commands,
	/pgfplots/extra x tick style/.code={%
		\pgfkeysalso{/pgfplots/every extra x tick/.append style={#1}}%
	},
	/pgfplots/extra tick style/.code={%
		\pgfkeysalso{%
			/pgfplots/every extra x tick/.append style={#1},%
			/pgfplots/every extra y tick/.append style={#1},%
			/pgfplots/every extra z tick/.append style={#1}}%
	},
	/pgfplots/every x tick scale label/.initial=,% set by compat/labels=...
	/pgfplots/every x tick scale label/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every x tick scale label}},
	/pgfplots/every x tick scale label/.belongs to family=/pgfplots/descriptions,
	/pgfplots/every y tick label/.style={},
	/pgfplots/every y tick label/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every y tick label}},
	/pgfplots/every y tick label/.belongs to family=/pgfplots/style commands,
	/pgfplots/every extra y tick/.style={
		/pgfplots/log identify minor tick positions=true,
		/pgfplots/hide obscured y ticks=false,
	},
	/pgfplots/every extra y tick/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every extra y tick}},
	/pgfplots/every extra y tick/.belongs to family=/pgfplots/style commands,
	/pgfplots/extra y tick style/.belongs to family=/pgfplots/style commands,
	/pgfplots/extra y tick style/.code={%
		\pgfkeysalso{/pgfplots/every extra y tick/.append style={#1}}%
	},
	/pgfplots/every y tick scale label/.initial=,% set by compat/labels=...
	/pgfplots/every y tick scale label/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every y tick scale label}},
	/pgfplots/every y tick scale label/.belongs to family=/pgfplots/descriptions,
	/pgfplots/every z tick label/.style={},
	/pgfplots/every z tick label/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every z tick label}},
	/pgfplots/every z tick label/.belongs to family=/pgfplots/style commands,
	/pgfplots/every extra z tick/.style={
		/pgfplots/log identify minor tick positions=true,
		/pgfplots/hide obscured z ticks=false,
	},
	/pgfplots/every extra z tick/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every extra z tick}},
	/pgfplots/every extra z tick/.belongs to family=/pgfplots/style commands,
	/pgfplots/extra z tick style/.belongs to family=/pgfplots/style commands,
	/pgfplots/extra z tick style/.code={%
		\pgfkeysalso{/pgfplots/every extra z tick/.append style={#1}}%
	},
	% FIXME : this is replicated in 'axis z line=box'!
	/pgfplots/every z tick scale label/.style={at={(zticklabel* cs:1.2,-0.3em)},anchor=near zticklabel,inner sep=0pt},
	/pgfplots/every z tick scale label/.belongs to family=/pgfplots/descriptions,
	/pgfplots/every axis legend/.style={%
		cells={anchor=center},
		inner xsep=3pt,inner ysep=2pt,nodes={inner sep=2pt,text depth=0.15em},
		anchor=north east,%
		shape=rectangle,%
		fill=white,%
		draw=black,
		at={(0.98,0.98)},
	},
	/pgfplots/every axis legend/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every axis legend}},
	/pgfplots/every axis legend/.belongs to family=/pgfplots/style commands,
	%
	% axis type:
	/pgfplots/axis type/.initial=rectangle,
	/pgfplots/axis type/.belongs to family=/pgfplots/scale,
	/pgfplots/@expected axis cs/.initial=cart,
	/pgfplots/every rectangle axis/.style={},
	% 
	% see \pgfplotsdefinecstransform{<from>}{<to>}{<code>}
	/pgfplots/data cs/.initial=cart,% the coordinate system of provided data. Will be transformed to the axis' internal coordinate system (@expected axis cs).
	%
	% Colorbar interface:
	/pgfplots/colorbar/.is if=pgfplots@colorbar,
	/pgfplots/colorbar/.default=true,
	/pgfplots/colorbar to label/.style={/pgfplots/colorbar to name={#1}},
	/pgfplots/colorbar to name/.initial=,
	/pgfplots/colorbar source/.code={\pgfplots@error{Sorry, you can only set `colorbar source' inside of \string\addplot\space (or a cycle list)}},
	/pgfplots/colorbar source/.default=true,
	/pgfplots/colorbar pos*/.initial=,% one of 'rltb' (right, left, top, bottom). for internal use, to handle checks.
	/pgfplots/every colorbar global/.style={
		data cs=cart,
		axis on top,
		title=,
		xlabel=,
		ylabel=,
		zlabel=,
		legend entries=,
		grid=none,
		enlargelimits=false,
		scale only axis,
		xtick=,
		xticklabel=,
		ytick=,
		yticklabel=,
	},
	/pgfplots/colorbar right/.style={%
		/pgfplots/colorbar=true,
		/pgfplots/colorbar pos*=r,
		/pgfplots/colorbar shift/.style={xshift=0.3cm},
		/pgfplots/every colorbar/.style={%
			/pgfplots/every colorbar global,
			at={(parent axis.right of north east)},
			anchor=north west,
			xmin=0,
			xmax=1,
			ymin=\pgfkeysvalueof{/pgfplots/point meta min},
			ymax=\pgfkeysvalueof{/pgfplots/point meta max},
			plot graphics/xmin=0,%
			plot graphics/xmax=1,
			plot graphics/ymin=\pgfkeysvalueof{/pgfplots/point meta min},
			plot graphics/ymax=\pgfkeysvalueof{/pgfplots/point meta max},
			height=\pgfkeysvalueof{/pgfplots/parent axis height},%
			width=\pgfkeysvalueof{/pgfplots/colorbar/width},
			xtick=\empty,
			yticklabel pos=right,% ATTENTION: I check for this setting in 'colorbar sampled line', see below!
			colorbar vertical/lowlevel,
		}%
	},%
	/pgfplots/colorbar left/.style={%
		/pgfplots/colorbar right,
		/pgfplots/colorbar pos*=l,
		/pgfplots/colorbar shift/.style={xshift=-0.3cm},
		/pgfplots/every colorbar/.append style={%
			at={(parent axis.left of north west)},
			anchor=north east,
			yticklabel pos=left,% ATTENTION: I check for this setting in 'colorbar sampled line', see below!
		}%
	},%
	/pgfplots/colorbar horizontal/.style={%
		/pgfplots/colorbar=true,
		/pgfplots/colorbar pos*=b,
		/pgfplots/colorbar shift/.style={yshift=-0.3cm},
		/pgfplots/every colorbar/.style={%
			/pgfplots/every colorbar global,
			at={(parent axis.below south west)},
			anchor=north west,
			ymin=0,
			ymax=1,
			xmin=\pgfkeysvalueof{/pgfplots/point meta min},
			xmax=\pgfkeysvalueof{/pgfplots/point meta max},
			plot graphics/ymin=0,%
			plot graphics/ymax=1,
			plot graphics/xmin=\pgfkeysvalueof{/pgfplots/point meta min},
			plot graphics/xmax=\pgfkeysvalueof{/pgfplots/point meta max},
			width=\pgfkeysvalueof{/pgfplots/parent axis width},%
			height=\pgfkeysvalueof{/pgfplots/colorbar/width},
			xticklabel pos=left,
			ytick=\empty,
			colorbar horizontal/lowlevel,
		}%
	},%
	% You might wonder why this special treatment with '/lowlevel'
	% keys is necessary. Well, It turned out that using '##' inside of
	% styles is incompatible with '.add code' -- and therefor also
	% with '.append style'. This here is a work-around which works.
	/pgfplots/colorbar vertical/lowlevel/.style={%
		/pgfplots/colorbar addplot=\addplot graphics {};,
		plot graphics/lowlevel draw/.code 2 args={%
			\if\pgfkeysvalueof{/pgfplots/y dir/value}n%
				\pgfplotscolormaptoshadingspec{\pgfkeysvalueof{/pgfplots/colormap name}}{##2}\pgfplots@loc@TMPa
			\else
				\pgfplotscolormapreversedtoshadingspec{\pgfkeysvalueof{/pgfplots/colormap name}}{##2}\pgfplots@loc@TMPa
			\fi
			\def\pgfplots@loc@TMPb{\pgfdeclareverticalshading{tempshading}{\pgfkeysvalueof{/pgfplots/colorbar/width}}}%
			\expandafter\pgfplots@loc@TMPb\expandafter{\pgfplots@loc@TMPa}%
			\pgfuseshading{tempshading}%
		},%
	},
	/pgfplots/colorbar horizontal/lowlevel/.style={%
		/pgfplots/colorbar addplot=\addplot graphics {};,
		plot graphics/lowlevel draw/.code 2 args={%
			\if\pgfkeysvalueof{/pgfplots/x dir/value}n%
				\pgfplotscolormaptoshadingspec{\pgfkeysvalueof{/pgfplots/colormap name}}{##1}\pgfplots@loc@TMPa
			\else
				\pgfplotscolormapreversedtoshadingspec{\pgfkeysvalueof{/pgfplots/colormap name}}{##1}\pgfplots@loc@TMPa
			\fi
			\def\pgfplots@loc@TMPb{\pgfdeclarehorizontalshading{tempshading}{\pgfkeysvalueof{/pgfplots/colorbar/width}}}%
			\expandafter\pgfplots@loc@TMPb\expandafter{\pgfplots@loc@TMPa}%
			\pgfuseshading{tempshading}%
		},%
	},%
	/pgfplots/colorbar right,
	/pgfplots/colorbar=false,
	/pgfplots/colorbar style/.style={/pgfplots/every colorbar/.append style={#1}},
	/pgfplots/colorbar/width/.initial=0.5cm,
	/pgfplots/colorbar addplot/.initial=\addplot graphics {};,
	/pgfplots/colorbar/draw/.code={%
		\axis[every colorbar,colorbar shift,colorbar=false]
		\pgfkeysvalueof{/pgfplots/colorbar addplot}%
		\endaxis
	},%
	/pgfplots/every colorbar sampled line/.style={help lines},
	/pgfplots/colorbar sampled line style/.style={/pgfplots/every colorbar sampled line/.append style={#1}},
	/pgfplots/colorbar sampled line/.style={%
		colorbar,
		/pgfplots/colorbar/draw/.code={%
			\axis[
				cycle list={#1\\},
				domain=\pgfkeysvalueof{/pgfplots/point meta min}:\pgfkeysvalueof{/pgfplots/point meta max},
				every colorbar,colorbar shift,colorbar=false]
			\pgfkeysvalueof{/pgfplots/colorbar addplot}%
			\endaxis
		},%
		/pgfplots/colorbar horizontal/lowlevel/.code={%
			\pgfkeysgetvalue{/pgfplots/colorbar pos*}\pgfplots@loc@TMPa
			\ifx\pgfplots@loc@TMPa\pgfutil@empty
				\def\pgfplots@loc@TMPa{b}%
			\fi
			\if b\pgfplots@loc@TMPa
				\pgfkeysalso{axis x line*=bottom}% DEFAULT.
			\else
				\pgfkeysalso{axis x line*=top}%
			\fi
			\pgfkeysalso{%
				y axis line style={/pgfplots/every colorbar sampled line},
				/pgfplots/colorbar addplot={\addplot {0.5};},
				point meta=x,
			}%
		},%
		/pgfplots/colorbar vertical/lowlevel/.code={%
			\pgfkeysgetvalue{/pgfplots/colorbar pos*}\pgfplots@loc@TMPa
			\ifx\pgfplots@loc@TMPa\pgfutil@empty
				\def\pgfplots@loc@TMPa{r}%
			\fi
			\if l\pgfplots@loc@TMPa
				\pgfkeysalso{axis y line*=left}%
			\else
				\pgfkeysalso{axis y line*=right}% DEFAULT
			\fi
			\pgfkeysalso{%
				x axis line style={/pgfplots/every colorbar sampled line},
				/pgfplots/colorbar addplot={\addplot (0.5,x);},
				point meta=y,
			}%
		},%
	},%
	/pgfplots/colorbar sampled line/.default={scatter,only marks},
	%
	/pgfplots/colorbar sampled/.style={%
		colorbar,
		/pgfplots/colorbar/draw/.code={%
			\axis[
				view={0}{90},
				cycle list={#1\\},
				domain=\pgfkeysvalueof{/pgfplots/point meta min}:\pgfkeysvalueof{/pgfplots/point meta max},
				samples y=2,
				domain y=0:1,
				zmin=0,zmax=1,
				every colorbar,colorbar shift,colorbar=false]
			\pgfkeysvalueof{/pgfplots/colorbar addplot}%
			\endaxis
		},%
		/pgfplots/colorbar horizontal/lowlevel/.style={%
			/pgfplots/colorbar addplot={\addplot3 {0};},
			point meta=x,
		},%
		/pgfplots/colorbar vertical/lowlevel/.style={%
			/pgfplots/colorbar addplot={\addplot3 (y,x,0);},
			point meta=y,
		},%
	},%
	/pgfplots/colorbar sampled/.default={surf,mark=none,shader=flat},
% tick options:
	/pgfplots/xticklabel/.store in=	\pgfplots@xticklabel,
	/pgfplots/xticklabel/.belongs to family=/pgfplots/tick,
	/pgfplots/xticklabel=,
	/pgfplots/xticklabels/.belongs to family=/pgfplots/tick,
	/pgfplots/xticklabels/.code={%
		\pgfplotslistnew\pgfplots@xticklabels{#1}%
		\let\pgfplots@xticklabel=\pgfplots@user@ticklabel@list@x
	},
	% #1 table name or macro
	% #2 column name (or alias or create on use)
	/pgfplots/xticklabels from table/.code 2 args={%
		\pgfplotstablegetcolumn{#2}\of{#1}\to\pgfplots@xticklabels
		\let\pgfplots@xticklabel=\pgfplots@user@ticklabel@list@x
	},
	/pgfplots/xticklabels from table/.belongs to family=/pgfplots/tick,
	/pgfplots/yticklabels/.belongs to family=/pgfplots/tick,
	/pgfplots/yticklabels/.code={%
		\pgfplotslistnew\pgfplots@yticklabels{#1}%
		\let\pgfplots@yticklabel=\pgfplots@user@ticklabel@list@y
	},
	% #1 table name or macro
	% #2 column name (or alias or create on use)
	/pgfplots/yticklabels from table/.code 2 args={%
		\pgfplotstablegetcolumn{#2}\of{#1}\to\pgfplots@yticklabels
		\let\pgfplots@yticklabel=\pgfplots@user@ticklabel@list@y
	},
	/pgfplots/yticklabels from table/.belongs to family=/pgfplots/tick,
	/pgfplots/yticklabel/.store in=	\pgfplots@yticklabel,
	/pgfplots/yticklabel/.belongs to family=/pgfplots/tick,
	/pgfplots/yticklabel=,
	/pgfplots/zticklabels/.belongs to family=/pgfplots/tick,
	/pgfplots/zticklabels/.code={%
		\pgfplotslistnew\pgfplots@zticklabels{#1}%
		\let\pgfplots@zticklabel=\pgfplots@user@ticklabel@list@z
	},
	% #1 table name or macro
	% #2 column name (or alias or create on use)
	/pgfplots/zticklabels from table/.code 2 args={%
		\pgfplotstablegetcolumn{#2}\of{#1}\to\pgfplots@zticklabels
		\let\pgfplots@zticklabel=\pgfplots@user@ticklabel@list@z
	},
	/pgfplots/zticklabels from table/.belongs to family=/pgfplots/tick,
	/pgfplots/zticklabel/.store in=	\pgfplots@zticklabel,
	/pgfplots/zticklabel/.belongs to family=/pgfplots/tick,
	/pgfplots/zticklabel=,
	/pgfplots/x tick label as interval/.is if=pgfplots@xticklabel@interval,
	/pgfplots/x tick label as interval/.default=true,
	/pgfplots/x tick label as interval/.belongs to family=/pgfplots/tick,
	/pgfplots/y tick label as interval/.is if=pgfplots@yticklabel@interval,
	/pgfplots/y tick label as interval/.default=true,
	/pgfplots/y tick label as interval/.belongs to family=/pgfplots/tick,
	/pgfplots/z tick label as interval/.is if=pgfplots@zticklabel@interval,
	/pgfplots/z tick label as interval/.default=true,
	/pgfplots/z tick label as interval/.belongs to family=/pgfplots/tick,
	/pgfplots/extra x tick label/.store in=	\pgfplots@extra@xticklabel,
	/pgfplots/extra x tick label/.belongs to family=/pgfplots/tick,
	/pgfplots/extra x tick label=,
	/pgfplots/extra x tick labels/.belongs to family=/pgfplots/tick,
	/pgfplots/extra x tick labels/.code={%
		\pgfplotslistnew\pgfplots@extra@xticklabels{#1}%
		\let\pgfplots@extra@xticklabel=\pgfplots@user@extra@ticklabel@list@x
	},
	/pgfplots/extra y tick labels/.code={%
		\pgfplotslistnew\pgfplots@extra@yticklabels{#1}%
		\let\pgfplots@extra@yticklabel=\pgfplots@user@extra@ticklabel@list@y
	},
	/pgfplots/extra z tick labels/.code={%
		\pgfplotslistnew\pgfplots@extra@zticklabels{#1}%
		\let\pgfplots@extra@zticklabel=\pgfplots@user@extra@ticklabel@list@z
	},
	/pgfplots/xtick/.store in=			\pgfplots@xtick,
	/pgfplots/xtick/.belongs to family=/pgfplots/tick,
	/pgfplots/xtick=,
	/pgfplots/extra x ticks/.store in=\pgfplots@extra@xtick,
	/pgfplots/extra x ticks/.belongs to family=/pgfplots/tick,
	/pgfplots/extra x ticks=,
	/pgfplots/xtickten/.store in=		\pgfplots@xtickten,
	/pgfplots/xtickten/.belongs to family=/pgfplots/tick,
	/pgfplots/xtickten=,
	/pgfplots/extra y tick label/.store in=	\pgfplots@extra@yticklabel,
	/pgfplots/extra y tick label/.belongs to family=/pgfplots/tick,
	/pgfplots/extra y tick label=,
	/pgfplots/ytick/.store in=			\pgfplots@ytick,
	/pgfplots/ytick/.belongs to family=/pgfplots/tick,
	/pgfplots/ytick=,
	/pgfplots/extra y ticks/.store in=\pgfplots@extra@ytick,
	/pgfplots/extra y ticks/.belongs to family=/pgfplots/tick,
	/pgfplots/extra y ticks=,
	/pgfplots/ytickten/.store in=		\pgfplots@ytickten,
	/pgfplots/ytickten/.belongs to family=/pgfplots/tick,
	/pgfplots/ytickten=,
	/pgfplots/extra z tick label/.store in=	\pgfplots@extra@zticklabel,
	/pgfplots/extra z tick label/.belongs to family=/pgfplots/tick,
	/pgfplots/extra z tick label=,
	/pgfplots/ztick/.store in=			\pgfplots@ztick,
	/pgfplots/ztick/.belongs to family=/pgfplots/tick,
	/pgfplots/ztick=,
	/pgfplots/extra z ticks/.store in=\pgfplots@extra@ztick,
	/pgfplots/extra z ticks/.belongs to family=/pgfplots/tick,
	/pgfplots/extra z ticks=,
	/pgfplots/ztickten/.store in=		\pgfplots@ztickten,
	/pgfplots/ztickten/.belongs to family=/pgfplots/tick,
	/pgfplots/ztickten=,
	/pgfplots/tick scale binop/.initial=\cdot,
	/pgfplots/xtick scale label code/.code={$\pgfkeysvalueof{/pgfplots/tick scale binop} 10^{#1}$},
	/pgfplots/xtick scale label code/.belongs to family=/pgfplots/tick,
	/pgfplots/ytick scale label code/.code={$\pgfkeysvalueof{/pgfplots/tick scale binop} 10^{#1}$},
	/pgfplots/ytick scale label code/.belongs to family=/pgfplots/tick,
	/pgfplots/ztick scale label code/.code={$\pgfkeysvalueof{/pgfplots/tick scale binop} 10^{#1}$},
	/pgfplots/ztick scale label code/.belongs to family=/pgfplots/tick,
	/pgfplots/tick scale label code/.style={%
		/pgfplots/xtick scale label code={#1},
		/pgfplots/ytick scale label code={#1}%
		/pgfplots/ztick scale label code={#1}%
	},%
	/pgfplots/scaled x ticks/.code={\pgfplots@scaled@ticks@setargs{x}{#1}},
	/pgfplots/scaled x ticks/false/.code=		{\def\pgfplots@scaled@ticks@x@choice{0}},
	/pgfplots/scaled x ticks/true/.code=		{\def\pgfplots@scaled@ticks@x@choice{1}},
	/pgfplots/scaled x ticks/base 10/.code=		{\def\pgfplots@scaled@ticks@x@choice{2}\def\pgfplots@scaled@ticks@x@arg{#1}},
	/pgfplots/scaled x ticks/real/.code=		{%
		\def\pgfplots@scaled@ticks@x@choice{3}\def\pgfplots@scaled@ticks@x@arg{#1}%
		\pgfkeys{/pgfplots/xtick scale label code/.code={$\pgfkeysvalueof{/pgfplots/tick scale binop} \pgfmathprintnumber{#1}$}}},
	/pgfplots/scaled x ticks/manual/.code 2 args=		{%
		\def\pgfplots@scaled@ticks@x@choice{4}\def\pgfplots@scaled@ticks@x@arg##1{#2}%
		\pgfkeys{/pgfplots/xtick scale label code/.code={#1}}},
	/pgfplots/scaled x ticks/.belongs to family=/pgfplots/tick,
	/pgfplots/scaled x ticks=true,
	/pgfplots/scaled y ticks/.code={\pgfplots@scaled@ticks@setargs{y}{#1}},
	/pgfplots/scaled y ticks/false/.code=		{\def\pgfplots@scaled@ticks@y@choice{0}},
	/pgfplots/scaled y ticks/true/.code=		{\def\pgfplots@scaled@ticks@y@choice{1}},
	/pgfplots/scaled y ticks/base 10/.code=		{\def\pgfplots@scaled@ticks@y@choice{2}\def\pgfplots@scaled@ticks@y@arg{#1}},
	/pgfplots/scaled y ticks/real/.code=		{%
		\def\pgfplots@scaled@ticks@y@choice{3}\def\pgfplots@scaled@ticks@y@arg{#1}%
		\pgfkeys{/pgfplots/ytick scale label code/.code={$\pgfkeysvalueof{/pgfplots/tick scale binop} \pgfmathprintnumber{#1}$}}},
	/pgfplots/scaled y ticks/manual/.code 2 args=		{%
		\def\pgfplots@scaled@ticks@y@choice{4}\def\pgfplots@scaled@ticks@y@arg##1{#2}%
		\pgfkeys{/pgfplots/ytick scale label code/.code={#1}}},
	/pgfplots/scaled y ticks/.belongs to family=/pgfplots/tick,
	/pgfplots/scaled y ticks=true,
	/pgfplots/scaled z ticks/.code={\pgfplots@scaled@ticks@setargs{z}{#1}},
	/pgfplots/scaled z ticks/false/.code=		{\def\pgfplots@scaled@ticks@z@choice{0}},
	/pgfplots/scaled z ticks/true/.code=		{\def\pgfplots@scaled@ticks@z@choice{1}},
	/pgfplots/scaled z ticks/base 10/.code=		{\def\pgfplots@scaled@ticks@z@choice{2}\def\pgfplots@scaled@ticks@z@arg{#1}},
	/pgfplots/scaled z ticks/real/.code=		{%
		\def\pgfplots@scaled@ticks@z@choice{3}\def\pgfplots@scaled@ticks@z@arg{#1}%
		\pgfkeys{/pgfplots/ztick scale label code/.code={$\pgfkeysvalueof{/pgfplots/tick scale binop} \pgfmathprintnumber{#1}$}}},
	/pgfplots/scaled z ticks/manual/.code 2 args=		{%
		\def\pgfplots@scaled@ticks@z@choice{4}\def\pgfplots@scaled@ticks@z@arg##1{#2}%
		\pgfkeys{/pgfplots/ztick scale label code/.code={#1}}},
	/pgfplots/scaled z ticks/.belongs to family=/pgfplots/tick,
	/pgfplots/scaled z ticks=true,
	/pgfplots/scaled ticks/.style={%
		/pgfplots/scaled x ticks=#1,
		/pgfplots/scaled y ticks=#1,
		/pgfplots/scaled z ticks=#1
	},
	/pgfplots/scale ticks above exponent/.store in=	\pgfplots@scale@ticks@above@exponent,
	/pgfplots/scale ticks above exponent/.belongs to family=/pgfplots/tick,
	/pgfplots/scale ticks above exponent=3,
	/pgfplots/scale ticks below exponent/.store in=	\pgfplots@scale@ticks@below@exponent,
	/pgfplots/scale ticks below exponent/.belongs to family=/pgfplots/tick,
	/pgfplots/scale ticks below exponent=-1,
	/pgfplots/minor x tick num/.initial=0,
	/pgfplots/minor x tick num/.belongs to family=/pgfplots/tick,
	/pgfplots/minor y tick num/.initial=0,
	/pgfplots/minor y tick num/.belongs to family=/pgfplots/tick,
	/pgfplots/minor z tick num/.initial=0,
	/pgfplots/minor z tick num/.belongs to family=/pgfplots/tick,
	/pgfplots/minor tick num/.style={
		/pgfplots/minor x tick num=#1,
		/pgfplots/minor y tick num=#1,
		/pgfplots/minor z tick num=#1,
	},
	/pgfplots/minor tick num/.belongs to family=/pgfplots/tick,
	/pgfplots/minor xtick/.initial=,
	/pgfplots/minor xtick/.belongs to family=/pgfplots/tick,
	/pgfplots/minor ytick/.initial=,
	/pgfplots/minor ytick/.belongs to family=/pgfplots/tick,
	/pgfplots/minor ztick/.initial=,
	/pgfplots/minor ztick/.belongs to family=/pgfplots/tick,
	/pgfplots/minor tick/.style={
		/pgfplots/minor xtick={#1},
		/pgfplots/minor ytick={#1},
		/pgfplots/minor ztick={#1},
	},
	/pgfplots/minor tick/.belongs to family=/pgfplots/tick,
	%
	/pgfplots/subtickwidth/.style=	{/pgfplots/minor tick length={#1}},
	/pgfplots/tickwidth/.style=		{/pgfplots/major tick length={#1}},
	/pgfplots/minor tick length/.belongs to family=/pgfplots/tick,
	/pgfplots/minor tick length/.initial=0.1cm,
	/pgfplots/major tick length/.belongs to family=/pgfplots/tick,
	/pgfplots/major tick length/.initial=0.15cm,
	%
	/pgfplots/max space between ticks/.estore in=\axisdefaulttickwidth,
	/pgfplots/max space between ticks/.belongs to family=/pgfplots/tick,
	/pgfplots/max space between ticks=35,% the maximum space between adjacent ticks (in pt, but don't specify the unit 'pt')
	/pgfplots/try min ticks/.estore in=			\axisdefaulttryminticks,
	/pgfplots/try min ticks/.belongs to family=/pgfplots/tick,
	/pgfplots/try min ticks=4,
	/pgfplots/try min ticks log/.estore in=			\pgfplots@default@try@minticks@log,
	/pgfplots/try min ticks log/.belongs to family=/pgfplots/tick,
	/pgfplots/try min ticks log=3,
	/pgfplots/log basis x/.initial=,
	/pgfplots/log basis y/.initial=,
	/pgfplots/log basis z/.initial=,
	/pgfplots/log base x/.style={log basis x={#1}},%
	/pgfplots/log base y/.style={log basis y={#1}},%
	/pgfplots/log base z/.style={log basis z={#1}},%
	/pgfplots/log plot exponent style/.style={/pgf/number format/fixed,/pgf/number format/precision=2},
	/pgfplots/log plot exponent style/.belongs to family=/pgfplots/tick,
	/pgfplots/log identify minor tick positions/.is if=pgfplots@identify@log@minor@tick@pos,
	/pgfplots/log identify minor tick positions/.belongs to family=/pgfplots/tick,
	/pgfplots/log identify minor tick positions=false,
	/pgfplots/log number format code/.code={%
		\begingroup
		\pgfmathlogtologten@{#1}%
		\ifpgfplots@identify@log@minor@tick@pos
			\expandafter\pgfplots@is@log@tick@a@minor@tick@pos\pgfmathresult\relax%
		\else
			\pgfplots@log@tick@isminor@tick@posfalse
		\fi
		\ifpgfplots@log@tick@isminor@tick@pos
			\pgfmathprintnumber[sci]{\pgfmathresult}%
		\else
			\pgfkeysalso{/pgfplots/log plot exponent style,/pgfplots/log base 10 number format code=\pgfmathresult}%
		\fi
		\endgroup
	},
	/pgfplots/log number format code/.belongs to family=/pgfplots/tick,
	/pgfplots/log base 10 number format code/.code={{\pgfplots@invoke@pgfkeyscode{/pgfplots/log number format basis/.@cmd}{{10}{#1}}}},
	/pgfplots/log base 10 number format code/.belongs to family=/pgfplots/tick,
	% #1 = basis
	% #2 = exponent
	/pgfplots/log number format basis/.code 2 args={$#1^{\pgfmathprintnumber{#2}}$},
	%
	% #1= number formatting options
	/pgfplots/log ticks with fixed point/.style={
		/pgfplots/log number format basis/.code 2 args={
			\begingroup
			\edef\pgfplots@exponent{##2}%
			\pgfkeysalso{/pgf/fpu}%
			% configure the style to avoid crap like
			% 10,000.2  or 0.000999937 :
			\pgfqkeys{/pgf/number format}{%
				% it is rounded relative to its (individual!) order of
				% magnitude:
				fixed relative,
				% ... and with three digits relative to its order of
				% magnitude. This should avoid rounding problems
				% since it is applied to each tick number
				% individually.
				precision=3,
			}%
			\ifdim##1pt=10pt
				\def\pgfplots@baselog{2.30258509299405}%
			\else
				\pgfmathparse{ln(##1)}%
				\let\pgfplots@baselog=\pgfmathresult
			\fi
			\pgfmathparse{exp(\pgfplots@exponent*\pgfplots@baselog)}%
			\pgfmathprintnumber[#1]\pgfmathresult
			\endgroup
		},
	},
	% takes #1 = [xyz]:
	/pgfplots/log basis ticks/.style={%
		/pgfplots/every #1 tick label/.append style={%
			/pgfplots/log number format code/.code={%
				\begingroup
				\pgfkeysalso{/pgfplots/log plot exponent style}%
				\pgfplots@invoke@pgfkeyscode{/pgfplots/log number format basis/.@cmd}{{\pgfkeysvalueof{/pgfplots/log basis #1}}{####1}}%
				\endgroup
			}%
		}%
	},
% sets \pgfplots@[xy]tickposnum to
	/pgfplots/xtick pos/.is choice,
	/pgfplots/xtick pos/.belongs to family=/pgfplots/tick,
	/pgfplots/xtick pos/left/.code	={\def\pgfplots@xtickposnum{1}},
	/pgfplots/xtick pos/left/.belongs to family=/pgfplots/tick,
	/pgfplots/xtick pos/right/.code	={\def\pgfplots@xtickposnum{3}},
	/pgfplots/xtick pos/right/.belongs to family=/pgfplots/tick,
	/pgfplots/xtick pos/both/.code	={\def\pgfplots@xtickposnum{0}},
	/pgfplots/xtick pos/both/.belongs to family=/pgfplots/tick,
	/pgfplots/xtick pos=both,
	/pgfplots/ytick pos/.is choice,
	/pgfplots/ytick pos/.belongs to family=/pgfplots/tick,
	/pgfplots/ytick pos/left/.code	={\def\pgfplots@ytickposnum{1}},
	/pgfplots/ytick pos/left/.belongs to family=/pgfplots/tick,
	/pgfplots/ytick pos/right/.code	={\def\pgfplots@ytickposnum{3}},
	/pgfplots/ytick pos/right/.belongs to family=/pgfplots/tick,
	/pgfplots/ytick pos/both/.code	={\def\pgfplots@ytickposnum{0}},
	/pgfplots/ytick pos/both/.belongs to family=/pgfplots/tick,
	/pgfplots/ytick pos/top/.style={/pgfplots/ytick pos/right},
	/pgfplots/ytick pos/bottom/.style={/pgfplots/ytick pos/left},
	/pgfplots/ytick pos=both,
	/pgfplots/ztick pos/.is choice,
	/pgfplots/ztick pos/.belongs to family=/pgfplots/tick,
	/pgfplots/ztick pos/left/.code	={\def\pgfplots@ztickposnum{1}},
	/pgfplots/ztick pos/left/.belongs to family=/pgfplots/tick,
	/pgfplots/ztick pos/right/.code	={\def\pgfplots@ztickposnum{3}},
	/pgfplots/ztick pos/right/.belongs to family=/pgfplots/tick,
	/pgfplots/ztick pos/both/.code	={\def\pgfplots@ztickposnum{0}},
	/pgfplots/ztick pos/both/.belongs to family=/pgfplots/tick,
	/pgfplots/ztick pos/top/.style={/pgfplots/ztick pos/right},
	/pgfplots/ztick pos/bottom/.style={/pgfplots/ztick pos/left},
	/pgfplots/ztick pos=both,
	/pgfplots/tickpos/.style={
		/pgfplots/xtick pos={#1},
		/pgfplots/ytick pos={#1},
		/pgfplots/ztick pos={#1}
	},
	/pgfplots/tickpos/.belongs to family=/pgfplots/tick,
	/pgfplots/tick pos/.style={/pgfplots/tickpos={#1}},
% sets the tick LABEL position, \pgfplots@[xy]ticklabel@pos
% to one of
% lower (alias left alias bottom)    : l
% upper (alias right alias top)      : u
% default: uses one matches 'tick pos'
	/pgfplots/xticklabel pos/.code={\pgfplots@setkey@ticklabelpos{x}{#1}},
	/pgfplots/xticklabel pos/.belongs to family=/pgfplots/tick,
	/pgfplots/xticklabel pos=default,
	/pgfplots/yticklabel pos/.code={\pgfplots@setkey@ticklabelpos{y}{#1}},
	/pgfplots/yticklabel pos/.belongs to family=/pgfplots/tick,
	/pgfplots/yticklabel pos=default,
	/pgfplots/zticklabel pos/.code={\pgfplots@setkey@ticklabelpos{z}{#1}},
	/pgfplots/zticklabel pos/.belongs to family=/pgfplots/tick,
	/pgfplots/zticklabel pos=default,
	/pgfplots/ticklabelpos/.style={/pgfplots/ticklabel pos={#1}},
	/pgfplots/ticklabel pos/.style={
		/pgfplots/xticklabel pos={#1},
		/pgfplots/yticklabel pos={#1},
		/pgfplots/zticklabel pos={#1},
	},
	% This feature is more or less deprecated.
	% The choice 'auto' should always use 'near ticklabel'.
	%
	% Choices are 
	% 	'auto' (value 0),
	% 	'near ticklabel' (value 1), 
	% 	'tikz' (value 2)
	% with values stored in \pgfplots@ticklabel@anchor@[xyz] 
	/pgfplots/xticklabel anchor/.code={\pgfplots@setticklabel@anchor@for x{#1}},
	/pgfplots/xticklabel anchor/.belongs to family=/pgfplots/tick,
	/pgfplots/yticklabel anchor/.code={\pgfplots@setticklabel@anchor@for y{#1}},
	/pgfplots/yticklabel anchor/.belongs to family=/pgfplots/tick,
	/pgfplots/zticklabel anchor/.code={\pgfplots@setticklabel@anchor@for z{#1}},
	/pgfplots/zticklabel anchor/.belongs to family=/pgfplots/tick,
	/pgfplots/ticklabel anchor/.style={
		/pgfplots/xticklabel anchor={#1},
		/pgfplots/yticklabel anchor={#1},
		/pgfplots/zticklabel anchor={#1}
	},
	/pgfplots/ticklabel anchor=auto,
	/pgfplots/xticklabel shift/.initial=,
	/pgfplots/yticklabel shift/.initial=,
	/pgfplots/zticklabel shift/.initial=,
	/pgfplots/ticklabel shift/.style={
		/pgfplots/xticklabel shift={#1},
		/pgfplots/yticklabel shift={#1},
		/pgfplots/zticklabel shift={#1}
	},%
% sets \pgfplots@{x,y}tickalignnum to
% inside=0
% outside=1
% center=2
	/pgfplots/xtick align/.is choice,
	/pgfplots/xtick align/.belongs to family=/pgfplots/tick,
	/pgfplots/xtick align/inside/.code	={\def\pgfplots@xtickalignnum{0}},
	/pgfplots/xtick align/inside/.belongs to family=/pgfplots/tick,
	/pgfplots/xtick align/outside/.code	={\def\pgfplots@xtickalignnum{1}},
	/pgfplots/xtick align/outside/.belongs to family=/pgfplots/tick,
	/pgfplots/xtick align/center/.code	={\def\pgfplots@xtickalignnum{2}},
	/pgfplots/xtick align/center/.belongs to family=/pgfplots/tick,
	/pgfplots/xtick align=inside,
	/pgfplots/ytick align/.is choice,
	/pgfplots/ytick align/.belongs to family=/pgfplots/tick,
	/pgfplots/ytick align/inside/.code	={\def\pgfplots@ytickalignnum{0}},
	/pgfplots/ytick align/inside/.belongs to family=/pgfplots/tick,
	/pgfplots/ytick align/outside/.code	={\def\pgfplots@ytickalignnum{1}},
	/pgfplots/ytick align/outside/.belongs to family=/pgfplots/tick,
	/pgfplots/ytick align/center/.code	={\def\pgfplots@ytickalignnum{2}},
	/pgfplots/ytick align/center/.belongs to family=/pgfplots/tick,
	/pgfplots/ytick align=inside,
	/pgfplots/ztick align/.is choice,
	/pgfplots/ztick align/.belongs to family=/pgfplots/tick,
	/pgfplots/ztick align/inside/.code	={\def\pgfplots@ztickalignnum{0}},
	/pgfplots/ztick align/inside/.belongs to family=/pgfplots/tick,
	/pgfplots/ztick align/outside/.code	={\def\pgfplots@ztickalignnum{1}},
	/pgfplots/ztick align/outside/.belongs to family=/pgfplots/tick,
	/pgfplots/ztick align/center/.code	={\def\pgfplots@ztickalignnum{2}},
	/pgfplots/ztick align/center/.belongs to family=/pgfplots/tick,
	/pgfplots/ztick align=inside,
	/pgfplots/tick align/.belongs to family=/pgfplots/tick,
	/pgfplots/tick align/.style={%
		/pgfplots/xtick align=#1,
		/pgfplots/ytick align=#1,
		/pgfplots/ztick align=#1,
	},%
% 'axis' options:
	/pgfplots/anchor/.belongs to family=/pgfplots,
	/pgfplots/anchor/.store in=			\pgfplots@anchorname,
	/pgfplots/anchor=south west,
	%
	% will be evaluated for *every* 'near ticklabel' anchor:
	/pgfplots/near ticklabel align/.is choice,
	/pgfplots/near ticklabel align/inside/.code= \def\pgfplots@borderanchor@align{0},
	/pgfplots/near ticklabel align/center/.code= \def\pgfplots@borderanchor@align{1},
	/pgfplots/near ticklabel align/outside/.code=\def\pgfplots@borderanchor@align{2},
	/pgfplots/near ticklabel align/center,
	/pgfplots/cell picture/.is choice,
	/pgfplots/cell picture/false/.code=\def\pgfplots@cell@picture@mode{0},
	/pgfplots/cell picture/true/.code=\def\pgfplots@cell@picture@mode{1},
	/pgfplots/cell picture/if necessary/.code=\def\pgfplots@cell@picture@mode{2},
	/pgfplots/cell picture/true, % backwards compatibility
	/pgfplots/log origin x/.is choice,
	/pgfplots/log origin x/infty/.code={\def\pgfplots@log@origin@choice@x{0}},
	/pgfplots/log origin x/0/.code={\def\pgfplots@log@origin@choice@x{1}},
	/pgfplots/log origin y/.is choice,
	/pgfplots/log origin y/infty/.code={\def\pgfplots@log@origin@choice@y{0}},
	/pgfplots/log origin y/0/.code={\def\pgfplots@log@origin@choice@y{1}},
	/pgfplots/log origin z/.is choice,
	/pgfplots/log origin z/infty/.code={\def\pgfplots@log@origin@choice@z{0}},
	/pgfplots/log origin z/0/.code={\def\pgfplots@log@origin@choice@z{1}},
	/pgfplots/log origin/.style={%
		/pgfplots/log origin x={#1},
		/pgfplots/log origin y={#1},
		/pgfplots/log origin z={#1},
	},
	/pgfplots/log origin=0,
% tick options:
	/pgfplots/ticks/.is choice,
	/pgfplots/ticks/.belongs to family=/pgfplots/tick,
	/pgfplots/ticks/none/.belongs to family=/pgfplots/tick,
	/pgfplots/ticks/none/.code={%
		\pgfplots@xminorticksfalse
		\pgfplots@yminorticksfalse
		\pgfplots@zminorticksfalse
		\pgfplots@xmajorticksfalse
		\pgfplots@ymajorticksfalse
		\pgfplots@zmajorticksfalse
	},
	/pgfplots/ticks/major/.belongs to family=/pgfplots/tick,
	/pgfplots/ticks/major/.code={%
		\pgfplots@xminorticksfalse
		\pgfplots@yminorticksfalse
		\pgfplots@zminorticksfalse
		\pgfplots@xmajortickstrue
		\pgfplots@ymajortickstrue
		\pgfplots@zmajortickstrue
	},
	/pgfplots/ticks/minor/.belongs to family=/pgfplots/tick,
	/pgfplots/ticks/minor/.code={%
		\pgfplots@xminortickstrue
		\pgfplots@yminortickstrue
		\pgfplots@zminortickstrue
		\pgfplots@xmajorticksfalse
		\pgfplots@ymajorticksfalse
		\pgfplots@zmajorticksfalse
	},
	/pgfplots/ticks/both/.belongs to family=/pgfplots/tick,
	/pgfplots/ticks/both/.code={%
		\pgfplots@xminortickstrue
		\pgfplots@yminortickstrue
		\pgfplots@zminortickstrue
		\pgfplots@xmajortickstrue
		\pgfplots@ymajortickstrue
		\pgfplots@zmajortickstrue
	},
	/pgfplots/ticks=both,
	/pgfplots/grid/.is choice,
	/pgfplots/grid/.belongs to family=/pgfplots/tick,
	/pgfplots/grid/none/.belongs to family=/pgfplots/tick,
	/pgfplots/grid/none/.code={%
		\pgfplots@xminorgridsfalse
		\pgfplots@yminorgridsfalse
		\pgfplots@zminorgridsfalse
		\pgfplots@xmajorgridsfalse
		\pgfplots@ymajorgridsfalse
		\pgfplots@zmajorgridsfalse
	},
	/pgfplots/grid/major/.belongs to family=/pgfplots/tick,
	/pgfplots/grid/major/.code={%
		\pgfplots@xminorgridsfalse
		\pgfplots@yminorgridsfalse
		\pgfplots@zminorgridsfalse
		\pgfplots@xmajorgridstrue
		\pgfplots@ymajorgridstrue
		\pgfplots@zmajorgridstrue
	},
	/pgfplots/grid/minor/.belongs to family=/pgfplots/tick,
	/pgfplots/grid/minor/.code={%
		\pgfplots@xminorgridstrue
		\pgfplots@yminorgridstrue
		\pgfplots@zminorgridstrue
		\pgfplots@xmajorgridsfalse
		\pgfplots@ymajorgridsfalse
		\pgfplots@zmajorgridsfalse
	},
	/pgfplots/grid/both/.belongs to family=/pgfplots/tick,
	/pgfplots/grid/both/.code={%
		\pgfplots@xminorgridstrue
		\pgfplots@yminorgridstrue
		\pgfplots@zminorgridstrue
		\pgfplots@xmajorgridstrue
		\pgfplots@ymajorgridstrue
		\pgfplots@zmajorgridstrue
	},
	/pgfplots/grid=none,
	/pgfplots/grid/.default=major,
	/pgfplots/xminorticks/.is if=pgfplots@xminorticks,
	/pgfplots/xminorticks/.default=true,
	/pgfplots/xminorticks/.belongs to family=/pgfplots/tick,
	/pgfplots/xmajorticks/.is if=pgfplots@xmajorticks,
	/pgfplots/xmajorticks/.default=true,
	/pgfplots/xmajorticks/.belongs to family=/pgfplots/tick,
	/pgfplots/yminorticks/.is if=pgfplots@yminorticks,
	/pgfplots/yminorticks/.default=true,
	/pgfplots/yminorticks/.belongs to family=/pgfplots/tick,
	/pgfplots/ymajorticks/.is if=pgfplots@ymajorticks,
	/pgfplots/ymajorticks/.default=true,
	/pgfplots/ymajorticks/.belongs to family=/pgfplots/tick,
	/pgfplots/zminorticks/.is if=pgfplots@zminorticks,
	/pgfplots/zminorticks/.default=true,
	/pgfplots/zminorticks/.belongs to family=/pgfplots/tick,
	/pgfplots/zmajorticks/.is if=pgfplots@zmajorticks,
	/pgfplots/zmajorticks/.default=true,
	/pgfplots/zmajorticks/.belongs to family=/pgfplots/tick,
	/pgfplots/xminorgrids/.is if=pgfplots@xminorgrids,
	/pgfplots/xminorgrids/.default=true,
	/pgfplots/xminorgrids/.belongs to family=/pgfplots/tick,
	/pgfplots/xmajorgrids/.is if=pgfplots@xmajorgrids,
	/pgfplots/xmajorgrids/.default=true,
	/pgfplots/xmajorgrids/.belongs to family=/pgfplots/tick,
	/pgfplots/yminorgrids/.is if=pgfplots@yminorgrids,
	/pgfplots/yminorgrids/.default=true,
	/pgfplots/yminorgrids/.belongs to family=/pgfplots/tick,
	/pgfplots/ymajorgrids/.is if=pgfplots@ymajorgrids,
	/pgfplots/ymajorgrids/.default=true,
	/pgfplots/ymajorgrids/.belongs to family=/pgfplots/tick,
	/pgfplots/zminorgrids/.is if=pgfplots@zminorgrids,
	/pgfplots/zminorgrids/.default=true,
	/pgfplots/zminorgrids/.belongs to family=/pgfplots/tick,
	/pgfplots/zmajorgrids/.is if=pgfplots@zmajorgrids,
	/pgfplots/zmajorgrids/.default=true,
	/pgfplots/zmajorgrids/.belongs to family=/pgfplots/tick,
% legend options:
	/pgfplots/legend entries/.initial={},
	/pgfplots/legend entries/.belongs to family=/pgfplots/legend,
	/pgfplots/legend to label/.style={/pgfplots/legend to name={#1}},
	/pgfplots/legend to name/.initial=,%
	/pgfplots/legend pos/.is choice,
	/pgfplots/legend pos/south west/.style={/pgfplots/legend style={at={(0.03,0.03)},anchor=south west}},
	/pgfplots/legend pos/south east/.style={/pgfplots/legend style={at={(0.97,0.03)},anchor=south east}},
	/pgfplots/legend pos/north west/.style={/pgfplots/legend style={at={(0.03,0.97)},anchor=north west}},
	/pgfplots/legend pos/north east/.style={/pgfplots/legend style={at={(0.97,0.97)},anchor=north east}},
	/pgfplots/legend pos/outer north east/.style={/pgfplots/legend style={at={(1.03,1)},anchor=north west}},
	/pgfplots/legend cell align/.is choice,
	/pgfplots/legend cell align/left/.style=	{/pgfplots/legend style={cells={anchor=west}}},
	/pgfplots/legend cell align/right/.style=	{/pgfplots/legend style={cells={anchor=east}}},
	/pgfplots/legend cell align/center/.style=	{/pgfplots/legend style={cells={anchor=center}}},
	/pgfplots/legend columns/.store in=\pgfplots@legend@columns,
	/pgfplots/legend columns/.belongs to family=/pgfplots/legend,
	/pgfplots/legend columns=1,
	/pgfplots/legend plot pos/.is choice,
	/pgfplots/legend plot pos/.belongs to family=/pgfplots/legend,
	/pgfplots/legend plot pos/left/.code=	{\def\pgfplots@legend@plot@pos{0}},
	/pgfplots/legend plot pos/left/.belongs to family=/pgfplots/legend,
	/pgfplots/legend plot pos/right/.code=	{\def\pgfplots@legend@plot@pos{1}},
	/pgfplots/legend plot pos/right/.belongs to family=/pgfplots/legend,
	/pgfplots/legend plot pos/none/.code=	{\def\pgfplots@legend@plot@pos{2}},
	/pgfplots/legend plot pos/none/.belongs to family=/pgfplots/legend,
	/pgfplots/legend plot pos=left,
	/pgfplots/every legend image post/.code={},%
	/pgfplots/legend image post style/.style={/pgfplots/every legend image post/.append style={#1}},
	/pgfplots/empty legend/.style={/pgfplots/legend image code/.code=},
	/pgfplots/line legend/.style={%
		/pgfplots/legend image code/.code={%
			\draw[mark repeat=2,mark phase=2,##1] 
				plot coordinates {
					(0cm,0cm) 
					(0.3cm,0cm)
					(0.6cm,0cm)%
				};%
		}%
	},	
	/pgfplots/line legend/.style/.code={\pgfplots@error{This style is supposed to be constant.}},%
	/pgfplots/line legend/.append style/.code={\pgfplots@error{This style is supposed to be constant.}},%
	/pgfplots/line legend,
	/pgfplots/legend image code/.belongs to family=/pgfplots/legend,
	/pgfplots/reverse legend/.is if=pgfplots@reverse@legend,
	/pgfplots/reverse legend/.default=true,
	/pgfplots/transpose legend/.is if=pgfplots@transpose@legend,
	/pgfplots/transpose legend/.default=true,
	/pgfplots/legend transposed/.style={transpose legend=#1},
	/pgfplots/legend reversed/.style={reverse legend=#1},
% axis description options:
	/pgfplots/title/.initial=,
	/pgfplots/xlabel/.initial=,
	/pgfplots/ylabel/.initial=,
	/pgfplots/zlabel/.initial=,
	/pgfplots/xlabel shift/.initial=0pt,
	/pgfplots/ylabel shift/.initial=0pt,
	/pgfplots/zlabel shift/.initial=0pt,
	/pgfplots/label shift/.style={%
		/pgfplots/xlabel shift={#1},
		/pgfplots/ylabel shift={#1},
		/pgfplots/zlabel shift={#1},
	},%
	/pgfplots/extra description/.code=,
% axis options:
	/pgfplots/at/.code={%
		\pgfplots@assert@tikzinternal@exists{tikz@scan@one@point}%
		\tikz@scan@one@point\pgfplots@set@at#1},
	/pgfplots/at/.belongs to family=/pgfplots,
	/pgfplots/trim axis left/.code={%
		\pgfutil@ifundefined{pgfsettrimleft}{%
			\pgfplots@error{Sorry, the 'trim axis left' requires a more recent PGF version.}%
		}{%
			\pgfkeysalso{/tikz/trim left=(current axis.south west)}%
		}%
	},%
	/tikz/trim axis left/.style={/pgfplots/trim axis left},
	/pgfplots/trim axis right/.code={%
		\pgfutil@ifundefined{pgfsettrimleft}{%
			\pgfplots@error{Sorry, the 'trim axis right' requires a more recent PGF version.}%
		}{%
			\pgfkeysalso{/tikz/trim right=(current axis.south east)}%
		}%
	},%
	/tikz/trim axis right/.style={/pgfplots/trim axis right},
	/pgfplots/clip limits/.is if=pgfplots@clip@limits,
	/pgfplots/clip limits/.default=true,
	/pgfplots/clip limits=true,
	/pgfplots/clip limits/.belongs to family=/pgfplots,
	/pgfplots/clip/.is if=pgfplots@clip,
	/pgfplots/clip/.default=true,
	/pgfplots/clip=true,
	/pgfplots/clip mode/.is choice,
	/pgfplots/clip mode/global/.code=		\def\pgfplots@clipmode{1},
	% this choice is implemented partially only (only for plots, not for
	% graphical elements):
	/pgfplots/clip mode/individual/.code=	\def\pgfplots@clipmode{2},
	/pgfplots/clip mode=global,
	/pgfplots/clip bounding box/.is choice,
	/pgfplots/clip bounding box/default tikz/.code=\def\pgfplots@clip@BB@mode{0},
	/pgfplots/clip bounding box/upper bound/.code=\def\pgfplots@clip@BB@mode{1},
	/pgfplots/clip bounding box=default tikz, % the compat stuff. this is for backw. compat.
	% will be used if it exists:
	/pgfplots/axis background/.style={},
	/pgfplots/axis background style/.style={/pgfplots/axis background/.append style={#1}},
	%
	% the 'axis background@' style is an optimization: it will only be
	% used if 'axis background' is non-empty.
	% The motivation is that once 'axis background' is non-empty, a
	% background path will be generated whereas the 'axis background@'
	% style can be changed at will.
	/pgfplots/axis background@/.style={},
	/pgfplots/axis background@ style/.style={/pgfplots/axis background@/.append style={#1}},
	%
	% 2d: 'unit vector ratio=2 1   is relative to y axis (x is twice as large as y)
	% 3d: 'unit vector ratio=2 2 1 is relative to z axis (x and y are both twice as large as z)
	% missing values are assumed to be 1.
	/pgfplots/unit vector ratio/.initial=,% empty means 'disable rescale'.
	/pgfplots/unit vector ratio axis/.initial=,% DEBUG. This is the reference axis which won't be scaled down. This key might vanish.
	/pgfplots/unit vector ratio*/.style={%
		/pgfplots/unit vector ratio={#1},
		/pgfplots/unit rescale keep size=false,
	},
	/pgfplots/unit rescale keep size/.is choice,
	/pgfplots/unit rescale keep size/true/.code={\def\pgfplots@unit@vector@rescale@keep@size{1}},
	/pgfplots/unit rescale keep size/false/.code={\def\pgfplots@unit@vector@rescale@keep@size{0}},
	/pgfplots/unit rescale keep size/unless limits declared/.code={\def\pgfplots@unit@vector@rescale@keep@size{2}},
	/pgfplots/unit rescale keep size/.default=true,
	/pgfplots/unit rescale keep size=unless limits declared,
	/pgfplots/axis equal/.is choice,
	/pgfplots/axis equal/true/.style={
		/pgfplots/unit vector ratio=1 1 1,
		/pgfplots/unit rescale keep size=true
	},
	/pgfplots/axis equal/false/.style={
		/pgfplots/unit vector ratio=,
	},
	/pgfplots/axis equal/.default=true,
	/pgfplots/axis equal image/.is choice,
	/pgfplots/axis equal image/true/.style={%
		/pgfplots/unit vector ratio=1 1 1,
		/pgfplots/unit rescale keep size=false
	},
	/pgfplots/axis equal image/false/.style={%
		/pgfplots/unit vector ratio=,
	},
	/pgfplots/axis equal image/.default=true,
	/pgfplots/xmin/.initial=,
	/pgfplots/xmax/.initial=,
	/pgfplots/ymin/.initial=,
	/pgfplots/ymax/.initial=,
	/pgfplots/zmin/.initial=,
	/pgfplots/zmax/.initial=,
	/pgfplots/min/.style={xmin={#1},ymin={#1},zmin={#1}},
	/pgfplots/max/.style={xmax={#1},ymax={#1},zmax={#1}},
	/pgfplots/xtickmin/.initial=,
	/pgfplots/xtickmax/.initial=,
	/pgfplots/ytickmin/.initial=,
	/pgfplots/ytickmax/.initial=,
	/pgfplots/ztickmin/.initial=,
	/pgfplots/ztickmax/.initial=,
	/pgfplots/stack plots/.is choice,
	/pgfplots/stack plots/.belongs to family=/pgfplots,
	/pgfplots/stack plots/x/.code={\def\pgfplots@stacked@dir{x}\pgfplots@stackedmodetrue},
	/pgfplots/stack plots/x/.belongs to family=/pgfplots,
	/pgfplots/stack plots/y/.code={\def\pgfplots@stacked@dir{y}\pgfplots@stackedmodetrue},
	/pgfplots/stack plots/y/.belongs to family=/pgfplots,
	/pgfplots/stack plots/z/.code={\def\pgfplots@stacked@dir{z}\pgfplots@stackedmodetrue},
	/pgfplots/stack plots/z/.belongs to family=/pgfplots,
	/pgfplots/stack plots/false/.code={\pgfplots@stackedmodefalse},
	/pgfplots/stack plots/false/.belongs to family=/pgfplots,
	/pgfplots/stack plots=false,
	/pgfplots/reverse stacked plots/.is if=pgfplots@stacked@reverse,
	/pgfplots/reverse stacked plots/.belongs to family=/pgfplots,
	/pgfplots/reverse stacked plots/.default=true,
	/pgfplots/reverse stacked plots=true,
	/pgfplots/stack dir/.is choice,
	/pgfplots/stack dir/.belongs to family=/pgfplots,
	/pgfplots/stack dir/plus/.code={\pgfplots@stacked@plustrue},
	/pgfplots/stack dir/plus/.belongs to family=/pgfplots,
	/pgfplots/stack dir/minus/.code={\pgfplots@stacked@plusfalse},
	/pgfplots/stack dir/minus/.belongs to family=/pgfplots,
	/pgfplots/stack dir=plus,
	/pgfplots/stacked ignores zero/.is if=pgfplots@stacked@ignores@zero,
	/pgfplots/stacked ignores zero/.default=true,
	%
	% The purpose of the following key is to control the case 'stacked ignores zero=true'
	% (it has no effect if 'stacked ignores zero=false').
	% The feature "stacked ignores zero" is active *if and only if*
	% 1. stacked ignores zero=true and
	% 2. stacked ignores zero/<phasename>=true
	% Valid <phasename>s are 'default', 'markers', 'errorbars'.
	/pgfplots/stacked ignores zero/\pgfplotsaxis@visphase@name@default/.initial=true,
	/pgfplots/stacked ignores zero/\pgfplotsaxis@visphase@name@markers/.initial=true,
	/pgfplots/stacked ignores zero/\pgfplotsaxis@visphase@name@errorbars/.initial=false,
	/pgfplots/filter discard warning/.is if=pgfplots@warn@for@filter@discards,
	/pgfplots/filter discard warning=true,
	/pgfplots/pre filter/.code={},
	/pgfplots/x filter/.code={},
	/pgfplots/x filter/.belongs to family=/pgfplots,
	/pgfplots/y filter/.code={},
	/pgfplots/y filter/.belongs to family=/pgfplots,
	/pgfplots/z filter/.code={},
	/pgfplots/z filter/.belongs to family=/pgfplots,
	/pgfplots/filter point/.code=,
	/pgfplots/restrict x to domain/.style={/pgfplots/@restrict to domain={x}{}{#1}{0}},%
	/pgfplots/restrict y to domain/.style={/pgfplots/@restrict to domain={y}{}{#1}{0}},%
	/pgfplots/restrict z to domain/.style={/pgfplots/@restrict to domain={z}{}{#1}{0}},%
	/pgfplots/restrict expr to domain/.style 2 args={/pgfplots/@restrict to domain={x}{#1}{#2}{0}},%
	/pgfplots/restrict x to domain*/.style={/pgfplots/@restrict to domain={x}{}{#1}{1}},%
	/pgfplots/restrict y to domain*/.style={/pgfplots/@restrict to domain={y}{}{#1}{1}},%
	/pgfplots/restrict z to domain*/.style={/pgfplots/@restrict to domain={z}{}{#1}{1}},%
	/pgfplots/restrict expr to domain*/.style 2 args={/pgfplots/@restrict to domain={x}{#1}{#2}{1}},%
	% '#1': the filter to install (like 'x', 'y', or even 'hist/data')
	% '#2': a mathematical expression (or empty)
	% '#3': the interval. must be numeric currently, and of the form min:max
	% '#4': bAssignLimits=0|1. if #4=1, any coordinate outside of the
	% allowed domain will take the domain boundary as value. If #4=0,
	% any coordinate outside of the allowed domain will get 'inf' or
	% '-inf'.
	/pgfplots/@restrict to domain/.code args={#1#2#3#4}{%
		\if0#4%
			\pgfkeysalso{/pgfplots/unbounded coords=jump}%
		\fi
		% when invoked, ##1 and ##2 will be floats:
		\def\pgfplots@loc@TMPb##1:##2\relax{%
			\pgfkeysalso{%
				/pgfplots/#1 filter/.append code={%
					\pgfplots@warn@if@log@basis@unset{#1}{domain restriction}%
					\let\pgfplots@restrict@to@domain@orig=\pgfmathresult
					\ifx\pgfmathresult\pgfutil@empty
						% the input value is empty... skip it!
					\else
						\def\pgfplots@restrict@to@domain@tmp{#2}%
						\ifx\pgfplots@restrict@to@domain@tmp\pgfutil@empty
							% we don't have an expression.
						\else
							% evaluate the expression!
							\pgfmathparse{#2}%
						\fi
						\pgfplotscoordmath{default}{parsenumber}{\pgfmathresult}%
						\let\pgfplots@restrict@to@domain@tmp=\pgfmathresult
						%
						\pgfplotscoordmath{default}{if less than}
							{\pgfplots@restrict@to@domain@tmp}{##1}% ##1 is the lower argument
							{%
								\edef\pgfmathresult{\if0#4inf\else ##1\fi}%
							}{%
								\pgfplotscoordmath{default}{if less than}
									{##2}{\pgfplots@restrict@to@domain@tmp}
									{\edef\pgfmathresult{\if0#4-inf\else ##2\fi}}
									{\let\pgfmathresult=\pgfplots@restrict@to@domain@orig}%
							}%
					\fi
				}%
			}%
		}%
		% when invoked, ##1 and ##2 will be the user-supplied args.
		\def\pgfplots@loc@TMPc##1:##2\relax{%
			\pgfplotscoordmath{default}{parsenumber}{##1}%
			\let\pgfplots@rangea=\pgfmathresult
			\pgfplotscoordmath{default}{parsenumber}{##2}%
			\edef\pgfplots@loc@TMPc{\pgfplots@rangea:\pgfmathresult}%
			\expandafter\pgfplots@loc@TMPb\pgfplots@loc@TMPc\relax
		}%
		\edef\pgfplots@loc@TMPa{#3}%
		\expandafter\pgfplots@loc@TMPc\pgfplots@loc@TMPa\relax
	},%
	% -> keeps only the nth point, all other ones will get ''. 
	/pgfplots/each nth point/.style={/pgfplots/each nth point*={x}{#1}},%
	% #1: the filter name: x, y, z, or something exotic like hist/data
	% #2: the N of 'each nth'
	/pgfplots/each nth point*/.style 2 args={%
		/pgfplots/#1 filter/.append code={%
			\ifnum\coordindex=0
				\def\c@pgfplots@eachnthpoint@xfilter{0}%
				\edef\c@pgfplots@eachnthpoint@xfilter@cmp{#2}%
			\else
				\pgfplotsutil@advancestringcounter\c@pgfplots@eachnthpoint@xfilter
				\ifx\c@pgfplots@eachnthpoint@xfilter@cmp\c@pgfplots@eachnthpoint@xfilter
					\def\c@pgfplots@eachnthpoint@xfilter{0}%
				\else
					\let\pgfmathresult\pgfutil@empty
				\fi
			\fi
		}%
	},
	/pgfplots/skip coords between index/.style 2 args={/pgfplots/skip coords between index*={x}{#1}{#2}},%
	% #1: the filter name
	% #2,#3: from 'skip coords between index'
	/pgfplots/skip coords between index*/.style n args={3}{%
		/pgfplots/#1 filter/.append code={%
			\ifnum\coordindex<#2\relax
			\else
				\ifnum\coordindex<#3\relax
					\let\pgfmathresult=\pgfutil@empty
				\fi
			\fi}
	},
	/pgfplots/translate gnuplot/.is if=pgfplots@translategnuplot,
	/pgfplots/gnuplot writes logscale/.is choice,
	/pgfplots/gnuplot writes logscale/true/.code={\gdef\pgfplots@gnuplot@logscale@writes@log{1}},%
	/pgfplots/gnuplot writes logscale/false/.code={\gdef\pgfplots@gnuplot@logscale@writes@log{0}},%
	/pgfplots/parametric/var 2d/.initial={\u,\v},
	/pgfplots/parametric/var 1d/.initial=\t,
	/pgfplots/xfilter/.initial=,% DEPRECATED
	/pgfplots/yfilter/.initial=,% DEPRECATED
	/pgfplots/zfilter/.initial=,% DEPRECATED
	% interpretation: 
	% if 'samples at'==empty && 'domain' == empty 
	% 	use tikz option	processing!
	% else if 'samples at' == empty
	% 	use 'domain'
	% else
	% 	use 'samples at'
	/pgfplots/domain/.initial=,% empty -> use value of /tikz/domain! see \pgfplots@validate@plot@domain@arguments
	/pgfplots/y domain/.initial=,% means: use the same as 'domain'
	/pgfplots/domain y/.style={/pgfplots/y domain={#1}},
	/pgfplots/samples at/.initial=,% empty -> use value of /tikz/samples at!
	/pgfplots/samples/.initial=,% empty -> use /tikz/samples!
	/pgfplots/samples y/.initial=,% empty -> use the same as 'samples'. For use in mesh plots.
	/pgfplots/variable/.code={\pgfkeysalso{/tikz/variable={#1}}},
	/pgfplots/variable y/.initial=\y,%
	/pgfplots/sample dim/.initial=auto,
	% and provide aliases in the '/pgfplots/' tree to avoid 
	% search path problems just for the following options:
	/pgfplots/name/.code={\pgfkeysalso{/tikz/name={#1}}},
	/pgfplots/overlay/.code={\pgfkeysalso{/tikz/overlay={#1}}},
	/pgfplots/alias/.code={\pgfkeysalso{/tikz/alias={#1}}},
	/pgfplots/id/.code={\pgfkeysalso{/tikz/id={#1}}},
	/pgfplots/prefix/.code={\pgfkeysalso{/tikz/prefix={#1}}},
	/pgfplots/raw gnuplot/.code={\pgfkeysalso{/tikz/raw gnuplot={#1}}},
	/pgfplots/parametric/.code={\pgfkeysalso{/tikz/parametric={#1}}},%
	% 
	/pgfplots/width/.initial=,%
	/pgfplots/width/.belongs to family=/pgfplots,
	/pgfplots/height/.initial=,%
	/pgfplots/height/.belongs to family=/pgfplots,
	/pgfplots/execute at begin plot/.initial=,
	/pgfplots/execute at begin plot visualization/.initial=,
	/pgfplots/execute at begin plot@@/.initial=,% an internal variant
	/pgfplots/execute at end plot/.initial=,
	/pgfplots/execute at end plot visualization/.initial=,
	/pgfplots/execute at end plot@@/.initial=,% an internal variant
	/pgfplots/execute at end survey/.initial=,%
	/pgfplots/execute at begin axis/.initial=,
	/pgfplots/execute at begin axis@@/.initial=,% an internal variant
	/pgfplots/execute at end axis/.initial=,
	/pgfplots/execute at end axis@@/.initial=,% an internal variant
	/pgfplots/execute for finished point/.initial=,
	/pgfplots/before end axis/.code=,
	/pgfplots/after end axis/.code=,
	/pgfplots/enlarge x limits/.initial=auto,
	/pgfplots/enlarge x limits/.default=true,
	/pgfplots/enlarge y limits/.initial=auto,
	/pgfplots/enlarge y limits/.default=true,
	/pgfplots/enlarge z limits/.initial=auto,
	/pgfplots/enlarge z limits/.default=true,
	/pgfplots/enlargelimits/.style={%
		/pgfplots/enlarge x limits={#1},%
		/pgfplots/enlarge y limits={#1},%
		/pgfplots/enlarge z limits={#1},%
	},%
	/pgfplots/enlargelimits/.default=true,
	/pgfplots/enlargelimits respects figure size/.is if=pgfplots@enlargelimits@respect@figure@size,
	/pgfplots/update limits/.is if=pgfplots@bb@isactive,
	/pgfplots/x/.initial=,% is implicitly set by 'width' and/or '\axisdefaultwidth'
	/pgfplots/x/.belongs to family=/pgfplots,
	/pgfplots/y/.initial=,% is implicitly set by 'width' and/or '\axisdefaultwidth'
	/pgfplots/y/.belongs to family=/pgfplots,
	/pgfplots/z/.initial=,
	/pgfplots/z/.belongs to family=/pgfplots,
	/pgfplots/view dir/.initial=,% DEBUG
	/pgfplots/x dir/.code={\pgfplots@setkey@axisdir@for x{#1}},%
	/pgfplots/y dir/.code={\pgfplots@setkey@axisdir@for y{#1}},%
	/pgfplots/z dir/.code={\pgfplots@setkey@axisdir@for z{#1}},%
	/pgfplots/x dir=normal,%
	/pgfplots/y dir=normal,%
	/pgfplots/z dir=normal,%
	/pgfplots/x post scale/.initial=,
	/pgfplots/y post scale/.initial=,
	/pgfplots/z post scale/.initial=,
	/pgfplots/scale/.style={%
		/pgfplots/x post scale={#1},%
		/pgfplots/y post scale={#1},%
		/pgfplots/z post scale={#1},%
  	},
	/pgfplots/scale mode/.is choice,
	/pgfplots/scale mode/auto/.code={\def\pgfplots@scale@mode@choice{0}},
	/pgfplots/scale mode/none/.code={\def\pgfplots@scale@mode@choice{1}},
	/pgfplots/scale mode/stretch to fill/.code={\def\pgfplots@scale@mode@choice{2}},
	/pgfplots/scale mode/scale uniformly/.code={\def\pgfplots@scale@mode@choice{3}},
	/pgfplots/scale mode/auto,
	/pgfplots/scale uniformly strategy/.is choice,
	% chooses one of the other choices depending on the target
	% width/height:
	/pgfplots/scale uniformly strategy/auto/.code=						{\def\pgfplots@scaleuniformly@choice{0}},
	% scales units only, but does not compensate limits:
	/pgfplots/scale uniformly strategy/units only/.code=					{\def\pgfplots@scaleuniformly@choice{1}},
	% changes only vertical limits, no horizontal limits:
	/pgfplots/scale uniformly strategy/change vertical limits/.code=	{\def\pgfplots@scaleuniformly@choice{2}},
	% changes X and Y limits, but not Z limits - adjusts scale accordingly:
	/pgfplots/scale uniformly strategy/change horizontal limits/.code=	{\def\pgfplots@scaleuniformly@choice{3}},
	/pgfplots/scale uniformly strategy/auto,
	/pgfplots/scale uniformly warning/.is if=pgfplots@scaleuniformly@warning,
	/pgfplots/scale uniformly warning=false,
	% number of iterations for the nonlinear method involved 
	/pgfplots/scale uniformly strategy iter/.initial=9,
	/pgfplots/allow reversal of rel axis cs/.is if=pgfplots@allow@reversal@of@rel@axis@cs,%
	/pgfplots/allow reversal of rel axis cs/.default=true,%
	/pgfplots/allow reversal of rel axis cs=true,%
	/pgfplots/plot box ratio/.initial=1 1 1,%
	/pgfplots/view/az/.initial=25,%
	/pgfplots/view/h/.code={\pgfkeyssetvalue{/pgfplots/view/az}{#1}},%
	/pgfplots/view/el/.initial=30,%
	/pgfplots/view/v/.code={\pgfkeyssetvalue{/pgfplots/view/el}{#1}},%
	/pgfplots/view/.style 2 args={%
		/pgfplots/view/az={#1},%
		/pgfplots/view/el={#2}%
	},%
	/pgfplots/cycle list/.code={%
		\pgfplots@assign@list\autoplotspeclist{#1}%
		\expandafter\let\csname pgfp@cyclist@auto@\endcsname=\autoplotspeclist
		\pgfkeyssetvalue{/pgfplots/cycle multi list/@dim}{0}% de-activate.
	},
	/pgfplots/cycle list/.belongs to family=/pgfplots,
	/pgfplots/cycle list name/.code={%
		\pgfplotsifcyclelistexists{#1}{%
			\expandafter\let\expandafter\autoplotspeclist\csname pgfp@cyclist@\string#1@\endcsname
			\expandafter\let\csname pgfp@cyclist@auto@\endcsname=\autoplotspeclist
			\pgfkeyssetvalue{/pgfplots/cycle multi list/@dim}{0}% de-activate.
		}{%
			\pgfplots@error{Sorry, there is no such cycle list named \string#1. Maybe you misspelled it?}%
		}%
	},
	/pgfplots/cycle list name/.belongs to family=/pgfplots,
	/pgfplots/cycle list name=color,
	/pgfplots/cycle list shift/.initial=,
	/pgfplots/mark list fill/.initial=.!80!black,
	% accepts arguments of the form
	% <first list spec>\nextlist <second list spec>\nextlist ....
	% where each list spec is EITHER a cycle list name OR a cycle list
	% argument.
	/pgfplots/cycle multi list/.code={\pgfplots@cycle@multi@list{#1}},
	% #1: list index
	% #2: maximum number of elements to use
	/pgfplots/cycle multi list/partial sublist/.code 2 args={%
		\ifnum#1<\pgfkeysvalueof{/pgfplots/cycle multi list/@dim}
			\ifnum#2<\pgfkeysvalueof{/pgfplots/cycle multi list/@totalN#1}
				\pgfkeyssetvalue{/pgfplots/cycle multi list/@N#1}{#2}%
			\fi
		\else
			\pgfplots@error{Sorry, the first argument of `cycle multi list/partial sublist=<list index><num elems>' is no valid list index (should be less than \pgfkeysvalueof{/pgfplots/cycle multi list/@dim}).}%
		\fi
	},%
	/pgfplots/cycle multi list/@dim/.initial=0,
	%/pgfplots/cycle multi list/@list0/.style={},
	%/pgfplots/cycle multi list/@N0/.initial=0,%
	%/pgfplots/cycle multi list/@totalN0/.initial=0,%
	/pgfplots/legend style/.belongs to family=/pgfplots/style commands,
	/pgfplots/legend style/.code={%
		\pgfkeysalso{/pgfplots/every axis legend/.append style={#1}}%
	},
	/pgfplots/every forget plot/.code={},%
	/pgfplots/forget plot style/.style={/pgfplots/every forget plot/.append style={#1}},
	/pgfplots/label style/.belongs to family=/pgfplots/style commands,
	/pgfplots/label style/.style={%
		/pgfplots/every axis x label/.append style={#1},%
		/pgfplots/every axis y label/.append style={#1},%
		/pgfplots/every axis z label/.append style={#1}%
	},%
	/pgfplots/x label style/.belongs to family=/pgfplots/style commands,
	/pgfplots/x label style/.code={%
		\pgfkeysalso{/pgfplots/every axis x label/.append style={#1}}%
	},
	/pgfplots/y label style/.belongs to family=/pgfplots/style commands,
	/pgfplots/y label style/.code={%
		\pgfkeysalso{/pgfplots/every axis y label/.append style={#1}}%
	},
	/pgfplots/z label style/.belongs to family=/pgfplots/style commands,
	/pgfplots/z label style/.code={%
		\pgfkeysalso{/pgfplots/every axis z label/.append style={#1}}%
	},
	/pgfplots/title style/.belongs to family=/pgfplots/style commands,
	/pgfplots/title style/.code={%
		\pgfkeysalso{/pgfplots/every axis title/.append style={#1}}%
	},
	/pgfplots/tick label style/.belongs to family=/pgfplots/style commands,
	/pgfplots/tick label style/.code={%
		\pgfkeysalso{/pgfplots/every tick label/.append style={#1}}%
	},
	/pgfplots/x tick label style/.belongs to family=/pgfplots/style commands,
	/pgfplots/x tick label style/.code={%
		\pgfkeysalso{/pgfplots/every x tick label/.append style={#1}}%
	},
	/pgfplots/y tick label style/.belongs to family=/pgfplots/style commands,
	/pgfplots/y tick label style/.code={%
		\pgfkeysalso{/pgfplots/every y tick label/.append style={#1}}%
	},
	/pgfplots/z tick label style/.belongs to family=/pgfplots/style commands,
	/pgfplots/z tick label style/.code={%
		\pgfkeysalso{/pgfplots/every z tick label/.append style={#1}}%
	},
	/pgfplots/x tick scale label style/.belongs to family=/pgfplots/style commands,
	/pgfplots/x tick scale label style/.code={%
		\pgfkeysalso{/pgfplots/every x tick scale label/.append style={#1}}%
	},
	/pgfplots/y tick scale label style/.belongs to family=/pgfplots/style commands,
	/pgfplots/y tick scale label style/.code={%
		\pgfkeysalso{/pgfplots/every y tick scale label/.append style={#1}}%
	},
	/pgfplots/z tick scale label style/.belongs to family=/pgfplots/style commands,
	/pgfplots/z tick scale label style/.code={%
		\pgfkeysalso{/pgfplots/every z tick scale label/.append style={#1}}%
	},
	/pgfplots/tick style/.belongs to family=/pgfplots/style commands,
	/pgfplots/tick style/.code={%
		\pgfkeysalso{/pgfplots/every tick/.append style={#1}}%
	},
	/pgfplots/minor tick style/.belongs to family=/pgfplots/style commands,
	/pgfplots/minor tick style/.code={%
		\pgfkeysalso{/pgfplots/every minor tick/.append style={#1}}%
	},
	/pgfplots/major tick style/.belongs to family=/pgfplots/style commands,
	/pgfplots/major tick style/.code={%
		\pgfkeysalso{/pgfplots/every major tick/.append style={#1}}%
	},
	/pgfplots/x tick style/.belongs to family=/pgfplots/style commands,
	/pgfplots/x tick style/.code={%
		\pgfkeysalso{/pgfplots/every x tick/.append style={#1}}%
	},
	/pgfplots/minor x tick style/.belongs to family=/pgfplots/style commands,
	/pgfplots/minor x tick style/.code={%
		\pgfkeysalso{/pgfplots/every minor x tick/.append style={#1}}%
	},
	/pgfplots/major x tick style/.belongs to family=/pgfplots/style commands,
	/pgfplots/major x tick style/.code={%
		\pgfkeysalso{/pgfplots/every major x tick/.append style={#1}}%
	},
	/pgfplots/y tick style/.belongs to family=/pgfplots/style commands,
	/pgfplots/y tick style/.code={%
		\pgfkeysalso{/pgfplots/every y tick/.append style={#1}}%
	},
	/pgfplots/minor y tick style/.belongs to family=/pgfplots/style commands,
	/pgfplots/minor y tick style/.code={%
		\pgfkeysalso{/pgfplots/every minor y tick/.append style={#1}}%
	},
	/pgfplots/major y tick style/.belongs to family=/pgfplots/style commands,
	/pgfplots/major y tick style/.code={%
		\pgfkeysalso{/pgfplots/every major y tick/.append style={#1}}%
	},
	/pgfplots/z tick style/.belongs to family=/pgfplots/style commands,
	/pgfplots/z tick style/.code={%
		\pgfkeysalso{/pgfplots/every z tick/.append style={#1}}%
	},
	/pgfplots/minor z tick style/.belongs to family=/pgfplots/style commands,
	/pgfplots/minor z tick style/.code={%
		\pgfkeysalso{/pgfplots/every minor z tick/.append style={#1}}%
	},
	/pgfplots/major z tick style/.belongs to family=/pgfplots/style commands,
	/pgfplots/major z tick style/.code={%
		\pgfkeysalso{/pgfplots/every major z tick/.append style={#1}}%
	},
	/pgfplots/grid style/.belongs to family=/pgfplots/style commands,
	/pgfplots/grid style/.code={%
		\pgfkeysalso{/pgfplots/every axis grid/.append style={#1}}%
	},
	/pgfplots/minor grid style/.belongs to family=/pgfplots/style commands,
	/pgfplots/minor grid style/.code={%
		\pgfkeysalso{/pgfplots/every minor grid/.append style={#1}}%
	},
	/pgfplots/major grid style/.belongs to family=/pgfplots/style commands,
	/pgfplots/major grid style/.code={%
		\pgfkeysalso{/pgfplots/every major grid/.append style={#1}}%
	},
	/pgfplots/x grid style/.belongs to family=/pgfplots/style commands,
	/pgfplots/x grid style/.code={%
		\pgfkeysalso{/pgfplots/every axis x grid/.append style={#1}}%
	},
	/pgfplots/minor x grid style/.belongs to family=/pgfplots/style commands,
	/pgfplots/minor x grid style/.code={%
		\pgfkeysalso{/pgfplots/every minor x grid/.append style={#1}}%
	},
	/pgfplots/major x grid style/.belongs to family=/pgfplots/style commands,
	/pgfplots/major x grid style/.code={%
		\pgfkeysalso{/pgfplots/every major x grid/.append style={#1}}%
	},
	/pgfplots/y grid style/.belongs to family=/pgfplots/style commands,
	/pgfplots/y grid style/.code={%
		\pgfkeysalso{/pgfplots/every axis y grid/.append style={#1}}%
	},
	/pgfplots/minor y grid style/.belongs to family=/pgfplots/style commands,
	/pgfplots/minor y grid style/.code={%
		\pgfkeysalso{/pgfplots/every minor y grid/.append style={#1}}%
	},
	/pgfplots/major y grid style/.belongs to family=/pgfplots/style commands,
	/pgfplots/major y grid style/.code={%
		\pgfkeysalso{/pgfplots/every major y grid/.append style={#1}}%
	},
	/pgfplots/z grid style/.belongs to family=/pgfplots/style commands,
	/pgfplots/z grid style/.code={%
		\pgfkeysalso{/pgfplots/every axis z grid/.append style={#1}}%
	},
	/pgfplots/minor z grid style/.belongs to family=/pgfplots/style commands,
	/pgfplots/minor z grid style/.code={%
		\pgfkeysalso{/pgfplots/every minor z grid/.append style={#1}}%
	},
	/pgfplots/major z grid style/.belongs to family=/pgfplots/style commands,
	/pgfplots/major z grid style/.code={%
		\pgfkeysalso{/pgfplots/every major z grid/.append style={#1}}%
	},
	/pgfplots/disablelogfilter x/.is if=pgfplots@disablelogfilter@x,
	/pgfplots/disablelogfilter x/.default=true,
	/pgfplots/disablelogfilter y/.is if=pgfplots@disablelogfilter@y,
	/pgfplots/disablelogfilter y/.default=true,
	/pgfplots/disablelogfilter z/.is if=pgfplots@disablelogfilter@z,
	/pgfplots/disablelogfilter z/.default=true,
	/pgfplots/disablelogfilter/.style={	
		/pgfplots/disablelogfilter x=#1,
		/pgfplots/disablelogfilter y=#1,
		/pgfplots/disablelogfilter z=#1,
	},
	/pgfplots/disabledatascaling/.is if=pgfplots@disabledatascaling,
	/pgfplots/disabledatascaling/.default=true,
	/pgfplots/disabledatascaling/.belongs to family=/pgfplots,
	/pgfplots/disabledatascaling=false,
	/pgfplots/hide x axis/.is if=pgfplots@hide@x,
	/pgfplots/hide x axis/.default=true,
	/pgfplots/hide x axis=false,
	/pgfplots/hide y axis/.is if=pgfplots@hide@y,
	/pgfplots/hide y axis/.default=true,
	/pgfplots/hide y axis=false,
	/pgfplots/hide z axis/.is if=pgfplots@hide@z,
	/pgfplots/hide z axis/.default=true,
	/pgfplots/hide z axis=false,
	/pgfplots/hide axis/.style={%
		/pgfplots/hide x axis=#1,
		/pgfplots/hide y axis=#1,
		/pgfplots/hide z axis=#1,
	},
	/pgfplots/hide axis/.default=true,
	/pgfplots/every non boxed x axis/.style={%
		xtick align=center,
		enlarge x limits=false,
		x axis line style={-stealth}
	},
	/pgfplots/every non boxed y axis/.style={%
		ytick align=center,
		enlarge y limits=false,
		y axis line style={-stealth}
	},
	/pgfplots/every non boxed z axis/.style={%
		ztick align=center,
		enlarge z limits=false,
		z axis line style={-stealth}
	},
	/pgfplots/every boxed x axis/.style={},
	/pgfplots/every boxed y axis/.style={},
	/pgfplots/every boxed z axis/.style={},
%	/pgfplots/hide axis/.belongs to family=/pgfplots,
% sets \pgfplots@xaxislinesnum to
% box=0
% bottom=1
% middle=2 ( aliased with center )
% top=3
	/pgfplots/axis x line*/.is choice,
	/pgfplots/axis x line*/box/.code	={\def\pgfplots@xaxislinesnum{0}\def\pgfplots@xtickposnum{0}},
	/pgfplots/axis x line*/bottom/.code	={\def\pgfplots@xaxislinesnum{1}\def\pgfplots@xtickposnum{1}\let\pgfplots@xticklabel@pos\pgfutil@empty},
	/pgfplots/axis x line*/left/.style={/pgfplots/axis x line*/bottom},
	/pgfplots/axis x line*/middle/.code	={\def\pgfplots@xaxislinesnum{2}\def\pgfplots@xtickposnum{2}\let\pgfplots@xticklabel@pos\pgfutil@empty},
	/pgfplots/axis x line*/center/.style	={/pgfplots/axis x line*/middle},
	/pgfplots/axis x line*/top/.code	={\def\pgfplots@xaxislinesnum{3}\def\pgfplots@xtickposnum{3}\let\pgfplots@xticklabel@pos\pgfutil@empty},
	/pgfplots/axis x line*/right/.style={/pgfplots/axis x line*/top},
	/pgfplots/axis x line*/none/.code	={\def\pgfplots@xaxislinesnum{4}\def\pgfplots@xtickposnum{4}\let\pgfplots@xticklabel@pos\pgfutil@empty},
	/pgfplots/axis x line*=box,
	%
% sets \pgfplots@yaxislinesnum to
% box=0
% left=1
% center=2 ( aliased with middle )
% right=3
	/pgfplots/axis y line*/.is choice,
	/pgfplots/axis y line*/box/.code	={\def\pgfplots@yaxislinesnum{0}\def\pgfplots@ytickposnum{0}},
	/pgfplots/axis y line*/left/.code	={\def\pgfplots@yaxislinesnum{1}\def\pgfplots@ytickposnum{1}\let\pgfplots@yticklabel@pos\pgfutil@empty},
	/pgfplots/axis y line*/center/.code	={\def\pgfplots@yaxislinesnum{2}\def\pgfplots@ytickposnum{2}\let\pgfplots@yticklabel@pos\pgfutil@empty},
	/pgfplots/axis y line*/middle/.style	={/pgfplots/axis y line*/center},
	/pgfplots/axis y line*/right/.code	={\def\pgfplots@yaxislinesnum{3}\def\pgfplots@ytickposnum{3}\let\pgfplots@yticklabel@pos\pgfutil@empty},
	/pgfplots/axis y line*/none/.code	={\def\pgfplots@yaxislinesnum{4}\def\pgfplots@ytickposnum{4}\let\pgfplots@yticklabel@pos\pgfutil@empty},
	/pgfplots/axis y line*=box,
	%
%
% sets \pgfplots@zaxislinesnum to
% box=0
% left=1
% center=2 ( aliased with middle )
% right=3
	/pgfplots/axis z line*/.is choice,
	/pgfplots/axis z line*/box/.code	={\def\pgfplots@zaxislinesnum{0}\def\pgfplots@ztickposnum{0}},
	/pgfplots/axis z line*/left/.code	={\def\pgfplots@zaxislinesnum{1}\def\pgfplots@ztickposnum{1}\let\pgfplots@zticklabel@pos\pgfutil@empty},
	/pgfplots/axis z line*/center/.code	={\def\pgfplots@zaxislinesnum{2}\def\pgfplots@ztickposnum{2}\let\pgfplots@zticklabel@pos\pgfutil@empty},
	/pgfplots/axis z line*/middle/.style	={/pgfplots/axis z line*/center},
	/pgfplots/axis z line*/right/.code	={\def\pgfplots@zaxislinesnum{3}\def\pgfplots@ztickposnum{3}\let\pgfplots@zticklabel@pos\pgfutil@empty},
	/pgfplots/axis z line*/none/.code	={\def\pgfplots@zaxislinesnum{4}\def\pgfplots@ztickposnum{4}\let\pgfplots@zticklabel@pos\pgfutil@empty},
	/pgfplots/axis z line*=box,
	%
	/pgfplots/axis x line/.is choice,
	/pgfplots/axis y line/.is choice,
	/pgfplots/axis z line/.is choice,
	/pgfplots/axis lines/.style={%
		axis x line=#1,%
		axis y line=#1,%
		axis z line=#1%
	},
	/pgfplots/axis lines*/.style={%
		axis x line*=#1,%
		axis y line*=#1,%
		axis z line*=#1%
	},
	/pgfplots/compat/axis line style pre 1.8/.style={%
		% ALL INSIDE OF THIS STYLE IS DEPRECATED.
		/pgfplots/axis x line/box/.style	={
			/pgfplots/axis x line*/box,
			/pgfplots/every boxed x axis
		},
		/pgfplots/axis x line/bottom/.style	={
			/pgfplots/axis x line*/bottom,
			/pgfplots/every non boxed x axis
		},
		/pgfplots/axis x line/left/.style={/pgfplots/axis x line/bottom},%
		/pgfplots/axis x line/middle/.code	={%
			\ifnum\pgfplots@yaxislinesnum=3 % if 'axis y line==right' then
				\pgfkeysalso{/pgfplots/every axis x label/.style={at={(current axis.left of origin)},anchor=south west}}%
			\else
				\pgfkeysalso{/pgfplots/every axis x label/.style={at={(current axis.right of origin)},anchor=south east}}%
			\fi
			\pgfkeysalso{/pgfplots/every axis x label/.append code={\pgfplots@label@upgrade@warning}}%
			\pgfkeysalso{/pgfplots/axis x line*/middle,
				/pgfplots/every non boxed x axis}%
		},
		/pgfplots/axis x line/center/.style	={/pgfplots/axis x line/middle},
		/pgfplots/axis x line/right/.style={/pgfplots/axis x line/top},%
		/pgfplots/axis x line/top/.code	={
			\ifnum\pgfplots@yaxislinesnum=2 % if 'axis y line==center' then
				\pgfkeysalso{
					/pgfplots/every axis y label/.style={at={(current axis.below origin)},anchor=south west}}%
			\fi
			\pgfkeysalso{%
				/pgfplots/axis x line*/top,
				/pgfplots/every axis x label/.style={at={(0.5,1)},anchor=south,yshift=15pt},
				/pgfplots/every non boxed x axis}%
		},
		/pgfplots/axis x line/none/.style	={axis x line*/none,hide x axis},
		%
		% Y :
		/pgfplots/axis y line/box/.style	={
			/pgfplots/axis y line*/box,
			/pgfplots/every boxed y axis
		},
		/pgfplots/axis y line/left/.style	={
			/pgfplots/axis y line*/left,
			/pgfplots/every non boxed y axis
		},
		/pgfplots/axis y line/center/.code	={
			\ifnum\pgfplots@xaxislinesnum=3 % if 'axis x line==top' then
				\pgfkeysalso{%
					/pgfplots/every axis y label/.style={at={(current axis.below origin)},anchor=south west}}%
			\else
				\pgfkeysalso{%
					/pgfplots/every axis y label/.style={at={(current axis.above origin)},anchor=north west}}%
			\fi
			\pgfkeysalso{/pgfplots/every axis y label/.append code={\pgfplots@label@upgrade@warning}}%
			\pgfkeysalso{%
				/pgfplots/axis y line*/center,
				/pgfplots/every non boxed y axis}%
		},
		/pgfplots/axis y line/middle/.style	={/pgfplots/axis y line/center},
		/pgfplots/axis y line/right/.code	={%
			\ifnum\pgfplots@xaxislinesnum=2
				\pgfkeysalso{every axis x label/.style={at={(current axis.left of origin)},anchor=south west}}%
			\fi
			\pgfkeysalso{
				axis y line*/right,
				%every axis y label/.style={at={(1,1)},anchor=north west,xshift=15pt},
				% FIXME : DEPRECATED !? USE 'near tick' things ....
				every axis y label/.style={at={(1,0.5)},xshift=33pt,rotate=90},
				/pgfplots/every non boxed y axis
			}%
		},%
		/pgfplots/axis y line/none/.style	={axis y line*/none,hide y axis},
		%
		%
		% Z :
		%
		/pgfplots/axis z line/box/.style	={
			/pgfplots/axis z line*/box,
			/pgfplots/every boxed z axis
		},
		/pgfplots/axis z line/left/.style	={
			/pgfplots/axis z line*/left,
			/pgfplots/every non boxed z axis
		},
		/pgfplots/axis z line/center/.code	={
		%	\ifnum\pgfplots@xaxislinesnum=3 % if 'axis x line==top' then
		%		\pgfkeysalso{%
		%			/pgfplots/every axis z label/.style={at={(current axis.below origin)},anchor=south west}}%
		%	\else
				\pgfkeysalso{%
					/pgfplots/every axis z label/.style={at={(current axis.above origin)},anchor=north west}}%
		%	\fi
			\pgfkeysalso{/pgfplots/every axis z label/.append code={\pgfplots@label@upgrade@warning}}%
			\pgfkeysalso{%
				/pgfplots/axis z line*/center,
				/pgfplots/every non boxed z axis}%
		},
		/pgfplots/axis z line/middle/.style	={/pgfplots/axis z line/center},
		/pgfplots/axis z line/right/.code	={%
			\ifnum\pgfplots@xaxislinesnum=2
				\pgfkeysalso{every axis x label/.style={at={(current axis.left of origin)},anchor=south west}}%
			\fi
			\pgfkeysalso{
				axis z line*/right,
				%every axis y label/.style={at={(1,1)},anchor=north west,xshift=15pt},
				every axis z label/.style={at={(1,0.5)},xshift=33pt,rotate=90},
				/pgfplots/every non boxed z axis
			}%
		},%
		/pgfplots/axis z line/none/.style	={axis z line*/none,hide z axis},
	},
	/pgfplots/compat/axis line style post 1.8/.style={%
		/pgfplots/axis x line/box/.style	={
			/pgfplots/axis x line*/box,
			/pgfplots/xlabel near ticks,
			/pgfplots/every boxed x axis
		},
		/pgfplots/axis x line/bottom/.style	={
			/pgfplots/axis x line*/bottom,
			/pgfplots/every non boxed x axis
		},
		/pgfplots/axis x line/left/.style={/pgfplots/axis x line/bottom},%
		/pgfplots/axis x line/middle/.code	={%
			\ifnum\pgfplots@yaxislinesnum=3 % if 'axis y line==right' then
				\pgfkeysalso{/pgfplots/every axis x label/.style={
					/pgfplots/near ticklabel align=inside,at={(ticklabel* cs:0)},anchor=near ticklabel opposite}}%
			\else
				\pgfkeysalso{/pgfplots/every axis x label/.style={
					/pgfplots/near ticklabel align=inside,at={(ticklabel* cs:1)},anchor=near ticklabel opposite}}%
			\fi
			\pgfkeysalso{/pgfplots/axis x line*/middle,
				/pgfplots/every x tick scale label/.code={%
					\ifpgfplotsthreedim
						\pgfkeysalso{at={(xticklabel* cs:1.03)},/pgfplots/near ticklabel align=outside,anchor=near xticklabel}%
					\else
						\pgfkeysalso{at={(xticklabel cs:0.9,5pt)},anchor=near xticklabel,inner sep=0pt}%
					\fi
				},%
				/pgfplots/every non boxed x axis}%
		},
		/pgfplots/axis x line/center/.style	={/pgfplots/axis x line/middle},
		/pgfplots/axis x line/right/.style={/pgfplots/axis x line/top},%
		/pgfplots/axis x line/top/.code	={
			\ifnum\pgfplots@yaxislinesnum=2 % if 'axis y line==center' then
				\pgfkeysalso{/pgfplots/every axis y label/.style={
					/pgfplots/near ticklabel align=inside,at={(ticklabel* cs:0)},anchor=near ticklabel opposite}}%
			\fi
			\pgfkeysalso{%
				/pgfplots/axis x line*/top,
				/pgfplots/every axis x label/.style={at={(ticklabel cs:0.5)},anchor=near ticklabel},%
				/pgfplots/every y tick scale label/.style={at={(yticklabel cs:0)},anchor=near yticklabel},
				/pgfplots/every non boxed x axis}%
		},
		/pgfplots/axis x line/none/.style	={axis x line*/none,hide x axis},
		%
		% Y :
		/pgfplots/axis y line/box/.style	={
			/pgfplots/axis y line*/box,
			/pgfplots/ylabel near ticks,
			/pgfplots/every boxed y axis
		},
		/pgfplots/axis y line/left/.style	={
			/pgfplots/axis y line*/left,
			/pgfplots/every non boxed y axis
		},
		/pgfplots/axis y line/center/.code	={
			\ifnum\pgfplots@xaxislinesnum=3 % if 'axis x line==top' then
				\pgfkeysalso{%
					/pgfplots/every axis y label/.style={
						/pgfplots/near ticklabel align=outside,at={(ticklabel* cs:0)},anchor=near ticklabel opposite}}%
			\else
				\pgfkeysalso{%
					/pgfplots/every axis y label/.style={
						/pgfplots/near ticklabel align=inside,at={(ticklabel* cs:1)},anchor=near ticklabel opposite}}%
			\fi
			\pgfkeysalso{%
				/pgfplots/axis y line*/center,
				/pgfplots/every y tick scale label/.code={%
					\ifpgfplotsthreedim
						\pgfkeysalso{at={(yticklabel* cs:1.03)},/pgfplots/near ticklabel align=outside,anchor=near yticklabel}%
					\else
						\pgfkeysalso{at={(yticklabel* cs:1.03,-0.3em)},/pgfplots/near ticklabel align=outside,anchor=near yticklabel opposite,inner sep=0pt}%
					\fi
				},%
				/pgfplots/every non boxed y axis}%
		},
		/pgfplots/axis y line/middle/.style	={/pgfplots/axis y line/center},
		/pgfplots/axis y line/right/.code	={%
			\ifnum\pgfplots@xaxislinesnum=2
				\pgfkeysalso{
					/pgfplots/every axis x label/.style={
						/pgfplots/near ticklabel align=outside,at={(ticklabel* cs:0)},anchor=near ticklabel opposite}}%
			\fi
			\pgfkeysalso{
				axis y line*/right,
				/pgfplots/every axis y label/.style={at={(ticklabel cs:0.5)},anchor=near ticklabel,
					/utils/exec={%
						\ifpgfplotsthreedim\else \pgfkeysalso{rotate=90}\fi
					},%
				},
				/pgfplots/every y tick scale label/.code={
					\ifpgfplotsthreedim
						\pgfkeysalso{at={(yticklabel cs:0)},anchor=near yticklabel}%
					\else
						\pgfkeysalso{at={(yticklabel cs:1)},anchor=near yticklabel}%
					\fi
				},%
				/pgfplots/every non boxed y axis
			}%
		},%
		/pgfplots/axis y line/none/.style	={axis y line*/none,hide y axis},
		%
		%
		% Z :
		%
		/pgfplots/axis z line/box/.style	={
			/pgfplots/axis z line*/box,
			/pgfplots/every axis z label/.style={at={(ticklabel cs:0.5)},rotate=90, anchor=near ticklabel},
			/pgfplots/every z tick scale label/.style={at={(zticklabel* cs:1.2,-0.3em)},anchor=near zticklabel,inner sep=0pt},
			/pgfplots/every boxed z axis
		},
		/pgfplots/axis z line/left/.style	={
			/pgfplots/axis z line*/left,
			/pgfplots/every non boxed z axis
		},
		/pgfplots/axis z line/center/.code	={
			\pgfkeysalso{%
				/pgfplots/every axis z label/.style={
					/pgfplots/near ticklabel align=inside,at={(ticklabel* cs:1)},anchor=near ticklabel opposite}}%
			\pgfkeysalso{%
				/pgfplots/axis z line*/center,
				/pgfplots/every non boxed z axis}%
		},
		/pgfplots/axis z line/middle/.style	={/pgfplots/axis z line/center},
		/pgfplots/axis z line/right/.code	={%
			\ifnum\pgfplots@xaxislinesnum=2
				\pgfkeysalso{
					/pgfplots/every axis z label/.style={
						/pgfplots/near ticklabel align=outside,at={(ticklabel* cs:0)},anchor=near ticklabel opposite}}%
			\fi
			\pgfkeysalso{
				axis z line*/right,
				every axis z label/.style={at={(ticklabel cs:0.5)},anchor=near ticklabel,rotate=90},
				/pgfplots/every z tick scale label/.style={at={(zticklabel cs:0)},anchor=near zticklabel},
				/pgfplots/every non boxed z axis
			}%
		},%
		/pgfplots/axis z line/none/.style	={axis z line*/none,hide z axis},
	},
	%
	/pgfplots/hide obscured x ticks/.is if=pgfplots@hide@obscured@xtick,
	/pgfplots/hide obscured y ticks/.is if=pgfplots@hide@obscured@ytick,
	/pgfplots/hide obscured z ticks/.is if=pgfplots@hide@obscured@ztick,
	/pgfplots/hide obscured x ticks=true,
	/pgfplots/hide obscured y ticks=true,
	/pgfplots/hide obscured z ticks=true,
	%
	/pgfplots/3d box/.is choice,
	/pgfplots/3d box/background/.code			={\def\pgfplots@threedimbox@choice{0}},%
	/pgfplots/3d box/complete/.code				={\def\pgfplots@threedimbox@choice{1}},%
	/pgfplots/3d box/complete*/.code				={\def\pgfplots@threedimbox@choice{2}},%
	/pgfplots/3d box/.default=complete,%
	/pgfplots/3d box/background,%
	/pgfplots/every 3d box foreground/.style={},
	/pgfplots/3d box foreground style/.style={%
		/pgfplots/every 3d box foreground/.append style={#1}%
	},
% set \pgfplots@xaxisdiscontnum
% none = 0
% crunch = 1
% open = 2
	/pgfplots/axis x discontinuity/.is choice,
	/pgfplots/axis x discontinuity/none/.code	={\def\pgfplots@xaxisdiscontnum{0}},
	/pgfplots/axis x discontinuity/crunch/.code	={\def\pgfplots@xaxisdiscontnum{1}},
	/pgfplots/axis x discontinuity/parallel/.code	={\def\pgfplots@xaxisdiscontnum{2}},
	/pgfplots/axis x discontinuity=none,
% set \pgfplots@yaxisdiscontnum
% none = 0
% crunch = 1
% open = 2
	/pgfplots/axis y discontinuity/.is choice,
	/pgfplots/axis y discontinuity/none/.code	={\def\pgfplots@yaxisdiscontnum{0}},
	/pgfplots/axis y discontinuity/crunch/.code	={\def\pgfplots@yaxisdiscontnum{1}},
	/pgfplots/axis y discontinuity/parallel/.code	={\def\pgfplots@yaxisdiscontnum{2}},
	/pgfplots/axis y discontinuity=none,
% set \pgfplots@yaxisdiscontnum
% none = 0
% crunch = 1
% open = 2
	/pgfplots/axis z discontinuity/.is choice,
	/pgfplots/axis z discontinuity/none/.code	={\def\pgfplots@zaxisdiscontnum{0}},
	/pgfplots/axis z discontinuity/crunch/.code	={\def\pgfplots@zaxisdiscontnum{1}},
	/pgfplots/axis z discontinuity/parallel/.code	={\def\pgfplots@zaxisdiscontnum{2}},
	/pgfplots/axis z discontinuity=none,
	/pgfplots/scale only axis/.is if=pgfplots@scale@only@axis,
	/pgfplots/scale only axis/.default=true,
	/pgfplots/scale only axis=false,
% sets \pgfplots@xislinear to
% normal=true
% log=false
	/pgfplots/xmode/.is choice,
	/pgfplots/xmode/.belongs to family=/pgfplots/scale,
	/pgfplots/xmode/normal/.code={\pgfplots@xislineartrue},
	/pgfplots/xmode/normal/.belongs to family=/pgfplots/scale,
	/pgfplots/xmode/linear/.code={\pgfplots@xislineartrue},
	/pgfplots/xmode/linear/.belongs to family=/pgfplots/scale,
	/pgfplots/xmode/log/.code={\pgfplots@xislinearfalse},
	/pgfplots/xmode/log/.belongs to family=/pgfplots/scale,
	/pgfplots/xmode=linear,
	/pgfplots/ymode/.is choice,
	/pgfplots/ymode/.belongs to family=/pgfplots/scale,
	/pgfplots/ymode/normal/.code={\pgfplots@yislineartrue},
	/pgfplots/ymode/normal/.belongs to family=/pgfplots/scale,
	/pgfplots/ymode/linear/.code={\pgfplots@yislineartrue},
	/pgfplots/ymode/linear/.belongs to family=/pgfplots/scale,
	/pgfplots/ymode/log/.code={\pgfplots@yislinearfalse},
	/pgfplots/ymode/log/.belongs to family=/pgfplots/scale,
	/pgfplots/ymode=linear,
	/pgfplots/zmode/.is choice,
	/pgfplots/zmode/.belongs to family=/pgfplots/scale,
	/pgfplots/zmode/normal/.code={\pgfplots@zislineartrue},
	/pgfplots/zmode/normal/.belongs to family=/pgfplots/scale,
	/pgfplots/zmode/linear/.code={\pgfplots@zislineartrue},
	/pgfplots/zmode/linear/.belongs to family=/pgfplots/scale,
	/pgfplots/zmode/log/.code={\pgfplots@zislinearfalse},
	/pgfplots/zmode/log/.belongs to family=/pgfplots/scale,
	/pgfplots/zmode=linear,
	/pgfplots/error bars/x fixed/.code=				\def\pgfplots@errorbars@xfixed{#1}\def\pgfplots@errorbars@xmode{0},
	/pgfplots/error bars/x fixed relative/.code=		\def\pgfplots@errorbars@xrel{#1}\def\pgfplots@errorbars@xmode{1},
	/pgfplots/error bars/x explicit/.code=			\def\pgfplots@errorbars@xmode{2},
	/pgfplots/error bars/x explicit relative/.code=	\def\pgfplots@errorbars@xmode{3},
	/pgfplots/error bars/x fixed relative=0,
	/pgfplots/error bars/x fixed=0,
	/pgfplots/error bars/y fixed/.code=				\def\pgfplots@errorbars@yfixed{#1}\def\pgfplots@errorbars@ymode{0},
	/pgfplots/error bars/y fixed relative/.code=		\def\pgfplots@errorbars@yrel{#1}\def\pgfplots@errorbars@ymode{1},
	/pgfplots/error bars/y explicit/.code=			\def\pgfplots@errorbars@ymode{2},
	/pgfplots/error bars/y explicit relative/.code=	\def\pgfplots@errorbars@ymode{3},
	/pgfplots/error bars/y fixed relative=0,
	/pgfplots/error bars/y fixed=0,
	/pgfplots/error bars/z fixed/.code=				\def\pgfplots@errorbars@zfixed{#1}\def\pgfplots@errorbars@zmode{0},
	/pgfplots/error bars/z fixed relative/.code=		\def\pgfplots@errorbars@zrel{#1}\def\pgfplots@errorbars@zmode{1},
	/pgfplots/error bars/z explicit/.code=			\def\pgfplots@errorbars@zmode{2},
	/pgfplots/error bars/z explicit relative/.code=	\def\pgfplots@errorbars@zmode{3},
	/pgfplots/error bars/z fixed relative=0,
	/pgfplots/error bars/z fixed=0,
	/pgfplots/error bars/x dir/.is choice,
	/pgfplots/error bars/x dir/none/.code={%
		\def\pgfplots@errorbars@xdirection{0}%
		\ifnum\pgfplots@errorbars@ydirection=0
			\ifnum\pgfplots@errorbars@zdirection=0
				\pgfplots@errorbars@enabledfalse
			\fi
		\fi
	},
	/pgfplots/error bars/x dir/plus/.code=				\def\pgfplots@errorbars@xdirection{1}\pgfplots@errorbars@enabledtrue,
	/pgfplots/error bars/x dir/minus/.code=				\def\pgfplots@errorbars@xdirection{2}\pgfplots@errorbars@enabledtrue,
	/pgfplots/error bars/x dir/both/.code=				\def\pgfplots@errorbars@xdirection{3}\pgfplots@errorbars@enabledtrue,
	/pgfplots/error bars/x dir=none,
	/pgfplots/error bars/y dir/.is choice,
	/pgfplots/error bars/y dir/none/.code={%
		\def\pgfplots@errorbars@ydirection{0}%
		\ifnum\pgfplots@errorbars@xdirection=0
			\ifnum\pgfplots@errorbars@zdirection=0
				\pgfplots@errorbars@enabledfalse
			\fi
		\fi
	},
	/pgfplots/error bars/y dir/plus/.code=				\def\pgfplots@errorbars@ydirection{1}\pgfplots@errorbars@enabledtrue,
	/pgfplots/error bars/y dir/minus/.code=				\def\pgfplots@errorbars@ydirection{2}\pgfplots@errorbars@enabledtrue,
	/pgfplots/error bars/y dir/both/.code=				\def\pgfplots@errorbars@ydirection{3}\pgfplots@errorbars@enabledtrue,
	/pgfplots/error bars/y dir=none,
	/pgfplots/error bars/z dir/.is choice,
	/pgfplots/error bars/z dir/none/.code={%
		\def\pgfplots@errorbars@zdirection{0}%
		\ifnum\pgfplots@errorbars@xdirection=0
			\ifnum\pgfplots@errorbars@ydirection=0
				\pgfplots@errorbars@enabledfalse
			\fi
		\fi
	},
	/pgfplots/error bars/z dir/plus/.code=				\def\pgfplots@errorbars@zdirection{1}\pgfplots@errorbars@enabledtrue,
	/pgfplots/error bars/z dir/minus/.code=				\def\pgfplots@errorbars@zdirection{2}\pgfplots@errorbars@enabledtrue,
	/pgfplots/error bars/z dir/both/.code=				\def\pgfplots@errorbars@zdirection{3}\pgfplots@errorbars@enabledtrue,
	/pgfplots/error bars/z dir=none,
	/pgfplots/error bars/error mark/.initial={-},
	/pgfplots/error bars/error mark options/.initial={rotate=90},
	/pgfplots/error bars/error bar style/.code={%
		\pgfkeysalso{/pgfplots/every error bar/.append style={#1}}%
	},
	/pgfplots/every error bar/.style={thin},
	/pgfplots/every error bar/.append code={\pgfplotsdeprecatedstylecheck{/tikz/every error bar}},
	/pgfplots/error bars/draw error bar/.code 2 args={%
%\message{/pgfplots/error bars/draw error bar:  working with '#1' -- '#2'.}%
		\pgfkeysgetvalue{/pgfplots/error bars/error mark}{\pgfplotserrorbarsmark}%
		\pgfkeysgetvalue{/pgfplots/error bars/error mark options}{\pgfplotserrorbarsmarkopts}%
		\draw #1 -- #2 node[pos=1,sloped,allow upside down] {%
			\expandafter\tikz\expandafter[\pgfplotserrorbarsmarkopts]{%
				\expandafter\pgfuseplotmark\expandafter{\pgfplotserrorbarsmark}%
				\pgfusepath{stroke}}%
		};
	},
	/pgfplots/every node near coord/.style={},
	%
	% Replaces the 'nodes near coords' CONFIGURATION by its default
	% settings. It does NOT activate 'nodes near coords'.
	/pgfplots/nodes near coords defaults/.style={
		% values: 'horizontal', 'vertical' or any tikz alignment command
		% like 'left' or 'anchor=south west' or so.
		/pgfplots/nodes near coords align/.initial=auto,%
		%
		% 'nodes near coords=<content of node>'.
		% The content is by default \pgfmathprintnumber\pgfplotspointmeta.
		% 
		% Use 'point meta=y' after 'nodes near coords' to typeset the y coordinates 
		% Use 'point meta=x' to typeset the x coordinates 
		/pgfplots/nodes near coords/.style={%
			/pgfplots/scatter/@pre marker code/.code={},%
			/pgfplots/scatter/@post marker code/.code={},%
			/pgfplots/nodes near coords*={##1},%
		},%
		/pgfplots/nodes near coords*/.style={%
			/pgfplots/scatter/true*,%
			/pgfplots/set point meta if empty=f(x),%
			scatter/@post marker code/.append code={%
				% determine default alignment:
				\pgfkeysgetvalue{/pgfplots/nodes near coords align}{\pgfplots@nodes@near@coords@align}%
				\edef\pgfplots@nodes@near@coords@align{\pgfplots@nodes@near@coords@align}%
				\def\pgfplots@loc@TMPa{auto}%
				\ifx\pgfplots@nodes@near@coords@align\pgfplots@loc@TMPa
					\def\pgfplots@loc@TMPa{x}%
					\ifx\pgfplotspointmetainputhandler\pgfplots@loc@TMPa%
						% point meta=x:
						\def\pgfplots@nodes@near@coords@align{horizontal}%
					\else
						\def\pgfplots@nodes@near@coords@align{vertical}%
					\fi
				\fi
				% check for sign-dependand alignment options:
				\def\pgfplots@loc@TMPa{horizontal}%
				\ifx\pgfplots@nodes@near@coords@align\pgfplots@loc@TMPa
					\if1\csname pgfpmeta@\pgfplotspointmetainputhandler @issymbolic\endcsname%
						\def\pgfplots@nodes@near@coords@align{above}%
					\else
						\pgfplotscoordmath{meta}{if is}{\pgfplotspointmeta}{-}{%
							% \pgfplotspointmeta < 0
							\def\pgfplots@nodes@near@coords@align{left}%
						}{%
							% \pgfplotspointmeta >= 0
							\def\pgfplots@nodes@near@coords@align{right}%
						}%
					\fi
				\else
					\def\pgfplots@loc@TMPa{vertical}%
					\ifx\pgfplots@nodes@near@coords@align\pgfplots@loc@TMPa
						\if1\csname pgfpmeta@\pgfplotspointmetainputhandler @issymbolic\endcsname%
							\def\pgfplots@nodes@near@coords@align{above}%
						\else
							\pgfplotscoordmath{meta}{if is}{\pgfplotspointmeta}{-}{%
								% \pgfplotspointmeta < 0
								\def\pgfplots@nodes@near@coords@align{below}%
							}{%
								% \pgfplotspointmeta >= 0
								\def\pgfplots@nodes@near@coords@align{above}%
							}%
						\fi
					\else
						\pgfutil@ifundefined{pgfplots@nodesnearcoordsalign@isanchor@\pgfplots@nodes@near@coords@align}
						{}%
						{%
							\t@pgfplots@toka=\expandafter{\pgfplots@nodes@near@coords@align}%
							\edef\pgfplots@nodes@near@coords@align{anchor=\the\t@pgfplots@toka}%
						}%
					\fi
				\fi
				% ok, place the node.
				\expandafter\node\expandafter[\pgfplots@nodes@near@coords@align,%
					/pgfplots/every node near coord] 
				{%
					\if1\csname pgfpmeta@\pgfplotspointmetainputhandler @issymbolic\endcsname%
						% point meta=explicit symbolic
						% do not try to invoke \pgfmathprintnumber on
						% symbolic data... this check should keep the user
						% interface simpler.
						\def\pgfplots@loc@TMPa{\pgfmathprintnumber\pgfplotspointmeta}%
						\def\pgfplots@loc@TMPb{##1}%
						\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
							\pgfplotspointmeta
						\else
							##1%
						\fi
					\else
						##1%
					\fi
				};
			},%
		},%
		/pgfplots/nodes near coords*/.default={\pgfmathprintnumber\pgfplotspointmeta},
	},
	/pgfplots/nodes near coords defaults,
	%
	%
	/pgfplots/nodes near coords bar offset/.initial=0.5,
	%
	% Replaces the 'nodes near coords' CONFIGURATION by one suitable
	% for xbar stacked
	/pgfplots/nodes near coords xbar stacked configuration/.style={
		/pgfplots/nodes near coords defaults,
		/pgfplots/nodes near coords*/.add code={%
			\pgfkeysalso{
				/pgfplots/set point meta if empty=rawx,%
			}%
		}{%
			\pgfkeysalso{%
				/pgfplots/scatter/position/absolute,
				/pgfplots/scatter/@post marker code/.add code={
					\pgfplotspointgetnormalizedcoordinates
					\pgfplotspointgetnormalizedzerolevelcoordinates
					\pgfkeysgetvalue{/pgfplots/nodes near coords bar offset}\pgfplots@nodes@near@coords@bar@offset
					\tikzset{
						every node/.append style={%
							at={(normalized axis cs:%
								{ (\pgfplots@nodes@near@coords@bar@offset)  *\pgfkeysvalueof{/data point/x}
								 +(1-\pgfplots@nodes@near@coords@bar@offset)*\pgfkeysvalueof{/data point/zero/x}},%
								\pgfkeysvalueof{/data point/y})%
							}%
						}
					}%
				}{},%
			}%
		},
		/pgfplots/nodes near coords align={%
			anchor=center,
		},
	},
	% Replaces the 'nodes near coords' CONFIGURATION by one suitable
	% for ybar stacked
	/pgfplots/nodes near coords ybar stacked configuration/.style={
		/pgfplots/nodes near coords defaults,
		/pgfplots/nodes near coords*/.add code={%
			\pgfkeysalso{
				/pgfplots/set point meta if empty=rawy,%
			}%
		}{%
			\pgfkeysalso{%
				/pgfplots/scatter/position/absolute,
				/pgfplots/scatter/@post marker code/.add code={
					\pgfplotspointgetnormalizedcoordinates
					\pgfplotspointgetnormalizedzerolevelcoordinates
					\pgfkeysgetvalue{/pgfplots/nodes near coords bar offset}\pgfplots@nodes@near@coords@bar@offset
					\tikzset{
						every node/.append style={%
							at={(normalized axis cs:%
								\pgfkeysvalueof{/data point/x},%
								{ (\pgfplots@nodes@near@coords@bar@offset)  *\pgfkeysvalueof{/data point/y}
								 +(1-\pgfplots@nodes@near@coords@bar@offset)*\pgfkeysvalueof{/data point/zero/y}})%
							}%
						}
					}%
				}{},%
			}%
		},
		/pgfplots/nodes near coords align={%
			anchor=center,
		},
	},
	%
	%
	%
	/pgfplots/scatter explicit color/.style 2 args={%
		/pgfplots/scatter/@pre marker code/.code=,%
		/pgfplots/scatter/@post marker code/.code=,%
		/pgfplots/scatter explicit color*={#1}{#2},%
	},%
	/pgfplots/scatter explicit color*/.style 2 args={%
		/pgfplots/point meta=explicit symbolic,
		/pgfplots/scatter/true*,%
		/pgfplots/scatter/@pre marker code/.append code={%
			\edef\pgfplots@loc@TMPa{\noexpand\pgfutil@definecolor{mapped color}{#1}{\pgfplotspointmeta}}%
			\pgfplots@loc@TMPa
			\scope[#2]%
		},%
		/pgfplots/scatter/@post marker code/.prefix code={%
			\endscope
		},%
	},
	/pgfplots/scatter rgb/.style={%
		/pgfplots/scatter/@pre marker code/.code=,%
		/pgfplots/scatter/@post marker code/.code=,%
		/pgfplots/scatter rgb*={#1},%
	},
	/pgfplots/scatter rgb*/.style={/pgfplots/scatter explicit color*={rgb}{#1}},
	/pgfplots/scatter rgb*/.default={draw=mapped color!80!black,fill=mapped color},
	%
	/pgfplots/scatter cmyk/.style={%
		/pgfplots/scatter/@pre marker code/.code=,%
		/pgfplots/scatter/@post marker code/.code=,%
		/pgfplots/scatter cmyk*={#1},%
	},
	/pgfplots/scatter cmyk*/.style={/pgfplots/scatter explicit color*={cmyk}{#1}},
	/pgfplots/scatter cmyk*/.default={draw=mapped color!80!black,fill=mapped color},
	%
	/pgfplots/visualization depends on/list/.initial=,%
	/pgfplots/visualization depends on/.style={%
		/pgfplots/visualization depends on/list/.add={}{,{#1}}%
	},
	/pgfplots/bar cycle list/.style={/pgfplots/cycle list={%
		{blue,fill=blue!30!white,mark=none},%
		{red,fill=red!30!white,mark=none},%
		{brown!60!black,fill=brown!30!white,mark=none},%
		{black,fill=gray,mark=none},%
		{violet!80!black,fill=violet,mark=none},%
		{green,fill=green!80!black,mark=none}%
		}
	},
	/pgfplots/area cycle list/.style={bar cycle list},
	/pgfplots/area legend/.style={%
		/pgfplots/legend image code/.code={%
			\draw[##1] (0cm,-0.1cm) rectangle (0.6cm,0.1cm);
		}%
	},
	/pgfplots/area style/.style={%
		area cycle list,
		area legend,
		axis on top,
	},
	/pgfplots/ybar legend/.style={
		/pgfplots/legend image code/.code={\draw[##1,/tikz/.cd,bar width=3pt,yshift=-0.2em,bar shift=0pt] plot coordinates {(0cm,0.8em) (2*\pgfplotbarwidth,0.6em)};},
	},
	/pgfplots/single ybar legend/.style={
		/pgfplots/legend image code/.code={\draw[##1,/tikz/.cd,bar width=6pt,yshift=-0.2em,bar shift=0pt] plot coordinates {(0pt,0.8em)};},
	},
	/pgfplots/ybar/.style={
		bar direction=y,
		bar cycle list,
		xtick align=outside,
		ybar legend,
		/pgfplots/set point meta if empty=f(x),%
		/pgf/bar shift={%
				% total width = n*w + (n-1)*skip
				% -> subtract half for centering
				-0.5*(\numplotsofactualtype*\pgfplotbarwidth + (\numplotsofactualtype-1)*#1)  + 
				% the '0.5*w' is for centering
				(.5+\plotnumofactualtype)*\pgfplotbarwidth + \plotnumofactualtype*#1},%
		/pgfplots/error bars/draw error bar/.code 2 args={%
% FIXME: simplify this code! It is just a replication of the default error stuff together with an xshift!
			\pgfkeysgetvalue{/pgfplots/error bars/error mark}{\pgfplotserrorbarsmark}%
			\pgfkeysgetvalue{/pgfplots/error bars/error mark options}{\pgfplotserrorbarsmarkopts}%
			\draw[xshift={\pgfplotbarshift}]
				##1 -- ##2 node[pos=1,sloped,allow upside down] {%
				\expandafter\tikz\expandafter[\pgfplotserrorbarsmarkopts]{%
					\expandafter\pgfuseplotmark\expandafter{\pgfplotserrorbarsmark}%
					\pgfusepath{stroke}}%
			};
		},%
		/pgfplots/every node near coord/.append style={xshift={\pgfplotbarshift}},%
		/tikz/ybar,
	},
	/pgfplots/ybar/.default=2pt,
	/pgfplots/xbar legend/.style={
		/pgfplots/legend image code/.code={\draw[##1,/tikz/.cd,bar width=3pt,yshift=-0.2em,bar shift=0pt] plot coordinates {(0cm,0.8em) (2*\pgfplotbarwidth,0.6em)};},
	},
	/pgfplots/single xbar legend/.style={
		/pgfplots/legend image code/.code={\draw[##1,/tikz/.cd,bar width=6pt,yshift=-0.2em,bar shift=0pt] plot coordinates {(0pt,0.8em)};},
	},
	/pgfplots/bar direction/.is choice,
	/pgfplots/bar direction/auto/.code=\def\pgfplots@bar@direction@choice{a},%
	/pgfplots/bar direction/x/.code=\def\pgfplots@bar@direction@choice{x},%
	/pgfplots/bar direction/y/.code=\def\pgfplots@bar@direction@choice{y},%
	/pgfplots/bar direction=auto,
	%
	/pgfplots/xbar/.style={
		bar direction=x,
		bar cycle list,
		ytick align=outside,
		/pgfplots/xbar legend,
		/pgfplots/set point meta if empty=x,%
		/pgf/bar shift={%
				% total width = n*w + (n-1)*skip
				% -> subtract half for centering
				-0.5*(\numplotsofactualtype*\pgfplotbarwidth + (\numplotsofactualtype-1)*#1)  + 
				% the '0.5*w' is for centering
				(.5+\plotnumofactualtype)*\pgfplotbarwidth + \plotnumofactualtype*#1},%
		/pgfplots/error bars/draw error bar/.code 2 args={%
% FIXME: simplify this code! It is just a replication of the default error stuff together with an xshift!
			\pgfkeysgetvalue{/pgfplots/error bars/error mark}{\pgfplotserrorbarsmark}%
			\pgfkeysgetvalue{/pgfplots/error bars/error mark options}{\pgfplotserrorbarsmarkopts}%
			\draw[yshift={\pgfplotbarshift}]
				##1 -- ##2 node[pos=1,sloped,allow upside down] {%
				\expandafter\tikz\expandafter[\pgfplotserrorbarsmarkopts]{%
					\expandafter\pgfuseplotmark\expandafter{\pgfplotserrorbarsmark}%
					\pgfusepath{stroke}}%
			};
		},%
		/pgfplots/every node near coord/.append style={yshift={\pgfplotbarshift}},%
		/tikz/xbar,
	},
	/pgfplots/xbar/.default=2pt,
	/pgfplots/ybar interval legend/.style={
		/pgfplots/legend image code/.code={\draw[##1,/tikz/.cd,yshift=-0.2em,bar interval width=0.7,bar interval shift=0.5] plot coordinates {(0cm,0.8em) (5pt,0.6em) (10pt,0.6em)};},
	},
	/pgfplots/ybar interval/.style={%
		bar direction=y,
		/pgfplots/set point meta if empty=f(x),%
		bar cycle list,
		x tick label as interval,
		xmajorgrids,
		xtick align=outside,
		xtick=data,
		ybar interval legend,
		bar interval width={#1/\numplotsofactualtype},
		bar interval shift={(\plotnumofactualtype+0.5)/\numplotsofactualtype},
		/tikz/ybar interval,
	},
	/pgfplots/ybar interval/.default=1,
	/pgfplots/xbar interval legend/.style={%
		/pgfplots/legend image code/.code={\draw[##1,/tikz/.cd,yshift=-0.2em,bar interval width=0.7,bar interval shift=0.5] plot coordinates {(0cm,0.8em) (5pt,0.6em) (10pt,0.6em)};},
	},
	/pgfplots/xbar interval/.style={%
		bar direction=x,
		/pgfplots/set point meta if empty=x,%
		bar cycle list,
		y tick label as interval,
		ytick=data,
		ymajorgrids,
		ytick align=outside,
		xbar interval legend,
		bar interval width={#1/\numplotsofactualtype},
		bar interval shift={(\plotnumofactualtype+0.5)/\numplotsofactualtype},
		/tikz/xbar interval,
	},
	/pgfplots/xbar interval/.default=1,
	/pgfplots/stacked since 1.9/.style={},
	/pgfplots/xbar stacked/.style={
		bar direction=x,
		bar cycle list,
		single xbar legend,
		stack plots=x,
		stack dir=#1,
		/tikz/xbar,
		stacked since 1.9,
		activate nodes near coords xbar stacked,
	},
	/pgfplots/xbar stacked/.default=plus,
	/pgfplots/ybar stacked/.style={
		bar direction=y,
		bar cycle list,
		single ybar legend,
		stack plots=y,
		stack dir=#1,
		/tikz/ybar,
		stacked since 1.9,
		activate nodes near coords ybar stacked,
	},
	/pgfplots/ybar stacked/.default=plus,
	/pgfplots/xbar interval stacked/.style={
		bar direction=x,
		/pgfplots/set point meta if empty=x,%
		bar cycle list,
		single xbar legend,
		stack plots=x,
		stack dir=#1,
		/tikz/xbar interval,
	},
	/pgfplots/xbar interval stacked/.default=plus,
	/pgfplots/ybar interval stacked/.style={
		bar direction=y,
		/pgfplots/set point meta if empty=f(x),%
		bar cycle list,
		single ybar legend,
		stack plots=y,
		stack dir=#1,
		/tikz/ybar interval,
	},
	/pgfplots/ybar interval stacked/.default=plus,
	/pgfplots/yticklabel interval boundaries/.style={%
		y tick label as interval,
		yticklabel={$\pgfmathprintnumber{\tick}$ -- $\pgfmathprintnumber{\nexttick}$}
	},
	/pgfplots/xticklabel interval boundaries/.style={%
		x tick label as interval,
		xticklabel={$\pgfmathprintnumber{\tick}$ -- $\pgfmathprintnumber{\nexttick}$}
	},
	/pgfplots/plot file/skip first/.is if=pgfplots@plot@file@skipfirst,
	/pgfplots/plot file/skip first/.default=true,
	/pgfplots/plot file/ignore first/.style={/pgfplots/plot file/skip first={#1}},
	/pgfplots/plot file/.search also=/pgfplots,%
	/pgfplots/plot coordinates/math parser/.is if=pgfplots@plot@coords@mathparser,
	/pgfplots/plot graphics/.code={\let\tikz@plot@handler=\pgfplotsplothandlergraphics},%
	/pgfplots/plot graphics/src/.initial=,
	/pgfplots/plot graphics/includegraphics/.initial=,
	/pgfplots/plot graphics/includegraphics cmd/.initial=\includegraphics,
	/pgfplots/plot graphics/xmin/.initial=,
	/pgfplots/plot graphics/xmax/.initial=,
	/pgfplots/plot graphics/ymin/.initial=,
	/pgfplots/plot graphics/ymax/.initial=,
	/pgfplots/plot graphics/zmin/.initial=,
	/pgfplots/plot graphics/zmax/.initial=,
	%
	% a) to provide a bounding box: points={(0,1) (0,2)} 
	% or b) to squeeze the graphics into internal image coordinates:
	% points={(0,1,0) => (0,4)  (0,0,1) => (40,600)}
	% or c) both of them.
	/pgfplots/plot graphics/points/.initial=,
	/pgfplots/plot graphics/auto adjust axis/.is if=pgfplots@plot@graphics@autoadjustaxis,
	/pgfplots/plot graphics/auto adjust axis=true,
	/pgfplots/plot graphics/snap z/.initial=0.02,
	% possible values: debug=<empty>|false|true|visual
	/pgfplots/plot graphics/debug/.initial=,
	/pgfplots/plot graphics/debug/.default=true,
	/pgfplots/plot graphics/squeeze tol/.initial=2pt,
	%
	% this command key should defined \pgfmathresult to be
	% \pgfmathresult -> {{<wd>}{<ht>}}
	% where <wd> is the natural width of the input image and 
	% <ht> is the natural height.
	% The input image file name is available as 'plot graphics/src'.
	% The default implementation invoked 'lowlevel draw={}{}' and
	% measures the resulting dimensions.
	/pgfplots/plot graphics/lowlevel get natural size/.code={%
		\pgfplots@plot@handler@graphics@getnaturalsize
	},
	/pgfplots/plot graphics/lowlevel draw/.code 2 args={%
		\pgfplots@plot@handler@graphics@DRAW{#1}{#2}%
	},%
	/pgfplots/plot graphics/node/.style={
		transform shape,
		inner sep=0pt,
		outer sep=0pt,
		every node/.style={},
		anchor=south west,
		at={(0pt,0pt)},
		rectangle
	},
	/tikz/pos segment/.initial=,
	% empty line=none|auto|scanline|nan|jump
	% nan and jump is the same.
	/pgfplots/empty line/.initial=auto,
	% 'mesh' plots.
	% The macro \pgfplots@meshmode is
	% n if meshmode == false,
	% m if meshmode == 'mesh',
	% s if meshmode == 'surf'.
	%
	% The type of surface plot can be configured with 'shader'.
	/pgfplots/mesh/.is choice,
	/pgfplots/mesh/true/.code={%
		\def\pgfplots@meshmode{m}%
		\let\tikz@plot@handler=\pgfplotsplothandlermesh
		\pgfkeysalso{/pgfplots/set point meta if empty=f(x),/pgfplots/every mesh,/pgfplots/mesh legend,/tikz/color=mapped color}%
	},
	/pgfplots/mesh/false/.code={
		\def\pgfplots@meshmode{n}%
		\ifx\tikz@plot@handler\pgfplotsplothandlermesh
			\let\tikz@plot@handler=\pgfplothandlerlineto
		\fi},
	/pgfplots/mesh/.default=true,
	/pgfplots/surf/.code={%
		\pgfkeysalso{/pgfplots/mesh=#1}%
		\def\pgfplots@meshmode{s}%
	},%
	/pgfplots/patch/.code={%
		\pgfkeysalso{/pgfplots/surf=#1,/pgfplots/mesh input=patches,/pgfplots/every patch}%
	},%
	%
	/pgfplots/mesh/color input/.is choice,
	/pgfplots/mesh/color input/colormap/.code=\def\pgfplotsplothandlermesh@colorinput{0},%
	/pgfplots/mesh/color input/explicit/.code={%
		\def\pgfplotsplothandlermesh@colorinput{1}%
		\def\pgfplotsplothandlermesh@colorinput@mathparse{0}%
		%
		\pgfplotsaxisifhaspointmeta{%
			\if1\csname pgfpmeta@\pgfplotspointmetainputhandler @issymbolic\endcsname
				% ok.
			\else
				% oh. the point meta is numeric, i.e. it will be
				% mapped. Change to symbolic for explicit color input:
				\pgfkeysalso{/pgfplots/point meta/explicit symbolic}%
			\fi
		}{%
			% there is no point meta. Set it to "reasonable" defaults:
			\pgfkeysalso{/pgfplots/point meta/explicit symbolic}%
		}%
	},%
	/pgfplots/mesh/color input/explicit mathparse/.code={%
		\pgfkeysalso{/pgfplots/mesh/color input/explicit}%
		\def\pgfplotsplothandlermesh@colorinput@mathparse{1}%
	},%
	/pgfplots/mesh/color input=colormap,
	%
	/pgfplots/mesh/colorspace explicit color output/.initial=rgb,
	/pgfplots/mesh/colorspace explicit color input/.initial=rgb,
	%
	/pgfplots/every patch/.style={miter limit=1},
	/pgfplots/patch table/value/.initial=,
	/pgfplots/patch table/.code={
		\pgfkeyssetvalue{/pgfplots/patch table/value}{#1}%
		\pgfplotsplothandlermesh@patchtable@hascdatafalse
	},
	/pgfplots/patch table with point meta/.code={%
		\pgfkeyssetvalue{/pgfplots/patch table/value}{#1}%
		\pgfplotsplothandlermesh@patchtable@hascdatatrue
		\pgfplotsplothandlermesh@patchtable@cdata@individualfalse
		\pgfkeysalso{/pgfplots/point meta/explicit}%
	},
	/pgfplots/patch table with individual point meta/.code={%
		\pgfkeyssetvalue{/pgfplots/patch table/value}{#1}%
		\pgfplotsplothandlermesh@patchtable@hascdatatrue
		\pgfplotsplothandlermesh@patchtable@cdata@individualtrue
		\pgfkeysalso{/pgfplots/point meta/explicit}%
	},
	/pgfplots/patch type/.initial=,
	/pgfplots/patch type sampling/.is if=pgfplotsplothandlermesh@patch@type@sampling,
	/pgfplots/patch internal depth/.is if=pgfplotsplothandlermesh@internaldepth,
	/pgfplots/patch internal depth=true,
	/pgfplots/patch to triangles/.is choice,
	/pgfplots/patch to triangles/false/.code=			{\def\pgfplotsplothandlermesh@triangulate{0}},
	/pgfplots/patch to triangles/true/.code=			{\def\pgfplotsplothandlermesh@triangulate{1}},
	/pgfplots/patch to triangles/true with edges/.code=	{\def\pgfplotsplothandlermesh@triangulate{2}},
	/pgfplots/patch to triangles=false,
	/pgfplots/patch to triangles/.default=true,
	/pgfplots/mesh input/.is choice,
	/pgfplots/mesh input/lattice/.code=	{\def\pgfplotsplothandlermesh@matrixinput{1}},
	/pgfplots/mesh input/patches/.code=	{\def\pgfplotsplothandlermesh@matrixinput{0}},
	/pgfplots/mesh input/lattice,
	/pgfplots/patch refines/.initial=0,
	/pgfplots/hide refined edges/.is if=pgfplotsplothandlermesh@hide@refined@edges,
	/pgfplots/hide refined edges/.default=true,
	/pgfplots/mesh/refines/.style={/pgfplots/patch refines={#1}},
	/pgfplots/mesh/rows/.initial=,
	/pgfplots/mesh/cols/.initial=,
	/pgfplots/mesh/scanline verbose/.is if=pgfplots@scanline@verbose,%
	/pgfplots/mesh/scanline verbose/.default=true,
	%
	% this is currently only a debug feature. Perhaps it will never
	% reach production state because of the lacking z buffering for
	% this technique.
	/pgfplots/mesh/show normals/.is if=pgfplotsplothandlermesh@shownormals,
	/pgfplots/mesh/show normals/.default=true,
	/pgfplots/mesh/show normals length factor/.initial=50,
	/pgfplots/every patch normal/.style={-stealth,red},
	%
	/pgfplots/mesh/interior colormap/.code 2 args={%
		\pgfplotscreatecolormap{#1}{#2}%
		\pgfkeysalso{/pgfplots/mesh/interior colormap name=#1}%
	},
	/pgfplots/mesh/interior colormap name/.initial=,
	/pgfplots/mesh/interior colormap thresh/.initial=0,
	/pgfplots/mesh/check/.code={%
		\pgfplotsutilifstringequal{#1}{false}{%
			\def\pgfplots@mesh@checkmode{0}%
		}{%
			\pgfplotsutilifstringequal{#1}{warning}{%
				\def\pgfplots@mesh@checkmode{1}%
			}{%
				\pgfplotsutilifstringequal{#1}{error}{%
					\def\pgfplots@mesh@checkmode{2}%
				}{%
					\pgfplots@error{Invalid value `#1' for /pgfplots/mesh/check. Please use one of false,warning,error}%
				}%
			}%
		}%
	},%
	/pgfplots/mesh/check=error,
	/pgfplots/mesh/ordering/.is choice,
	/pgfplots/mesh/ordering/x varies/.code={\def\pgfplots@plot@mesh@ordering{0}},
	/pgfplots/mesh/ordering/y varies/.code={\def\pgfplots@plot@mesh@ordering{1}},
	/pgfplots/mesh/ordering/rowwise/.style={/pgfplots/mesh/ordering/x varies},
	/pgfplots/mesh/ordering/colwise/.style={/pgfplots/mesh/ordering/y varies},
	/pgfplots/mesh/ordering/x varies,
	/pgfplots/every mesh/.code={%
		% is slower:
		%\pgfkeysalso{/pgfplots/unbounded coords=jump}% mesh plots need balanced cols!
	},%
	/pgfplots/mesh legend/.style={%
		/pgfplots/legend image code/.code={%
			\pgfplotsplothandlermesh@defaultlegend@img{##1}%
		}%
	},
	/pgfplots/mesh/num points/.initial=,%\numcoords,% this is NOT part of the public interface. Don't change it.
	/pgfplots/z buffer/.is choice,%
	/pgfplots/z buffer/none/.code={\def\pgfplotsplothandlermesh@zbuffer@choice{0}},%
	/pgfplots/z buffer/reverse x seq/.code={\def\pgfplotsplothandlermesh@zbuffer@choice{1}},%
	/pgfplots/z buffer/reverse y seq/.code={\def\pgfplotsplothandlermesh@zbuffer@choice{2}},%
	/pgfplots/z buffer/reverse xy seq/.code={\def\pgfplotsplothandlermesh@zbuffer@choice{3}},%
	/pgfplots/z buffer/sort/.code={\def\pgfplotsplothandlermesh@zbuffer@choice{4}},%
	/pgfplots/z buffer/auto/.code={\def\pgfplotsplothandlermesh@zbuffer@choice{5}},%
	/pgfplots/z buffer/default/.code={\def\pgfplotsplothandlermesh@zbuffer@choice{6}},%
	/pgfplots/z buffer/default,%
	%
	% Set the shader used for surface plots.
	% RULES:
	% 	1. meshmode == 'm' (mesh):  
	% 		This means we use "shader/flat" to determine the colors
	% 		and ignore fill colors.
	% 	2. meshmode == 's' (surf):
	% 		the shader specifies how colors are used.
	% 	3. Onedimensional mesh/surf plots are treated like 'mesh'
	% 	plots.
	/pgfplots/shader/.is choice,
	/pgfplots/shader/flat corner/.code={\def\pgfplotsplothandlermesh@shader{0}\def\pgfplotsplothandlermesh@flatmode{c}},
	/pgfplots/shader/flat mean/.code={\def\pgfplotsplothandlermesh@shader{0}\def\pgfplotsplothandlermesh@flatmode{m}},
	/pgfplots/shader/flat/.style={/pgfplots/shader/flat mean},%
	/pgfplots/shader/faceted/.code={\def\pgfplotsplothandlermesh@shader{1}},
	/pgfplots/shader/interp/.code={\def\pgfplotsplothandlermesh@shader{2}},
	/pgfplots/shader/faceted interp/.code={\def\pgfplotsplothandlermesh@shader{3}},
	/pgfplots/shader/faceted,
	/pgfplots/faceted color/.initial=mapped color!80!black,
	/pgfplots/marker layer/.initial=auto,
	/pgfplots/clip marker paths/.is if=pgfplots@clip@marker@paths,
	/pgfplots/clip marker paths/.default=true,
	/pgfplots/axis on top/.is if=pgfplots@axis@on@top,
	/pgfplots/axis on top/.default=true,
	/pgfplots/invoke before crossref tikzpicture/.initial={%
		\expandafter\ifx\csname tikzappendtofigurename\endcsname\relax
		\else
			\begingroup
			\tikzappendtofigurename{_crossref}%
		\fi
	},
	/pgfplots/invoke after crossref tikzpicture/.initial={%
		\expandafter\ifx\csname tikzappendtofigurename\endcsname\relax
		\else
			\endgroup
		\fi
	},%
	/pgfplots/every crossref picture/.style={%
		baseline,yshift=0.3em
	},
	/pgfplots/unbounded coords/.code={%
		\edef\pgfplots@loc@TMPa{#1}%
		\def\pgfplots@loc@TMPb{discard}%
		\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
			\def\pgfplots@unbounded@handler{d}%
		\else
			\def\pgfplots@loc@TMPb{jump}%
			\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
				\def\pgfplots@unbounded@handler{j}%
			\else
				\pgfplots@error{Sorry, the choice `#1' is unknown for \pgfkeyscurrentkey. Please use either 'discard' or 'jump'.}%
			\fi
		\fi
	},%
	/pgfplots/unbounded coords=discard,
	/pgfplots/x coord trafo/.code={},
	/pgfplots/x coord inv trafo/.code={},
	/pgfplots/y coord trafo/.code={},
	/pgfplots/y coord inv trafo/.code={},
	/pgfplots/z coord trafo/.code={},
	/pgfplots/z coord inv trafo/.code={},
	%
	/pgfplots/symbolic coords/magic prefix/.initial={[normalized]},
	% #1 : the coordinate in question. Can be x,y,z, or even hist/data
	% or similar constructs.
 	% #2 : {<symbol1>,<symbol2>,....<symboln>}
	/pgfplots/symbolic coords/.code 2 args={%
		\expandafter\pgfplotsarraynew\csname pgfplots@symbolic@coords@#1@inverse\endcsname{#2}%
		\expandafter\pgfplotsarrayforeachungrouped\csname pgfplots@symbolic@coords@#1@inverse\endcsname\as\pgfplots@loc@TMPa{%
			\pgfplots@command@to@string\pgfplots@loc@TMPa\pgfplots@loc@TMPa
%			\message{Defining symb coords \pgfplots@loc@TMPa^^J}%
			\expandafter\edef\csname pgfp@symb@coords@#1@\pgfplots@loc@TMPa\endcsname{\pgfplotsarrayforeachindex}%
		}%
		\pgfkeysgetvalue{/pgfplots/symbolic coords/magic prefix}\pgfplots@symb@magic@prefix
		\pgfkeysdef{/pgfplots/#1 coord trafo}{%
			\expandafter\pgfplotsutilifstartswith\expandafter{\pgfplots@symb@magic@prefix}{##1}{%
				% Ah - something like [normalized]1.5
				% we need to assign the suffix 1.5:
				\edef\pgfmathresult{\pgfplotsretval}%
			}{%
				% ensure that special (unexpandable) characters are
				% preserved:
				\def\pgfplots@loc@TMPa{##1}%
				\pgfplots@command@to@string\pgfplots@loc@TMPa\pgfplots@loc@TMPa
				\pgfutil@ifundefined{pgfp@symb@coords@#1@\pgfplots@loc@TMPa}{%
					\t@pgfplots@toka={##1}%
					\t@pgfplots@tokb={#2}%
					\pgfplots@error{Sorry, the input coordinate `\the\t@pgfplots@toka' has not been defined with 'symbolic #1 coords={\the\t@pgfplots@tokb}... Maybe it has been misspelled? Or did you mean something like \pgfplots@symb@magic@prefix\the\t@pgfplots@toka?}%
					\def\pgfmathresult{0}%
				}{%
					\edef\pgfmathresult{\csname pgfp@symb@coords@#1@\pgfplots@loc@TMPa\endcsname}%
				}%
			}%
%\message{#1 coord trafo{\pgfplots@loc@TMPa} --> \pgfmathresult^^J}%
		}%
		\pgfkeysdef{/pgfplots/#1 coord inv trafo}{%
			\begingroup
			% discard everything up to the period:
			\pgfmath@basic@round@{##1}%
			\afterassignment\pgfplots@gobble@until@relax
			\count0=\pgfmathresult\relax
			\ifnum\count0<0
				\count0=0
			\else
				\edef\pgfplots@loc@TMPa{\expandafter\pgfplotsarraysizeof\csname pgfplots@symbolic@coords@#1@inverse\endcsname}%
				\count1=\pgfplots@loc@TMPa\relax
				\ifnum\count0<\count1
				\else
					\count0=\count1
					\advance\count0 by-1
				\fi
			\fi
			\expandafter\pgfplotsarrayselect\expandafter\count\expandafter0\expandafter\of\csname pgfplots@symbolic@coords@#1@inverse\endcsname\to\pgfmathresult
%\message{#1 coord inv trafo{##1} -->\the\count0 --> \meaning\pgfmathresult^^J}%
			\pgfmath@smuggleone\pgfmathresult
			\endgroup
		}%
		\pgfkeysifdefined{/pgfplots/#1ticklabel/.@cmd}{%
			\pgfkeysalso{%
				/pgfplots/#1ticklabel={\pgfplots@ticklabel@typeset@arg\tick},%
				/pgfplots/scaled #1 ticks=false,%
				/pgfplots/plot coordinates/math parser=false,%
			}%
		}{%
			% OK. The style can be used for other coordinates as well
			% (like hist/data)
		}%
		%
		\pgfkeysifdefined{/pgfplots/#1 is expr}{%
			\pgfkeyssetvalue{/pgfplots/#1 is expr}{0}%
		}{}%
		%
		% Allow a callback (optional)
		\pgfkeysifdefined{/pgfplots/#1/@execute on coord trafo changed/.@cmd}{%
			\pgfkeysalso {/pgfplots/#1/@execute on coord trafo changed}%
		}{}%
	},%
	/pgfplots/symbolic x coords/.style={symbolic coords={x}{#1}},%
	/pgfplots/symbolic y coords/.style={symbolic coords={y}{#1}},%
	/pgfplots/symbolic z coords/.style={symbolic coords={z}{#1}},%
% Defines the class name \pgfplotspointmetainputhandler:
	/pgfplots/point meta/.code={%
		\pgfplots@pgfkeys@set@point@meta@value{#1}%
	},%
	/pgfplots/point meta/none/.code	={\pgfplotssetpointmetainput{}{}},%
	/pgfplots/point meta/x/.code	={\pgfplotssetpointmetainput{x}{}},%
	/pgfplots/point meta/y/.code	={\pgfplotssetpointmetainput{y}{}},%
	/pgfplots/point meta/z/.code	={\pgfplotssetpointmetainput{z}{}},%
	/pgfplots/point meta/expr/.code={\pgfplotssetpointmetainput{expr}{#1}},%
	/pgfplots/point meta/explicit/.code={\pgfplotssetpointmetainput{explicit}{}},%
	/pgfplots/point meta/explicit symbolic/.code={\pgfplotssetpointmetainput{explicit symbolic}{}},%
	/pgfplots/point meta/f(x)/.code={\pgfplotssetpointmetainput{f(x)}{}},%
	/pgfplots/point meta/TeX code/.code={\pgfplotssetpointmetainput{TeX code}{#1}},%
	/pgfplots/point meta/TeX code/.value required,
	/pgfplots/point meta/TeX code symbolic/.code={\pgfplotssetpointmetainput{TeX code symbolic}{#1}},%
	/pgfplots/point meta/TeX code symbolic/.value required,
	/pgfplots/point meta/symbolic/.style={/pgfplots/point meta/TeX code symbolic={\def\pgfplotspointmeta{#1}}},
	/pgfplots/set point meta if empty/.code={%
		\ifx\pgfplotspointmetainputhandler\pgfutil@empty
			\pgfkeysalso{/pgfplots/point meta=#1}%
		\fi
	},%
	/pgfplots/point meta/none,
	/pgfplots/point meta rel/.is choice,
	/pgfplots/point meta rel/axis wide/.code={\def\pgfplots@perpointmeta@rel@choice{0}},%
	/pgfplots/point meta rel/per plot/.code={\def\pgfplots@perpointmeta@rel@choice{1}},%
	/pgfplots/point meta rel/axis wide,%
	/pgfplots/point meta min/.initial=,%
	/pgfplots/point meta max/.initial=,%
	/pgfplots/colormap name/.initial=hot,
	/pgfplots/colormap access/.is choice,
	/pgfplots/colormap access/direct/.code={\def\pgfplots@colormap@access{d}},%
	/pgfplots/colormap access/map/.code={\def\pgfplots@colormap@access{m}},%
	/pgfplots/colormap access/map,%
	%/pgfplots/colormap default colorspace/.initial=auto,% declared in pgfplotscolormap.code.tex
	/pgfplots/colormap/.code 2 args={%
		\pgfplotscreatecolormap{#1}{#2}%
		\pgfkeysalso{/pgfplots/colormap name=#1}%
	},
	/pgfplots/colormap/hot/.style={
		% attention: copied from pgfplots.colormap.code.tex:
		/pgfplots/colormap={hot}{color(0cm)=(blue); color(1cm)=(yellow); color(2cm)=(orange); color(3cm)=(red)}
	},
 	/pgfplots/colormap/hot2/.style={
 		/pgfplots/colormap={hot2}{[1cm]rgb255(0cm)=(0,0,0) rgb255(3cm)=(255,0,0) rgb255(6cm)=(255,255,0) rgb255(8cm)=(255,255,255)}
 	},
	/pgfplots/colormap/bluered/.style={
		/pgfplots/colormap={bluered}{rgb255(0cm)=(0,0,180); rgb255(1cm)=(0,255,255); rgb255(2cm)=(100,255,0); rgb255(3cm)=(255,255,0); rgb255(4cm)=(255,0,0); rgb255(5cm)=(128,0,0)}
	},
	/pgfplots/colormap/cool/.style={
		/pgfplots/colormap={cool}{rgb255(0cm)=(255,255,255); rgb255(1cm)=(0,128,255); rgb255(2cm)=(255,0,255)}
	},
	/pgfplots/colormap/greenyellow/.style={
		/pgfplots/colormap={greenyellow}{rgb255(0cm)=(0,128,0); rgb255(1cm)=(255,255,0)}
	},
	/pgfplots/colormap/redyellow/.style={
		/pgfplots/colormap={redyellow}{rgb255(0cm)=(255,0,0); rgb255(1cm)=(255,255,0)}
	},
	/pgfplots/colormap/blackwhite/.style={
		/pgfplots/colormap={blackwhite}{gray(0cm)=(0); gray(1cm)=(1)}
	},
	/pgfplots/colormap/violet/.style={
		/pgfplots/colormap={violet}{rgb255=(25,25,122) color=(white) rgb255=(238,140,238)}
	},
 	/pgfplots/colormap/jet/.style={
 		/pgfplots/colormap={jet}{rgb255(0cm)=(0,0,128) rgb255(1cm)=(0,0,255) rgb255(3cm)=(0,255,255) rgb255(5cm)=(255,255,0) rgb255(7cm)=(255,0,0) rgb255(8cm)=(128,0,0)}
 	},
	%
	%
	%%
	/pgfplots/scatter/.is choice,
	/pgfplots/scatter/false/.code={%
		\pgfplots@scatterplotenabledfalse
	},%
	/pgfplots/scatter/true*/.code={%
		\pgfplots@scatterplotenabledtrue
		\pgfkeysalso{/pgfplots/set point meta if empty=f(x)}%
	},%
	/pgfplots/scatter/true/.code={%
		\pgfplots@scatterplotenabledtrue
		\pgfkeysalso{/pgfplots/set point meta if empty=f(x)}%
		% make sure there is a mark set!
		\pgfplots@gettikzinternal@keyval{mark}{tikz@plot@mark}{}%
		\def\pgfplots@loc@TMPa{none}%
		\ifx\tikz@plot@mark\pgfplots@loc@TMPa
			% this here happens only in older versions of pgf.
			\pgfqkeys{/tikz}{mark=*}%
		\else
			\ifx\tikz@plot@mark\pgfutil@empty
				\pgfqkeys{/tikz}{mark=*}%
			\fi
		\fi
	},
	/pgfplots/scatter/.default=true,
	/pgfplots/scatter src/.style={/pgfplots/point meta={#1}},
	/tikz/scatter/.style={/pgfplots/scatter=#1},
	%
	% ARGUMENTS: the macros
	% - \pgfplotspointmeta
	% - \pgfplotspointmetarange
	% - \pgfplotspointmetatransformed
	% - \pgfplotspointmetatransformedrange
	% are set during @pre marker code and @post marker code.
	% '#1' is empty.
	/pgfplots/scatter/@pre marker code/.code=,%
	/pgfplots/scatter/@post marker code/.code=,%
	/pgfplots/scatter/position/.is choice,
	/pgfplots/scatter/position/absolute/.code={\def\pgfplots@scatter@position{a}},
	/pgfplots/scatter/position/relative/.code={\def\pgfplots@scatter@position{r}},
	/pgfplots/scatter/position=relative,
	/pgfplots/scatter/use mapped color/.style={%
		/pgfplots/scatter/@pre marker code/.code=,%
		/pgfplots/scatter/@post marker code/.code=,%
		/pgfplots/scatter/use mapped color*={#1},%
	},%
	/pgfplots/scatter/use mapped color*/.style={
		/pgfplots/scatter/@pre marker code/.append code={
			\pgfplotscolormapdefinemappedcolor\pgfplotspointmetatransformed
			\scope[#1]%
		},
		/pgfplots/scatter/@post marker code/.prefix code={\endscope}
	},
	/pgfplots/scatter/use mapped color*/.default={draw=mapped color!80!black,fill=mapped color},
	/pgfplots/scatter/use mapped color*,
	% expect '#1 = {<class>=<style>,<class>=<style>,...} where <class>
	% is expected as SYMBOL, not as number. See 'point meta/explicit symbolic'
	/pgfplots/scatter/classes/.style={%
		/pgfplots/scatter/@pre marker code/.code=,%
		/pgfplots/scatter/@post marker code/.code=,%
		/pgfplots/scatter/classes*={#1},%
	},%
	/pgfplots/scatter/classes*/.code={%
		% Step 1: remember the per class-styles as
		% \csname pgfp@scatter@class@<class name>\endcsname
		% -> this is done locally!
		\def\pgfplots@loc@TMPa##1=##2\pgfplots@EEOI{%
			\expandafter\def\csname pgfp@scatter@class@##1\endcsname{##2}%
		}%
		\pgfplotsforeachentryinCSV{\pgfplots@loc@TMPb}{#1}{%
			\expandafter\pgfplots@loc@TMPa\pgfplots@loc@TMPb\pgfplots@EEOI
		}%
		%
		\pgfkeysalso{%
			/pgfplots/scatter/@pre marker code/.append code={\pgfplots@scatter@classes@pre@marker@code},%
			/pgfplots/scatter/@post marker code/.prefix code={\endscope}%
		}%
		% Now:remember the classes.
		\pgfkeyssetvalue{/pgfplots/scatter/classes/values}{#1}% 
		%
		% and generate legend items for every single class,
		% But ONLY if we really *have* a plot which uses
		% scatter/classes!
		\pgfkeys{/pgfplots/execute at begin plot@@/.add={}{%
				\ifpgfplots@scatterplotenabled
					\pgfkeysgetvalue{/pgfplots/scatter/@pre marker code/.@cmd}\pgfplots@loc@TMPa
					\def\pgfplots@loc@TMPb{\pgfutil@in@{\pgfplots@scatter@classes@pre@marker@code}}%
					\expandafter\pgfplots@loc@TMPb\expandafter{\pgfplots@loc@TMPa\pgfeov}%
					\ifpgfutil@in@
						% modify '\pgfplots@rememberplotspec' such
						% that it generates entries for every class:
						\let\pgfplots@rememberplotspec@orig=\pgfplots@rememberplotspec
						\def\pgfplots@rememberplotspec##1{%
							\def\pgfplots@scatter@loc@TMPa####1=####2\pgfplots@EEOI{%
								\pgfplots@rememberplotspec@orig{##1,####2}%
								\pgfplots@rememberplotspec@for@label[####1]{##1,####2}%
							}%
							\pgfplotsforeachentryinCSV{\pgfplots@scatter@loc@TMPb}{#1}{%
								\expandafter\pgfplots@scatter@loc@TMPa\pgfplots@scatter@loc@TMPb\pgfplots@EEOI
							}%
						}%
					\fi
				\fi
			}%
		}%
	},
	/pgfplots/refstyle/.code={%
		\pgfutil@ifundefined{pgfplots@labelstyle@#1}{%
			\G@refundefinedtrue
			\@latex@warning{Reference `#1' on page \thepage \space undefined}%
		}{%
			\t@pgfplots@toka=\expandafter\expandafter\expandafter{\csname pgfplots@labelstyle@#1\endcsname}%
			\expandafter\pgfkeysalso\expandafter{\the\t@pgfplots@toka}%
		}%
	},%
	/pgfplots/forget plot/.is if=pgfplots@curplot@isirrelevant,
	/pgfplots/forget plot/.default=true,
	/pgfplots/normalsize/.style={
		/pgfplots/width=240pt,
		/pgfplots/height=207pt,
		/pgfplots/max space between ticks=35,
	},
	/pgfplots/small/.style={
		width=6.5cm,
		height=,
		tick label style={font=\footnotesize},
		label style={font=\small},
		max space between ticks=25,
	},
	/pgfplots/footnotesize/.style={
		width=5cm,
		height=,
		legend style={font=\footnotesize},
		tick label style={font=\footnotesize},
		label style={font=\small},
		title style={font=\small},
		every axis title shift=0pt,
		max space between ticks=15,
		every mark/.append style={mark size=8},
		major tick length=0.1cm,
		minor tick length=0.066cm,
	},
	/pgfplots/tiny/.style={
		width=4cm,
		height=,
		legend style={font=\tiny},
		tick label style={font=\tiny},
		label style={font=\tiny},
		title style={font=\footnotesize},
		every axis title shift=0pt,
		max space between ticks=12,
		every mark/.append style={mark size=6},
		major tick length=0.1cm,
		minor tick length=0.066cm,
		every legend image post/.append style={scale=0.8},
    },
	/pgfplots/cube/set size/.code 2 args={%
		\expandafter\def\csname pgfplots@cube@gethalf@#1\endcsname{%
			\afterassignment\pgfplots@gobble@until@relax
			\pgfplots@tmpa=#2pt\relax
			\pgfplotsconvertunittocoordinate #1{0.5\pgfplots@tmpa}%
		}%
	},%
	/pgfplots/cube/size x/.style={/pgfplots/cube/set size=x{#1}},
	/pgfplots/cube/size y/.style={/pgfplots/cube/set size=y{#1}},
	/pgfplots/cube/size z/.style={/pgfplots/cube/set size=z{#1}},
	/pgfplots/cube/size x=\pgfplotmarksize,
	/pgfplots/cube/size y=\pgfplotmarksize,
	/pgfplots/cube/size z=\pgfplotmarksize,
	/pgfplots/trig format/.style={/pgf/trig format={#1}},
	/pgfplots/xtick placement tolerance/.initial=0.05pt,
	/pgfplots/ytick placement tolerance/.initial=0.05pt,
	/pgfplots/ztick placement tolerance/.initial=0.05pt,
	%
	/pgfplots/compat/anchors/.is choice,
	/pgfplots/compat/anchors/pre 1.3/.code={\pgfplots@deprecated@anchorstrue},% FIXME: WAS \global
	/pgfplots/compat/anchors/1.3/.code= {\pgfplots@deprecated@anchorsfalse},%
	/pgfplots/compat/anchors/1.4/.style= 	{/pgfplots/compat/anchors/1.3},%
	/pgfplots/compat/anchors/1.5/.style= 	{/pgfplots/compat/anchors/1.3},%
	/pgfplots/compat/anchors/1.5.1/.style= 	{/pgfplots/compat/anchors/1.3},%
	/pgfplots/compat/anchors/1.6/.style= 	{/pgfplots/compat/anchors/1.3},%
	/pgfplots/compat/anchors/1.7/.style= 	{/pgfplots/compat/anchors/1.3},%
	/pgfplots/compat/anchors/1.8/.style= 	{/pgfplots/compat/anchors/1.3},%
	/pgfplots/compat/anchors/1.9/.style= 	{/pgfplots/compat/anchors/1.3},%
	/pgfplots/compat/anchors/1.10/.style= 	{/pgfplots/compat/anchors/1.3},%
	/pgfplots/compat/anchors/1.11/.style= 	{/pgfplots/compat/anchors/1.3},%
	/pgfplots/compat/anchors/newest/.style= {/pgfplots/compat/anchors/1.3},%
	/pgfplots/compat/anchors/default/.style={/pgfplots/compat/anchors/1.3},%
	%
	/pgfplots/compat/empty line/.is choice,
	/pgfplots/compat/empty line/pre 1.3/.code={\pgfplots@emptyline@compattrue},% FIXME: WAS \global
	/pgfplots/compat/empty line/1.3/.style= {/pgfplots/compat/empty line/pre 1.3},%
	/pgfplots/compat/empty line/1.4/.code= 	{\pgfplots@emptyline@compatfalse},%
	/pgfplots/compat/empty line/1.5/.style= 	{/pgfplots/compat/empty line/1.4},%
	/pgfplots/compat/empty line/1.5.1/.style= 	{/pgfplots/compat/empty line/1.4},%
	/pgfplots/compat/empty line/1.6/.style= 	{/pgfplots/compat/empty line/1.4},%
	/pgfplots/compat/empty line/1.7/.style= 	{/pgfplots/compat/empty line/1.4},%
	/pgfplots/compat/empty line/1.8/.style= 	{/pgfplots/compat/empty line/1.4},%
	/pgfplots/compat/empty line/1.9/.style= 	{/pgfplots/compat/empty line/1.4},%
	/pgfplots/compat/empty line/1.10/.style= 	{/pgfplots/compat/empty line/1.4},%
	/pgfplots/compat/empty line/1.11/.style= 	{/pgfplots/compat/empty line/1.4},%
	/pgfplots/compat/empty line/newest/.style=	{/pgfplots/compat/empty line/1.4},%
	/pgfplots/compat/empty line/default/.style=	{/pgfplots/compat/empty line/1.4},%
	%
	/pgfplots/compat/path replacement/.is choice,
	/pgfplots/compat/path replacement/pre 1.3/.code= {\pgfplots@path@replace@ellipsefalse},
	/pgfplots/compat/path replacement/1.3/.style=    {/pgfplots/compat/path replacement/pre 1.3},%
	/pgfplots/compat/path replacement/1.4/.style=  	 {/pgfplots/compat/path replacement/pre 1.3},
	/pgfplots/compat/path replacement/1.5/.style=    {/pgfplots/compat/path replacement/pre 1.3},%
	/pgfplots/compat/path replacement/1.5.1/.code=   {\pgfplots@path@replace@ellipsetrue},%
	/pgfplots/compat/path replacement/1.6/.style=   	{/pgfplots/compat/path replacement/1.5.1},
	/pgfplots/compat/path replacement/1.7/.style=   	{/pgfplots/compat/path replacement/1.5.1},
	/pgfplots/compat/path replacement/1.8/.style=   	{/pgfplots/compat/path replacement/1.5.1},
	/pgfplots/compat/path replacement/1.9/.style=   	{/pgfplots/compat/path replacement/1.5.1},
	/pgfplots/compat/path replacement/1.10/.style=   	{/pgfplots/compat/path replacement/1.5.1},
	/pgfplots/compat/path replacement/1.11/.style=   	{/pgfplots/compat/path replacement/1.5.1},
	/pgfplots/compat/path replacement/newest/.style= 	{/pgfplots/compat/path replacement/1.5.1},%
	/pgfplots/compat/path replacement/default/.style=	{/pgfplots/compat/path replacement/pre 1.3},%
	%
	/pgfplots/compat/pgfpoint substitution/.is choice,
	/pgfplots/compat/pgfpoint substitution/pre 1.3/.code= {\pgfplots@substitute@pgfpointfalse},
	/pgfplots/compat/pgfpoint substitution/1.3/.style=    {/pgfplots/compat/pgfpoint substitution/pre 1.3},%
	/pgfplots/compat/pgfpoint substitution/1.4/.style=  	 {/pgfplots/compat/pgfpoint substitution/pre 1.3},
	/pgfplots/compat/pgfpoint substitution/1.5/.style=    {/pgfplots/compat/pgfpoint substitution/pre 1.3},%
	/pgfplots/compat/pgfpoint substitution/1.5.1/.style=	{/pgfplots/compat/pgfpoint substitution/pre 1.3},%
	/pgfplots/compat/pgfpoint substitution/1.6/.style=   	{/pgfplots/compat/pgfpoint substitution/pre 1.3},
	/pgfplots/compat/pgfpoint substitution/1.7/.style=   	{/pgfplots/compat/pgfpoint substitution/pre 1.3},
	/pgfplots/compat/pgfpoint substitution/1.8/.style=   	{/pgfplots/compat/pgfpoint substitution/pre 1.3},
	/pgfplots/compat/pgfpoint substitution/1.9/.style=   	{/pgfplots/compat/pgfpoint substitution/pre 1.3},
	/pgfplots/compat/pgfpoint substitution/1.10/.style=   	{/pgfplots/compat/pgfpoint substitution/pre 1.3},
	/pgfplots/compat/pgfpoint substitution/1.11/.code=   	{\pgfplots@substitute@pgfpointtrue},
	/pgfplots/compat/pgfpoint substitution/newest/.style= 	{/pgfplots/compat/pgfpoint substitution/1.11},%
	/pgfplots/compat/pgfpoint substitution/default/.style=	{/pgfplots/compat/pgfpoint substitution/pre 1.3},%
	%ellipse/.is if=pgfplots@path@replace@ellipse,
	%
	/pgfplots/compat/labels/.is choice,
	/pgfplots/compat/labels/pre 1.3/.style={%
		/pgfplots/compat/axis line style pre 1.8,
		/pgfplots/xlabel absolute,
		/pgfplots/ylabel absolute},%
	/pgfplots/compat/labels/1.3/.style={%
		/pgfplots/compat/axis line style pre 1.8,
		/pgfplots/xlabel near ticks,
		/pgfplots/ylabel near ticks},%
	/pgfplots/compat/labels/1.4/.style=		{/pgfplots/compat/labels/1.3},%
	/pgfplots/compat/labels/1.5/.style=		{/pgfplots/compat/labels/1.3},%
	/pgfplots/compat/labels/1.5.1/.style=	{/pgfplots/compat/labels/1.3},%
	/pgfplots/compat/labels/1.6/.style=		{/pgfplots/compat/labels/1.3},%
	/pgfplots/compat/labels/1.7/.style=		{/pgfplots/compat/labels/1.3},%
	/pgfplots/compat/labels/1.8/.style=		{
		/pgfplots/compat/labels/1.3,
		/pgfplots/compat/axis line style post 1.8,
	},%
	/pgfplots/compat/labels/1.9/.style=		{/pgfplots/compat/labels/1.8},%
	/pgfplots/compat/labels/1.10/.style=		{/pgfplots/compat/labels/1.8},%
	/pgfplots/compat/labels/1.11/.style=		{/pgfplots/compat/labels/1.8},%
	/pgfplots/compat/labels/newest/.style=	{/pgfplots/compat/labels/1.8},%
	/pgfplots/compat/labels/default/.style=	{/pgfplots/compat/labels/pre 1.3},% maintain backwards compatibility 
	%
	/pgfplots/compat/bar nodes/.is choice,
	/pgfplots/compat/bar nodes/pre 1.3/.style={%
		/pgfplots/stacked since 1.9/.style={
			/pgfplots/stacked ignores zero=false,% backwards compatible.
		},%
		%
		% empty - early versions did not know anything about them.
		% But people might have arrived at suitable work-arounds; do
		% not destroy their work.
		/pgfplots/activate nodes near coords xbar stacked/.style={%
			/pgfplots/set point meta if empty=f(x),%
		},%
		/pgfplots/activate nodes near coords ybar stacked/.code={%
			/pgfplots/set point meta if empty=f(x),%
		},%
	},%
	/pgfplots/compat/bar nodes/1.3/.style=		{/pgfplots/compat/bar nodes/pre 1.3},%
	/pgfplots/compat/bar nodes/1.4/.style=		{/pgfplots/compat/bar nodes/pre 1.3},%
	/pgfplots/compat/bar nodes/1.5/.style=		{/pgfplots/compat/bar nodes/pre 1.3},%
	/pgfplots/compat/bar nodes/1.5.1/.style=	{/pgfplots/compat/bar nodes/pre 1.3},%
	/pgfplots/compat/bar nodes/1.6/.style=		{/pgfplots/compat/bar nodes/pre 1.3},%
	/pgfplots/compat/bar nodes/1.7/.style=		{/pgfplots/compat/bar nodes/pre 1.3},%
	/pgfplots/compat/bar nodes/1.8/.style=		{/pgfplots/compat/bar nodes/pre 1.3},%
	/pgfplots/compat/bar nodes/1.9/.style=		{
		/pgfplots/stacked since 1.9/.style={
			/pgfplots/stacked ignores zero=true,%
		},
		/pgfplots/activate nodes near coords xbar stacked/.style={
			/pgfplots/nodes near coords xbar stacked configuration,
		},
		/pgfplots/activate nodes near coords ybar stacked/.style={
			/pgfplots/nodes near coords ybar stacked configuration,
		},
	},%
	/pgfplots/compat/bar nodes/1.10/.style=		{/pgfplots/compat/bar nodes/1.9},%
	/pgfplots/compat/bar nodes/1.11/.style=		{/pgfplots/compat/bar nodes/1.9},%
	/pgfplots/compat/bar nodes/newest/.style=	{/pgfplots/compat/bar nodes/1.9},%
	/pgfplots/compat/bar nodes/default/.style=	{/pgfplots/compat/bar nodes/pre 1.3},% maintain backwards compatibility 
	/pgfplots/compat/bar nodes/default,
	%
	% search for the \pgfplots@compat@scaling@coordmath -- using float
	% is much more accurate. But it changes the spacing slightly.
	/pgfplots/compat/scaling/.is choice,
	/pgfplots/compat/scaling/pre 1.3/.code={%
		\def\pgfplots@compat@scaling@zunitfix@enable{0}%
		\def\pgfplots@compat@scaling@coordmath{pgfbasic}%
		\def\pgfplots@compat@scaling@coordmath@final{pgfbasic}%
	},
	/pgfplots/compat/scaling/1.3/.style={/pgfplots/compat/scaling/pre 1.3},
	/pgfplots/compat/scaling/1.4/.code={%
		\def\pgfplots@compat@scaling@zunitfix@enable{1}%
		\def\pgfplots@compat@scaling@coordmath{float}%
		\def\pgfplots@compat@scaling@coordmath@final{pgfbasic}%
	},
	/pgfplots/compat/scaling/1.5/.style={/pgfplots/compat/scaling/1.4},
	/pgfplots/compat/scaling/1.5.1/.style={/pgfplots/compat/scaling/1.4},
	/pgfplots/compat/scaling/1.6/.code={%
		\def\pgfplots@compat@scaling@zunitfix@enable{1}%
		\def\pgfplots@compat@scaling@coordmath{float}%
		\def\pgfplots@compat@scaling@coordmath@final{float}%
	},
	/pgfplots/compat/scaling/1.7/.style={/pgfplots/compat/scaling/1.6},
	/pgfplots/compat/scaling/1.8/.style={/pgfplots/compat/scaling/1.6},
	/pgfplots/compat/scaling/1.9/.style={/pgfplots/compat/scaling/1.6},
	/pgfplots/compat/scaling/1.10/.style={/pgfplots/compat/scaling/1.6},
	/pgfplots/compat/scaling/1.11/.style={/pgfplots/compat/scaling/1.6},
	/pgfplots/compat/scaling/newest/.style={/pgfplots/compat/scaling/1.6},
	/pgfplots/compat/scaling/default/.style={/pgfplots/compat/scaling/1.4},
	%
	/pgfplots/compat/scale mode/.is choice,
	/pgfplots/compat/scale mode/pre 1.3/.code=\def\pgfplots@compat@scale@mode@compatible@mode{1},%
	/pgfplots/compat/scale mode/1.3/.style=		{/pgfplots/compat/scale mode/pre 1.3},
	/pgfplots/compat/scale mode/1.4/.style=		{/pgfplots/compat/scale mode/pre 1.3},
	/pgfplots/compat/scale mode/1.5/.style=	 	{/pgfplots/compat/scale mode/pre 1.3},
	/pgfplots/compat/scale mode/1.5.1/.style=	{/pgfplots/compat/scale mode/pre 1.3},
	/pgfplots/compat/scale mode/1.6/.code=\def\pgfplots@compat@scale@mode@compatible@mode{0},
	/pgfplots/compat/scale mode/1.7/.style={/pgfplots/compat/scale mode/1.6},
	/pgfplots/compat/scale mode/1.8/.style={/pgfplots/compat/scale mode/1.6},
	/pgfplots/compat/scale mode/1.9/.style={/pgfplots/compat/scale mode/1.6},
	/pgfplots/compat/scale mode/1.10/.style={/pgfplots/compat/scale mode/1.6},
	/pgfplots/compat/scale mode/1.11/.style={/pgfplots/compat/scale mode/1.6},
	/pgfplots/compat/scale mode/newest/.style={/pgfplots/compat/scale mode/1.6},
	/pgfplots/compat/scale mode/default/.style={/pgfplots/compat/scale mode/1.5},
	%
	%
	/pgfplots/compat/plot3graphics/.is choice,
	/pgfplots/compat/plot3graphics/pre 1.3/.style=	{/pgfplots/compat/plot3graphics/1.5},
	/pgfplots/compat/plot3graphics/1.3/.style=		{/pgfplots/compat/plot3graphics/1.5},
	/pgfplots/compat/plot3graphics/1.4/.style=		{/pgfplots/compat/plot3graphics/1.5},%
	/pgfplots/compat/plot3graphics/1.5/.code=		{\def\b@pgfplots@compat@plot@graphics@threedim{1}},%
	/pgfplots/compat/plot3graphics/1.5.1/.style=	{/pgfplots/compat/plot3graphics/1.5},%
	/pgfplots/compat/plot3graphics/1.6/.code=		{\def\b@pgfplots@compat@plot@graphics@threedim{2}},%
	/pgfplots/compat/plot3graphics/1.7/.style=	{/pgfplots/compat/plot3graphics/1.6},%
	/pgfplots/compat/plot3graphics/1.8/.style=	{/pgfplots/compat/plot3graphics/1.6},%
	/pgfplots/compat/plot3graphics/1.9/.style=	{/pgfplots/compat/plot3graphics/1.6},%
	/pgfplots/compat/plot3graphics/1.10/.style=	{/pgfplots/compat/plot3graphics/1.6},%
	/pgfplots/compat/plot3graphics/1.11/.style=	{/pgfplots/compat/plot3graphics/1.6},%
	/pgfplots/compat/plot3graphics/newest/.style=	{/pgfplots/compat/plot3graphics/1.6},%
	/pgfplots/compat/plot3graphics/default/.style=	{/pgfplots/compat/plot3graphics/1.5},%
	%
	% ATTENTION: there is a compatibility issue which slipped through
	% the quality assurance: if tick labels where generated in scientific notation
	% (NOT log tick labels; these are special), and the numbers were
	% negative, the spacing changed as follows:
	% pre 1.3:  - 1*10^5  (binary minus sign)
	%     1.3:  - 1*10^5  (binary minus sign)
	%     1.4:  - 1*10^5  (binary minus sign)
	%     1.5:  -1*10^5   (unary minus sign - correct!)
	%     1.6:  -1*10^5   (unary minus sign - correct!)
	% This is (was) a bug in the PGF number printer which has been
	% fixed in the meantime; it occurred only if
	% $\pgfmathprintnumber{-1e5}$ was used (i.e. with the '$' signs).
	% Unfortunately, version 1.5 has been released without realizing
	% the changes; I detected them right before the release of 1.6.
	% Consequently, I cannot introduce compatibity switches without
	% loosing compatibility.
	%
	% I chose to keep the correct unary minus sign. If you ever want 
	% to revert to the old version in order to keep spacing intact, use
	%  
	% \pgfkeys{/pgf/compat/number printer=2.10}
	%
	% Risk: the size of such tick labels changed and the
	% figure has been moved somewhat.
	%
	% Sorry.
	%
	/pgfplots/compat/bar width by units/.is choice,
	/pgfplots/compat/bar width by units/pre 1.3/.code=	{\def\b@pgfplots@compat@bar@width@units{1}},%
	/pgfplots/compat/bar width by units/1.3/.style=	{/pgfplots/compat/bar width by units/pre 1.3},
	/pgfplots/compat/bar width by units/1.4/.style=	{/pgfplots/compat/bar width by units/pre 1.3},%
	/pgfplots/compat/bar width by units/1.5/.style=	{/pgfplots/compat/bar width by units/pre 1.3},%
	/pgfplots/compat/bar width by units/1.5.1/.style=	{/pgfplots/compat/bar width by units/pre 1.3},%
	/pgfplots/compat/bar width by units/1.6/.style=	{/pgfplots/compat/bar width by units/pre 1.3},%
	/pgfplots/compat/bar width by units/1.7/.code=		{\def\b@pgfplots@compat@bar@width@units{0}},%
	/pgfplots/compat/bar width by units/1.8/.style=		{/pgfplots/compat/bar width by units/1.7},
	/pgfplots/compat/bar width by units/1.9/.style=		{/pgfplots/compat/bar width by units/1.7},
	/pgfplots/compat/bar width by units/1.10/.style=		{/pgfplots/compat/bar width by units/1.7},
	/pgfplots/compat/bar width by units/1.11/.style=		{/pgfplots/compat/bar width by units/1.7},
	/pgfplots/compat/bar width by units/newest/.style=	{/pgfplots/compat/bar width by units/1.7},
	/pgfplots/compat/bar width by units/default/.style={/pgfplots/compat/bar width by units/pre 1.3},
	%
	/pgfplots/compat/BB/.is choice,
	/pgfplots/compat/BB/pre 1.3/.style={/pgfplots/clip bounding box=default tikz},%
	/pgfplots/compat/BB/1.3/.style=	{/pgfplots/compat/BB/pre 1.3},
	/pgfplots/compat/BB/1.4/.style=	{/pgfplots/compat/BB/pre 1.3},%
	/pgfplots/compat/BB/1.5/.style=	{/pgfplots/compat/BB/pre 1.3},%
	/pgfplots/compat/BB/1.5.1/.style=	{/pgfplots/compat/BB/pre 1.3},%
	/pgfplots/compat/BB/1.6/.style=	{/pgfplots/compat/BB/pre 1.3},%
	/pgfplots/compat/BB/1.7/.style=	{/pgfplots/compat/BB/pre 1.3},%
	/pgfplots/compat/BB/1.8/.style=	{/pgfplots/clip bounding box=upper bound},%
	/pgfplots/compat/BB/1.9/.style=	{/pgfplots/compat/BB/1.8},%
	/pgfplots/compat/BB/1.10/.style=	{/pgfplots/compat/BB/1.8},%
	/pgfplots/compat/BB/1.11/.style=	{/pgfplots/compat/BB/1.8},%
	/pgfplots/compat/BB/newest/.style=	{/pgfplots/compat/BB/1.8},
	/pgfplots/compat/BB/default/.style={/pgfplots/compat/BB/pre 1.3},
	%
	/pgfplots/compat/general/.is choice,
	/pgfplots/compat/general/pre 1.3/.style={/pgfplots/log origin=infty,/pgfplots/enable tick line clipping=true},%
	/pgfplots/compat/general/1.3/.style=	{/pgfplots/compat/general/pre 1.3},
	/pgfplots/compat/general/1.4/.style=	{/pgfplots/compat/general/pre 1.3},%
	/pgfplots/compat/general/1.5/.style=	{/pgfplots/log origin=0,/pgfplots/enable tick line clipping=true},%
	/pgfplots/compat/general/1.5.1/.style=	{/pgfplots/compat/general/1.5},%
	/pgfplots/compat/general/1.6/.style=	{/pgfplots/compat/general/1.5},%
	/pgfplots/compat/general/1.7/.style=	{/pgfplots/compat/general/1.5},%
	/pgfplots/compat/general/1.8/.style=	{/pgfplots/compat/general/1.5},%
	/pgfplots/compat/general/1.9/.style=	{/pgfplots/compat/general/1.5},%
	/pgfplots/compat/general/1.10/.style=	{/pgfplots/compat/general/1.5},%
	/pgfplots/compat/general/1.11/.style=	{/pgfplots/compat/general/1.5,/pgfplots/enable tick line clipping=false},%
	/pgfplots/compat/general/newest/.style=	{/pgfplots/compat/general/1.11},
	/pgfplots/compat/general/default/.style={/pgfplots/compat/general/1.11},
	%
	/pgfplots/enable tick line clipping/.is if=pgfplots@enable@tick@line@clipping,
	/pgfplots/enable tick line clipping/.default=true,
	%
	/pgfplots/default typeset ticklabel/.style={
		/pgfplots/typeset ticklabel/.code={##1},
	},
	/pgfplots/default typeset ticklabel,
	/pgfplots/typeset ticklabels with strut/.style={
		/pgfplots/typeset ticklabel/.code={\strut ##1},
	},
	%
	%
	/pgfplots/compat/show suggested version/.is if=pgfplots@show@suggested@version,
	/pgfplots/compat/show suggested version=true,
	/pgfplots/compat/current/.initial=,
	/pgfplots/compat/mostrecent/.initial=1.11,
	/pgfplots/compat/.style={%
		% ATTENTION: *every* /pgfplots/compat/ setting needs to accept
		% the same choices due to this construction:
		/pgfplots/compat/current=#1,% remember the value
		/pgfplots/compat/anchors=#1,%
		/pgfplots/compat/labels=#1,%
		/pgfplots/compat/empty line=#1,%
		/pgfplots/compat/scaling=#1,%
		/pgfplots/compat/scale mode=#1,%
		/pgfplots/compat/general=#1,%
		/pgfplots/compat/BB=#1,%
		/pgfplots/compat/path replacement=#1,%
		/pgfplots/compat/plot3graphics=#1,%
		/pgfplots/compat/bar width by units=#1,%
		/pgfplots/compat/bar nodes=#1,%
		/pgfplots/compat/pgfpoint substitution=#1,%
	},%
	/pgfplots/compat/.default=pre 1.3,% this is used if you type '\pgfplotsset{compat}' without value
	/pgfplots/compat=default,% this is the initial config.
	%
	/pgfplots/show outer normals/.style={%
		extra description/.append code={
			\def\length{15}
			\def\pgfplots@@draw@normal####1####2{%
				\pgfpathmoveto{####1}
				\pgfpathlineto{%
					\pgfpointadd
					{####1}
					{\pgfqpointscale{\length}{\pgfplotspointouternormalvectorofticklabelaxis{####2}}}%
				}%
			}%
			\draw[->,blue] \pgfextra{\pgfplots@@draw@normal{#1}{x}};
			\draw[->,blue] \pgfextra{\pgfplots@@draw@normal{\pgfplotsqpointoutsideofticklabelaxisrel{x}{1}{0}}{x}};
			\draw[->,red] \pgfextra{\pgfplots@@draw@normal{#1}{y}};
			\draw[->,red] \pgfextra{\pgfplots@@draw@normal{\pgfplotsqpointoutsideofticklabelaxisrel{y}{1}{0}}{y}};
			\ifpgfplots@threedim
			\draw[->,black] \pgfextra{\pgfplots@@draw@normal{#1}{z}};
			\draw[->,black] \pgfextra{\pgfplots@@draw@normal{\pgfplotsqpointoutsideofticklabelaxisrel{z}{1}{0}}{z}};
			\fi
		},
	},
	/pgfplots/show outer normals/.default={%
		\ifpgfplots@threedim
			\pgfplotspointrelaxisxy{-0.03}{-0.03}%
		\else
			\pgfplotspointrelaxisxyz{-0.03}{-0.03}{-0.03}%
		\fi
	},
	/pgfplots/profiler/.code={%
		\pgfutil@ifundefined{pgfprofilenew}{%
			\usepgflibrary{profiler}%
		}{}%
		\pgfprofilenewforenvironment[all axes]{pgfplots@environment@opt}%
		\pgfprofilesetrel{all axes}%
		\pgfprofilenewforcommand[pgfkeys variants]{\pgfkeys}{1}%
		\pgfprofilenewforcommand[pgfkeys variants]{\pgfqkeys}{2}%
		\pgfprofilenewforcommand[pgfkeys variants]{\pgfkeysalso}{1}%
		\pgfprofilenewforcommand[pgfkeys variants]{\pgfkeysfiltered}{1}%
		\pgfprofilenewforcommand[pgfkeys variants]{\pgfqkeysfiltered}{2}%
		\pgfprofilenewforcommand[pgfkeys variants]{\pgfkeysalsofiltered}{1}%
		\pgfprofilenewforcommand[pgfplotsapplistXX handling]{\pgfplotsapplistXXpushback}{1}%
		\pgfprofilenewforcommand[pgfplotsapplistXX handling]{\pgfplotsapplistXXflushbuffers}{0}%
		\pgfprofilenewforcommandpattern
				[pgfplots(app|prepend)listX handling]{\pgfplotsapplistXpushback}{##1\to##2}{{##1}\to{##2}}%
		\pgfprofilenewforcommand
				[pgfplots(app|prepend)listX handling]{\pgfplotsapplistXflushbuffers}{1}%
		\pgfprofilenewforcommandpattern
				[pgfplots(app|prepend)listX handling]{\pgfplotsprependlistXpushfront}{##1\to##2}{{##1}\to{##2}}%
		\pgfprofilenewforcommand
				[pgfplots(app|prepend)listX handling]{\pgfplotsprependlistXflushbuffers}{1}%
		\pgfprofilenewforcommand
				[pgfsys buffer]{\pgfsyssoftpath@addtocurrentpath}{1}%
		\pgfprofilenewforcommand
				[pgfsys buffer]{\pgfsyssoftpath@flushcurrentpath}{0}%
		\pgfprofilenewforcommand[math parser (basic)]{\pgfmathparse}{1}%
		\pgfprofilenewforcommand[math parser (fpu)]{\pgfmathfloatparse@}{1}%
		\pgfprofilenewforcommand[math: division (basic)]{\pgfmathdivide@}{2}%
		\pgfprofilenewforcommand[math: division (basic)]{\pgfmath@basic@divide@}{2}%
		\pgfprofilenewforcommand[near ticklabel anchors]{\pgfplots@borderanchor@for@axis}{3}%
		\pgfprofilenewforcommand[ticklabel cs]{\pgfplotspointticklabelcs}{2}%
	%	\pgfprofilenewforcommand[binary conversion]{\pgfplotsbinaryencodeunsigned}{1}%
	%	\pgfprofilenewforcommand[binary conversion]{\pgfplotsbinaryencodesignedmaplinearly}{1}%
	%	\pgfprofilenewforcommand[binary conversion]{\pgfplotsbinaryencodedimenmaplinearly}{1}%
	},%
}

\def\pgfplots@ticklabel@typeset@arg#1{\pgfkeysvalueof{/pgfplots/typeset ticklabel/.@cmd}{#1}\pgfeov}%

% backwards compatibility:
\def\pgfplots@tickwidth{\pgfkeysvalueof{/pgfplots/major tick length}}%
\def\pgfplots@subtickwidth{\pgfkeysvalueof{/pgfplots/minor tick length}}%

\pgfkeysgetvalue{/pgfplots/colorbar/draw/.@cmd}\pgfplots@colorbar@draw@defaultimpl

% call 
%   \pgfkeyslet{.../.@cmd}\pgfplots@cant@set@in@this@context
% to replace a key with a generic error message.
\def\pgfplots@cant@set@in@this@context#1\pgfeov{\pgfplots@cant@set@in@this@context@}
\def\pgfplots@cant@set@in@this@context@{%
	\pgfplotsthrow{unsupported operation}{Sorry, you can't change `\pgfkeyscurrentkeyRAW' in this context. Maybe you need to provide it as \string\begin{axis}[\pgfkeyscurrentkeyRAW=...] ?}\pgfeov
}


{
\pgfkeysdef{/empty}{}%
\pgfkeysgetvalue{/empty/.@cmd}\pgfplots@loc@TMPa
\global\let\pgfplots@empty@command@key=\pgfplots@loc@TMPa
%
\pgfkeys{/empty/.style={}}%
\pgfkeysgetvalue{/empty/.@cmd}\pgfplots@loc@TMPa
\global\let\pgfplots@empty@style@key=\pgfplots@loc@TMPa
}

% Only define if it is undefined. It may be possible that related libraries
% habe been loaded before pgfplots.
\pgfkeysifdefined{/pgfplots/@backgroundpath@hook/.@cmd}{\relax}{%
	\pgfkeysdef{/pgfplots/@backgroundpath@hook}{}%
}

\def\pgfplots@cmdkey@alias#1=#2;{%
	\pgfkeysgetvalue{/pgfplots/#2/.@cmd}\pgfplots@glob@TMPa
	\pgfkeyslet{/pgfplots/#1/.@cmd}\pgfplots@glob@TMPa
}%
\pgfplots@cmdkey@alias xlabel style=x label style;
\pgfplots@cmdkey@alias ylabel style=y label style;
\pgfplots@cmdkey@alias zlabel style=z label style;
\pgfplots@cmdkey@alias xticklabel style=x tick label style;
\pgfplots@cmdkey@alias yticklabel style=y tick label style;
\pgfplots@cmdkey@alias zticklabel style=z tick label style;
\pgfplots@cmdkey@alias ticklabel style=tick label style;
%\pgfplots@cmdkey@alias xtick scale label style=x tick scale label style;
%\pgfplots@cmdkey@alias ytick scale label style=y tick scale label style;
\pgfplots@cmdkey@alias xtick style=x tick style;
\pgfplots@cmdkey@alias ytick style=y tick style;
\pgfplots@cmdkey@alias ztick style=z tick style;


% A backwards compatibility method which works as follows:
% if any user specified arguments exist for the 'domain' or 'samples
% at' or 'samples' keys, nothing is done.
%
% It these keys are empty, we switch to backwards compatibility mode
% and acquire the key settings from tikz.
%
% This allows something like
% \begin{tikzpicture}[samples=70,domain=1:5]
%   \begin{axis}
%		\addplot {x^2};
%   \end{axis}
% \end{tikzpicture}
%
%  POSTCONDITION:
%  		- \pgfplots@plot@domain = value of '/pgfplots/domain',
%  		- \pgfplots@plot@samples@at = the value of	'/pgfplots/samples at',
%  		- \pgfplots@plot@samples = value of '/pgfplots/samples',
%  	the values after any backwards compatibility issues will be used.
\def\pgfplots@validate@plot@domain@arguments{%
	\pgfkeysgetvalue{/pgfplots/samples}\pgfplots@plot@samples
	\ifx\pgfplots@plot@samples\pgfutil@empty
		\pgfplots@gettikzinternal@keyval{samples}{tikz@plot@samples}{25}%
		\pgfkeyslet{/pgfplots/samples}{\tikz@plot@samples}%
		\let\pgfplots@plot@samples=\tikz@plot@samples
		\def\pgfplots@loc@TMPa{0}% <- whether the tikz backw. compatibility shall resample
	\else
		\def\pgfplots@loc@TMPa{1}%
	\fi
	\pgfkeysgetvalue{/pgfplots/domain}\pgfplots@plot@domain
	\pgfkeysgetvalue{/pgfplots/samples at}\pgfplots@plot@samples@at
	\ifx\pgfplots@plot@domain\pgfutil@empty
		% simply acquire /tikz/domain value:
		\pgfplots@gettikzinternal@keyval{domain}{tikz@plot@domain}{-5:5}%
		\pgfkeyslet{/pgfplots/domain}{\tikz@plot@domain}%
		\let\pgfplots@plot@domain=\tikz@plot@domain
		%
		\ifx\pgfplots@plot@samples@at\pgfutil@empty
			\if 1\pgfplots@loc@TMPa
				% Resample! See above.
				\tikzset{%
					/pgf/fpu/output format=fixed,% seems as if /tikz/samples calls register arithmetics.
					samples=\pgfplots@plot@samples,
					/pgf/fpu/output format=float,%
				}%
			\fi
			\pgfplots@gettikzinternal@keyval{samples at}{tikz@plot@samplesat}{-5,-4.6,...,5}%
			\pgfkeyslet{/pgfplots/samples at}{\tikz@plot@samplesat}%
			\let\pgfplots@plot@samples@at=\tikz@plot@samplesat
		\else
			% routines should use \pgfplots@plot@samples@at.
		\fi
	\fi
	% do that such that any active ':' sign will be expanded - for
	% french babel support.
	\edef\pgfplots@plot@domain{\pgfplots@plot@domain}%
	\pgfkeyslet{/pgfplots/domain}\pgfplots@plot@domain
}%

\def\pgfplots@set@at#1{\def\pgfplots@at{#1}}%


% DEPRECATED
\long\def\axispreset#1{%
	\pgfplotsset{every axis/.append style={#1}}%
}
% DEPRECATED
\long\def\legendpreset#1{%
	\pgfplots@error{Sorry, legendpreset is now deprecated, along with the legend options text width and font. Legends are now TikZ-matrizes which provide better alignment and can be placed horizontally. See the manual for details.}%
}

% #1: axis (x, y, or z)
% #2: display name of context information
\def\pgfplots@warn@if@log@basis@unset#1#2{%
	\pgfplots@if{pgfplots@#1islinear}{%
	}{%
		\pgfplots@warn@if@log@basis@unset@{#1}{#2}%
	}%
}%
\def\pgfplots@warn@if@log@basis@unset@#1#2{%
	\pgfkeysgetvalue{/pgfplots/log basis #1}\pgfplots@loc@TMPa
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\pgfplotswarning{log basis required}{#1}{#2}\pgfeov
	\fi
	\gdef\pgfplots@warn@if@log@basis@unset##1##2{}%
}%


% #1 axis (x or y)
% #2 the label
\long\def\pgfplots@show@label#1#2{%
	\begingroup
	% Prepare special alignment features here.
	%
	% The idea is to:
	% 1. Declare a local COORDINATE SYSTEM to place labels, 
	% the 'ticklabel cs' for the current axis.
	% It takes 1-2 arguments where the first is the coordinate on the
	% ticklabel axis (between 0 and 1). The second is an optional shift orthogonal to
	% the axis in direction of the outer normal. The minimum shift is
	% the largest' ticklabels dimension.
	%
	% 2. Declare a local ANCHOR to align labels, the 'near ticklabel'
	% anchor.
	%
	% Both things are not necessary - but they *can* be used.
	\tikzdeclarecoordinatesystem{ticklabel}{\pgfplotspointticklabelcs[\pgfkeysvalueof{/pgfplots/#1label shift}]{#1}{##1}}%
	\tikzdeclarecoordinatesystem{ticklabel*}{\pgfplotspointticklabelnoshiftcs{#1}{##1}}%
	\pgfplotsdeclareborderanchorforticklabelaxis{#1}{near ticklabel}%
	%
	\pgfkeysgetvalue{/tikz/sloped/.@cmd}\pgfplots@loc@TMPa
	\pgfkeyslet{/tikz/sloped/orig/.@cmd}\pgfplots@loc@TMPa
	\pgfkeysdef{/tikz/sloped}{\pgfkeysalso{/tikz/sloped like #1 axis={##1}}}%
	%
	\node 
		[/pgfplots/every axis label,%
		/pgfplots/every axis #1 label]
	{#2};
	\endgroup
}


\long\def\pgfplots@show@title#1{%
	\node%
		[/pgfplots/every axis title]
		{#1};
}


% #1: the 'a' axis on the oriented surface (the same as \pgfplotspointonorientedsurfaceA)
% #2: the 'b' axis on the orentied surface (the same as \pgfplotspointonorientedsurfaceB)
\def\pgfplots@drawaxis@innerlines@onorientedsurf#1#2#3{%
	\if2\csname pgfplots@#1axislinesnum\endcsname
		\draw[/pgfplots/every inner #1 axis line,%
			decorate,%
			#1discont,%
			decoration={%
				% these keys appears to be checked via an \ifx on
				% '0pt'. Make sure that this \ifx works by means of
				% the expand twice construction:
				pre length/.expand twice=\csname #1disstart\endcsname,%
				post length/.expand twice=\csname #1disend\endcsname%
			}]
		\pgfextra
		\csname pgfplotspointonorientedsurfaceabsetupforset#3\endcsname{\csname pgfplots@logical@ZERO@#3\endcsname}{2}%
		\pgfpathmoveto{\pgfplotspointonorientedsurfaceab{\csname pgfplots@#1min\endcsname}{\csname pgfplots@logical@ZERO@#2\endcsname}}%
		\pgfpathlineto{\pgfplotspointonorientedsurfaceab{\csname pgfplots@#1max\endcsname}{\csname pgfplots@logical@ZERO@#2\endcsname}}%
		\endpgfextra
		;
	\fi
}%

% Ok, we don't mind whether edges with thick lines look ugly. We just
% draw separate lines. This here is necessary if we want arrow heads.
%
% #1: the 'a' axis on the oriented surface (the same as \pgfplotspointonorientedsurfaceA)
% #2: the 'b' axis on the oriented surface (the same as \pgfplotspointonorientedsurfaceB)
\def\pgfplots@drawaxis@outerlines@separate@onorientedsurf#1#2{%
	\if2\csname pgfplots@#1axislinesnum\endcsname
		% centered axis lines handled elsewhere.
	\else
	\scope[/pgfplots/every outer #1 axis line,
		#1discont,decoration={pre length/.expand twice=\csname #1disstart\endcsname, post length/.expand twice=\csname #1disend\endcsname}]
		\pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn{0}{%
			\draw decorate {
				\pgfextra
				% exchange roles of A <-> B axes:
				\pgfplotspointonorientedsurfaceabsetupfor{#2}{#1}{\pgfplotspointonorientedsurfaceN}%
				\pgfplots@drawgridlines@onorientedsurf@fromto{\csname pgfplots@#2min\endcsname}%
				\endpgfextra 
				};
		}{}%
		\pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn{1}{%
			\draw decorate {
				\pgfextra
				% exchange roles of A <-> B axes:
				\pgfplotspointonorientedsurfaceabsetupfor{#2}{#1}{\pgfplotspointonorientedsurfaceN}%
				\pgfplots@drawgridlines@onorientedsurf@fromto{\csname pgfplots@#2max\endcsname}%
				\endpgfextra 
				};
		}{}%
	\endscope
	\fi
}%

% This here is complicated: we try to create good edges and draw a
% SINGLE path for the partial or complete rectangle
%
%  -----
%  |   |
%  |   |
%  -----
%
%  ATTENTION: this thing is used IF AND ONLY IF  d=2 and the axis is
%  drawn as box.
\def\pgfplots@drawaxis@outerlines@cycledpath{%
	\pgfplots@loc@tmptrue
	\ifpgfplots@hide@x
		\ifpgfplots@hide@y
			\pgfplots@loc@tmpfalse
		\fi
	\fi
\ifpgfplots@loc@tmp
	\draw[
		/pgfplots/every outer x axis line, % using these outer styles is only useful in conjunction with 'separate axis lines=true'
		/pgfplots/every outer y axis line]
	\pgfextra\pgfpathmoveto{\pgfplotsqpointxy{\pgfplots@xmin}{\pgfplots@ymin}}\endpgfextra
\ifpgfplots@hide@y
	{ \pgfextra\pgfpathmoveto{\pgfplotsqpointxy{\pgfplots@xmin}{\pgfplots@ymax}}\endpgfextra }
\else
	decorate [ydiscont,decoration={pre length=\ydisstart, post length=\ydisend}]
	% { -- (\pgfplots@xmin,	\pgfplots@ymax) }
	{ \pgfextra\pgfpathlineto{\pgfplotsqpointxy{\pgfplots@xmin}{\pgfplots@ymax}}\endpgfextra }
\fi
\ifpgfplots@hide@x
	%{ (\pgfplots@xmax,	\pgfplots@ymax) }
	{ \pgfextra\pgfpathmoveto{\pgfplotsqpointxy{\pgfplots@xmax}{\pgfplots@ymax}}\endpgfextra }
\else
	decorate [xdiscont,decoration={pre length=\xdisstart, post length=\xdisend}] 
	%{ -- (\pgfplots@xmax,	\pgfplots@ymax) }
	{ \pgfextra\pgfpathlineto{\pgfplotsqpointxy{\pgfplots@xmax}{\pgfplots@ymax}}\endpgfextra }
\fi
\ifpgfplots@hide@y
	%{ (\pgfplots@xmax,	\pgfplots@ymin) }
	{ \pgfextra\pgfpathmoveto{\pgfplotsqpointxy{\pgfplots@xmax}{\pgfplots@ymin}}\endpgfextra }
\else
	decorate [ydiscont,decoration={pre length=\ydisend, post length=\ydisstart}] 
	%{ -- (\pgfplots@xmax,	\pgfplots@ymin) }
	{ \pgfextra\pgfpathlineto{\pgfplotsqpointxy{\pgfplots@xmax}{\pgfplots@ymin}}\endpgfextra }
\fi
\ifpgfplots@hide@x
	%{ (\pgfplots@xmin,	\pgfplots@ymin) }
	{ \pgfextra\pgfpathmoveto{\pgfplotsqpointxy{\pgfplots@xmin}{\pgfplots@ymin}}\endpgfextra }
\else
	decorate [xdiscont,decoration={pre length=\xdisend, post length=\xdisstart}] 
	%{ -- (\pgfplots@xmin,	\pgfplots@ymin) }
	{ \pgfextra\pgfpathlineto{\pgfplotsqpointxy{\pgfplots@xmin}{\pgfplots@ymin}}\endpgfextra }
\fi
	% make sure that we do not have any of the axis discontinuities
	% here - they should not be closed.
	\if0\pgfplots@xaxisdiscontnum
		\if0\pgfplots@yaxisdiscontnum
			-- cycle
		\fi
	\fi
	;%
\fi
}%

% Assigns the macros
% #1disstart
% #1disend
% and the key /tikz/#1discont  for use in the axis line routines.
%
% #1 : either x or y.
\def\pgfplots@drawaxis@lines@preparediscont@for#1{%
	\ifnum\csname pgfplots@#1axisdiscontnum\endcsname>0
		\begingroup
		% this group employs several temporary dimension registers
		% and is therefor scoped:
		\let\disstart=\pgf@ya
		\let\disend=\pgf@yb
		\disend=\csname pgfplots@#1max@reg\endcsname
		\advance\disend by -\csname pgfplots@#1min@reg\endcsname
		\disend=\csname pgfplots@#1@veclength\endcsname\disend
		\ifcase\csname pgfplots@#1axisdiscontnum\endcsname\relax
			% has already been checked above.
		\or
			\def\discontstyle{decoration={zigzag,segment length=12pt, amplitude=4pt}}%
			\advance \disend by -16pt
		\or
			\def\discontstyle{decoration={ticks,segment length=4pt, amplitude=8pt}}%
			\advance \disend by -8pt
		\fi
		\pgfplotscoordmath{#1}{datascaletrafo get params}%
		% if #1max + shift < 0pt  (shift is 0 without the scaling trafo)
		\ifdim\csname pgfplots@#1max@reg\endcsname<-\pgfplotsretvalb pt
			% swap start and end
			\disstart=\disend
			\disend=4pt
		\else
			\disstart=4pt
		\fi
		% carry local computations outside of group:
		\xdef\pgfplots@glob@TMPa{%
			\noexpand\def\expandafter\noexpand\csname #1disstart\endcsname{\the\disstart}%
			\noexpand\def\expandafter\noexpand\csname #1disend\endcsname{\the\disend}%
			\noexpand\pgfkeysdef{/tikz/#1discont}{\noexpand\pgfkeysalso{\discontstyle}}%
		}%
		\endgroup
		\pgfplots@glob@TMPa
	\else
		\expandafter\def\csname #1disstart\endcsname{0pt}%
		\expandafter\def\csname #1disend\endcsname{0pt}%
		\pgfkeyslet{/tikz/#1discont}=\pgfutil@empty
	\fi
}%

\def\pgfplots@rememberplotspec@for@label{\pgfplotsutil@ifnextchar[{\pgfplots@rememberplotspec@for@label@}{\pgfplots@rememberplotspec@for@label@[]}}%
\def\pgfplots@rememberplotspec@for@label@[#1]#2{%
	\t@pgfplots@tokc={#2}% this token register stuff allows '#' inside of '#2'
	\expandafter\xdef\csname pgfplots@last@plot@style@#1\endcsname{\the\t@pgfplots@tokc}%
	\global\pgfplots@has@label@informationtrue
}%
\def\pgfplots@rememberplotspec{\pgfplotsutil@ifnextchar[{\pgfplots@rememberplotspec@opt}{\pgfplots@rememberplotspec@opt[]}}%
\def\pgfplots@rememberplotspec@opt[#1]#2{%
	\pgfplots@rememberplotspec@for@label[#1]{#2}%
	\pgfplotslistpushbackglobal{#2}\to\pgfplots@plotspeclist
}

\def\pgfplots@getautoplotspec into#1{%
	\begingroup
	\let#1=\pgfutil@empty
	\pgfkeysgetvalue{/pgfplots/cycle multi list/@dim}\pgfplots@cycle@dim
	%
	\let\pgfplots@listindex=\pgfplots@numplots
	\pgfkeysgetvalue{/pgfplots/cycle list shift}\pgfplots@listindex@shift
	\ifx\pgfplots@listindex@shift\pgfutil@empty
	\else
		\c@pgf@counta=\pgfplots@listindex\relax
		\advance\c@pgf@counta by\pgfplots@listindex@shift\relax
		\ifnum\c@pgf@counta<0
			\c@pgf@counta=-\c@pgf@counta
		\fi
		\edef\pgfplots@listindex{\the\c@pgf@counta}%
	\fi
	\ifnum\pgfplots@cycle@dim>0
		% use the 'cycle multi list' feature.
		%
		% it employs a scalar -> multiindex map like
		% void fromScalar( size_t d, size_t scalar, size_t* Iout, const size_t* N )
		% {
		% 	size_t ret=scalar;
		% 	for( int i = d-1; i>=0; --i ) {
		% 		Iout[i] = ret % N[i];
		% 		ret /= N[i];
		% 	}
		% }
		% to get the different indices into the cycle lists.
		%-------------------------------------------------- 
		\c@pgf@counta=\pgfplots@cycle@dim\relax
		\c@pgf@countb=\pgfplots@listindex\relax
		\advance\c@pgf@counta by-1
		\pgfplotsloop{%
			\ifnum\c@pgf@counta<0
				\pgfplotsloopcontinuefalse
			\else
				\pgfplotsloopcontinuetrue
			\fi
		}{%
			\pgfkeysgetvalue{/pgfplots/cycle multi list/@N\the\c@pgf@counta}\pgfplots@cycle@N
			% compute list index:
			\pgfplotsmathmodint{\c@pgf@countb}{\pgfplots@cycle@N}%
			\divide\c@pgf@countb by \pgfplots@cycle@N\relax
			%
			\expandafter\pgfplots@getautoplotspec@
				\csname pgfp@cyclist@/pgfplots/cycle multi list/@list\the\c@pgf@counta @\endcsname
				{\pgfplots@cycle@N}%
				{\pgfmathresult}%
			\t@pgfplots@toka=\expandafter{#1,}%
			\t@pgfplots@tokb=\expandafter{\pgfplotsretval}%
			\edef#1{\the\t@pgfplots@toka\the\t@pgfplots@tokb}%
			\advance\c@pgf@counta by-1
		}%
	\else
		% normal cycle list:
		\pgfplotslistsize\autoplotspeclist\to\c@pgf@countd
		\pgfplots@getautoplotspec@{\autoplotspeclist}{\c@pgf@countd}{\pgfplots@listindex}%
		\let#1=\pgfplotsretval
	\fi
	\pgfmath@smuggleone#1%
	\endgroup
}
% #1: list name (macro!)
% #2: list size (integer register or value)
% #3: list element index
%
% defines \pgfplotsretval
\def\pgfplots@getautoplotspec@#1#2#3{%
	\ifnum#2=0
		\let\pgfplotsretval=\pgfutil@empty
	\else
		\pgfplotsmathmodint{#3}{#2}%
		\pgfplotslistselect\pgfmathresult\of#1\to\pgfplotsretval
	\fi
}


\long\def\pgfplots@path#1;{%
	\pgfplots@path@enqueue{#1;}%
}

% This thing here shall be used to replace any '\path' where \axispath
% shall be used.
\long\def\pgfplots@replacement@for@tikz@path#1;{%
	\axispath\path#1;%
}
\def\pgfplots@replacement@for@scope{\pgfutil@ifnextchar[{\pgfplots@replacement@for@scope@}{\pgfplots@replacement@for@scope@[]}}%
\long\def\pgfplots@replacement@for@scope@[#1]{%
	\pgfplotsextra{\scope[#1]}%
	\begingroup
	% I need to apply anything which might be relevant for \addplot
	% here.
	% But I do NOT want \scope since this might already affect the low
	% level output. 
	%
	% This here works:
	% 1. set them to activate plot handlers and parameters like
	% samples and domain:
	\tikzset{#1}%
	%
	% 2. we need to remember all these options inside of 
	% 'current plot style' -- otherwise, they would not appear
	% inside of legend images and markers.
	\pgfplotssurveyphaseaddoptionsbeforesurveybegins{#1}%
}%
\def\pgfplots@replacement@for@endscope{%
	\endgroup
	\pgfplotsextra{\endscope}%
}%

\def\pgfplots@replacement@for@onlayer#1{%
	\edef\pgfplots@loc@TMPa{#1}%
	\expandafter\pgfplots@replacement@for@onlayer@{#1}%
}
\def\pgfplots@replacement@for@onlayer@#1{%
	\pgfplotsextra{\pgfonlayer{#1}}%
}%
\def\pgfplots@replacement@for@endonlayer{\pgfplotsextra{\endpgfonlayer}}%

{
	% A block which handles active semicolons.
	%
	% ATTENTION: this block does only work if
	% \pgfplots@addplotimpl.... changes are reflected here!
	%
	\catcode`\;=\active
	\globaldefs=1
	% 'AS' == 'active semicolon'
	\def\pgfplots@path@AS#1;{\pgfplots@path@enqueue{#1;}}%
	\long\def\pgfplots@replacement@for@tikz@path@AS#1;{%
		\axispath\path#1;%
	}%
	\pgfplots@appendto@activesemicolon@switcher{%
		\let\pgfplots@path=\pgfplots@path@AS
		\let\pgfplots@replacement@for@tikz@path=\pgfplots@replacement@for@tikz@path@AS
	}%
}


% Will be available as \closedcycle command inside of an axis.
%
% It closes the current plot by drawing lines to the last "zero
% level".
%
% That means the current plot is connected orthogonally with the
% x-axis, allowing fill commands.
%
% For stacked plots, \closedcycle is special (it connects with the
% previous \addplot command).
%
% Example:
% \addplot coordinates {(3,0.5) (4,2) (5,1)} \closedcycle;
\def\pgfplots@path@closed@cycle{%
	\ifpgfplots@stackedmode
		\pgfplots@stacked@path@closed@cycle
	\else
		\pgfplots@path@closed@cycle@std
	\fi
}
\def\pgfplots@path@closed@cycle@std{%
	|- (perpendicular cs: 
		vertical line through={(current plot begin)}, 
		horizontal line through={(\pgfplots@ZERO@x,\pgfplots@ZERO@y)})
	-- cycle
}%

% Remembers the plotting command #2 and '#3=plot coordinates {...} ...';
% for later postprocessing of the coordinates.
%
% #1: pre-commands which should be executed before issueing the plotting
%        command #2 #3.
% #2: the drawing-command.
%    - If #2 is NOT '\pgfutil@empty', we expect #3 to contain only
%      EXPANDABLE DATA.
%      That's important for postponed floating point arithmetics in #3.
%    - If #2='\pgfutil@empty', we don't make any assumption about #3
%      and process it as-is.
%
% #3: the plot data. If #2 is empty, this can be any command.
%
% #4: commands which should be executed after '#2 #3'.
%
\long\def\pgfplots@path@enqueue@coords#1#2#3#4{%
	\begingroup
	\def\pgfplots@loc@TMPa{#2}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\def\pgfplots@stored@current@precmd{#1}%
		\def\pgfplots@stored@current@cmd{#2}%
		\def\pgfplots@stored@current@data{#3}%
		\def\pgfplots@stored@current@postcmd{#4}%
		\ifx\pgfplots@stored@current@precmd\pgfutil@empty
		\else
			\pgfplots@wrong@plotlist@format@error
		\fi
		\ifx\pgfplots@stored@current@postcmd\pgfutil@empty
		\else
			\pgfplots@wrong@plotlist@format@error
		\fi
		\pgfplotslistpushbackglobal{#1}{#2}{#3}{#4}\to\pgfplots@stored@plotlist
	\else
		\pgfkeysgetvalue{/pgfplots/execute at begin plot visualization}\pgfplots@loc@TMPa
		\pgfkeysgetvalue{/pgfplots/execute at end plot visualization}\pgfplots@loc@TMPb
		\t@pgfplots@toka={#1}%
		\t@pgfplots@tokb=\expandafter{\pgfplots@loc@TMPa}%
		\t@pgfplots@tokc=\expandafter{\pgfplots@loc@TMPb}%
		\edef\pgfplots@loc@TMPa{%
			\noexpand\pgfkeyssetvalue{/pgfplots/execute at begin plot visualization}{\the\t@pgfplots@tokb}%
			\noexpand\pgfkeyssetvalue{/pgfplots/execute at end plot visualization}{\the\t@pgfplots@tokc}%
			\the\t@pgfplots@toka
		}%
		\expandafter\pgfplotslistpushbackglobal\expandafter{\pgfplots@loc@TMPa}{#2}{#3}{#4}\to\pgfplots@stored@plotlist
	\fi
	\endgroup
}
\def\pgfplots@wrong@plotlist@format@error{%
	\pgfplots@error{Internal logic error: someone used \string \pgfplots@path@enqueue@coords\space in an unexpected way: if the second argument is empty, ONLY the third argument should be non-empty.^^J I found: pre command (1st arg): \meaning\pgfplots@stored@current@precmd;^^J  command (2nd arg): \meaning\pgfplots@stored@current@cmd;^^J  data (3rd arg): \meaning\pgfplots@stored@current@data^^J; post cmd (4th arg): \meaning\pgfplots@stored@current@postcmd^^J}%
}%

% this was formerly slightly different than
% \pgfplots@path@enqueue@coords, but it is now the same.
\let\pgfplots@addplot@enqueue@coords=\pgfplots@path@enqueue@coords


% Remembers the plotting command #1.
\long\def\pgfplots@path@enqueue#1{%
	\pgfplots@path@enqueue@coords{}{}{#1}{}%
}
% Use
%\begin{axis}
%	\pgfplotsextra{
%	... basic level commands or whatever...
%	}
%\end{axis}
% to process the special commands by pgfplots.
% This is the same treatment as for TikZ \path commands:
% the commands will be processed as soon as the axis is finished- not
% before.
%
% In contrast to \path, \pgfplotsextra can contain any command(s).
%
% Syntax: either 
% \pgfplotsextra{<argument>}
% or
% \pgfplotsextra <argument> \endpgfplotsextra
\def\pgfplotsextra{%
	\pgfutil@ifnextchar\bgroup{\pgfplots@path@enqueue}{\pgfplotsextra@}%
}%
\long\def\pgfplotsextra@#1\endpgfplotsextra{\pgfplots@path@enqueue{#1}}%


% Assigns a legend.
% Syntax:
% \legend{entry 1\\entry2\\entry3}
\def\pgfplots@command@legend{
	\pgfutil@ifnextchar[{%
		\pgfplots@error{Sorry, legend options are now deprecated. Legends are now TikZ-matrizes which provide better alignment and can be placed horizontally. See the manual for details.}%
		\pgfplots@command@legend@impl
	}{%
		\pgfplots@command@legend@impl
	}%
}

\def\pgfplots@command@legend@impl#1{%
	\pgfplots@assign@list\pgfplots@loc@TMPc{#1}%
	\global\let\pgfplots@legend=\pgfplots@loc@TMPc
}

\def\pgfplots@reverselegend{%
	% Reverse \pgfplots@plotspeclist
	\begingroup
		\pgfplotslistnewempty\pgfplots@plotspeclist@reversed
		\pgfplotslistforeachungrouped\pgfplots@plotspeclist\as\pgfplots@plotspeclisttmp{%
			\expandafter\pgfplotslistpushfront\pgfplots@plotspeclisttmp\to\pgfplots@plotspeclist@reversed
		}%
		\global\let\pgfplots@plotspeclist=\pgfplots@plotspeclist@reversed
		\let\pgfplots@legend@reversed=\relax
		%
		% Reverse \pgfplots@legend
		\pgfplotslistnewempty\pgfplots@legend@reversed
		\pgfplotslistforeachungrouped\pgfplots@legend\as\pgfplots@legendtmp{%
			\expandafter\pgfplotslistpushfront\pgfplots@legendtmp\to\pgfplots@legend@reversed
		}%
		\global\let\pgfplots@legend=\pgfplots@legend@reversed
	\endgroup
}

\def\pgfplots@transposelegend{%
	\ifnum\pgfplots@legend@columns>1
		\begingroup
		\pgfplots@transposelegend@
		\let\pgfplots@legend@columns=\c@pgfplots@row@end
		\pgfmath@smuggleone\pgfplots@legend@columns
		\endgroup
	\fi
}
\def\pgfplots@transposelegend@{%
	\let\c@pgfplots@row=\c@pgf@countb
	\let\c@pgfplots@col=\c@pgf@countc
	\let\c@pgfplots@no=\c@pgf@countd
	\c@pgfplots@row=0
	\c@pgfplots@col=0
	\c@pgfplots@no=0
	\pgfplotslistforeachungrouped\pgfplots@legend\as\entry{%
		\expandafter\let\csname m@pgfplots@\the\c@pgfplots@row,\the\c@pgfplots@col\endcsname=\entry
		\advance\c@pgfplots@col by1
		\ifnum\pgfplots@legend@columns=\c@pgfplots@col\relax
			\c@pgfplots@col=0
			\advance\c@pgfplots@row by1
		\fi
		\advance\c@pgfplots@no by1
	}%
	\ifnum\c@pgfplots@col=0
	\else
		\advance\c@pgfplots@row by1
	\fi
	\edef\c@pgfplots@row@end{\the\c@pgfplots@row}%
	\edef\c@pgfplots@no@leg{\the\c@pgfplots@no}%
	%
	%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	\c@pgfplots@row=0
	\c@pgfplots@col=0
	\c@pgfplots@no=0
	\pgfplotslistforeachungrouped\pgfplots@plotspeclist\as\entry{%
		\expandafter\let\csname m@pgfplots@img@\the\c@pgfplots@row,\the\c@pgfplots@col\endcsname=\entry
		\advance\c@pgfplots@col by1
		\ifnum\pgfplots@legend@columns=\c@pgfplots@col\relax
			\c@pgfplots@col=0
			\advance\c@pgfplots@row by1
		\fi
		\advance\c@pgfplots@no by1
	}%
	\ifnum\c@pgfplots@col=0
	\else
		\advance\c@pgfplots@row by1
	\fi
	\ifnum\c@pgfplots@row<\c@pgfplots@row@end
		\edef\c@pgfplots@row@end{\the\c@pgfplots@row}%
	\fi
	\ifnum\c@pgfplots@no<\c@pgfplots@no@leg
		\edef\c@pgfplots@no@leg{\the\c@pgfplots@no}%
	\fi
	%
	%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	\c@pgfplots@col=0
	\global\pgfplotslistnewempty\pgfplots@legend%
	\global\pgfplotslistnewempty\pgfplots@plotspeclist%
	\pgfplotsloop{%
		\ifnum\pgfplots@legend@columns=\c@pgfplots@col
			\pgfplotsloopcontinuefalse
		\else
			\pgfplotsloopcontinuetrue
		\fi
	}{%
		\c@pgfplots@row=0
		\pgfplotsloop{%
			\ifnum\c@pgfplots@row@end=\c@pgfplots@row
				\pgfplotsloopcontinuefalse
			\else
				\pgfplotsloopcontinuetrue
			\fi
		}{%
			\pgfutil@ifundefined{m@pgfplots@\the\c@pgfplots@row,\the\c@pgfplots@col}{%
			}{%
				\pgfutil@ifundefined{m@pgfplots@img@\the\c@pgfplots@row,\the\c@pgfplots@col}{%
				}{%
					\expandafter\let\expandafter\pgfplots@legendtmp\csname m@pgfplots@\the\c@pgfplots@row,\the\c@pgfplots@col\endcsname
					\expandafter\pgfplotslistpushbackglobal\expandafter{\pgfplots@legendtmp}\to\pgfplots@legend%
					%
					\expandafter\let\expandafter\pgfplots@legendtmp\csname m@pgfplots@img@\the\c@pgfplots@row,\the\c@pgfplots@col\endcsname
					\expandafter\pgfplotslistpushbackglobal\expandafter{\pgfplots@legendtmp}\to\pgfplots@plotspeclist%
				}%
			}%
			\advance\c@pgfplots@row by1
		}%
		\advance\c@pgfplots@col by1
	}%
}%


\def\pgfplots@addlegendentryexpanded{%
	\pgfutil@ifnextchar[{%
		\pgfplots@addlegendentryexpanded@opts
	}{%
		\pgfplots@addlegendentryexpanded@opts[]%
	}%
}
\long\def\pgfplots@addlegendentryexpanded@opts[#1]#2{%
	\begingroup
		\let\protect=\noexpand
		\long\edef\pgfplots@loc@TMPa{#2}%
		\def\pgfplots@loc@TMPb{\pgfplots@addlegendentry@opts[#1]}%
		\expandafter\pgfplots@loc@TMPb\expandafter{\pgfplots@loc@TMPa}%
	\endgroup
}%

\def\pgfplots@addlegendimage{\pgfutil@ifnextchar[{\pgfplots@addlegendimage@opt}{\pgfplots@addlegendimage@opt[]}}%
\def\pgfplots@addlegendimage@opt[#1]#2{%
	\pgfplots@rememberplotspec[#1]{/pgfplots/every axis plot,#2,/pgfplots/.cd,/pgfplots/every axis plot post}%
}%

% This implements \addlegendentry
\def\pgfplots@addlegendentry{%
	\pgfutil@ifnextchar[{%
		\pgfplots@addlegendentry@opts
	}{%
		\pgfplots@addlegendentry@opts[]%
	}%
}
\long\def\pgfplots@addlegendentry@opts[#1]#2{%
	\pgfplotslistpushbackglobal[#1]#2\to\pgfplots@legend
}

\def\pgfplots@pop@next@legend{{%
	\globaldefs=1
	\pgfplotslistcheckempty\pgfplots@plotspeclist
	\ifpgfplotslistempty
		\let\pgfplots@curplotlist=\relax
	\else
		\pgfplotslistpopfront\pgfplots@plotspeclist\to\pgfplots@curplotlist
		\pgfplotslistcheckempty\pgfplots@legend
		\ifpgfplotslistempty
			\let\pgfplots@curlegend=\pgfutil@empty
		\else
			\pgfplotslistpopfront\pgfplots@legend\to\pgfplots@curlegend
		\fi
	\fi
	%
}}

\def\pgfplots@try@mirror@plot@handler{%
	\pgfplots@getcurrent@plothandler\pgfplots@basiclevel@plothandler
	% this method assigns '\tikz@plot@handler'.
	% That's ok and does not introduce incompatibilities.
	\ifx\pgfplots@basiclevel@plothandler\pgfplothandlerconstantlineto
		\let\tikz@plot@handler=\pgfplothandlerconstantlinetomarkright
	\else
		\ifx\pgfplots@basiclevel@plothandler\pgfplothandlerconstantlinetomarkright
			\let\tikz@plot@handler=\pgfplothandlerconstantlineto
		\fi
	\fi
}

% #1: DEPRECATED. Unused.
% #2: plot style
\long\def\pgfplots@show@small@legendplots#1#2{%
	\begingroup
	\pgfplots@define@currentplotstyle@as{#1,#2}%
	\pgfplots@restore@state@before@legend@style
	\scope[/tikz/current plot style,/pgfplots/every legend image post]% this scoping construction allows plot styles to change 'legend image code'.
		\pgfkeysvalueof{/pgfplots/legend image code/.@cmd}\pgfeov
	\endscope
	\endgroup
	%\pgfkeysvalueof{/pgfplots/legend image code/.@cmd}{/pgfplots/.cd,#1,#2}\pgfeov
}

% A work-around method to undo the 'every axis legend' style.
%
% It is called within legend's cell pictures in order to undo global
% settings like stroke colors or the-like.
\def\pgfplots@restore@state@before@legend@style{%
	\pgfsetfillcolor{black}% 
	% disable the transformations of pgfplots. This is only used by
	% pgfplots-specific plot handlers which work only if used inside
	% of an axis... disable it.
	\def\pgfplotsaxisvisphasetransformcoordinate##1##2##3{}%
}%

\def\pgfplots@split@opts{%
	\pgfutil@ifnextchar[{%
		\pgfplots@split@opts@opts
	}{%
		\pgfplots@split@opts@opts[]%
	}%
}
\long\def\pgfplots@split@opts@opts[#1]#2\pgfplots@result@to#3#4{%
	\long\def#3{#2}%
	\long\def#4{#1}%
}

% Typesets a legend node.
%
% It will either typeset a previously computed legend (which needs to be
% stored in the macro \pgfplots@already@computed@legend@node)
%
% or it creates a legend, stores the commands into the macro named
% above and typesets it.
\def\pgfplots@createlegend{%
	\pgfkeysgetvalue{/pgfplots/legend to name}\pgfplots@createlegend@toname
	\ifx\pgfplots@already@computed@legend@node\pgfutil@empty
		\pgfplotslistcheckempty\pgfplots@legend
		\ifpgfplotslistempty
			% No legend commands appeared in the document. So,
			% consider the key:
			\pgfkeysgetvalue{/pgfplots/legend entries}\pgfplots@legend
			\expandafter\pgfplots@assign@list\expandafter\pgfplots@legend\expandafter{\pgfplots@legend}%
			\pgfplotslistcheckempty\pgfplots@legend
		\fi
%\message{Legend: \meaning\pgfplots@legend^^J}%
		\ifpgfplotslistempty
		\else
		\ifpgfplots@reverse@legend
			\pgfplots@reverselegend
		\fi
		\ifpgfplots@transpose@legend
			\pgfplots@transposelegend
		\fi
		%
		% 
		\begingroup
			\ifx\pgfplots@createlegend@toname\pgfutil@empty
				% ok, draw legend.
				\def\pgfplots@createlegend@prepareimage@to##1{%
					\t@pgfplots@tokc=\expandafter{\pgfplots@curplotlist}%
					\edef##1{\noexpand\pgfplots@show@small@legendplots{}{\the\t@pgfplots@tokc}}%
				}%
			\else
				% export legend instead of drawing it.
				\def\pgfplots@createlegend@prepareimage@to##1{%
					\t@pgfplots@tokc=\expandafter{\pgfplots@curplotlist}%
					\edef\pgfplots@loc@TMPa{\noexpand\pgfplots@export@legend@image@to@macro{\the\t@pgfplots@tokc}{}}%
					\pgfplots@loc@TMPa
					\let##1=\pgfplotsretval
				}%
			\fi
			% assemble a 
			% \matrix {
			% 	small plot  & legend1\\
			% 	small plot  & legend2\\
			% 	...
			% };
			% command [and using the 'legend columns' option]
			%
			% \t@pgfplots@toka={
			% 	small plot  & legend1\\
			% 	small plot  & legend2\\
			% 	...
			% }
			% ( I have allocated the token registers in my
			% liststructure.sty)
			% 
			% \global\def\pgfplots@glob@TMPa{
			% 	\matrix {
			% 		\TOKL@TA
			% 	};
			% }
			% -> finally, \pgfplots@glob@TMPa will contain the complete command.
			\t@pgfplots@toka={}%
			\let\curcolumnNum=\c@pgf@counta
			\let\maxcolumnCount=\c@pgf@countb
			\let\legendplotpos=\c@pgf@countc
			\legendplotpos\expandafter=\pgfplots@legend@plot@pos
			\curcolumnNum=0
			\maxcolumnCount=\pgfplots@legend@columns\relax
			%
			\pgfplotsloop{%
				\pgfplots@pop@next@legend
				\ifpgfplotslistempty
					\pgfplotsloopcontinuefalse
				\else
					\pgfplotsloopcontinuetrue
				\fi
			}{%
				\ifx\pgfplots@curlegend\pgfutil@empty
				\else
					\advance\curcolumnNum by1
					\begingroup
					% \pgfplots@curlegend@opts are any options for
					% this single legend text, provided as
					% \addlegendentry[<options>]{<text>}
					% or
					% legend entries={...,[<options>]<text>, ....}
					\expandafter\pgfplots@split@opts\pgfplots@curlegend\pgfplots@result@to{\pgfplots@curlegend}{\pgfplots@curlegend@opts}%
					\pgfplots@createlegend@prepareimage@to{\pgfplotsretval}%
					%
					\t@pgfplots@tokb=\expandafter{\pgfplots@curlegend@opts}%
					\t@pgfplots@tokc=\expandafter{\pgfplots@curlegend}%
					%
					% prepare the \node[<options>] {<text>} into \t@pgfplots@tokc
					\edef\pgfplots@loc@TMPa{\noexpand\node[\the\t@pgfplots@tokb]{\the\t@pgfplots@tokc};}%
					\t@pgfplots@tokc=\expandafter{\pgfplots@loc@TMPa}%
					%
					% and the legend image into \t@pgfplots@tokb:
					\t@pgfplots@tokb=\expandafter{\pgfplotsretval}%
					% ok. Now, the 
					% - 'b' register contains the IMAGE and
					% - 'c' register contains the TEXT
					\ifcase\legendplotpos
						% legend plot pos=left 
						\edef\pgfplots@matrixentry{%
							\the\t@pgfplots@tokb
							\noexpand\pgfmatrixnextcell
							\the\t@pgfplots@tokc%
						}%
					\or
						% legend plot pos=right
						\edef\pgfplots@matrixentry{%
							\the\t@pgfplots@tokc%
							\noexpand\pgfmatrixnextcell
							\the\t@pgfplots@tokb
						}%
					\or
						% legend plot pos=none
						\edef\pgfplots@matrixentry{%
							\the\t@pgfplots@tokc%
						}%
					\fi
					% copy it back to 'b' register:
					\t@pgfplots@tokb=\expandafter{\pgfplots@matrixentry}%
					%
					\ifnum\curcolumnNum=\maxcolumnCount
						\t@pgfplots@tokb=\expandafter{\the\t@pgfplots@tokb\\}%
					\else
						\pgfplotslistcheckempty\pgfplots@legend
						\ifpgfplotslistempty
						\else
							\pgfplotslistcheckempty\pgfplots@plotspeclist
						\fi
						\ifpgfplotslistempty
							% Ok, either the legend list is empty or
							% there are no more plot specifications.
							%
							% Finalize matrix:
							\t@pgfplots@tokb=\expandafter{\the\t@pgfplots@tokb\\}%
						\else
							\t@pgfplots@tokb=\expandafter{\the\t@pgfplots@tokb\pgfmatrixnextcell}%
						\fi
					\fi
					\xdef\pgfplots@glob@TMPa{%
						\the\t@pgfplots@toka
						\the\t@pgfplots@tokb
					}%
					\endgroup
					\ifnum\curcolumnNum=\maxcolumnCount
						\curcolumnNum=0
					\fi
					\expandafter\t@pgfplots@toka\expandafter{\pgfplots@glob@TMPa}%
				\fi
			}%
			\t@pgfplots@tokb={\matrix[/pgfplots/every axis legend]}%
			\xdef\pgfplots@glob@TMPa{%
				\noexpand\def\noexpand\plotnum{0}%
				\noexpand\def\noexpand\plotnumofactualtype{0}%
				\the\t@pgfplots@tokb {%
					\the\t@pgfplots@toka
				};%
			}%
		\endgroup
		\let\pgfplots@already@computed@legend@node=\pgfplots@glob@TMPa
		\fi
	\fi
	\ifx\pgfplots@createlegend@toname\pgfutil@empty
		% DRAW:
		\pgfplotsgetlayerforstyle{every axis legend}%
		\pgfplotsonlayer\pgfplotsretval{legend style}%
		\pgfplots@already@computed@legend@node
		\endpgfplotsonlayer
	\else
		% apply the 'legend to name' feature:
		%
		% store legend contents:
		%
		\t@pgfplots@toka=\expandafter{\pgfplots@already@computed@legend@node}%
		\pgfkeysgetvalue{/pgfplots/every axis legend/.@cmd}\pgfplots@loc@TMPa
		\t@pgfplots@tokb=\expandafter{\pgfplots@loc@TMPa\pgfeov}%
		%
		\pgfplots@assemble@ref@picture
			{\pgfplots@legend@to@name}
			{\tikz[/pgfplots/every legend to name picture/.try]{\pgfplots@legend@to@name}}%
		\t@pgfplots@tokc=\expandafter{\pgfplotsretval}%
		%
		\begingroup
		\pgfkeysgetvalue{/pgfplots/every legend image post/.@cmd}\pgfplots@loc@TMPa
		% steal \toks0 temporarily. Within this group, it won't be
		% used by any LaTeX code:
		\toks0=\expandafter{\pgfplots@loc@TMPa\pgfeov}%
		%
		\expandafter\xdef\csname pgfplots@legend@to@name@\pgfplots@createlegend@toname\endcsname{%
			\noexpand\begingroup
			\noexpand\def\noexpand\pgfplots@legend@to@name{%
				\noexpand\pgfkeysdef{/pgfplots/every axis legend}{\the\t@pgfplots@tokb}%
				\noexpand\pgfkeysdef{/pgfplots/every legend image post}{\the\toks0 }%
				\noexpand\def\noexpand\numplots{\numplots}%
				\the\t@pgfplots@toka
			}%
			\the\t@pgfplots@tokc
			\noexpand\endgroup
		}%
		\endgroup
		\t@pgfplots@toka=\expandafter\expandafter\expandafter{\csname pgfplots@legend@to@name@\pgfplots@createlegend@toname\endcsname}%
		\pgfplots@auxwrite{%
			\noexpand\expandafter
			\noexpand\gdef
				\noexpand\csname pgfplots@legend@to@name@\pgfplots@createlegend@toname\noexpand\endcsname%
					{\the\t@pgfplots@toka}%
		}%
		\begingroup
		%
		% make sure \ref{<legendname>} works:
		\pgfplots@label{\pgfplots@createlegend@toname}{pgfplots@legend@to@name@}%
		\endgroup
	\fi
}

\pgfutil@IfUndefined{AtBeginDocument}{}{%
	\AtBeginDocument{%
		\let\pgfplots@original@LaTeX@label@loadtime=\label
	}%
}

% Defines a new \label{#1}. When \ref{#1} is used, the code 
% \csname #3#2\endcsname
% will be invoked.
% \pgfplots@label[<optional prefix>]{<label name>}{<command prefix>}
% invokes
% \label<optional prefix>{<label name>}
\def\pgfplots@label{\pgfutil@ifnextchar[{\pgfplots@label@@}{\pgfplots@label@@[]}}%
\def\pgfplots@label@@[#1]#2#3{%
	\begingroup
	\edef\@currentlabel{%
		\string\expandafter
		\string\protect
		\string\csname\space #3#2\string\endcsname
	}%
	\pgfutil@IfUndefined{hyper@makecurrent}{}{%
		\hyper@makecurrent{pgfplotslink}%
		\hyper@anchorstart{\@currentHref}{}\hyper@anchorend
		\pgfplotsutil@advancestringcounter@global\c@pgfplots@label
	}%
	%
	\pgfplots@label@configure@package@workarounds
	%
	\pgfutil@IfUndefined{label}{%
	}{%
		\def\pgfplots@loc@TMPa{\label #1}%
		\expandafter\pgfplots@loc@TMPa\expandafter{#2}% the \expandafter is a convenience method; the name should be expandable anyway
	}%
	\endgroup
}%
\gdef\c@pgfplots@label{0}%
\def\theHpgfplotslink{\theHsection.\c@pgfplots@label}%

\def\pgfplots@label@configure@package@workarounds{%
	% this is a work-around to support the memoir class (it overwrites
	% \label in sub
	\let\sf@@memsub@label=\pgfplots@original@LaTeX@label@loadtime
	%
	\ifx\label\mcaption@label
		% this is a work-around to support the mcaption class: it
		% simply remembers the label name and invokes \label later-on.
		% This appears to be wrong in this context: I want to generate
		% a pgfplots label. 
		%
		% If someone writes \label{fig:one}, that label will be
		% redeclared in the margin - which appears to be correct. And
		% that will still work.
		%
		% This here will activate pgfplots' labels:
		\let\label=\pgfplots@original@LaTeX@label@loadtime
	\fi
}

% this is deprecated. Use \ref{#1} instead.
\def\pgfplotslegendfromname#1{%
	\pgfplots@texdist@protect\pgfplotslegendfromname@{#1}%
}%
\def\pgfplotslegendfromname@#1{%
	\pgfutil@IfUndefined{pgfplots@legend@to@name@#1}{%
		\pgfutil@IfUndefined{ref}{%
			\pgfplotswarning{no such legend to name}{#1}\pgfeov
			\string\pgfplotslegendfromname{#1}: ??%
		}{%
			\ref{\string\pgfplotslegendfromname{#1}}%
		}%
	}{%
		\csname pgfplots@legend@to@name@#1\endcsname
	}%
}%
% this is deprecated. Use \ref{#1} instead.
\def\pgfplotscolorbarfromname#1{%
	\pgfplots@texdist@protect\pgfplotscolorbarfromname@{#1}%
}%
\def\pgfplotscolorbarfromname@#1{%
	\pgfutil@IfUndefined{pgfplots@colorbar@to@name@#1}{%
		\pgfutil@IfUndefined{ref}{%
			\pgfplotswarning{no such colorbar to name}{#1}\pgfeov
			\string\pgfplotscolorbarfromname{#1}: ??%
		}{%
			\ref{\string\pgfplotscolorbarfromname{#1}}%
		}%
	}{%
		\csname pgfplots@colorbar@to@name@#1\endcsname
	}%
}%

\def\pgfplotsplotfromname#1{%
	\pgfplots@texdist@protect\pgfplotsplotfromname@{#1}%
}%
\def\pgfplotsplotfromname@#1{%
	\pgfutil@IfUndefined{pgfplots@show@ref@#1}{%
		\pgfutil@IfUndefined{ref}{%
			\pgfplotswarning{no such addplot label}{#1}\pgfeov
			\string\pgfplotsplotfromname{#1}: ??%
		}{%
			\ref{\string\pgfplotsplotfromname{#1}}%
		}%
	}{%
		\csname pgfplots@show@ref@#1\endcsname
	}%
}%

\def\pgfplots@ifintikzpicture#1#2{%
	\ifpgfpicture #1\else #2\fi
}%

% DEPRECATED.
\def\skipsuffixzero#1.#2|{
	{%
	\def\pgfplots@loc@TMPa{#2}%
	\def\pgfplots@loc@TMPb{0}%
	\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
		\global\def\pgfmathresult{#1}%
	\else
		\global\def\pgfmathresult{#1.#2}%
	\fi
	}%
}

\def\pgfmathlogtologten#1{%
	\pgfmathparse{#1}%
	\expandafter\pgfmathlogtologten@\expandafter{\pgfmathresult}%
}

% Simply divides #1 by log(10).
% ATTENTION: in order to implement per-axis log basis, this will be
% OVERWRITTEN in pgfplotsticks.code.tex !
\def\pgfmathlogtologten@#1{%
	\pgfmathmultiply@{#1}\reciproclogten%
}%

% DEPRECATED.
\def\logtologtentomacro#1#2{%
	\pgfmathlogtologten@{#1}%
	\expandafter\skipsuffixzero\pgfmathresult|%
	\let#2=\pgfmathresult
}

% DEPRECATED.
\def\logtologten#1{%
	\pgfmathlogtologten@{#1}%
	\expandafter\skipsuffixzero\pgfmathresult|%
	\pgfmathresult
}

\pgfkeysdef{/pgfplots/@enlargelimits/true}{%
	\def\bool@pgfplots@loc@enlargelimits@min{1}%
	\def\bool@pgfplots@loc@enlargelimits@max{1}%
}%
\pgfkeysdef{/pgfplots/@enlargelimits/false}{%
	\def\bool@pgfplots@loc@enlargelimits@min{0}%
	\def\bool@pgfplots@loc@enlargelimits@max{0}%
}%
\pgfkeysdef{/pgfplots/@enlargelimits/upper}{%
	\def\bool@pgfplots@loc@enlargelimits@min{0}%
	\def\bool@pgfplots@loc@enlargelimits@max{1}%
}%
\pgfkeysdef{/pgfplots/@enlargelimits/lower}{%
	\def\bool@pgfplots@loc@enlargelimits@min{1}%
	\def\bool@pgfplots@loc@enlargelimits@max{0}%
}%
\pgfkeysdef{/pgfplots/@enlargelimits/auto}{%
	\def\bool@pgfplots@loc@enlargelimits@min{0}%
	\def\bool@pgfplots@loc@enlargelimits@max{0}%
	\def\pgfplots@loc@TMPa{0}%
	\ifpgfplots@threedim
		\if\pgfplots@enlargelimits@curaxis z%
			\def\pgfplots@loc@TMPa{1}%
		\fi
	\else
		\def\pgfplots@loc@TMPa{1}%
	\fi
	\if1\pgfplots@loc@TMPa
		\pgfplots@if{pgfplots@autocompute@\pgfplots@enlargelimits@curaxis min}{%
			\def\bool@pgfplots@loc@enlargelimits@min{1}%
		}{}%
		\pgfplots@if{pgfplots@autocompute@\pgfplots@enlargelimits@curaxis max}{%
			\def\bool@pgfplots@loc@enlargelimits@max{1}%
		}{}%
	\fi
}%

\def\pgfplots@enlargelimits@rel@unitserror#1{%
	\pgfplots@error{enlarge limits only supports values with units for 'abs=#1' and/or 'abs value=#1'. Ignoring unit}%
}%
\pgfkeysdef{/pgfplots/@enlargelimits/value}{%
	\pgfmathparse{#1}%
	\ifpgfmathunitsdeclared
		\pgfplots@enlargelimits@rel@unitserror{#1}%
	\fi
	\let\pgfplots@enlargelimits@relthresh=\pgfmathresult
	\let\pgfplots@enlargelimits@absthresh=\pgfutil@empty
}%
\pgfkeysdef{/pgfplots/@enlargelimits/rel}{\pgfkeysalso{true,value={#1}}}%
\pgfkeysdef{/pgfplots/@enlargelimits/abs value}{%
	\begingroup
		\ifpgfplots@usefpu
			\pgfkeys{/pgf/fpu,/pgf/fpu/output format=fixed}%
		\fi
		\pgfmathparse{#1}%
		\xdef\pgfplots@glob@TMPa{%
			\ifpgfmathunitsdeclared
				\noexpand\pgfmathunitsdeclaredtrue
			\else
				\noexpand\pgfmathunitsdeclaredfalse
			\fi
			\noexpand\def\noexpand\pgfmathresult{\pgfmathresult}%
		}%
	\endgroup
	\pgfplots@glob@TMPa
	\ifpgfmathunitsdeclared
		\edef\pgfplots@enlargelimits@absdimension{\pgfmathresult pt}%
		\let\pgfplots@enlargelimits@absthresh=\pgfutil@empty
	\else
		\let\pgfplots@enlargelimits@absdimension=\pgfutil@empty
		\csname pgfplotstransformdirection\pgfplots@enlargelimits@curaxis\endcsname{\pgfmathresult}%
		\let\pgfplots@enlargelimits@absthresh=\pgfmathresult
	\fi
	\let\pgfplots@enlargelimits@relthresh=\pgfutil@empty
}%
\pgfkeysdef{/pgfplots/@enlargelimits/abs}{\pgfkeysalso{true,abs value={#1}}}%
\pgfkeysdef{/pgfplots/@enlargelimits/.unknown}{\pgfkeysalso{true,value={\pgfkeyscurrentname}}}%

\def\pgfplots@enlarge@limit@ifconfigured#1{%
	\begingroup
	% ATTENTION: this uses similar access patterns as
	% \pgfplots@enlarge@limit@by@dimension
	\def\bool@pgfplots@loc@enlargelimits@min{0}%
	\def\bool@pgfplots@loc@enlargelimits@max{0}%
	%
	% we can either enlarge 
	% ... using a relative limit (like 0.1 -> 10%)
	\def\pgfplots@enlargelimits@relthresh{0.1}% the default
	% ...or an absolute limit ( like 4 units)
	\let\pgfplots@enlargelimits@absthresh=\pgfutil@empty
	% or an absolute dimension (like 1cm).
	%
	% Relative and absolute values are relatively simple: we only need to compute and
	% add the changes to the already existing limits. The value with
	% an absolute dimension is surprisingly complicated. 
	% 
	% The problem is: enlargelimits has to be computed before the
	% image has been scaled into its final size. This is not merely a
	% technical problem; this is how one wants it to be!
	%
	% The solution taken here is to communicate such an absolute
	% dimension to the scaling routines. The scaling routines will
	% handle the case; we don't change limits here.
	%
	\let\pgfplots@enlargelimits@absdimension=\pgfutil@empty
	\def\pgfplots@enlargelimits@curaxis{#1}%
	%
	\pgfkeysgetvalue{/pgfplots/enlarge #1 limits}{\pgfplots@loc@TMPa}%
	\def\pgfplots@loc@TMPb{\pgfqkeys{/pgfplots/@enlargelimits}}% set the argument keys
	\expandafter\pgfplots@loc@TMPb\expandafter{\pgfplots@loc@TMPa}%
	%
	\def\bool@pgfplots@loc@enlargeany{0}%
	\if1\bool@pgfplots@loc@enlargelimits@min
		\def\bool@pgfplots@loc@enlargeany{1}%
	\else
		\if1\bool@pgfplots@loc@enlargelimits@max
			\def\bool@pgfplots@loc@enlargeany{1}%
		\fi
	\fi
	\if1\bool@pgfplots@loc@enlargeany
		\pgfplots@enlarge@limit@for{#1}%
	\fi
	\global\let\pgfplots@glob@TMPa=\bool@pgfplots@loc@enlargeany
	% limits assignments are made globally.
	\xdef\pgfplots@glob@TMPb{%
		\noexpand\pgfplots@enlargelimits@remember@abs@dimension{#1}%
			{\bool@pgfplots@loc@enlargelimits@min}%
			{\bool@pgfplots@loc@enlargelimits@max}%
			{\pgfplots@enlargelimits@absdimension}%
	}%
	\endgroup
	\pgfplots@glob@TMPb
	\if1\pgfplots@glob@TMPa
		\pgfplots@visphase@notify@changeofcanvaslimits{#1}%
	\fi
}

% Reconfigures the scaling routines such that following calls to
% \pgfplots@scaleaxes@to@BB@ will enlarge the limit for a specific
% axis by an absolute dimension.
%
% This enlargement is different from standard limit enlargement:
% Standart limit enlargement is typically applied (and finished) long
% before the scaling routines start. In fact, the result of
% enlargelimits is typically the input argument for the scaling
% (compare the pgfplots manual (pdf)).
%
% This here needs a different treatment because "enlarge x limits={abs=1cm}"
% has to be applied AFTER the scaling is complete. To this end, it is
% applied as the very last scaling step. It is applied after any post
% scales, and it only modifies axis limits. 
%
% #1: x,y, or z
% #2: 1 if the lower limit shall be enlarged, 0 if not
% #3: 1 if the upper limit shall be enlarged, 0 if not
% #4: some absolute dimension (like 1cm) by which we want to enlarge
% axis limits.
\def\pgfplots@enlargelimits@remember@abs@dimension#1#2#3#4{%
	\expandafter\edef\csname pgfplots@enlargelimits@absdimension@#1\endcsname{#4}%
	\expandafter\edef\csname pgfplots@enlargelimits@absdimension@#1@minmax\endcsname{{#2}{#3}}%
}%
\let\pgfplots@enlargelimits@absdimension@x=\pgfutil@empty
\let\pgfplots@enlargelimits@absdimension@y=\pgfutil@empty
\let\pgfplots@enlargelimits@absdimension@z=\pgfutil@empty

% Called as soon as the scaling is completely set up and any 
% "enlarge #1 limits={abs=1cm}"
% enlargements shall be done, i.e. enlargement by unit.
% 
% #1: x,y, or z
\def\pgfplots@scaling@apply@enlargelimits@by@dimension#1{%
	\expandafter\ifx\csname pgfplots@enlargelimits@absdimension@#1\endcsname\pgfutil@empty
	\else
		\pgfplotsconvertunittocoordinate{#1}{\csname pgfplots@enlargelimits@absdimension@#1\endcsname}%
		\edef\pgfplots@loc@TMPa{%
			\noexpand\pgfplots@enlarge@limit@by@dimension{#1}
				\csname pgfplots@enlargelimits@absdimension@#1@minmax\endcsname
				{\pgfmathresult}%
		}%
		\pgfplots@loc@TMPa
	\fi
}%


% PRECONDITION: 
%   1. width/height are set
%   2. the unit vectors point indicate whether the axis is a standard
%   box or some skewed plot (their precise direction and magnitude is
%   irrelevant)
%   3. the enlargelimits code has already evaluated the case 
%   "enlargelimits={abs=1cm}"
%
% POSTCONDITION:
% 	width and/or height might be modified
\def\pgfplots@scaling@changewidthheight@for@enlargelimits@by@dimension{%
	\ifpgfplots@enlargelimits@respect@figure@size
		% 
		% decide if we need to do anything at all, i.e. if there IS
		% some option 'enlarge * limits={abs=1cm}' :
		\pgfplots@loc@tmpfalse
		\ifx\pgfplots@enlargelimits@absdimension@x\pgfutil@empty
		\else
			\pgfplots@loc@tmptrue
		\fi
		\ifx\pgfplots@enlargelimits@absdimension@y\pgfutil@empty
		\else
			\pgfplots@loc@tmptrue
		\fi
		\ifx\pgfplots@enlargelimits@absdimension@z\pgfutil@empty
		\else
			\pgfplots@loc@tmptrue
		\fi
		%
		\ifpgfplots@loc@tmp
			\def\pgfplotsretval{}%
			% ok. We encountered an option 'enlarge * limits={abs=1cm}' for at least one axis.
			% and we WANT to keep 'width', 'height'.
			%
			% This is not quite trivial because in order to compute
			% enlarge-by-dimension, we NEED the unit vectors. But the
			% unit vectors need the limits - a nonlinear problem.
			%
			% Since this here is not really a common use-case, I
			% decided to implement a heuristics which works in most
			% common cases: for standard 2d axes. It might fail for
			% skewed axes and it will probably fail for 3d axes.
			%
			% My idea is to change width and/or height BEFORE the unit
			% vectors have been computed.
			%
			% First: check if we HAVE a standard 2d axis.
			\pgfplots@loc@tmpfalse
			\ifpgfplots@threedim
			\else
				\ifdim\pgf@xx=0sp %
				\else
					\ifdim\pgf@xy=0sp %
						\ifdim\pgf@yx=0sp %
							\ifdim\pgf@yy=0sp %
							\else
								\pgfplots@loc@tmptrue
							\fi
						\fi
					\fi
				\fi
			\fi
			%
			\ifpgfplots@loc@tmp
				\def\pgfplots@loc@TMPc{{1}{1}}%
				%
				% ah - we really *have* a standard boxed axis.
				% Compute 
				% newwidth  = width - enlargevalue
				% newheight = height - enlargevalue 
				%
				% newwidth will be stored in \pgfplots@loc@TMPa
				% and newheight in \pgfplots@loc@TMPb
				\ifx\pgfplots@enlargelimits@absdimension@x\pgfutil@empty
					\let\pgfplots@loc@TMPa=\pgfplots@width
				\else
					\ifx\pgfplots@enlargelimits@absdimension@x@minmax\pgfplots@loc@TMPc
						\def\pgfmathresult{2}%
					\else
						\def\pgfmathresult{1}%
					\fi
					\pgfmathparse{\pgfplots@width - \pgfmathresult * \pgfplots@enlargelimits@absdimension@x}%
					\edef\pgfplots@loc@TMPa{\pgfmathresult pt}%
				\fi
				%
				\ifx\pgfplots@enlargelimits@absdimension@y\pgfutil@empty
					\let\pgfplots@loc@TMPb=\pgfplots@height
				\else
					\ifx\pgfplots@enlargelimits@absdimension@y@minmax\pgfplots@loc@TMPc
						\def\pgfmathresult{2}%
					\else
						\def\pgfmathresult{1}%
					\fi
					\pgfmathparse{\pgfplots@height - \pgfmathresult * \pgfplots@enlargelimits@absdimension@y}%
					\edef\pgfplots@loc@TMPb{\pgfmathresult pt}%
				\fi
				%
				% OK. if( newwidth>0 && newheight>0 ), we can proceed.
				\pgfplots@loc@tmpfalse
				\ifdim\pgfplots@loc@TMPa>10pt %
					\ifdim\pgfplots@loc@TMPb>10pt %
						\pgfplots@loc@tmptrue
					\fi
				\fi
				\ifpgfplots@loc@tmp
					% Ah: newheight>0 && newheight>0 . Good.
					\let\pgfplots@width=\pgfplots@loc@TMPa
					\let\pgfplots@height=\pgfplots@loc@TMPb
				\else
					\def\pgfplotsretval{enlarge value are bigger than old picture size}%
				\fi
			\else
				\def\pgfplotsretval{size adjust is unavailable for non-standard axes}%
			\fi
			\ifx\pgfplotsretval\pgfutil@empty
			\else
				\pgfplotswarning{enlargelimits respects figure size failed}\pgfeov%
			\fi
		\fi
	\fi
}

% this here applies changes required for 'enlarge #1 limits={abs=1cm}', i.e. 
% for the case of numbers with units.
%
% The main difference is that it is applied AFTER the scaling of the
% axis is complete.
%
% #1: x,y,or z
% #2: 1 if lower limit shall be changed
% #3: 1 if upper limit shall be changed
% #4: the absolute value
\def\pgfplots@enlarge@limit@by@dimension#1#2#3#4{%
	\begingroup
	% ATTENTION: this uses similar access patterns as
	% \pgfplots@enlarge@limit@ifconfigured
	\def\bool@pgfplots@loc@enlargelimits@min{#2}%
	\def\bool@pgfplots@loc@enlargelimits@max{#3}%
	%
	\let\pgfplots@enlargelimits@relthresh=\pgfutil@empty
	\def\pgfplots@enlargelimits@absthresh{#4}
	\def\pgfplots@enlargelimits@curaxis{#1}%
	%
	\def\bool@pgfplots@loc@enlargeany{0}%
	\if1\bool@pgfplots@loc@enlargelimits@min
		\def\bool@pgfplots@loc@enlargeany{1}%
	\else
		\if1\bool@pgfplots@loc@enlargelimits@max
			\def\bool@pgfplots@loc@enlargeany{1}%
		\fi
	\fi
	\if1\bool@pgfplots@loc@enlargeany
		\pgfplots@enlarge@limit@for{#1}%
	\fi
	\global\let\pgfplots@glob@TMPa=\bool@pgfplots@loc@enlargeany
	% limits assignments are made globally.
	\endgroup
	\if1\pgfplots@glob@TMPa
		\pgfplots@visphase@notify@changeofcanvaslimits{#1}%
	\fi
}


% Helper method inside of \pgfplots@enlarge@limit@ifconfigured.
%
% It modifies '#1min' and '#1max' (globally!) according to the already prepared
% booleans.
\def\pgfplots@enlarge@limit@for#1{%
	\begingroup
	\expandafter\let\expandafter\pgfplots@@min\csname pgfplots@#1min\endcsname
	\expandafter\let\expandafter\pgfplots@@max\csname pgfplots@#1max\endcsname
	\ifx\pgfplots@enlargelimits@relthresh\pgfutil@empty
		\ifx\pgfplots@enlargelimits@absthresh\pgfutil@empty
			% ups. No enlargement!? OK, can happen for 'abs=1cm' ...
			% numbers with unit are processed later (after the scaling
			% is set up)
			\pgf@xb=0pt %
		\else
			% we have an absolute enlarge value:
			\let\enlargeabsolute=\pgfplots@enlargelimits@absthresh
			\pgf@xb=\pgfplots@enlargelimits@absthresh pt
		\fi
	\else
		% we have a relative enlarge value:
		\pgfmathsubtract@\pgfplots@@max\pgfplots@@min%
		\pgf@xa=\pgfmathresult pt
		\pgf@xb=\pgfplots@enlargelimits@relthresh\pgf@xa
		\edef\enlargeabsolute{\pgf@sys@tonumber{\pgf@xb}}%
	\fi
	\ifdim\pgf@xb>0.001pt
		% the case with 
		%   enlargeabsolute ~= 0
		% means that \pgfplots@@min ~= \pgfplots@@max.
		% It is handled in another method.
		%
		\if1\bool@pgfplots@loc@enlargelimits@min
			\pgfmathsubtract@\pgfplots@@min\enlargeabsolute%
			\expandafter\global\expandafter\let\csname pgfplots@#1min\endcsname=\pgfmathresult
		\fi
		\if1\bool@pgfplots@loc@enlargelimits@max
			\pgfmathadd@\pgfplots@@max\enlargeabsolute%
			\expandafter\global\expandafter\let\csname pgfplots@#1max\endcsname=\pgfmathresult
		\fi
	\fi
	\endgroup
}


% Initialises the data scale transformation and applies it to any
% user specified options.
%
% PRECONDITION:
%   - all axis limits are already transformed
%   - \pgfplots@set@default@size@options has been called before
%   - the scaling transformation for direction x is set up
%   (\pgfplots@set@optimal@datatrafo@for@),
% POSTCONDITION:
%   - any user input (like ticks and tick labels)
%     EXCEPT unit vectors will reflect the changes.
%
% Unit vectors will be scaled later.
% @see \pgfplots@apply@datatrafo@to@axis@limits
\def\pgfplots@check@and@apply@datatrafo@for#1{%
	\pgfplots@if{pgfplots@apply@datatrafo@#1}{%
		% Transform axis limits: ALREADY DONE.
		%
		% Transform tick limits (if they are set):
%\message{#1- display tick limits BEFORE data transformation: [\csname pgfplots@#1tickmin\endcsname:\csname pgfplots@#1tickmax\endcsname]}%
		\expandafter\ifx\csname pgfplots@#1tickmin\endcsname\pgfutil@empty
		\else
			\pgfplotscoordmath{#1}{datascaletrafo}{\csname pgfplots@#1tickmin\endcsname}%
			\expandafter\global\expandafter\let\csname pgfplots@#1tickmin\endcsname=\pgfmathresult
		\fi
		%
		\expandafter\ifx\csname pgfplots@#1tickmax\endcsname\pgfutil@empty
		\else
			\pgfplotscoordmath{#1}{datascaletrafo}{\csname pgfplots@#1tickmax\endcsname}%
			\expandafter\global\expandafter\let\csname pgfplots@#1tickmax\endcsname=\pgfmathresult
		\fi
%\message{#1- display tick limits after data transformation: [\csname pgfplots@#1tickmin\endcsname:\csname pgfplots@#1tickmax\endcsname]}%
		%
		% Convert any user-specified ticks:
		\edef\pgfplots@loc@TMPa{\csname pgfplots@#1tick\endcsname}%
		% this here should also work with 'xtick=\empty', the "No tick" command.
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\def\pgfplots@loc@TMPb{data}%
			\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
				% we have #1tick = data
				\edef\pgfplots@loc@TMPa{\csname pgfplots@firstplot@coords@#1\endcsname}%
				\expandafter\pgfplotsutil@unify@short@csv@list\expandafter{\pgfplots@loc@TMPa}%
				\let\pgfplots@loc@TMPa=\pgfplotsretval
			\fi
%\message{Converting #1tick='\csname pgfplots@#1tick\endcsname'}%
			\expandafter\pgfplots@apply@data@scale@trafo@to@user@ticks\expandafter{\pgfplots@loc@TMPa}%
				{\pgfplotscoordmath{#1}{datascaletrafo}}%
				\to\pgfplots@loc@TMPc
			\expandafter\let\csname pgfplots@#1tick\endcsname=\pgfplots@loc@TMPc
		\fi
		%
		% Convert any extra-ticks, see above.
		\edef\pgfplots@loc@TMPa{\csname pgfplots@extra@#1tick\endcsname}%
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\edef\pgfplots@loc@TMPa{{\csname pgfplots@extra@#1tick\endcsname}}%
			\expandafter\pgfplots@apply@data@scale@trafo@to@user@ticks\pgfplots@loc@TMPa
				{\pgfplotscoordmath{#1}{datascaletrafo}}%
				\to\pgfplots@loc@TMPc
			\expandafter\let\csname pgfplots@extra@#1tick\endcsname=\pgfplots@loc@TMPc
		\fi
		%
		% Convert any minor tick lists in the same way.
		\pgfkeysgetvalue{/pgfplots/minor #1tick}\pgfplots@loc@TMPa
		\edef\pgfplots@loc@TMPa{\pgfplots@loc@TMPa}%
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\def\pgfplots@loc@TMPb{data}%
			\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
				% we have #1tick = data
				\edef\pgfplots@loc@TMPa{\csname pgfplots@firstplot@coords@#1\endcsname}%
				\expandafter\pgfplotsutil@unify@short@csv@list\expandafter{\pgfplots@loc@TMPa}%
				\let\pgfplots@loc@TMPa=\pgfplotsretval
			\fi
			\expandafter\pgfplots@apply@data@scale@trafo@to@user@ticks\expandafter{\pgfplots@loc@TMPa}%
				{\pgfplotscoordmath{#1}{datascaletrafo}}%
				\to\pgfplots@loc@TMPc
			\pgfkeyslet{/pgfplots/minor #1tick}\pgfplots@loc@TMPc
		\fi
		%
		% Transform any explicit axis unit scalings: ALREADY DONE
	}{%
		% case apply trafo == false:
		\def\pgfplots@loc@TMPb{data}%
		\expandafter\ifx\csname pgfplots@#1tick\endcsname\pgfplots@loc@TMPb
			\edef\pgfplots@loc@TMPa{\csname pgfplots@firstplot@coords@#1\endcsname}%
			\expandafter\pgfplotsutil@unify@short@csv@list\expandafter{\pgfplots@loc@TMPa}%
			\expandafter\let\csname pgfplots@#1tick\endcsname=\pgfplotsretval%
		\fi
		\pgfkeysgetvalue{/pgfplots/minor #1tick}\pgfplots@loc@TMPa
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\def\pgfplots@loc@TMPb{data}%
			\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
				\edef\pgfplots@loc@TMPa{\csname pgfplots@firstplot@coords@#1\endcsname}%
				\expandafter\pgfplotsutil@unify@short@csv@list\expandafter{\pgfplots@loc@TMPa}%
				\pgfkeyslet{/pgfplots/minor #1tick}\pgfplotsretval
			\fi
		\fi
	}%
}

\newif\ifpgfplots@determinedefaultvalues@isuniform
\newif\ifpgfplots@determinedefaultvalues@needs@check@uniformtick
\newif\ifpgfplots@limits@are@computed

\def\pgfplots@handle@invalid@range@defaultlimits{%
	\pgfplotscoordmath{x}{parsenumber}{0}%
	\global\let\pgfplots@xmin=\pgfmathresult
	\pgfplotscoordmath{x}{parsenumber}{1}%
	\global\let\pgfplots@xmax=\pgfmathresult
	\global\let\pgfplots@data@xmin=\pgfplots@xmin
	\global\let\pgfplots@data@xmax=\pgfplots@xmax
	%
	\pgfplotscoordmath{y}{parsenumber}{0}%
	\global\let\pgfplots@ymin=\pgfmathresult
	\pgfplotscoordmath{y}{parsenumber}{1}%
	\global\let\pgfplots@ymax=\pgfmathresult
	\global\let\pgfplots@data@ymin=\pgfplots@ymin
	\global\let\pgfplots@data@ymax=\pgfplots@ymax
}
\def\pgfplots@handle@invalid@range{%
	% COMPLETELY EMPTY AXIS:
	\pgfplotswarning{empty range cleared axis}\pgfplots@loc@TMPa\pgfeov
	\pgfplots@handle@invalid@range@defaultlimits
	%
	\pgfplots@threedimfalse
	\def\pgfplots@xtick{}%
	\def\pgfplots@ytick{}%
	\def\pgfplots@extra@xtick{}%
	\def\pgfplots@extra@ytick{}%
	\def\pgfplots@xtickten{}%
	\def\pgfplots@ytickten{}%
	% clear all plots!
	\pgfplots@init@cleared@structures
}
\def\pgfplots@check@invalid@range{%
	\pgfplots@limits@are@computedtrue
	\def\pgfplots@loc@TMPa{}%
	\ifx\pgfplots@xmin\pgfplots@invalidrange@xmin
		\pgfplots@limits@are@computedfalse
		\edef\pgfplots@loc@TMPa{x}%
	\fi
	\ifx\pgfplots@xmax\pgfplots@invalidrange@xmax
		\pgfplots@limits@are@computedfalse
		\edef\pgfplots@loc@TMPa{x}%
	\fi
	\ifx\pgfplots@ymin\pgfplots@invalidrange@ymin
		\pgfplots@limits@are@computedfalse
		\edef\pgfplots@loc@TMPa{y}%
	\fi
	\ifx\pgfplots@ymax\pgfplots@invalidrange@ymax
		\pgfplots@limits@are@computedfalse
		\edef\pgfplots@loc@TMPa{y}%
	\fi
	\ifpgfplots@threedim
		\ifx\pgfplots@zmin\pgfplots@invalidrange@zmin
			\pgfplots@limits@are@computedfalse
			\edef\pgfplots@loc@TMPa{z}%
		\fi
		\ifx\pgfplots@zmax\pgfplots@invalidrange@zmax
			\pgfplots@limits@are@computedfalse
			\edef\pgfplots@loc@TMPa{z}%
		\fi
	\fi
	\ifpgfplots@limits@are@computed
		\ifx\pgfplots@data@xmin\pgfplots@invalidrange@xmin
			\global\let\pgfplots@data@xmin=\pgfplots@xmin
		\fi
		\ifx\pgfplots@data@xmin\pgfplots@invalidrange@xmax
			\global\let\pgfplots@data@xmax=\pgfplots@xmax
		\fi
		\ifx\pgfplots@data@ymin\pgfplots@invalidrange@ymin
			\global\let\pgfplots@data@ymin=\pgfplots@ymin
		\fi
		\ifx\pgfplots@data@ymin\pgfplots@invalidrange@ymax
			\global\let\pgfplots@data@ymax=\pgfplots@ymax
		\fi
		\ifx\pgfplots@data@zmin\pgfplots@invalidrange@zmin
			\global\let\pgfplots@data@zmin=\pgfplots@zmin
		\fi
		\ifx\pgfplots@data@zmin\pgfplots@invalidrange@zmax
			\global\let\pgfplots@data@zmax=\pgfplots@zmax
		\fi
		\ifpgfplots@clip@limits
		\else
			% there is a rare change that min > max.
			% Handle that ...
			\pgfplotscoordmath{x}{min}{\pgfplots@xmin}{\pgfplots@xmax}%
			\global\let\pgfplots@xmin=\pgfmathresult
			\pgfplotscoordmath{x}{max}{\pgfplots@xmin}{\pgfplots@xmax}%
			\global\let\pgfplots@xmax=\pgfmathresult
			%
			\pgfplotscoordmath{y}{min}{\pgfplots@ymin}{\pgfplots@ymax}%
			\global\let\pgfplots@ymin=\pgfmathresult
			\pgfplotscoordmath{y}{max}{\pgfplots@ymin}{\pgfplots@ymax}%
			\global\let\pgfplots@ymax=\pgfmathresult
			%
			\ifpgfplots@threedim
				\pgfplotscoordmath{z}{min}{\pgfplots@zmin}{\pgfplots@zmax}%
				\global\let\pgfplots@zmin=\pgfmathresult
				\pgfplotscoordmath{z}{max}{\pgfplots@zmin}{\pgfplots@zmax}%
				\global\let\pgfplots@zmax=\pgfmathresult
			\fi
		\fi
	\else
		\pgfplots@handle@invalid@range
	\fi
}%


% This method finishes the accumulated information of axis limits and
% all internal flag fields.
%
% PRECONDITION:  
% 	- all plots are finally finished; axis and data limits are known.
%
% POSTCONDITION:
% 	- the scaling transformation is set-up and applied to all user
% 	inputs and axis limits.
% 	- the \pgfplots@[xy][min,max] variables and associated TeX
% 	registers are set up and final. They should not be changed
% 	afterwards.
% 	- any tick lists etc. are final.
%
\def\pgfplots@determinedefaultvalues{%
	\pgfplots@check@invalid@range
	%
%\message{untransformed: x = [\pgfplots@xmin:\pgfplots@xmax]  y = [\pgfplots@ymin:\pgfplots@ymax]. }%
	%
	%
	\pgfplots@set@default@size@options
	%
	\ifpgfplots@threedim
		\pgfplotsthreedimtrue
	\else
		\pgfplotsthreedimfalse
	\fi
	%
	\pgfplots@set@optimal@datatrafos@allaxes
	%
	% Now, the data scaling has been set up.
	% However, it may need to be changed if axis equal and/or unit
	% vector ratio changes the axis limits considerably. If so, it
	% will be done in \pgfplots@initsizes
	\pgfplots@apply@datatrafo@to@axis@limits x%
	\pgfplots@apply@datatrafo@to@axis@limits y%
	\ifpgfplots@threedim
		\pgfplots@apply@datatrafo@to@axis@limits z%
	\fi
	%
	\pgfplots@datascaletrafo@initialisedtrue
%\message{transformed: x = [\pgfplots@xmin:\pgfplots@xmax]  y = [\pgfplots@ymin:\pgfplots@ymax].}%
	%
	% From now on, we can always work with pgfmath.
	% We simply need to apply the data scaling trafo before doing so.
	\pgfplots@enlarge@limit@ifconfigured x
	\pgfplots@avoid@empty@axis@range@for x%
	%
	\pgfplots@enlarge@limit@ifconfigured y
	\pgfplots@avoid@empty@axis@range@for y%

	\ifpgfplots@threedim
		\pgfplots@enlarge@limit@ifconfigured z
		\pgfplots@avoid@empty@axis@range@for z%
	\fi
	%
	\pgfplots@initsizes
	%
	\pgfplots@check@and@apply@datatrafo@for x%
	\pgfplots@check@and@apply@datatrafo@for y%
	\ifpgfplots@threedim
		\pgfplots@check@and@apply@datatrafo@for z%
	\fi
	% clear structure:
	\global\let\pgfplots@firstplot@coords@x=\pgfutil@empty
	\global\let\pgfplots@firstplot@coords@y=\pgfutil@empty
	\global\let\pgfplots@firstplot@coords@z=\pgfutil@empty
	%
	\pgfplots@limits@ready
	\pgfplotspoint@initialisation
	%
	%
	\pgfplots@BEGIN@prepare@description@styles
	%
	%
	\pgfplots@init@ticks@for x%
	\pgfplots@init@ticks@for y%
	\ifpgfplots@threedim
		\pgfplots@init@ticks@for z%
	\fi
	\pgfplots@init@ticks@ready
	%
	%
	\pgfplots@prepare@ZERO@coordinates
	%
	\pgfplots@decide@which@figure@surfaces@are@drawn
	\pgfplots@init@ticklabelaxisspec
	%
	\pgfplots@define@threedim@marks
	%
	\pgfplots@clippath@prepare
	%
	\pgfplots@ticklabel@maxtickdimen@reset x%
	\pgfplots@ticklabel@maxtickdimen@reset y%
	\pgfplots@ticklabel@maxtickdimen@reset z%
}
\def\pgfplots@init@ticks@ready{}%
\def\pgfplots@init@ticks@for#1{%
	\pgfplots@isuniformticktrue
	\pgfplots@determinedefaultvalues@needs@check@uniformticktrue
	\expandafter\ifx\csname pgfplots@#1tick\endcsname\pgfutil@empty
		\pgfplots@assign@default@tick@foraxis{#1}%
	\fi
	\ifpgfplots@determinedefaultvalues@needs@check@uniformtick
		\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@#1tick\endcsname
		\edef\pgfplots@loc@TMPb{\pgfplots@loc@TMPa}%
		\ifx\pgfplots@loc@TMPb\pgfutil@empty
			% there are no ticks left.
			\pgfplots@isuniformtickfalse
		\else
			\pgfplots@if{pgfplots@#1islinear}{%
				\def\pgfplots@loc@TMPb{\expandafter\pgfplots@checkisuniformLINEARtick\expandafter{\pgfplots@loc@TMPa}}%
				\expandafter\pgfplots@loc@TMPb\csname pgfplots@tick@distance@#1\endcsname%
			}{%
				\expandafter\pgfplots@checkisuniformLOGtick\expandafter{\pgfplots@loc@TMPa}%
			}%
		\fi
	\fi
	\pgfplots@check@for@minor@ticks{#1}%
	\ifpgfplots@isuniformtick
	\else
		\pgfkeysgetvalue{/pgfplots/minor #1tick}\pgfplots@loc@TMPb
		\ifx\pgfplots@loc@TMPb\pgfutil@empty
			\csname pgfplots@#1minorticksfalse\endcsname
			\csname pgfplots@#1minorgridsfalse\endcsname
		\fi
	\fi
	%
	\expandafter\ifx\csname pgfplots@#1ticklabel\endcsname\pgfutil@empty
		\pgfplots@if{pgfplots@#1islinear}{%
			\expandafter\def\csname pgfplots@#1ticklabel\endcsname{\axisdefaultticklabel}%
		}{%
			\expandafter\def\csname pgfplots@#1ticklabel\endcsname{\axisdefaultticklabellog}%
		}% 
	\fi
	\expandafter\ifx\csname pgfplots@extra@#1ticklabel\endcsname\pgfutil@empty
		\pgfutil@namelet{pgfplots@extra@#1ticklabel}{pgfplots@#1ticklabel}%
	\fi
	%
	\if0\csname pgfplots@#1axislinesnum\endcsname\else
		% axis x line* != box
		\expandafter\let\csname pgfplots@#1ticklabel@pos\endcsname=\pgfutil@empty
	\fi
	\expandafter\ifx\csname pgfplots@#1ticklabel@pos\endcsname\pgfutil@empty
		\expandafter\def\csname pgfplots@#1ticklabel@pos\endcsname{%
			\if3\csname pgfplots@#1tickposnum\endcsname% right
				u%
			\else
				l%
			\fi
		}%
	\fi
}%

\def\pgfplots@check@for@minor@ticks#1{%
	\pgfkeysgetvalue{/pgfplots/minor #1 tick num}\pgfplots@loc@TMPa
	\pgfkeysgetvalue{/pgfplots/minor #1tick}\pgfplots@loc@TMPb
	\pgfplots@if{pgfplots@#1islinear}{%
		\ifnum\pgfplots@loc@TMPa=0\relax
			\ifx\pgfplots@loc@TMPb\pgfutil@empty
				\csname pgfplots@#1minorticksfalse\endcsname
				\csname pgfplots@#1minorgridsfalse\endcsname
			\fi
		\else
			\csname pgfplots@#1minortickstrue\endcsname
		\fi
	}{%
	}%
	\ifx\pgfplots@loc@TMPb\pgfutil@empty
	\else
		\csname pgfplots@#1minortickstrue\endcsname
	\fi
}

% Invoked as soon as all axis limits are ready and final (in TeX
% number range, all data scaling is applied at this point).
\def\pgfplots@limits@ready{%
	\pgfplots@limits@ready@tostring{x}{min}%
	\pgfplots@limits@ready@tostring{x}{max}%
	\pgfplots@limits@ready@tostring{y}{min}%
	\pgfplots@limits@ready@tostring{y}{max}%
	\ifpgfplots@threedim
		\pgfplots@limits@ready@tostring{z}{min}%
		\pgfplots@limits@ready@tostring{z}{max}%
	\fi
}%

% write a limit into /pgfplots/#1#2
% #1: either x,y or z
% #2: either 'min' or 'max'
%
% \pgfplots@limits@ready@tostring{x}{min}
\def\pgfplots@limits@ready@tostring#1#2{%
	\pgfplots@if{pgfplots@apply@datatrafo@#1}{%
		\pgfplotscoordmath{#1}{datascaletrafo inverse}{\csname pgfplots@#1#2\endcsname}%
	}{%
		\edef\pgfmathresult{\csname pgfplots@#1#2\endcsname}%
	}%
	\pgfplotscoordmath{#1}{tostring}{\pgfmathresult}%
	\pgfkeyslet{/pgfplots/#1#2}\pgfmathresult
	% this runs \pgfkeyslet{/pgfplots/xmin}\pgfmathresult
}%


\newif\ifpgfplots@avoid@emptyrange@@range@is@approx@equal
% Checks whether axis limits in coordinate #1 are approximately equal.
%
% If that is the case, force a non-zero width of the range.
%
\def\pgfplots@avoid@empty@axis@range@for#1{%
	% Check if axis limits are empty:
	\begingroup
	\expandafter\let\expandafter\if@cur@is@scaled\csname ifpgfplots@apply@datatrafo@#1\endcsname
	\expandafter\let\expandafter\pgfplots@@min\csname pgfplots@#1min\endcsname
	\expandafter\let\expandafter\pgfplots@@max\csname pgfplots@#1max\endcsname
	\let\min@d=\pgf@xa
	\let\max@d=\pgf@xb
	\let\diff=\pgf@xc
	\expandafter\min@d\pgfplots@@min pt %
	\expandafter\max@d\pgfplots@@max pt %
	\diff=\max@d
	\advance\diff by-\min@d
	% FIXME : I need a RELATIVE check here!
	% but: real number point division is expensive
	\if@cur@is@scaled
		% this here should be sufficient because the axis
		% has absolute values of order O( 10^3 ) or so.
		\ifdim\diff<0.0001pt
			\pgfplots@avoid@emptyrange@@range@is@approx@equaltrue
		\fi
	\else
		% there is no data scaling, so I should be much more defensive
		% with absolute thresholds...
		\ifdim\diff<0.0001pt
			\pgfplots@avoid@emptyrange@@range@is@approx@equaltrue
		\fi
	\fi
	\ifpgfplots@avoid@emptyrange@@range@is@approx@equal
		\begingroup
		\pgfplotscoordmath{#1}{datascaletrafo inverse to fixed}{\csname pgfplots@#1min\endcsname}%
		\let\pgfplots@min=\pgfmathresult
		\pgfplotscoordmath{#1}{datascaletrafo inverse to fixed}{\csname pgfplots@#1max\endcsname}%
		\let\pgfplots@max=\pgfmathresult
		\pgfplotswarning{approx empty range enlarged}{#1}{\pgfplots@min}{\pgfplots@max}\pgfeov
		\endgroup
		% the case \pgfplots@@min ~= \pgfplots@@max
		%
		% enlarge \pgfplots@@max and shrink \min:
		\ifdim\max@d<0pt%
			\ifdim\max@d<-1pt%
				\max@d=0.8\max@d
				\min@d=1.2\min@d
			\else
				\advance\max@d by-1pt%
				\advance\min@d by1pt%
			\fi
		\else
			\ifdim\max@d>1pt%
				\max@d=1.2\max@d
				\min@d=0.8\min@d
			\else
				\ifdim\max@d=0pt%
					\if@cur@is@scaled
						\expandafter\let\expandafter\min@unscaled\csname pgfplots@#1min@unscaled@as@float\endcsname
						\expandafter\let\expandafter\max@unscaled\csname pgfplots@#1max@unscaled@as@float\endcsname
						% **sigh**. That's really work.
						%
						% This here happens ALWAYS if min == max for
						% linear axis because the scaling
						% transformation will result in T(min) = T(max) = 0
						%
						% -> we need to enlarge limits in floating
						%  point arithmetics.
						%
						\pgfplotscoordmath{#1}{parsenumber}{0}%
						\let\pgfplotsmath@zero=\pgfmathresult
						%
						\ifx\max@unscaled\pgfplotsmath@zero
							% max == 0
							\pgfplotscoordmath{#1}{parsenumber}{1}%
							\let\max@unscaled=\pgfmathresult
							\pgfplotscoordmath{#1}{parsenumber}{-1}%
							\let\min@unscaled=\pgfmathresult
						\else
							%
							\pgfplotscoordmath{#1}{parsenumber}{1.2}%
							\let\pgfplotsmath@scalea=\pgfmathresult
							\pgfplotscoordmath{#1}{parsenumber}{8e-1}%
							\let\pgfplotsmath@scaleb=\pgfmathresult
							%
							\pgfplotscoordmath{#1}{if less than}
								{\pgfplotsmath@zero}{\max@unscaled}%
								{%
									% 0 < max
									\pgfplotscoordmath{#1}{op}{multiply}
										{{\max@unscaled}{\pgfplotsmath@scalea}}%
									\let\max@unscaled=\pgfmathresult
									\pgfplotscoordmath{#1}{op}{multiply}
										{{\min@unscaled}{\pgfplotsmath@scaleb}}%
									\let\min@unscaled=\pgfmathresult
								}%
								{%
									\pgfplotscoordmath{#1}{op}{multiply}
										{{\max@unscaled}{\pgfplotsmath@scaleb}}%
									\let\max@unscaled=\pgfmathresult
									\pgfplotscoordmath{#1}{op}{multiply}
										{{\min@unscaled}{\pgfplotsmath@scalea}}%
									\let\min@unscaled=\pgfmathresult
								}%
						\fi
						\pgfplotscoordmath{#1}{datascaletrafo}{\min@unscaled}%
						\let\pgfplots@@min=\pgfmathresult
						\pgfplotscoordmath{#1}{datascaletrafo}{\max@unscaled}%
						\let\pgfplots@@max=\pgfmathresult
						\min@d=\pgfplots@@min pt
						\max@d=\pgfplots@@max pt
					\else
						\advance\max@d by1pt
						\advance\min@d by-1pt
					\fi
				\else
					\advance\max@d by1pt
					\advance\min@d by-1pt
				\fi
			\fi
		\fi
		\xdef\pgfplots@glob@TMPa{\pgf@sys@tonumber{\min@d}}%
		\xdef\pgfplots@glob@TMPb{\pgf@sys@tonumber{\max@d}}%
%\pgfplots@message{ -> #1 = \pgfplots@glob@TMPa : \pgfplots@glob@TMPb;}%
	\else
		\global\let\pgfplots@glob@TMPa=\pgfplots@@min%
		\global\let\pgfplots@glob@TMPb=\pgfplots@@max%
	\fi
	\endgroup
	\expandafter\global\expandafter\let\csname pgfplots@#1min\endcsname=\pgfplots@glob@TMPa
	\expandafter\global\expandafter\let\csname pgfplots@#1max\endcsname=\pgfplots@glob@TMPb
}


% should be invoked whenever \pgfplots@#1min or \pgfplots@#1max have
% been changed during the visualization phase (for example, axis equal
% or enlargelimits)
\def\pgfplots@visphase@notify@changeofcanvaslimits#1{%
	\csname pgfplots@#1min@reg\endcsname=\csname pgfplots@#1min\endcsname pt %
	\csname pgfplots@#1max@reg\endcsname=\csname pgfplots@#1max\endcsname pt %
	\pgfplots@if{pgfplots@apply@datatrafo@#1}{%
		\pgfplotscoordmath{#1}{datascaletrafo inverse}{\csname pgfplots@#1min\endcsname}%
		\expandafter\let\csname pgfplots@#1min@unscaled@as@float\endcsname=\pgfmathresult
		\pgfplotscoordmath{#1}{datascaletrafo inverse}{\csname pgfplots@#1max\endcsname}%
		\expandafter\let\csname pgfplots@#1max@unscaled@as@float\endcsname=\pgfmathresult
	}{}%
}%

% Invokes #3 if ||D_#1||_CANVAS  < ||D_#2||_CANVAS  and #4 if that is not the case.
% Here D_x = (1,0,0) , D_y = (0,1,0) and D_z=(0,0,1).
%
% Due to the data scaling transformation,
% ||D_a|| = || T(1) * e_a||
% where e_x, e_y, e_z are the lowlevel, transformed unit vectors.
% We have
% ||D_a|| = T(1) * veclen_a.
% Note that the shift in T is not of interest, we only deal with
% T_a(x) = 10^{s_a} x.
%
% Thus, this routine invokes #3 if 
% ( 10^{s1} * veclen1 < 10^{s2} * veclen2 )
%   <=>
% ( 10^{s1-s2} * veclen1 < veclen2 ).
%
% Here s1/s2 are the respective scales of the data scaling
% transformation.
%
% If the condition is false, '#4' is invoked.
\def\pgfplots@if@unitveclenlessthan@untransformed#1#2#3#4{%
	\def\pgfplots@loc@TMPa{0}%
	\def\pgfplots@loc@TMPb{0}%
	\pgfplots@if{pgfplots@apply@datatrafo@#1}{%
		\pgfplots@letcsname{pgfplots@loc@TMPa}={pgfplots@data@scale@trafo@EXPONENT@#1}%
	}{}%
	\pgfplots@if{pgfplots@apply@datatrafo@#2}{%
		\pgfplots@letcsname{pgfplots@loc@TMPb}={pgfplots@data@scale@trafo@EXPONENT@#2}%
	}{}%
	\begingroup
%\message{[comparison: [#1] < [#2]: 10^\pgfplots@loc@TMPa\space * \csname pgfplots@#1@veclength\endcsname < 10^\pgfplots@loc@TMPb\space * \csname pgfplots@#2@veclength\endcsname]^^J}%
	\pgf@xb=\csname pgfplots@#2@veclength\endcsname pt
	%
	\c@pgf@counta=\pgfplots@loc@TMPa
	\advance\c@pgf@counta by-\pgfplots@loc@TMPb
	%
	\ifnum\c@pgf@counta=0
		\pgf@xa=\csname pgfplots@#1@veclength\endcsname pt
	\else
		\pgfplotsmathmultiplypowten@{\csname pgfplots@#1@veclength\endcsname}{\c@pgf@counta}%
		\pgf@xa=\pgfmathresult pt
	\fi
	%
	\ifdim\pgf@xa<\pgf@xb
		\gdef\pgfplots@glob@TMPc{1}%
	\else
		\gdef\pgfplots@glob@TMPc{0}%
	\fi
	\endgroup
	\if1\pgfplots@glob@TMPc #3\else #4\fi
}%


\def\pgfplots@low@level@shape@INNER@define{%
	\anchor{image}{\pgfpointorigin}%
	%
	%
	\anchor{center}{\pgfplotsqpointdescriptionxy{0.5}{0.5}}%
	\anchor{north}{\pgfplotsqpointdescriptionxy{0.5}{1}}%
	\anchor{north east}{\pgfplotsqpointdescriptionxy{1}{1}}%
	\anchor{east}{\pgfplotsqpointdescriptionxy{1}{0.5}}
	\anchor{south east}{\pgfplotsqpointdescriptionxy{1}{0}}%
	\anchor{south}{\pgfplotsqpointdescriptionxy{0.5}{0}}%
	\anchor{south west}{\pgfplotsqpointdescriptionxy{0}{0}}%
	\anchor{west}{\pgfplotsqpointdescriptionxy{0}{0.5}}%
	\anchor{north west}{\pgfplotsqpointdescriptionxy{0}{1}}%
	%%
	\anchor{origin}{\pgfplotspointaxisorigin}%
	\anchor{above origin}{%
		\pgfpointintersectionoflines
			{\pgfplotspointaxisorigin}
			{\pgfpointadd
				{\pgfplotspointaxisorigin}%
				{\pgfplotspointyaxis
				 \pgfplots@assert@not@zero{\pgf@y}{y axis has eyy=0; cannot compute above origin anchor}%
			    }%
			}%
			{\pgfplotsqpointdescriptionxy{0}{1}}
			{\pgfplotsqpointdescriptionxy{1}{1}}%
	}%
	\anchor{left of origin}{%
		\pgfpointintersectionoflines
			{\pgfplotspointaxisorigin}
			{\pgfpointadd{\pgfplotspointaxisorigin}{\pgfplotspointxaxis}}
			{\pgfplotsqpointdescriptionxy{0}{0}}
			{\pgfplotsqpointdescriptionxy{0}{1}}%
	}%
	\anchor{right of origin}{%
		\pgfpointintersectionoflines
			{\pgfplotspointaxisorigin}
			{\pgfpointadd{\pgfplotspointaxisorigin}{\pgfplotspointxaxis}}
			{\pgfplotsqpointdescriptionxy{1}{0}}
			{\pgfplotsqpointdescriptionxy{1}{1}}%
	}%
	\anchor{below origin}{%
		\pgfpointintersectionoflines
			{\pgfplotspointaxisorigin}
			{\pgfpointadd{\pgfplotspointaxisorigin}{\pgfplotspointyaxis}}
			{\pgfplotsqpointdescriptionxy{0}{0}}
			{\pgfplotsqpointdescriptionxy{1}{0}}%
	}%
}

% This here is a low-weight node. It can ONLY be used during axis
% descriptions and is completely useless otherwise.
%
% See pgfplots@low@level@shape below.
\pgfdeclareshape{pgfplots@low@level@shape@INNER}{%
	\nodeparts{image}%
	%%
	%%
	\pgfplots@low@level@shape@INNER@define
	%%
	%%
	\anchorborder{}%
	\backgroundpath{}%
	\foregroundpath{}%
	\behindbackgroundpath{}%
	\beforebackgroundpath{}%
	\behindforegroundpath{}%
	\beforeforegroundpath{}%
}

% This is the main axis shape.
%
% It has one node part, which is the complete image. It provides a lot
% of anchors.
\pgfdeclareshape{pgfplots@low@level@shape}{%
	% The '(0,0)' point is the LOWER LEFT OUTER CORNER.
	\savedanchor\upperrightcorner{%
		% FIXME : is this correct?
		\pgfplotspointupperrightcorner
		%\global\pgf@x=\wd\pgfnodepartimagebox
		%\global\pgf@y=\ht\pgfnodepartimagebox
	}%
	\savedanchor\lowerleftinnercorner{%
		\pgfplotspointlowerleftinnercorner%
	}%
	\savedanchor\innerdiagonal{\pgfplotspointbbdiagonal}%
	\savedanchor\origin{%
		\pgfplotspointaxisorigin
	}%
	%
	\nodeparts{image}%
	\anchor{image}{%
		\global\pgf@x=0pt %
		\global\pgf@y=0pt %
	}%
	%
	\anchor{center}{%
		\pgfpointadd
			{\lowerleftinnercorner}%
			{\pgfpointscale
				{0.5}
				{\innerdiagonal}}%
	}%
	\anchor{north}{%
		\pgfpointadd
			{\lowerleftinnercorner}
			{\innerdiagonal\global\divide\pgf@x by2 }%
	}%
	\anchor{north east}{%
		\pgfpointadd
			\lowerleftinnercorner
			\innerdiagonal
	}%
	\anchor{east}{%
		\pgfpointadd
			\lowerleftinnercorner
			{\innerdiagonal\global\divide\pgf@y by2 }%
	}%
	\anchor{south east}{%
		\pgfpointadd
			\lowerleftinnercorner
			{\innerdiagonal\global\pgf@y=0sp }%
	}%
	\anchor{south}{%
		\pgfpointadd
			\lowerleftinnercorner
			{\innerdiagonal\global\divide\pgf@x by2 \global\pgf@y=0sp }%
	}%
	\anchor{south west}{\lowerleftinnercorner}%
	\anchor{west}{%
		\pgfpointadd
			\lowerleftinnercorner
			{\innerdiagonal\global\pgf@x=0sp \global\divide\pgf@y by2 }%
	}
	\anchor{north west}{%
		\pgfpointadd
			\lowerleftinnercorner
			{\innerdiagonal\global\pgf@x=0sp }%
	}%
	%%
	\anchor{origin}{%
		\origin
	}%
	\anchor{above origin}{%
		\pgfpointintersectionoflines
			{\origin}
			{\pgfpointadd{\origin}{%
					\innerdiagonal\global\pgf@x=0sp 
					 \pgfplots@assert@not@zero{\pgf@y}{y axis has eyy=0; cannot compute above origin anchor}%
				}%
			}%
			{\pgfpointadd{\lowerleftinnercorner}{\innerdiagonal\global\pgf@x=0sp }}
			{\pgfpointadd{\lowerleftinnercorner}{\innerdiagonal}}%
	}%
	\anchor{left of origin}{%
		\pgfpointintersectionoflines
			{\origin}
			{\pgfpointadd{\origin}{\innerdiagonal\global\multiply\pgf@x by-1 \global\pgf@y=0sp }}
			{\lowerleftinnercorner}
			{\pgfpointadd{\lowerleftinnercorner}{\innerdiagonal\global\pgf@x=0sp }}%
	}%
	\anchor{right of origin}{%
		\pgfpointintersectionoflines
			{\origin}
			{\pgfpointadd{\origin}{\innerdiagonal\global\pgf@y=0sp }}
			{\pgfpointadd{\lowerleftinnercorner}{\innerdiagonal\global\pgf@y=0sp }}
			{\pgfpointadd{\lowerleftinnercorner}{\innerdiagonal}}%
	}%
	\anchor{below origin}{%
		\pgfpointintersectionoflines
			{\origin}
			{\pgfpointadd{\origin}{\innerdiagonal\global\pgf@x=0sp \global\multiply\pgf@y by-1 }}
			{\lowerleftinnercorner}
			{\pgfpointadd{\lowerleftinnercorner}{\innerdiagonal\global\pgf@y=0sp }}%
	}%
	%
	%%
	%
	\anchor{outer north}{%
		\upperrightcorner
		\global\pgf@x=.5\pgf@x
	}%
	\anchor{outer north east}{\upperrightcorner}%
	\anchor{outer east}{%
		\upperrightcorner
		\global\pgf@y=.5\pgf@y
	}%
	\anchor{outer south east}{%
		\upperrightcorner
		\global\pgf@y=0pt
	}%
	\anchor{outer south}{%
		\upperrightcorner
		\global\pgf@x=.5\pgf@x
		\global\pgf@y=0pt
	}%
	\anchor{outer south west}{%
		\global\pgf@x=0pt
		\global\pgf@y=0pt
	}%
	\anchor{outer west}{%
		\upperrightcorner
		\global\pgf@x=0pt
		\global\pgf@y=.5\pgf@y
	}%
	\anchor{outer north west}{%
		\upperrightcorner
		\global\pgf@x=0pt
	}%
	\anchor{outer center}{%
		\upperrightcorner
		\global\pgf@x=.5\pgf@x
		\global\pgf@y=.5\pgf@y
	}%
	%
	%
	%%
	%%
	\anchor{above north}{%
		\upperrightcorner
		\pgfutil@tempdima=\pgf@y
		\pgfpointadd
			{\lowerleftinnercorner}
			{\innerdiagonal\divide\pgf@x by2 }%
		\global\pgf@y=\pgfutil@tempdima
	}%
	\anchor{above north east}{%
		\upperrightcorner
		\pgfutil@tempdima=\pgf@y
		\pgfpointadd
			\lowerleftinnercorner
			\innerdiagonal
		\global\pgf@y=\pgfutil@tempdima
	}%
	\anchor{right of north east}{%
		\upperrightcorner
		\pgfutil@tempdima=\pgf@x
		\pgfpointadd
			\lowerleftinnercorner
			\innerdiagonal
		\global\pgf@x=\pgfutil@tempdima
	}%
	\anchor{right of east}{%
		\upperrightcorner
		\pgfutil@tempdima=\pgf@x
		\pgfpointadd
			\lowerleftinnercorner
			{\innerdiagonal\global\divide\pgf@y by2 }%
		\global\pgf@x=\pgfutil@tempdima
	}%
	\anchor{right of south east}{%
		\upperrightcorner
		\pgfutil@tempdima=\pgf@x
		\pgfpointadd
			\lowerleftinnercorner
			{\innerdiagonal\global\pgf@y=0sp }%
		\global\pgf@x=\pgfutil@tempdima
	}%
	\anchor{below south east}{%
		\pgfpointadd
			\lowerleftinnercorner
			{\innerdiagonal\global\pgf@y=0sp }%
		\global\pgf@y=0pt
	}%
	\anchor{below south}{%
		\pgfpointadd
			\lowerleftinnercorner
			{\innerdiagonal\global\divide\pgf@x by2 \global\pgf@y=0sp }%
		\pgf@y=0pt
	}%
	\anchor{below south west}{%
		\lowerleftinnercorner
		\global\pgf@y=0pt
	}%
	\anchor{left of south west}{%
		\lowerleftinnercorner
		\global\pgf@x=0pt
	}%
	\anchor{left of west}{%
		\pgfpointadd
			\lowerleftinnercorner
			{\innerdiagonal\global\pgf@x=0sp \global\divide\pgf@y by2 }%
		\global\pgf@x=0pt
	}%
	\anchor{left of north west}{%
		\pgfpointadd
			\lowerleftinnercorner
			{\innerdiagonal\global\pgf@x=0sp }%
		\global\pgf@x=0pt
	}%
	\anchor{above north west}{%
		\upperrightcorner
		\pgfutil@tempdima=\pgf@y
		\pgfpointadd
			\lowerleftinnercorner
			{\innerdiagonal\global\pgf@x=0sp }%
		\global\pgf@y=\pgfutil@tempdima
	}%
	%%
	%%
	\anchorborder{%
		% remember the input coords:
		\edef\pgfplots@loc@TMPa{\pgf@x=\the\pgf@x\space\pgf@y=\the\pgf@y\space}%
		%
		% I want to use \pgfpointborderrectangle which expects that
		% (0,0) is the CENTER.
		% Ok, then: shift it:
		\pgfpointadd
			{\lowerleftinnercorner}%
			{\pgfpointscale
				{0.5}
				{\innerdiagonal}}%
		\edef\pgfplots@loc@center{\pgf@x=\the\pgf@x\space\pgf@y=\the\pgf@y\space}%
		\pgfpointadd{%
			\pgfpointborderrectangle%
				{\pgfplots@loc@TMPa}%
				{\pgfpointscale
				{0.5}
				{\innerdiagonal}}%
		}{%
			% and add the center to undo the local shift:
			\pgfplots@loc@center
		}%
	}%
	\backgroundpath{%
		\pgfkeysvalueof{/pgfplots/@backgroundpath@hook/.@cmd}\pgfeov
		\pgfpathrectangle{\pgfpointorigin}{\upperrightcorner}%
	}%
	\foregroundpath{}%
	\behindbackgroundpath{}%
	\beforebackgroundpath{}%
	\behindforegroundpath{}%
	\beforeforegroundpath{}%
}

\def\pgfplots@restore@deprecated@lowlevel@shape{%
	\pgfutil@ifundefined{pgfplots@low@level@shape@deprecated@isdefined}{%
	\gdef\pgfplots@low@level@shape@deprecated@isdefined{1}%
	%
	% all these assignments are global, so it is save to call this
	% macro inside of scopes:
	\pgfdeclareshape{pgfplots@low@level@shape@deprecated}{%
		% The '(0,0)' point is the LOWER LEFT OUTER CORNER.
		\savedanchor\upperrightcorner{
			% FIXME : is this correct?
			\pgfplotspointupperrightcorner
			%\global\pgf@x=\wd\pgfnodepartimagebox
			%\global\pgf@y=\ht\pgfnodepartimagebox
		}%
		\savedanchor\lowerleftinnercorner{%
			\pgfplotspointlowerleftinnercorner%
		}%
		\savedanchor\xaxisvec{\pgfplotspointxaxis}%
		\savedanchor\yaxisvec{\pgfplotspointyaxis}%
		\savedanchor\origin{%
			\pgfplotspointaxisorigin
		}%
		%
		\nodeparts{image}%
		\anchor{image}{%
			\global\pgf@x=0pt %
			\global\pgf@y=0pt %
		}%
		%
		%
		\anchor{center}{%
			\pgfpointadd
				{\lowerleftinnercorner}%
				{\pgfpointscale{0.5}{\pgfpointadd{\xaxisvec}{\yaxisvec}}}%
		}%
		\anchor{north}{%
			\pgfpointadd
				{\lowerleftinnercorner}%
				{\pgfpointadd{\yaxisvec}{\pgfpointscale{0.5}{\xaxisvec}}}%
		}%
		\anchor{north east}{%
			\pgfpointadd
				{\lowerleftinnercorner}%
				{\pgfpointadd{\yaxisvec}{\xaxisvec}}%
		}%
		\anchor{east}{%
			\pgfpointadd
				{\lowerleftinnercorner}%
				{\pgfpointadd{\xaxisvec}{\pgfpointscale{0.5}{\yaxisvec}}}%
		}%
		\anchor{south east}{%
			\pgfpointadd
				{\lowerleftinnercorner}%
				{\xaxisvec}%
		}%
		\anchor{south}{%
			\pgfpointadd
				{\lowerleftinnercorner}%
				{\pgfpointscale{0.5}{\xaxisvec}}%
		}%
		\anchor{south west}{\lowerleftinnercorner}%
		\anchor{west}{%
			\pgfpointadd
				{\lowerleftinnercorner}%
				{\pgfpointscale{0.5}{\yaxisvec}}%
		}%
		\anchor{north west}{%
			\pgfpointadd
				{\lowerleftinnercorner}%
				{\yaxisvec}%
		}%
		%%
		\anchor{origin}{%
			\origin
		}%
		\anchor{above origin}{%
			\pgfpointintersectionoflines
				{\origin}
				{\pgfpointadd{\origin}{\yaxisvec}}
				{\pgfpointadd{\lowerleftinnercorner}{\yaxisvec}}
				{\pgfpointadd{\pgfpointadd{\lowerleftinnercorner}{\yaxisvec}}{\xaxisvec}}%
		}%
		\anchor{left of origin}{%
			\pgfpointintersectionoflines
				{\origin}
				{\pgfpointadd{\origin}{\pgfpointscale{-1}{\xaxisvec}}}
				{\lowerleftinnercorner}
				{\pgfpointadd{\lowerleftinnercorner}{\yaxisvec}}%
		}%
		\anchor{right of origin}{%
			\pgfpointintersectionoflines
				{\origin}
				{\pgfpointadd{\origin}{\xaxisvec}}
				{\pgfpointadd{\lowerleftinnercorner}{\xaxisvec}}
				{\pgfpointadd{\pgfpointadd{\lowerleftinnercorner}{\xaxisvec}}{\yaxisvec}}%
		}%
		\anchor{below origin}{%
			\pgfpointintersectionoflines
				{\origin}
				{\pgfpointadd{\origin}{\pgfpointscale{-1}{\yaxisvec}}}
				{\lowerleftinnercorner}
				{\pgfpointadd{\lowerleftinnercorner}{\xaxisvec}}%
		}%
		%
		%%
		%
		\anchor{outer north}{%
			\upperrightcorner
			\global\pgf@x=.5\pgf@x
		}%
		\anchor{outer north east}{\upperrightcorner}%
		\anchor{outer east}{%
			\upperrightcorner
			\global\pgf@y=.5\pgf@y
		}%
		\anchor{outer south east}{%
			\upperrightcorner
			\global\pgf@y=0pt
		}%
		\anchor{outer south}{%
			\upperrightcorner
			\global\pgf@x=.5\pgf@x
			\global\pgf@y=0pt
		}%
		\anchor{outer south west}{%
			\global\pgf@x=0pt
			\global\pgf@y=0pt
		}%
		\anchor{outer west}{%
			\upperrightcorner
			\global\pgf@x=0pt
			\global\pgf@y=.5\pgf@y
		}%
		\anchor{outer north west}{%
			\upperrightcorner
			\global\pgf@x=0pt
		}%
		\anchor{outer center}{%
			\upperrightcorner
			\global\pgf@x=.5\pgf@x
			\global\pgf@y=.5\pgf@y
		}%
		%
		%
		%%
		%%
		\anchor{above north}{%
			\upperrightcorner
			\pgfutil@tempdima=\pgf@y
			\pgfpointadd
				{\lowerleftinnercorner}%
				{\pgfpointadd{\yaxisvec}{\pgfpointscale{0.5}{\xaxisvec}}}%
			\global\pgf@y=\pgfutil@tempdima
		}%
		\anchor{above north east}{%
			\upperrightcorner
			\pgfutil@tempdima=\pgf@y
			\pgfpointadd
				{\lowerleftinnercorner}%
				{\pgfpointadd{\yaxisvec}{\xaxisvec}}%
			\global\pgf@y=\pgfutil@tempdima
		}%
		\anchor{right of north east}{%
			\upperrightcorner
			\pgfutil@tempdima=\pgf@x
			\pgfpointadd
				{\lowerleftinnercorner}%
				{\pgfpointadd{\yaxisvec}{\xaxisvec}}%
			\global\pgf@x=\pgfutil@tempdima
		}%
		\anchor{right of east}{%
			\upperrightcorner
			\pgfutil@tempdima=\pgf@x
			\pgfpointadd
				{\lowerleftinnercorner}%
				{\pgfpointadd{\xaxisvec}{\pgfpointscale{0.5}{\yaxisvec}}}%
			\global\pgf@x=\pgfutil@tempdima
		}%
		\anchor{right of south east}{%
			\upperrightcorner
			\pgfutil@tempdima=\pgf@x
			\pgfpointadd
				{\lowerleftinnercorner}%
				{\xaxisvec}%
			\global\pgf@x=\pgfutil@tempdima
		}%
		\anchor{below south east}{%
			\pgfpointadd
				{\lowerleftinnercorner}%
				{\xaxisvec}%
			\global\pgf@y=0pt
		}%
		\anchor{below south}{%
			\pgfpointadd
				{\lowerleftinnercorner}%
				{\pgfpointscale{0.5}{\xaxisvec}}%
			\global\pgf@y=0pt
		}%
		\anchor{below south west}{%
			\lowerleftinnercorner
			\global\pgf@y=0pt
		}%
		\anchor{left of south west}{%
			\lowerleftinnercorner
			\global\pgf@x=0pt
		}%
		\anchor{left of west}{%
			\pgfpointadd
				{\lowerleftinnercorner}%
				{\pgfpointscale{0.5}{\yaxisvec}}%
			\global\pgf@x=0pt
		}%
		\anchor{left of north west}{%
			\pgfpointadd
				{\lowerleftinnercorner}%
				{\yaxisvec}%
			\global\pgf@x=0pt
		}%
		\anchor{above north west}{%
			\upperrightcorner
			\pgfutil@tempdima=\pgf@y
			\pgfpointadd
				{\lowerleftinnercorner}%
				{\yaxisvec}%
			\global\pgf@y=\pgfutil@tempdima
		}%
		%%
		%%
		\anchorborder{%
			% Call a function that computes a border point. Since this
			% function will modify dimensions like \pgf@x, we must move them to
			% other dimensions.
			\pgfutil@tempdima=\pgf@x
			\pgfutil@tempdimb=\pgf@y
			\pgfpointborderrectangle%
				{\pgfpoint{\pgfutil@tempdima}{\pgfutil@tempdimb}}%
				{\upperrightcorner}%
		}%
		\backgroundpath{%
			\pgfkeysvalueof{/pgfplots/@backgroundpath@hook/.@cmd}\pgfeov
			\pgfpathrectangle{\pgfpointorigin}{\upperrightcorner}%
		}%
		\foregroundpath{}%
		\behindbackgroundpath{}%
		\beforebackgroundpath{}%
		\behindforegroundpath{}%
		\beforeforegroundpath{}%
	}%
	}{}%
}%


% Defines a new axis type `#1' with initialization code `#2'.
% 
% The name #1 will be available as value for 'axis type=#1' and
% furthermore, an environment '\begin{#1axis}'  will be available.
%
% For ConTeXt, the \start#1axis and \stop#1axis commands will be
% available.
%
% #1: the axis type name
% #2: initialization TeX code.
%
% OPTIONAL: you can provide the expected axis coordinate system in
% square brackets.
%
% \pgfplotsdefineaxistype{rectangle}{...}
% \pgfplotsdefineaxistype[polar]{polar}{...}
\def\pgfplotsdefineaxistype{\pgfutil@ifnextchar[{\pgfplotsdefineaxistype@}{\pgfplotsdefineaxistype@[cart]}}%
\def\pgfplotsdefineaxistype@[#1]#2#3{%
	\expandafter\def\csname pgfplots@axistype@#2\endcsname{%
		\pgfkeyssetvalue{/pgfplots/@expected axis cs}{#1}%
		#3%
	}%
	\expandafter\def\csname pgfplots@environment@#2axis\endcsname{%
		\pgfutil@ifnextchar[%
			{\csname pgfplots@environment@#2axis@\endcsname}%
			{\csname pgfplots@environment@#2axis@\endcsname[]}%
	}%
	\expandafter\long\expandafter\def\csname pgfplots@environment@#2axis@\endcsname[##1]{%
		\begin{axis}[%
			##1,%
			data cs=#1,%  assume that coordinates provided by \addplot are in the correct coordsystem
			axis type=#2% active the correct axis type
		]%
	}%
	\expandafter\def\csname endpgfplots@environment@#2axis\endcsname{\end{axis}}%
	\edef\pgfplots@glob@TMPc{\expandafter\noexpand\csname #2axis\endcsname\expandafter\noexpand\csname pgfplots@environment@#2axis\endcsname}%
	\expandafter
	\tikzaddtikzonlycommandshortcutlet\pgfplots@glob@TMPc
	%
	\edef\pgfplots@glob@TMPc{\expandafter\noexpand\csname end#2axis\endcsname\expandafter\noexpand\csname endpgfplots@environment@#2axis\endcsname}%
	\expandafter
	\tikzaddtikzonlycommandshortcutlet\pgfplots@glob@TMPc
	%
	% ConTeXt compatibility:
	\t@pgfplots@toka=\expandafter{\csname #2axis\endcsname}%
	\t@pgfplots@tokb=\expandafter{\csname end#2axis\endcsname}%
	\expandafter\edef\csname start#2axis\endcsname{\the\t@pgfplots@toka}%
	\expandafter\edef\csname stop#2axis\endcsname{\the\t@pgfplots@tokb}%
}%

\def\pgfplotssetaxistype#1{%
	\pgfutil@IfUndefined{pgfplots@axistype@#1}{%
		\pgfplots@error{Sorry, 'axis type=#1' is unknown. Maybe you need to load a proper library first or you misspelled the name? Ignoring it}%
	}{%
		\csname pgfplots@axistype@#1\endcsname
	}%
}%

% A command which has to be invoked BEFORE \pgfplots@draw@axis to
% prepare everything.
\def\pgfplots@draw@axis@pre{%
	% Preparation for axis lines and discontinuities:
	\pgfplots@drawaxis@lines@preparediscont@for{x}%
	\pgfplots@drawaxis@lines@preparediscont@for{y}%
	\ifpgfplots@threedim
		\pgfplots@drawaxis@lines@preparediscont@for{z}%
	\fi
	\ifpgfplots@threedim
		\pgfplots@separate@axis@linestrue
	\else
		\if\pgfplots@xaxislinesnum0\else
			\pgfplots@separate@axis@linestrue
		\fi
		\if\pgfplots@yaxislinesnum0\else
			\pgfplots@separate@axis@linestrue
		\fi
	\fi
	% compute tick position lists
	% 	\pgfplots@prepared@tick@positions@minor@x
	% and
	% 	\pgfplots@prepared@tick@positions@major@x
	\ifpgfplots@hide@x\else
		\expandafter\pgfplots@prepare@tick@coordlists@for\expandafter x\expandafter{\pgfplots@xtick}%
	\fi
	\ifpgfplots@hide@y\else
		\expandafter\pgfplots@prepare@tick@coordlists@for\expandafter y\expandafter{\pgfplots@ytick}%
	\fi
	\ifpgfplots@threedim
		\ifpgfplots@hide@z\else
			\expandafter\pgfplots@prepare@tick@coordlists@for\expandafter z\expandafter{\pgfplots@ztick}%
		\fi
	\fi
}

\def\pgfplots@draw@axis@is@prepared{}%

% PRECONDITION:
% 	\pgfplots@draw@axis@pre has been called.
\def\pgfplots@draw@axis{%
	%
	%
	%
%\message{Ok, I am now in pgfplots@draw@axis; ready to do work. Hide flags: hide x = \ifpgfplots@hide@x true\else false\fi; hide y = \ifpgfplots@hide@y true\else false\fi hide z = \ifpgfplots@hide@z true \else false \fi. Vector length: x = \pgfplots@x@veclength (1/x = \pgfplots@x@inverseveclength). y = \pgfplots@y@veclength (1/y = \pgfplots@y@inverseveclength) z = \pgfplots@z@veclength (1/z = \pgfplots@z@inverseveclength)}%
	\ifpgfplots@threedim
%\if10
		\if2\pgfplots@zaxislinesnum
			% axis z line*=center
			\pgfplotspointonorientedsurfaceabsetupforsetz{\pgfplots@logical@ZERO@z}{2}%
			\pgfplots@draw@axis@insurface@symmetric xyz
		\else
			% the other cases are handled in
			% \pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn
			\pgfplotspointonorientedsurfaceabsetupforsetz{\pgfplots@zmin}{0}%
			\pgfplots@draw@axis@insurface@symmetric xyz
			%
			\pgfplotspointonorientedsurfaceabsetupforsetz{\pgfplots@zmax}{1}%
			\pgfplots@draw@axis@insurface@symmetric xyz
		\fi
		%
%\fi\if10
		\if2\pgfplots@xaxislinesnum
			% axis x line*=center
			\pgfplotspointonorientedsurfaceabsetupforsetx{\pgfplots@logical@ZERO@x}{2}%
			\pgfplots@draw@axis@insurface@onlyticksandgrid yzx
			\pgfplots@draw@axis@insurface zyx
		\else
			\pgfplotspointonorientedsurfaceabsetupforsetx{\pgfplots@xmin}{0}%
			\pgfplots@draw@axis@insurface@onlyticksandgrid yzx
			\pgfplots@draw@axis@insurface zyx
			%
			\pgfplotspointonorientedsurfaceabsetupforsetx{\pgfplots@xmax}{1}%
			\pgfplots@draw@axis@insurface@onlyticksandgrid yzx
			\pgfplots@draw@axis@insurface zyx
		\fi
%\fi\if10
		%
		\if2\pgfplots@yaxislinesnum
			\pgfplotspointonorientedsurfaceabsetupforsety{\pgfplots@logical@ZERO@y}{2}%
			\pgfplots@draw@axis@insurface@onlyticksandgrid xzy
			\pgfplots@draw@axis@insurface@onlyticksandgrid zxy
		\else
			\pgfplotspointonorientedsurfaceabsetupforsety{\pgfplots@ymin}{0}%
			\pgfplots@draw@axis@insurface@onlyticksandgrid xzy
			\pgfplots@draw@axis@insurface@onlyticksandgrid zxy
			%
			\pgfplotspointonorientedsurfaceabsetupforsety{\pgfplots@ymax}{1}%
			\pgfplots@draw@axis@insurface@onlyticksandgrid xzy
			\pgfplots@draw@axis@insurface@onlyticksandgrid zxy
		\fi
%\fi
	\else
		% Just use the 2d-point commands (assuming Z=0)
		\let\pgfplotspointonorientedsurfaceabsetupfor@@xyz=\pgfplotspointonorientedsurfaceabsetupfor@@xy
		\let\pgfplotspointonorientedsurfaceabsetupfor@@yxz=\pgfplotspointonorientedsurfaceabsetupfor@@yx
		\pgfplots@draw@axis@insurface@symmetric xyz
	\fi
}%

% The complement of \pgfplots@draw@axis which will ALWAYS be drawn on
% top of every thing else; it complements the rest.
%
% This implements only the 3d box=complete feature.
%
% PRECONDITION:
% 	\pgfplots@draw@axis@pre has been called.
\def\pgfplots@draw@axis@post{%
	\ifpgfplots@threedim
		\if0\pgfplots@threedimbox@choice
			% 3d box=background
		\else
			\if0\pgfplots@xaxislinesnum
			\else
				\def\pgfplots@threedimbox@choice{0}%
			\fi
			\if0\pgfplots@yaxislinesnum
			\else
				\def\pgfplots@threedimbox@choice{0}%
			\fi
			\if0\pgfplots@zaxislinesnum
			\else
				\def\pgfplots@threedimbox@choice{0}%
			\fi
			\if\pgfplots@threedimbox@choice0%
				\pgfplots@error{Sorry, your choice for '3d box' and 'axis x line' is incompatible.}%
			\else
				% 3d box=complete or complete*
				\pgfplotsgetlayerforstyle{every 3d box foreground}%
				\pgfplotsonlayer{\pgfplotsretval}{every 3d box foreground}%
				\begingroup
				\pgfplots@layered@graphicsfalse% no distinction of layers here.
				\pgfplotsset{every 3d box foreground}%
				\let\pgfplots@drawticklabels@onorientedsurf=\relax
				\if2\pgfplots@threedimbox@choice
					\def\pgfplots@ifgridlines@onorientedsurf@should@be@drawn##1##2{%
						##1%
					}%
				\else
					\let\pgfplots@drawgridlines@onorientedsurf=\relax
				\fi
				%
				\let\pgfplots@drawticklabels@onorientedsurf=\relax
				%
				% negate the meaning of this if:
				\let\pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn@@ORIG=\pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn@%
				\def\pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn@##1##2##3{%
					\pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn@@ORIG{##1}{##3}{##2}%
				}%
				%
				% the following code is *almost* the same as if we would
				% have called
				% \pgfplots@draw@axis again.
				% The difference is in the
				% \pgfplotsifaxissurfaceisforeground checks. 
				% Furthermore, I have removed the case distinctions for
				% the different axis line combinations.
	%\if10
				% axis z line*=box
				%
				\pgfplotsifaxissurfaceisforeground{vv0}{%
					\pgfplotspointonorientedsurfaceabsetupforsetz{\pgfplots@zmin}{0}%
					\pgfplots@draw@axis@insurface@symmetric xyz
				}{}%
				%
				\pgfplotsifaxissurfaceisforeground{vv1}{%
					\pgfplotspointonorientedsurfaceabsetupforsetz{\pgfplots@zmax}{1}%
					\pgfplots@draw@axis@insurface@symmetric xyz
				}{}%
				%
	%\fi\if10
				% axis x line*=box
				\pgfplotsifaxissurfaceisforeground{0vv}{%
					\pgfplotspointonorientedsurfaceabsetupforsetx{\pgfplots@xmin}{0}%
					\pgfplots@draw@axis@insurface@onlyticksandgrid yzx
					\pgfplots@draw@axis@insurface zyx
				}{}
				%
				\pgfplotsifaxissurfaceisforeground{1vv}{%
					\pgfplotspointonorientedsurfaceabsetupforsetx{\pgfplots@xmax}{1}%
					\pgfplots@draw@axis@insurface@onlyticksandgrid yzx
					\pgfplots@draw@axis@insurface zyx
				}{}
	%\fi\if11
				%
				\pgfplotsifaxissurfaceisforeground{v0v}{%
					\pgfplotspointonorientedsurfaceabsetupforsety{\pgfplots@ymin}{0}%
					\pgfplots@draw@axis@insurface@onlyticksandgrid xzy
					\pgfplots@draw@axis@insurface@onlyticksandgrid zxy
				}{}%
				%
				\pgfplotsifaxissurfaceisforeground{v1v}{%
					\pgfplotspointonorientedsurfaceabsetupforsety{\pgfplots@ymax}{1}%
					\pgfplots@draw@axis@insurface@onlyticksandgrid xzy
					\pgfplots@draw@axis@insurface@onlyticksandgrid zxy
				}{}%
	%\fi
				\endgroup
				\endpgfplotsonlayer
				% end of 3d box=complete
			\fi
		\fi
	\fi
}%

\def\pgfplots@define@threedim@marks{%
	\ifpgfplots@threedim
		% FIXME : there is always the same arithmetics going on here. I could try to optimize it -- for fixed mark size.
		\pgfdeclareplotmark{cube}
		{%
			\pgfplots@cube@gethalf@x
			\let\pgfplots@cube@halfx=\pgfmathresult
			\pgfplots@cube@gethalf@y
			\let\pgfplots@cube@halfy=\pgfmathresult
			\pgfplots@cube@gethalf@z
			\let\pgfplots@cube@halfz=\pgfmathresult
			%
			\pgfpathmoveto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
			\pgfpathlineto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
			\pgfpathlineto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
			\pgfpathlineto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
			\pgfpathclose
			%
			\pgfpathmoveto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
			\pgfpathlineto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
			\pgfpathlineto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
			\pgfpathlineto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
			\pgfpathclose
			%
			\pgfpathmoveto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
			\pgfpathlineto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
			%
			\pgfpathmoveto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
			\pgfpathlineto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
			%
			\pgfpathmoveto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
			\pgfpathlineto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
			%
			\pgfpathmoveto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
			\pgfpathlineto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
			\pgfusepathqstroke
			%
		}%
		\pgfdeclareplotmark{cube*}
		{%
			\pgfplots@cube@gethalf@x
			\let\pgfplots@cube@halfx=\pgfmathresult
			\pgfplots@cube@gethalf@y
			\let\pgfplots@cube@halfy=\pgfmathresult
			\pgfplots@cube@gethalf@z
			\let\pgfplots@cube@halfz=\pgfmathresult
			%
			\pgfplotsifaxissurfaceisforeground{0vv}{%
				\pgfpathmoveto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
				\pgfpathlineto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
				\pgfpathlineto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
				\pgfpathlineto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
				\pgfpathclose
				\pgfusepathqfillstroke
			}{%
				\pgfpathmoveto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
				\pgfpathlineto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
				\pgfpathlineto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
				\pgfpathlineto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
				\pgfpathclose
				\pgfusepathqfillstroke
			}%
			\pgfplotsifaxissurfaceisforeground{v0v}{%
				\pgfpathmoveto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
				\pgfpathlineto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
				\pgfpathlineto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
				\pgfpathlineto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
				\pgfpathclose
				\pgfusepathqfillstroke
			}{%
				\pgfpathmoveto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
				\pgfpathlineto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
				\pgfpathlineto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
				\pgfpathlineto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
				\pgfpathclose
				\pgfusepathqfillstroke
			}%
			\pgfplotsifaxissurfaceisforeground{vv0}{%
				\pgfpathmoveto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
				\pgfpathlineto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
				\pgfpathlineto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
				\pgfpathlineto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{-\pgfplots@cube@halfz}}%
				\pgfpathclose
				\pgfusepathqfillstroke
			}{%
				\pgfpathmoveto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
				\pgfpathlineto{\pgfplotsqpointxyz{-\pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
				\pgfpathlineto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{ \pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
				\pgfpathlineto{\pgfplotsqpointxyz{ \pgfplots@cube@halfx}{-\pgfplots@cube@halfy}{ \pgfplots@cube@halfz}}%
				\pgfpathclose
				\pgfusepathqfillstroke
			}%
		}%
	\else
		\pgfdeclareplotmark{cube}{\pgfuseplotmark{square}}%
		\pgfdeclareplotmark{cube*}{\pgfuseplotmark{square*}}%
	\fi
}

% Defines booleans for every surface of the axis cube indicating
% whether they shall be drawn or not.
%
% For 2D, the only available surface is 'vv0' (x=varying; y=varying; z=zmin)
% For 3D, there are surfaces
% 	- 'vv0' 'vv1'
% 	- 'v0v' 'v1v'
% 	' '0vv' '1vv'
% 
% @see \pgfplotspointonorientedsurfaceabmatchaxisline for details
% about those three-character ids.
%
% @PRECONDITION
%
% @POSTCONDITION
%   - for every available surface, a macro '\pgfplots@surfviewdepth@CCC'
%   is defined to be either 'f' (foreground) or 'b' (background).
%   Thus, we don't have real TeX booleans, "only" those one-character
%   strings.
%   There are high-level routines to check these flags.
%   - every tick label position will be initialised, i.e. the macros
%   	\pgfplots@[xyz]ticklabelaxisspec
%     will be initialised.
%
% ABOUT THE ALGORITHM:
% Given \pgfplots@view@dir@threedim, we know the view direction (in 3D!).
% Now, we compute the scalar products <n,(1,0,0)'>  <n,(0,1,0)'> and
% <n,(0,0,1)'> between the view direction n and the unit vectors in 3D
% space. Of course, these scalar products are just specific components
% of n. Using the sign of the scalar product, we know whether n points
% roughly into the same or the opposite direction of each unit vector
% and we can deduce foreground and background side surfaces of the
% unit cube. The idea is: foreground surfaces won't be drawn, only
% background surfaces.
%
% Given this knowledge, we can also deduce the default axes for tick
% labels.
%
% The operation is relatively fast.
\def\pgfplots@decide@which@figure@surfaces@are@drawn{%
	\expandafter\def\csname pgfplots@surfviewdepth@2vv\endcsname{f}% 
	\expandafter\def\csname pgfplots@surfviewdepth@v2v\endcsname{f}% 
	\expandafter\def\csname pgfplots@surfviewdepth@vv2\endcsname{f}% 
	\ifpgfplots@threedim
		\pgfplotsmathvectortocomponents\pgfplots@view@dir@threedim{pgfplots@loc@}{default}%
		% respect reversed axes here. If I am not mistaken, it should
		% be completely sufficient to flip signs here:
		\pgfplotscoordmath{default}{if is}{\pgfplots@loc@x}{\if\pgfkeysvalueof{/pgfplots/x dir/value}n+\else-\fi}{%
			\expandafter\def\csname pgfplots@surfviewdepth@0vv\endcsname{f}% foreground
			\expandafter\def\csname pgfplots@surfviewdepth@1vv\endcsname{b}% background
		}{%
			\expandafter\def\csname pgfplots@surfviewdepth@0vv\endcsname{b}% 
			\expandafter\def\csname pgfplots@surfviewdepth@1vv\endcsname{f}% 
		}%
		\pgfplotscoordmath{default}{if is}{\pgfplots@loc@y}{\if\pgfkeysvalueof{/pgfplots/y dir/value}n+\else-\fi}{%
			\expandafter\def\csname pgfplots@surfviewdepth@v0v\endcsname{f}% foreground
			\expandafter\def\csname pgfplots@surfviewdepth@v1v\endcsname{b}% background
		}{%
			\expandafter\def\csname pgfplots@surfviewdepth@v0v\endcsname{b}% 
			\expandafter\def\csname pgfplots@surfviewdepth@v1v\endcsname{f}% 
		}%
		\pgfplotscoordmath{default}{if is}{\pgfplots@loc@z}{\if\pgfkeysvalueof{/pgfplots/z dir/value}n+\else-\fi}{%
			\expandafter\def\csname pgfplots@surfviewdepth@vv0\endcsname{f}% foreground
			\expandafter\def\csname pgfplots@surfviewdepth@vv1\endcsname{b}% background
		}{%
			\expandafter\def\csname pgfplots@surfviewdepth@vv0\endcsname{b}% 
			\expandafter\def\csname pgfplots@surfviewdepth@vv1\endcsname{f}% 
		}%
	\else
		% FIXME : it might be better to implement that stuff here
		% implicilty using the 3D algorithms.
		%
		% this here is the only important one:
		\expandafter\def\csname pgfplots@surfviewdepth@vv0\endcsname{b}% 
		%
		\expandafter\def\csname pgfplots@surfviewdepth@0vv\endcsname{b}% 
		\expandafter\def\csname pgfplots@surfviewdepth@1vv\endcsname{f}% 
		\expandafter\def\csname pgfplots@surfviewdepth@v0v\endcsname{b}% 
		\expandafter\def\csname pgfplots@surfviewdepth@v1v\endcsname{f}% 
		\expandafter\def\csname pgfplots@surfviewdepth@vv1\endcsname{f}% 
		\def\pgfplotsifaxislineisonconvexhull##1##2##3{##2}% ALWAYS TRUE
		\def\pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn@##1##2##3{##2}% ALWAYS TRUE
		%
	\fi
}

% Initialises the 'pgfplots@[xyz]ticklabelaxisspecs' macro according to
% the foreground/background situation of the axis and the '[xyz]ticklabel pos' 
% keys.
\def\pgfplots@init@ticklabelaxisspec{%
	\ifpgfplots@threedim
		%
		%
		% Now, determine which axis line shall get tick labels.
		% The strategy is as follows:
		% - only lines on the convex hull of the 2D projected axis
		%   rectangle can get tick labels,
		% - for each axis, there are two such choices in the general
		%   case,
		% - for X and Y: prefer the one on the lower side.
		% - for Z: prefer the one on the left hand side.
		%
		\pgfplotspointcenter
		\edef\pgfplots@tmp@centerx{\the\pgf@x}%
		\edef\pgfplots@tmp@centery{\the\pgf@y}%
		%
		\pgfplots@init@ticklabelaxisspecfor xy%
		%
		\pgfplots@init@ticklabelaxisspecfor yy%
		%
		\pgfplots@init@ticklabelaxisspecfor zx%
	\else
		\pgfplotspointcenter
		\edef\pgfplots@tmp@centerx{\the\pgf@x}%
		\edef\pgfplots@tmp@centery{\the\pgf@y}%
		%
		\pgfplots@init@ticklabelaxisspec@twodim@for xy%
		%
		\pgfplots@init@ticklabelaxisspec@twodim@for yx%
	\fi
}%

% A helper method which is to be invoked ONLY inside of
% \pgfplots@init@ticklabelaxisspec.
% It does NOT work outside of it.
%
% It initialises the 'pgfplots@#1ticklabelaxisspec' macro according to
% the foreground/background situation of the axis and the '#1ticklabel pos' 
% key.
%
% #1: the axis: x,y or z
% #2: either x or y. It refers to the PROJECTED coordinate which
% should be used to compare the 'lower' and 'upper' arguments of the 
% |[xyz]ticklabel pos| key.
%  
% PRECONDITION:
% 	\pgfplots@tmp@center[xy] is set.
%
% POSTCONDITION:
% 	- pgfplots@#1ticklabelaxisspec is set,
%
% @see also \pgfplots@init@ticklabelaxisspec@twodim@for
\def\pgfplots@init@ticklabelaxisspecfor#1#2{%
	\if#1x%
		\def\pgfplots@loc@to@threedim##1##2{v##1##2}%
		\def\pgfplots@loc@axischar@for@first{y}%
	\else
		\if#1y%
			\def\pgfplots@loc@to@threedim##1##2{##1v##2}%
			\def\pgfplots@loc@axischar@for@first{x}%
		\else
			\def\pgfplots@loc@to@threedim##1##2{##1##2v}%
			\def\pgfplots@loc@axischar@for@first{x}%
		\fi
	\fi
	%
	% First, compute stuff as if we had a box. Ignore the "center"
	% styles with a single axis line for now.
	%
	\pgfplotsifaxislineisonconvexhull{\pgfplots@loc@to@threedim 00}{%
		% -> both, v00 or v11 are on CH.
		%
		% Decide whether the '{0.5}{0}{0}' point is above or below
		% the {0.5}{0.5}{0.5}
		% point. This '<' operation is based on the '#1ticklabel pos'
		% key, the 2D projection of the axis and the argument '#2'.
		\expandafter\edef\csname pgfplots@#1ticklabelaxisspec\endcsname{\pgfplots@loc@to@threedim 00}%
		\pgfqpointscale{0.5}{\csname pgfplotspoint#1axis\endcsname}%
		\ifdim\csname pgf@#2\endcsname<\csname pgfplots@tmp@center#2\endcsname\relax
			\if u\csname pgfplots@#1ticklabel@pos\endcsname
				\expandafter\edef\csname pgfplots@#1ticklabelaxisspec\endcsname{\pgfplots@loc@to@threedim 11}%
			\fi
		\else
			\if l\csname pgfplots@#1ticklabel@pos\endcsname
				\expandafter\edef\csname pgfplots@#1ticklabelaxisspec\endcsname{\pgfplots@loc@to@threedim 11}%
			\fi
		\fi
	}{%
		% -> both, v01 or v10 are on CH
		%--------------------------------------------------
		% \pgfplotsifaxislineisonconvexhull{\pgfplots@loc@to@threedim 01}{% FIXME : eliminate sanity assertion if possible
		% }{%
		% 	\pgfplots@error{INTERNAL ERROR}%
		% }%
		%-------------------------------------------------- 
		% Decide whether the '{0.5}{1}{0}' point is above or below
		% the {0.5}{0.5}{0.5} point. Again, the '<' operation is based
		% on the '#1ticklabel pos' key, the projection and #2.
		\expandafter\edef\csname pgfplots@#1ticklabelaxisspec\endcsname{\pgfplots@loc@to@threedim 10}%
		% compute the middle point on \pgfplots@loc@to@threedim 10
		\pgfpointadd
			{\csname pgfplotspoint\pgfplots@loc@axischar@for@first axis\endcsname}
			{\pgfpointscale{0.5}{\csname pgfplotspoint#1axis\endcsname}}%
		%
		\ifdim\csname pgf@#2\endcsname<\csname pgfplots@tmp@center#2\endcsname\relax
			\if u\csname pgfplots@#1ticklabel@pos\endcsname
				\expandafter\edef\csname pgfplots@#1ticklabelaxisspec\endcsname{\pgfplots@loc@to@threedim 01}%
			\fi
		\else
			\if l\csname pgfplots@#1ticklabel@pos\endcsname
				\expandafter\edef\csname pgfplots@#1ticklabelaxisspec\endcsname{\pgfplots@loc@to@threedim 01}%
			\fi
		\fi
	}%
	%
	% Now, adapt result to "center" styles:
	\if2\csname pgfplots@#1axislinesnum\endcsname
		% axis #1 lines=center .
		%
		\expandafter\edef\csname pgfplots@#1ticklabelaxisspec@box\endcsname{\csname pgfplots@#1ticklabelaxisspec\endcsname}%
		%
		% well, for 3d, this implies that all others also have
		% "center". And since "0" == lower, "1" == upper", "2" ==
		% center, we have to use center:
		\expandafter\edef\csname pgfplots@#1ticklabelaxisspec\endcsname{\pgfplots@loc@to@threedim 22}%
	\fi
}%
\def\pgfplots@init@ticklabelaxisspec@twodim@for#1#2{%
	% First, compute stuff as if we had a box. Ignore the "center"
	% styles with a single axis line for now.
	%
	\if#1x%
		\def\pgfplots@loc@to@threedim##1{v##10}%
		\def\pgfplots@loc@axischar@for@first{y}%
	\else
		\def\pgfplots@loc@to@threedim##1{##1v0}%
		\def\pgfplots@loc@axischar@for@first{x}%
	\fi
	% Decide whether the '{0.5}{0}' point is above or below
	% the {0.5}{0.5}
	% point. This '<' operation is based on the '#1ticklabel pos'
	% key, the 2D projection of the axis and the argument '#2'.
	\expandafter\edef\csname pgfplots@#1ticklabelaxisspec\endcsname{\pgfplots@loc@to@threedim 0}%
	\pgfqpointscale{0.5}{\csname pgfplotspoint#1axis\endcsname}%
	\ifdim\csname pgf@#2\endcsname<\csname pgfplots@tmp@center#2\endcsname\relax
		\if u\csname pgfplots@#1ticklabel@pos\endcsname
			\expandafter\edef\csname pgfplots@#1ticklabelaxisspec\endcsname{\pgfplots@loc@to@threedim 1}%
		\fi
	\else
		%--------------------------------------------------
		%FIXME : I have the impression that this here is DEPRECATED
		% \if3\csname pgfplots@#1tickposnum\endcsname % is 'right'
		% 	\expandafter\def\csname pgfplots@#1tickposnum\endcsname{1}% set to 'left'
		% \else
		% 	\if1\csname pgfplots@#1tickposnum\endcsname % is 'left'
		% 		\expandafter\def\csname pgfplots@#1tickposnum\endcsname{3}% set to 'right'
		% 	\fi
		% \fi
		%-------------------------------------------------- 
		\if l\csname pgfplots@#1ticklabel@pos\endcsname
			\expandafter\edef\csname pgfplots@#1ticklabelaxisspec\endcsname{\pgfplots@loc@to@threedim 1}%
		\fi
	\fi
	%
	% Now, adapt result to "center" styles:
	\if2\csname pgfplots@#1axislinesnum\endcsname
		% axis #1 lines=center .
		%
		\expandafter\edef\csname pgfplots@#1ticklabelaxisspec@box\endcsname{\csname pgfplots@#1ticklabelaxisspec\endcsname}%
		%
		% well, for 3d, this implies that all others also have
		% "center". And since "0" == lower, "1" == upper", "2" ==
		% center, we have to use center:
		\expandafter\edef\csname pgfplots@#1ticklabelaxisspec\endcsname{\pgfplots@loc@to@threedim 2}%
	\fi
}%


% Processes every tick mark in direction #1 and draws tick lines, tick
% labels, grid lines, axis lines and extra ticks.
% 
% #1 : the direction into which tick positions are processed.
% #2 : the direction in which tick lines and grid lines shall be drawn.
% #3 : the direction which is currently fixed.
\def\pgfplots@draw@axis@insurface#1#2#3{%
	\pgfplots@if{pgfplots@hide@#1}{\relax}{%
		\pgfplotspointonorientedsurfaceabsetupfor #1#2#3%
		\pgfplots@drawgridlines@onorientedsurf
		%
		\pgfplots@drawticklines@onorientedsurf
		%
		\pgfplots@drawaxis@outerlines@separate@onorientedsurf#1#2%
		\pgfplots@drawaxis@innerlines@onorientedsurf#1#2#3%
		%
		\pgfplots@drawticklabels@onorientedsurf
		%
		\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@extra@#1tick\endcsname
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\pgfplotspointonorientedsurfaceabsetupfor #1#2#3%
			\expandafter\pgfplots@draw@extra@ticks@onorientedsurf\expandafter{\pgfplots@loc@TMPa}%
		\fi
	}%
}%

% A variant of \pgfplots@draw@axis@insurface which is equivalent to
% \pgfplots@draw@axis@insurface #1#2#3
% \pgfplots@draw@axis@insurface #2#1#3
% with slightly optimized execution sequence.
\def\pgfplots@draw@axis@insurface@symmetric#1#2#3{%
	\pgfplots@if{pgfplots@hide@#1}{\relax}{%
		\pgfplotspointonorientedsurfaceabsetupfor #1#2#3%
		\pgfplots@drawgridlines@onorientedsurf
	}%
	\pgfplots@if{pgfplots@hide@#2}{\relax}{%
		\pgfplotspointonorientedsurfaceabsetupfor #2#1#3%
		\pgfplots@drawgridlines@onorientedsurf
	}%
	%
	\pgfplots@if{pgfplots@hide@#1}{\relax}{%
		\pgfplotspointonorientedsurfaceabsetupfor #1#2#3%
		\pgfplots@drawticklines@onorientedsurf
	}%
	\pgfplots@if{pgfplots@hide@#2}{\relax}{%
		\pgfplotspointonorientedsurfaceabsetupfor #2#1#3%
		\pgfplots@drawticklines@onorientedsurf
	}%
	%
	\ifpgfplots@separate@axis@lines
		\pgfplots@if{pgfplots@hide@#1}{\relax}{%
			\pgfplotspointonorientedsurfaceabsetupfor #1#2#3%
			\pgfplots@drawaxis@outerlines@separate@onorientedsurf#1#2%
			\pgfplots@drawaxis@innerlines@onorientedsurf#1#2#3%
		}%
		%
		\pgfplots@if{pgfplots@hide@#2}{\relax}{%
			\pgfplotspointonorientedsurfaceabsetupfor #2#1#3%
			\pgfplots@drawaxis@outerlines@separate@onorientedsurf#2#1%
			\pgfplots@drawaxis@innerlines@onorientedsurf#2#1#3%
		}%
	\else
		% this happens if and only if d=2 and the axis lines are drawn
		% as box.
		\pgfplots@drawaxis@outerlines@cycledpath
	\fi
	%
	\pgfplots@if{pgfplots@hide@#1}{\relax}{%
		\pgfplotspointonorientedsurfaceabsetupfor #1#2#3%
		\pgfplots@drawticklabels@onorientedsurf
	}%
	\pgfplots@if{pgfplots@hide@#2}{\relax}{%
		\pgfplotspointonorientedsurfaceabsetupfor #2#1#3%
		\pgfplots@drawticklabels@onorientedsurf
	}%
	%
	\pgfplots@if{pgfplots@hide@#1}{\relax}{%
		\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@extra@#1tick\endcsname
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\pgfplotspointonorientedsurfaceabsetupfor #1#2#3%
			\expandafter\pgfplots@draw@extra@ticks@onorientedsurf\expandafter{\pgfplots@loc@TMPa}%
		\fi
	}%
	\pgfplots@if{pgfplots@hide@#2}{\relax}{%
		\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@extra@#2tick\endcsname
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\pgfplotspointonorientedsurfaceabsetupfor #2#1#3%
			\expandafter\pgfplots@draw@extra@ticks@onorientedsurf\expandafter{\pgfplots@loc@TMPa}%
		\fi
	}%
}%

\def\pgfplots@draw@axis@insurface@onlyticksandgrid#1#2#3{%
	\pgfplots@if{pgfplots@hide@#1}{\relax}{%
		\pgfplotspointonorientedsurfaceabsetupfor #1#2#3%
		\pgfplots@drawgridlines@onorientedsurf
		\pgfplots@drawticklines@onorientedsurf
		%
		\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@extra@#1tick\endcsname
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\begingroup
			\let\pgfplots@drawticklabels@onorientedsurf=\relax
			\pgfplotspointonorientedsurfaceabsetupfor #1#2#3%
			\expandafter\pgfplots@draw@extra@ticks@onorientedsurf\expandafter{\pgfplots@loc@TMPa}%
			\endgroup
		\fi
	}%
}%

% Handles the 'every 3d description' style.
%
% This requires a different type of attention than any other key --
% because all other keys are set in a context where the dimension of
% the axis is unknown (it might be 2 or 3 dimensional).
%
% The idea is:
% Call \pgfplots@BEGIN@prepare@description@styles as soon as the
% dimension is fixed, but before any style changes of the user
% interface are applied.
%
% Example:
% \begin{axis}[xlabel style={}]
% will be processed here. The reason: 'every 3d description' will
% certainly use a different style for axis labels than the default 2d
% style.
%
% Thus, all style changes which are relevant for 'every 3d description' 
% have NOT YET been processed (they have been appended to 'every axis').
\def\pgfplots@BEGIN@prepare@description@styles{%
	\ifpgfplots@threedim
		\pgfplotsset{every 3d description,every 3d view {\pgfkeysvalueof{/pgfplots/view/az}}{\pgfkeysvalueof{/pgfplots/view/el}}/.try}%
	\fi
	\pgfkeysgetvalue{/pgfplots/.unknown/.@cmd}\pgfplots@BEGIN@prepare@description@styles@oldhandler
	\pgfkeysdef{/pgfplots/.unknown}{}% ignore unknown keys here.
	\pgfkeysactivatefamily{/pgfplots/style commands}%
	\pgfkeysactivatefamily{/pgfplots/descriptions}%
%\pgfkeys{/pgfplots/every axis/.show code}%
	\pgfplots@set@keys@from@tikz@style{every axis}%
	\pgfkeysdeactivatefamily{/pgfplots/descriptions}%
	\pgfkeysdeactivatefamily{/pgfplots/style commands}%
	\pgfkeyslet{/pgfplots/.unknown/.@cmd}\pgfplots@BEGIN@prepare@description@styles@oldhandler
}%

\newif\ifpgfplots@layered@graphics


% Shortcut for '\pgfplotsset{set layers={#1}}'.
%	
% USAGE:
% 1. \pgfplotssetlayers{<layer config name>} (one declared with /.define layer set)
% 2. \pgfplotssetlayers (no braces)
% 3. \pgfplotssetlayers{<comma-separated-list-of-layers>}
%
% This command immediately installs a \pgfsetlayers command. It also prepares following axes.
% ATTENTION: this might affect tikzpictures as well.
%
\def\pgfplotssetlayers{%
	\pgfutil@ifnextchar\bgroup{\pgfplotssetlayers@}{\pgfplotsset{set layers}}%
}%
\def\pgfplotssetlayers@#1{%
	\pgfplotsset{set layers={#1}}%
}%

% This method checks if '#1' is a well-known layer set. If that is the case, the layer set is initialized.
% If there is no such layer set, #1 is assumed to be a comma-separated-list of layer names.
% These layers are defined if they do not exist already.
%
% POSTCONDITION:
%   - a \pgfsetlayers{<list>} is issued (immediately)
%   - '/pgfplots/@set layers arg' is defined such that any following axes can initialized their layers.
\def\pgfplots@key@set@layers#1{%
	% 
	% auto detect if '#1' is a defined layer set:
	\pgfkeysifdefined{#1/list}{%
		\def\pgfkeyscurrentname{#1}%
	}{%
		\pgfkeysifdefined{/pgfplots/layers/#1/list}{%
			\edef\pgfkeyscurrentname{/pgfplots/layers/#1}%
		}{%
			\let\pgfkeyscurrentname\pgfutil@empty
		}%
	}%
	\ifx\pgfkeyscurrentname\pgfutil@empty
		% OK. The argument is NO layer set configuration.
		\pgfplots@key@set@layers@{#1}%
		\pgfkeyslet{/pgfplots/@set layers arg}\pgfutil@empty%
	\else
		% OK, The argument is the key name of some '/.define layer set' key.
		% Remember it for later and initialize the layers:
		\pgfkeyslet{/pgfplots/@set layers arg}\pgfkeyscurrentname%
		\pgfkeysgetvalue{\pgfkeyscurrentname/list}\pgfplots@loc@TMPa
		\expandafter\pgfplots@key@set@layers@\expandafter{\pgfplots@loc@TMPa}%
	\fi
}
% a simple method which (immediately) invokes \pgfsetlayers{#1}.
%
% The only difference is that it creates missing layers on-the-fly.
\def\pgfplots@key@set@layers@#1{%
	\edef\pgfplots@loc@TMPa{#1}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		% DEFAULT.
		\pgfsetlayers{main}%
	\else
		\def\pgfplots@loc@TMPb{false}%
		\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
			% "use layers=false"
			\pgfsetlayers{main}%
		\else
			\def\pgfplots@loc@TMPb{main}%
			\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
				% "use layers=main"
				\pgfsetlayers{main}%
			\else
				% declare all layers, and collect the normalised list
				% into \pgfplots@loc@TMPd
				\def\pgfplots@loc@TMPd{}%
				\expandafter\pgfplotsutilforeachcommasep\expandafter{\pgfplots@loc@TMPa}\as\pgfplots@loc@TMPa{%
					% normalize argument:
					\edef\pgfplots@loc@TMPa{\pgfplots@loc@TMPa}%
					\expandafter\pgfplotsutil@trim\expandafter{\pgfplots@loc@TMPa}%
					\let\pgfplots@loc@TMPa=\pgfplotsretval
					%
					\ifx\pgfplots@loc@TMPa\pgfutil@empty
					\else
						\def\pgfplots@loc@TMPb{main}%
						\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
						\else
							\expandafter\pgfdeclarelayer\expandafter{\pgfplots@loc@TMPa}%
						\fi
						\edef\pgfplots@loc@TMPd{\ifx\pgfplots@loc@TMPd\pgfutil@empty\else\pgfplots@loc@TMPd,\fi\pgfplots@loc@TMPa}%
					\fi
				}%
				% activate layers:
				\pgfplots@log3{Setting layers '\pgfplots@loc@TMPd'...}%
				\expandafter\pgfsetlayers\expandafter{\pgfplots@loc@TMPd}%
			\fi
		\fi
	\fi
}%

\def\pgfplots@prepare@layered@graphics{%
	% check if there are no layers at all.
	\ifpgfplots@layered@graphics
		\pgfutil@IfUndefined{pgf@layerlist}{%
		}{%
			\ifx\pgf@layerlist\pgfutil@empty
				\pgfplots@layered@graphicsfalse
			\else
				\def\pgfplots@loc@TMPa{main}%
				\ifx\pgf@layerlist\pgfplots@loc@TMPa
					\pgfplots@layered@graphicsfalse
				\fi
			\fi
		}%
	\fi
}%

% #2: context information (for improved error recovery), optional
\def\pgfplotsonlayer#1{%
	\pgfutil@ifnextchar\bgroup{\pgfplotsonlayer@{#1}}{\pgfplotsonlayer@{#1}{}}%
}
\def\pgfplotsonlayer@#1#2{%
	\begingroup
	\def\b@pgfplotsonlayer@started{0}%
	\ifpgfplots@layered@graphics
		\edef\pgfplots@loc@TMPa{#1}%
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\def\b@pgfplotsonlayer@started{1}%
			\pgfonlayer{#1}%
		\fi
	\fi
}%
\def\endpgfplotsonlayer{%
	\ifpgfplots@layered@graphics
		\if1\b@pgfplotsonlayer@started
			\endpgfonlayer
		\fi
	\fi
	\endgroup
}%


% Searches for the layers of a (set of) style name(s).
%
% #1 is a style name like 'every major grid'. It can also be a list of
% style names.
%
% The last "on layer" key found in these styles will be used here.
%
% Note that the "on layer" keys have already been extracted in during
% the key filtering procedure.
\def\pgfplotsgetlayerforstyle#1{%
	\let\pgfplotsretval=\pgfutil@empty
	\ifpgfplots@layered@graphics
		% this here is the return value:
		\let\pgfplots@loc@TMPc=\pgfutil@empty
		%
		% search list:
		\pgfplotsutilforeachcommasep{#1}\as\pgfplots@loc@TMPa{%
			\pgfkeysifdefined{/pgfplots/layers for styles/\pgfplots@loc@TMPa}{%
				% oh, good: I have already processed the requested
				% style, and I already know if it has a particular
				% layer.
				\pgfkeysgetvalue{/pgfplots/layers for styles/\pgfplots@loc@TMPa}\pgfplots@loc@TMPb
			}{%
				% hm. Ok, then process the style. Throw everything
				% away, keep only the layer.
				\begingroup
				\pgfkeyslet{/pgfplots/on layer}\pgfutil@empty
				\pgfkeysdef{/handlers/.unknown}{}% do nothing
				\pgfkeysdef{/tikz/.unknown}{}% also, do nothing.
				\pgfplotsset{#1}% let's hope this works with unknown keys...
				\pgfkeysgetvalue{/pgfplots/on layer}\pgfplots@loc@TMPb
				\pgfmath@smuggleone\pgfplots@loc@TMPb
				\endgroup
			}%
			\ifx\pgfplots@loc@TMPb\pgfutil@empty
			\else
				% update return value:
				\let\pgfplots@loc@TMPc=\pgfplots@loc@TMPb
			\fi
		}%
		\let\pgfplotsretval=\pgfplots@loc@TMPc
%\message{\string\pgfplotsgetlayerforstyle{#1} = '\pgfplotsretval'^^J}%
	\fi
}%

% The purpose of this method is to check for the cases where no cell picture is necessary.
% The idea behind this anchor is to insert the axis DIRECTLY into the embedding tikzpicture, without
% a posteriori shifting. 
%
% A posteriori shifting == anchors whose dimensions are not fixed
% until the complete axis has been "typeset". 
%
% Disabling the cell picture will still prepare ALL anchors correctly,
% but it disables many of the anchor choices when it comes to the
% alignment of the current axis (in other words: other node can align
% using the anchors of this axis, but this axis cannot be aligned based on its anchors).
%
% The motivation for this feature is to implement multi-axis support together with layered graphics.
%
% The 'cell picture=false' feature may be interesting for SVG export as
% well.
\def\pgfplots@prepare@cell@picture{%
	\pgfplots@ifcellpicture@required{%
		\pgfplots@has@cell@picturetrue
	}{%
		% cell picture=false or cell picture=if necessary
		%
		% anchor processing is special in this case! The standard
		% anchor processing uses a posteriori shifts. This feature
		% here REQUIRES a priori shifts.
		% Prepare special handling for these shifts:
		\pgfplots@has@cell@picturefalse
		\edef\pgfplots@anchorname@internal{\pgfplots@anchorname}%
		%\def\pgfplots@anchorname{image}% 
		%
		\let\pgfplots@BEGIN@cell@picture=\pgfplots@BEGIN@cell@picture@DISABLED
		\let\pgfplots@END@cell@picture=\pgfplots@END@cell@picture@DISABLED
		\def\pgfplots@add@named@child@node##1{}% do nothing here
		\let\pgfplots@finally@correct@child@node@positions=\relax
		%
		% translate the coordinate system before the 'current axis'
		% node is generated. 
		\expandafter\def\expandafter\pgfplots@beforenode\expandafter{\pgfplots@beforenode
			\setbox\pgfnodepartimagebox=\hbox{}%
		}%	
	}%
}

\long\def\pgfplots@ifcellpicture@required#1#2{%
	\if1\pgfplots@cell@picture@mode
		% cell picture=true
		#1\relax
	\else
		% cell picture=false | cell picture=if necessary
		\edef\pgfplots@shapename{pgfplots@low@level@shape@INNER}%
		\pgfutil@IfUndefined{pgf@anchor@\pgfplots@shapename @\pgfplots@anchorname}{%
			% we need to compute the anchor a posteriorily.
			\if0\pgfplots@cell@picture@mode
				% cell picture=false is forbidden here...
				\pgfplots@error{Sorry, 'cell picture=false' is UNSUPPORTED for 'anchor=\pgfplots@anchorname'.}%
			\fi
			\if2\pgfplots@cell@picture@mode
				\pgfplots@log3{'cell picture=if necessary' resulted in 'cell picture=true'}%
			\fi
			#1\relax
		}{%
			\pgfplots@log3{'cell picture=if necessary' resulted in 'cell picture=false'}%
			% OK, an a priori anchor is available - we do not really need
			% a cell picture and this is compatible with the input
			% options:
			#2\relax
		}%
	\fi
}%

\def\pgfplots@define@preliminary@current@axis@node{%
	\begingroup
	\pgfplots@sys@beforenode
	% create a leight-weight 'current axis' node for anchor references
	% (which may happen during both, the axis descriptions or any
	% path/plot commands). 
	\pgfmultipartnode{pgfplots@low@level@shape@INNER}{image}{current axis}{\pgfusepath{discard}}%
	\endgroup
}%

\def\pgfplots@BEGIN@cell@picture[#1]{%
	%
	\pgfplots@define@preliminary@current@axis@node
	%
	\pgfplotsutil@BEGIN@cell@picture[#1]%
}%
\def\pgfplotsutil@BEGIN@cell@picture[#1]{%
	\setbox\pgfnodepartimagebox=\hbox\bgroup\bgroup
		\pgfinterruptpicture
		\tikzpicture[#1]%
		% set baseline for sub-picture to default value.
		% the baseline option will be applied to the OUTER picture.
		\pgfsetbaseline{\pgf@picminy}%
		\pgfutil@ifundefined{pgfsettrimleft}{}{%
			\pgfsettrimleft{\pgf@picminx}%
			\pgfsettrimright{\pgf@picmaxx}%
		}%
		\begingroup
			\pgfgettransformentries\aa\ab\ba\bb\pgfplots@loc@TMPa\pgfplots@loc@TMPb
			\xdef\pgfplots@savedtransformshift{%
				\global\pgf@x=\pgfplots@loc@TMPa\space
				\global\pgf@y=\pgfplots@loc@TMPb\space
			}%
			\xdef\pgfplots@glob@TMPa{{\aa}{\ab}{\ba}{\bb}}%
		\endgroup
		\expandafter\pgfsettransformentries\pgfplots@glob@TMPa{0pt}{0pt}%
}

\def\pgfplotsutil@END@cell@picture#1{%
		\xdef\pgfplots@cell@picture@remembered{%
			\ifpgfrememberpicturepositiononpage
				\noexpand\pgfrememberpicturepositiononpagetrue
			\else
				\noexpand\pgfrememberpicturepositiononpagefalse
			\fi
		}%
		\xdef\pgfplots@cell@pictureid{\pgfpictureid}%
		\endtikzpicture%
		\begingroup
			\ifdim\pgf@picmaxx=-16000pt\relax%
				\pgf@picmaxx=0pt\relax%
				\pgf@picminx=0pt\relax%
				\pgf@picmaxy=0pt\relax%
				\pgf@picminy=0pt\relax%
			\fi%
			#1
		\endgroup
		\endpgfinterruptpicture
	\egroup\egroup% end of pgfnodepartimagebox
	%
	% restore any shift transformations provided to an axis.
	% These would be lost otherwise.
	\pgftransformshift{\pgfplots@savedtransformshift}%
	%
	% allow positioning of colorbars with this hook.
	% It is \relax unless this here is a color bar axis.
	% Its intention is to re-define `\pgfplots@at':
	\pgfplots@colorbar@position@hook%
	%
    \pgftransformshift{\pgfplots@at}%
	%
}%
\def\pgfplots@END@cell@picture{%
	\pgfplotsutil@END@cell@picture{\pgfplots@END@cell@picture@preparepoints}%
}%

\def\pgfplots@END@cell@picture@preparepoints{%
	% Protocol sizes for the axis-shape.
	% That needs to be done globally, do avoid all those
	% \endgroup's in and after \endpgfinterruptpicture ...
	%
	\xdef\pgfplotspointorigininternal{\global\pgf@x=\the\pgf@picminx\space\global\pgf@y=\the\pgf@picminy\space}%
	%
	\ifpgfplots@deprecated@anchors
		\pgfplotspointminminmin
	\else
		\pgfplotspointbblowerleft
	\fi
	\pgf@xa=\pgf@x
	\pgf@ya=\pgf@y
	\pgf@pos@transform\pgf@xa\pgf@ya
	\advance\pgf@xa by-\pgf@picminx
	\advance\pgf@ya by-\pgf@picminy
	\xdef\pgfplotspointlowerleftinnercorner{%
		\global\pgf@x=\the\pgf@xa\space
		\global\pgf@y=\the\pgf@ya\space
	}%
	%
	\global\pgf@x=\pgf@picmaxx
	\global\pgf@y=\pgf@picmaxy
	\global\advance\pgf@x by-\pgf@picminx
	\global\advance\pgf@y by-\pgf@picminy
	\xdef\pgfplotspointupperrightcorner{\global\pgf@x=\the\pgf@x\space\global\pgf@y=\the\pgf@y\space}%
	%
	\pgfplotspointaxisorigin
	\pgf@pos@transform\pgf@x\pgf@y
	\global\advance\pgf@x by-\pgf@picminx
	\global\advance\pgf@y by-\pgf@picminy
	\xdef\pgfplotspointaxisorigin{\global\pgf@x=\the\pgf@x\space\global\pgf@y=\the\pgf@y\space}%
}

% this here is essentially the same as
%		\pgfpointanchor{current axis}{#1}
% but it does not need a node.
\def\pgfplotspointdescriptionbyanchor#1{%
	\begingroup
	\edef\pgfplotspointdescriptionbyanchor@{#1}%
	\gdef\pgfplots@glob@TMPa{0}%
	% do a linear search through all anchors of
	% shape pgfplots@low@level@shape@INNER :
	\def\anchor##1##2{%
		\def\pgfplots@loc@TMPa{##1}%
		\ifx\pgfplots@loc@TMPa\pgfplotspointdescriptionbyanchor@
			\pgf@process{##2}%
			\gdef\pgfplots@glob@TMPa{1}%
		\fi
	}%
	\pgfplots@low@level@shape@INNER@define
	\if0\pgfplots@glob@TMPa
		\pgfplots@error{The anchor '#1' is unsupported in this context.}%
	\fi
	\endgroup
}%

\def\pgfplots@BEGIN@cell@picture@DISABLED[#1]{%
	\begingroup
	\pgfinterruptboundingbox
		%
		%
		% allow positioning of colorbars with this hook.
		% It is \relax unless this here is a color bar axis.
		% Its intention is to re-define `\pgfplots@at':
		\pgfplots@colorbar@position@hook%
		%
		\pgftransformshift{\pgfplots@at}%
		%
		% prepare a priori anchor transformation (see
		% \pgfplots@prepare@cell@picture for details):
		\pgftransformshift{%
			\pgfqpointscale{-1}{\pgfplotspointdescriptionbyanchor{\pgfplots@anchorname@internal}}%
		}%
		%
		\pgfplots@define@preliminary@current@axis@node
		%
		\scope[#1]%
}%
\def\pgfplots@END@cell@picture@DISABLED{%
		\endscope%
		\begingroup
			\pgfplots@END@cell@picture@preparepoints%
		\endgroup
	\endpgfinterruptboundingbox
	\endgroup
	\global\let\pgfplots@cell@picture@remembered=\relax
	\global\let\pgfplots@cell@pictureid=\pgfutil@empty
}%

\def\pgfplots@BEGIN@init@and@draw@axis{%
		%
		%
		\pgfplots@draw@axis@pre
		\pgfplots@draw@axis@is@prepared
		\scope
		%
		\pgfkeysgetvalue{/pgfplots/axis background/.@cmd}\pgfplots@loc@TMPa
		\ifx\pgfplots@loc@TMPa\pgfplots@empty@style@key
		\else
			\pgfplotsgetlayerforstyle{/pgfplots/axis background,/pgfplots/axis background@}%
			\pgfplotsonlayer{\pgfplotsretval}{axis background}%
			\path[/pgfplots/axis background,/pgfplots/axis background@] \pgfextra{\pgfplots@clippath@install{}};%
			\endpgfplotsonlayer
		\fi
		%
		\ifpgfplots@axis@on@top
		\else
			\pgfplots@draw@axis
		\fi
		% CLIPPING:
		\ifpgfplots@clip
			\if1\pgfplots@clipmode
				% 'clip=true' and 'clip/mode=global':
				\pgfplots@clippath@install{\pgfusepath{clip}}%
			\fi
		\fi
		\pgfplotspointbb@assertvaluesexist%
}

% something which is invoked after a clippath segment is complete.
% #1 should be something like \pgfusepath{clip}
\def\pgfplots@clippath@use@#1{%
	\ifx\pgfplotspoint@bb@@@\relax
		% remember the axis dimensions:
		\ifdim\pgf@pathmaxx=-16000pt
		\else
			\begingroup
			\pgf@xa=\pgf@pathmaxx
			\advance\pgf@xa by-\pgf@pathminx
			\pgf@ya=\pgf@pathmaxy
			\advance\pgf@ya by-\pgf@pathminy
			\xdef\pgfplots@glob@TMPa{{\the\pgf@pathminx}{\the\pgf@pathminy}{\the\pgf@xa}{\the\pgf@ya}}%
			\endgroup
			\global\let\pgfplotspoint@bb@@@=\pgfplots@glob@TMPa
		\fi
	\fi
	#1%
}%
\def\pgfplots@clippath@prepare@for@axistype{%
	\ifpgfplots@threedim
		% FIXME : this can't be done in three dimensions. :-(
		% -> for 3d, I need to clip at least the 2d projection.
		%
		% -> Identify the convex hull of the 2D projection:
		\pgfplotsifaxissurfaceisforeground{0vv}{%
			\pgfplotsifaxissurfaceisforeground{v0v}{%
				\pgfplotsifaxissurfaceisforeground{vv0}{%
					% ok. Do NOT use the intersection lines
					% - 00v
					% - 0v0
					% - v00
					% so, use 
					%    010 (01v) 011
					%    011 (0v1) 001
					%    001 (v01) 101
					%    101 (10v) 100
					%    100 (1v0) 110 
					%    110 (v10) 011 (cycle)
					\def\pgfplots@clippath@install##1{%
						\pgfpathmoveto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymax}{\pgfplots@zmin}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymax}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymin}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymin}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymin}{\pgfplots@zmin}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymax}{\pgfplots@zmin}}%
						\pgfpathclose
						\pgfplots@clippath@use@{##1}%
					}%
				}{%
					% foreground surfs: 0vv, v0v, vv1
					%
					% ok. Do NOT use the intersection lines
					% - 00v
					% - 0v1
					% - v01
					% so, use 
					%    010 (01v) 011
					%    011 (v11) 111   
					%    111 (1v1) 101 
					%    101 (10v) 100
					%    100 (v00) 000
					%    000 (0v0) 010 (cycle)
					\def\pgfplots@clippath@install##1{\relax%
						\pgfpathmoveto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymax}{\pgfplots@zmin}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymax}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymax}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymin}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymin}{\pgfplots@zmin}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymin}{\pgfplots@zmin}}%
						\pgfpathclose
						\pgfplots@clippath@use@{##1}%
					}%
				}%
			}{%
				\pgfplotsifaxissurfaceisforeground{vv0}{%
					% foreground surfs: 0vv, v1v, vv0
					%
					% ok. Do NOT use the intersection lines
					% - 01v
					% - 0v0
					% - v10
					% so, use
					%   000  (00v) 001   
					%   001  (0v1) 011   
					%   011  (v11) 111   
					%   111  (11v) 110   
					%   110  (1v0) 100   
					%   100  (v00) 000 (cycle)
					\def\pgfplots@clippath@install##1{%
						\pgfpathmoveto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymin}{\pgfplots@zmin}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymin}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymax}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymax}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymax}{\pgfplots@zmin}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymin}{\pgfplots@zmin}}%
						\pgfpathclose
						\pgfplots@clippath@use@{##1}%
					}%
				}{%
					% foreground surfs: 0vv, v1v, vv1
					%
					% ok. Do NOT use the intersection lines
					% - 01v
					% - 0v1
					% - v11
					% so, use
					%   000  (00v) 001   
					%   001  (v01) 101   
					%   101  (1v1) 111   
					%   111  (11v) 110   
					%   110  (v10) 010   
					%   010  (0v0) 000 (cycle)
					\def\pgfplots@clippath@install##1{%
						\pgfpathmoveto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymin}{\pgfplots@zmin}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymin}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymin}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymax}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymax}{\pgfplots@zmin}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymax}{\pgfplots@zmin}}%
						\pgfpathclose
						\pgfplots@clippath@use@{##1}%
					}%
				}%
			}%
		}{%
			\pgfplotsifaxissurfaceisforeground{v0v}{%
				\pgfplotsifaxissurfaceisforeground{vv0}{%
					% foreground surfs: 1vv, v0v, vv0.
					%
					% Thus: DON'T use the intersection lines
					% - 10v
					% - 1v0
					% - v00
					% So, use
					%   110 (11v) 111   
					%   111 (1v1) 101   
					%   101 (v01) 001   
					%   001 (00v) 000   
					%   000 (0v0) 010   
					%   010 (v10) 110 (cycle)
					\def\pgfplots@clippath@install##1{%
						\pgfpathmoveto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymax}{\pgfplots@zmin}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymax}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymin}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymin}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymin}{\pgfplots@zmin}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymax}{\pgfplots@zmin}}%
						\pgfpathclose
						\pgfplots@clippath@use@{##1}%
					}%
				}{%
					% foreground surfs: 1vv, v0v, vv1
					% Thus: DON'T use the intersection lines
					% - 10v
					% - 1v1
					% - v01
					% So, use
					%   110 (11v) 111   
					%   111 (v11) 011   
					%   011 (0v1) 001   
					%   001 (00v) 000   
					%   000 (v00) 100   
					%   100 (1v0) 110 (cycle)
					\def\pgfplots@clippath@install##1{%
						\pgfpathmoveto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymax}{\pgfplots@zmin}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymax}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymax}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymin}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymin}{\pgfplots@zmin}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymin}{\pgfplots@zmin}}%
						\pgfpathclose
						\pgfplots@clippath@use@{##1}%
					}%
				}%
			}{%
				\pgfplotsifaxissurfaceisforeground{vv0}{%
					% foreground surfs: 1vv, v1v, vv0
					% Thus: DON'T use the intersection lines
					% - 11v
					% - 1v0
					% - v10
					% So, use
					%   100 (10v) 101   
					%   101 (1v1) 111   
					%   111 (v11) 011   
					%   011 (01v) 010   
					%   010 (0v0) 000   
					%   000 (v00) 100 (cycle)
					\def\pgfplots@clippath@install##1{%
						\pgfpathmoveto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymin}{\pgfplots@zmin}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymin}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymax}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymax}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymax}{\pgfplots@zmin}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymin}{\pgfplots@zmin}}%
						\pgfpathclose
						\pgfplots@clippath@use@{##1}%
					}%
				}{%
					% foreground surfs: 1vv, v1v, vv1
					% Thus: DON'T use the intersection lines
					% - 11v
					% - 1v1
					% - v11
					% So, use
					%   100 (10v) 101   
					%   101 (v01) 001   
					%   001 (0v1) 011   
					%   011 (01v) 010   
					%   010 (v10) 110   
					%   110 (1v0) 100 (cycle)
					\def\pgfplots@clippath@install##1{%
						\pgfpathmoveto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymin}{\pgfplots@zmin}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymin}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymin}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymax}{\pgfplots@zmax}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymax}{\pgfplots@zmin}}%
						\pgfpathlineto{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymax}{\pgfplots@zmin}}%
						\pgfpathclose
						\pgfplots@clippath@use@{##1}%
					}%
				}%
			}%
		}%
				
	\else
		\pgfplotsqpointxy{\pgfplots@xmin}{\pgfplots@ymin}%
		\edef\pgfplots@loc@TMPa{\global\pgf@x=\the\pgf@x\space\global\pgf@y=\the\pgf@y\space}%
		\pgfplotsqpointxy{\pgfplots@xmax}{\pgfplots@ymin}%
		\edef\pgfplots@loc@TMPb{\global\pgf@x=\the\pgf@x\space\global\pgf@y=\the\pgf@y\space}%
		\pgfplotsqpointxy{\pgfplots@xmax}{\pgfplots@ymax}%
		\edef\pgfplots@loc@TMPc{\global\pgf@x=\the\pgf@x\space\global\pgf@y=\the\pgf@y\space}%
		\pgfplotsqpointxy{\pgfplots@xmin}{\pgfplots@ymax}%
		\edef\pgfplots@loc@TMPd{\global\pgf@x=\the\pgf@x\space\global\pgf@y=\the\pgf@y\space}%
		\begingroup
		\toks0=\expandafter{\pgfplots@loc@TMPa}%
		\toks1=\expandafter{\pgfplots@loc@TMPb}%
		\toks2=\expandafter{\pgfplots@loc@TMPc}%
		\toks3=\expandafter{\pgfplots@loc@TMPd}%
		\xdef\pgfplots@glob@TMPa##1{%
			\noexpand\pgfpathmoveto{\the\toks0 }%
			\noexpand\pgfpathlineto{\the\toks1 }%
			\noexpand\pgfpathlineto{\the\toks2 }%
			\noexpand\pgfpathlineto{\the\toks3 }%
			\noexpand\pgfpathclose
			\noexpand\pgfplots@clippath@use@{##1}%
		}%
		\endgroup
		\let\pgfplots@clippath@install=\pgfplots@glob@TMPa
	\fi
}%
% Defines \pgfplots@clippath@install.
% @PRECONDITION  the axis limits must be ready.
\def\pgfplots@clippath@prepare{%
	\pgfplots@clippath@prepare@for@axistype
	% now, the \pgfplots@clippath@install routine should be ready.
	%
	% it is used to compute the bounding box. prepare that:
	\global\let\pgfplotspoint@bb@@@=\relax
	%
	% Now, I SET the clip path temporarily and record the low level
	% protocol.
	% This low level protocol is used to create a highly optimized
	% clip path routine; it will be used quite often.
	%
	\let\pgfplots@clippath@install@pathcmd=\pgfplots@clippath@install
	\iffalse
		% FIXME : this was an idea to optimize the installation of the
		% clip path (cache the protocolled version). FIX IT
		%
		\pgf@resetpathsizes% FIXME: this here should not be necessary!
		\pgfsysprotocol@getcurrentprotocol\pgfplots@loc@TMPa%
		\begingroup
			% when I do this work, I can as well compute the bounding
			% box (done in \pgfplots@clippath@use@)
			\pgfinterruptboundingbox
			\pgf@relevantforpicturesizetrue
			%
			\pgfsysprotocol@bufferedtrue%
			\pgfsysprotocol@setcurrentprotocol\pgfutil@empty%
		%	\pgfplots@clippath@install@pathcmd{\pgfusepath{clip}}%
			\pgfsysprotocol@getcurrentprotocol\pgfplots@loc@TMPa%
			\global\let\pgfplots@glob@TMPa=\pgfplots@loc@TMPa
			\endpgfinterruptboundingbox
		\endgroup
		\let\pgfplots@clippath@install@clip@protocolled=\pgfplots@glob@TMPa
		\pgfsysprotocol@setcurrentprotocol\pgfplots@loc@TMPa%
	\fi
	%
	% Replace \pgfplots@clippath@install by one which makes use of the
	% optimized version (if ##1=\pgfusepath{clip})
	\def\pgfplots@clippath@install##1{%
		\def\pgfplots@loc@TMPa{##1}%
		\let\pgfplots@clippath@install@aftergroup=\pgfutil@empty
			% the 'clip' path has been precomputed because it is often
			% used: FIXME: unfinished, see above
			%\expandafter\pgfsys@invoke\expandafter{\pgfplots@clippath@install@clip@protocolled}%
		\ifx\pgfplots@loc@TMPa\pgfplots@clippath@install@test
			\if0\pgfplots@clip@BB@mode
				% clip bounding box=default tikz
			\else
				% clip bounding box=upper bound
				%
				% do NOT take the clip path into account for the bounding
				% box! That is very strange when you hide the axis.
				%
				% note that we do not need it: the path's BB will be
				% extracted anyway by this BB code.
				%
				% However, we will use the clip path's BB as
				% *upper bound* - but only after the paths in the
				% current scope have been completed.
				% The implementation of this upper bound is hooked
				% into '\endscope':
				\edef\pgfplots@clippath@install@aftergroup{%
					\ifpgf@relevantforpicturesize
						\noexpand\pgf@relevantforpicturesizetrue
					\else
						\noexpand\pgf@relevantforpicturesizefalse
					\fi
					\noexpand\pgfplots@clippath@install@BB@upper@bound
				}%
				\pgf@relevantforpicturesizefalse
				%
			\fi
		\fi
		\pgf@resetpathsizes% FIXME: this here should not be necessary!
		\pgfplots@clippath@install@pathcmd{##1}%
		\pgfplots@clippath@install@aftergroup
	}%
	%
}%
\def\pgfplots@clippath@install@test{\pgfusepath{clip}}%

% This is the main part of the implementation for 
% 'clip bounding box=upper bound' : it collects the bounding box of everything inside of
% the clipped area. Then in the associated \endscope, it clips that bounding box to the expected 
% clip path -- and protocols that size.
\def\pgfplots@clippath@install@BB@upper@bound{%
	\tikzset{
		execute at end scope=\pgfplots@clippath@install@BB@update,
		%
		% no special handling for nested scopes:
		% unnecessary; tikz handles that on its own:
		%execute at begin scope=\let\pgfplots@clippath@install@BB@update=\relax,
	}%
	\pgfinterruptboundingbox
	% count everything in the current scope into a separate bounding box
}%

\def\pgfplots@clippath@install@BB@update{%
	% we are inside of \endscope.
	%
	% this here is the BB of the current scope!
	% More precisely: in *the* scope in which we started the clip
	% path, not in nested scopes.
	%
	\ifdim\pgf@picminx=16000pt %
		\xdef\pgfplots@glob@TMPa{}%
	\else
		\xdef\pgfplots@glob@TMPa{%
			{\the\pgf@picminx}%
			{\the\pgf@picminy}%
			{\the\pgf@picmaxx}%
			{\the\pgf@picmaxy}%
		}%
	\fi
	\endpgfinterruptboundingbox
	\ifx\pgfplots@glob@TMPa\pgfutil@empty
	\else
		\expandafter\pgfplots@clippath@install@BB@update@\pgfplots@glob@TMPa
	\fi
}%

\def\pgfplots@clippath@install@BB@update@#1#2#3#4{%
	\pgfqpoint{#1}{#2}%
	\pgfplots@clip@to@clippath%
	\pgf@protocolsizes{\pgf@x}{\pgf@y}%
	%
	\pgfqpoint{#3}{#4}%
	\pgfplots@clip@to@clippath%
	\pgf@protocolsizes{\pgf@x}{\pgf@y}%
}%

\def\pgfplots@clip@to@clippath{%
	\pgf@xa=\pgf@x
	\pgf@ya=\pgf@y
	\begingroup\pgf@process{\pgfplotspointbblowerleft}\endgroup%
	\ifdim\pgf@xa<\pgf@x \pgf@xa=\pgf@x \fi
	\ifdim\pgf@ya<\pgf@y \pgf@ya=\pgf@y \fi
	%
	\begingroup\pgf@process{\pgfplotspointbbupperright}\endgroup
	\ifdim\pgf@xa>\pgf@x \pgf@xa=\pgf@x \fi
	\ifdim\pgf@ya>\pgf@y \pgf@ya=\pgf@y \fi
	%
	\pgfqpoint{\pgf@xa}{\pgf@ya}%
}%


\def\pgfplotspointbb@assertvaluesexist{%
	\ifx\pgfplotspoint@bb@@@\relax
		% (RE)COMPUTE:
		%
		% Determine tight 2D bounding box for the axis as such:
		\begingroup
		% hm. seems as if it is sufficient to set
		% \pgf@relevantforpicturesizefalse. but it does not hurt; I
		% will see to it eventually. Perhaps.
		\pgfinterruptboundingbox
			\pgf@relevantforpicturesizetrue
			\pgfplots@clippath@install{\pgfusepath{discard}}
		\endpgfinterruptboundingbox
		\endgroup
	\fi
}%

% Point commands which expand to the bounding box which contains at
% least the (projected) visible part of the axis
\def\pgfplotspointbblowerleft{%
	\pgfplotspointbb@assertvaluesexist
	\expandafter\pgfplotspointbblowerleft@\pgfplotspoint@bb@@@
}%
\def\pgfplotspointbbupperright{%
	\pgfpointadd{\pgfplotspointbblowerleft}{\pgfplotspointbbdiagonal}%
}%
\def\pgfplotspointbbdiagonal{%
	\pgfplotspointbb@assertvaluesexist
	\expandafter\pgfplotspointbbdiagonal@\pgfplotspoint@bb@@@
}%
\let\pgfplotspoint@bb@@@=\relax
\def\pgfplotspointbblowerleft@#1#2#3#4{\global\pgf@x=#1 \global\pgf@y=#2 }%
\def\pgfplotspointbbdiagonal@#1#2#3#4{\global\pgf@x=#3 \global\pgf@y=#4 }%

% #1: a complete \pgfusepath command what to do with the clip path.
\def\pgfplots@clippath@install#1{%
	\pgfplots@error{Can't install a clippath here - the command has not yet been prepared.}%
}%


% Generates a path representing the outline of the axis.
% Example:
%
% \pgfplotspathaxisoutline
% \pgfusepath{clip}
\def\pgfplotspathaxisoutline{%
	\pgfplots@clippath@install{}%
}%

% This is the counterpart for \pgfplots@BEGIN@init@and@draw@axis
\def\pgfplots@END@init@and@draw@axis{%
	\endscope%
	%
	\ifpgfplots@axis@on@top
		\pgfplots@draw@axis
	\fi
	\pgfplots@draw@axis@post
	%
	\pgfplots@markers@visphase@after@axis
	\global\pgfplotslistnewempty\pgfplots@stored@plotlist% delete contents.
	%
	\begingroup
	\pgfkeysvalueof{/pgfplots/after end axis/.@cmd}\pgfeov%
	\endgroup
	%
}

% Writes output to \pgfmathresult
% #1: the tick list (not a macro!)
% #2: the axis
\def\pgfplots@filter@input@ticks@with@log#1#2{%
	\let\pgfplots@glob@TMPa=\pgfutil@empty
	\foreach \pgfplots@loc@TMPb in {#1} {%
		\pgfplotscoordmath{#2}{log}{\pgfplots@loc@TMPb}%
		\ifx\pgfplots@glob@TMPa\pgfutil@empty
			\xdef\pgfplots@glob@TMPa{\pgfmathresult}%
		\else
			\xdef\pgfplots@glob@TMPa{\pgfplots@glob@TMPa,\pgfmathresult}%
		\fi
	}%
	\let\pgfmathresult=\pgfplots@glob@TMPa
}

% Writes output to \pgfmathresult
% #1: the input ticks
% #2: the transformation command key as macro
\def\pgfplots@filter@input@ticks@with@highleveltrafo#1#2{%
	\let\pgfplots@glob@TMPa=\pgfutil@empty
	\foreach \pgfplots@loc@TMPb in {#1} {%
		\expandafter#2\expandafter{\pgfplots@loc@TMPb}\pgfeov%
		\ifx\pgfplots@glob@TMPa\pgfutil@empty
			\xdef\pgfplots@glob@TMPa{\pgfmathresult}%
		\else
			\xdef\pgfplots@glob@TMPa{\pgfplots@glob@TMPa,\pgfmathresult}%
		\fi
	}%
	\let\pgfmathresult=\pgfplots@glob@TMPa
}

% definition of 'axis cs':
\tikzdeclarecoordinatesystem{axis}{\edef\pgfplots@loc@TMPa{#1}\expandafter\pgfplots@evalute@tikz@coord@system@interface\pgfplots@loc@TMPa,\pgfplots@coord@end}
\def\pgfplotspointaxisxy#1#2{\pgfplots@evalute@tikz@coord@system@interface{#1},{#2},\pgfplots@coord@end}%
\def\pgfplotspointaxisxyz#1#2#3{\pgfplots@evalute@tikz@coord@system@interface{#1},{#2},{#3},\pgfplots@coord@end}%
\def\pgfplotsqpointaxisxy#1#2{%
	\edef\pgfplotspointaxis@restore{%
		\ifpgfplots@plot@coords@mathparser
			\noexpand\pgfplots@plot@coords@mathparsertrue
		\else
			\noexpand\pgfplots@plot@coords@mathparserfalse
		\fi
	}%
	\pgfplots@plot@coords@mathparserfalse
	%
	\pgfplotspointaxisxy{#1}{#2}%
	%
	\pgfplotspointaxis@restore
}
\def\pgfplotsqpointaxisxyz#1#2#3{%
	\edef\pgfplotspointaxis@restore{%
		\ifpgfplots@plot@coords@mathparser
			\noexpand\pgfplots@plot@coords@mathparsertrue
		\else
			\noexpand\pgfplots@plot@coords@mathparserfalse
		\fi
	}%
	\pgfplots@plot@coords@mathparserfalse
	%
	\pgfplotspointaxisxyz{#1}{#2}{#3}%
	%
	\pgfplotspointaxis@restore
}

% definition of 'normalized axis cs':
\tikzdeclarecoordinatesystem{normalized axis}{\edef\pgfplots@loc@TMPa{#1}\expandafter\pgfplots@evalute@tikz@coord@system@interface@normalized\pgfplots@loc@TMPa,\pgfplots@coord@end}
\def\pgfplotspointnormalizedaxisxy#1#2{\pgfplots@evalute@tikz@coord@system@interface@normalized{#1},{#2},\pgfplots@coord@end}%
\def\pgfplotspointnormalizedaxisxyz#1#2#3{\pgfplots@evalute@tikz@coord@system@interface@normalized{#1},{#2},{#3},\pgfplots@coord@end}%

\tikzdeclarecoordinatesystem{axis direction}{%
	\edef\pgfplots@loc@TMPa{%
		\noexpand\pgfplots@evalute@tikz@coord@system@interface[ noshift]%
			#1,\noexpand\pgfplots@coord@end
	}%
	\pgfplots@loc@TMPa
}
\def\pgfplotspointaxisdirectionxy#1#2{\pgfplots@evalute@tikz@coord@system@interface[ noshift]{#1},{#2},\pgfplots@coord@end}%
\def\pgfplotspointaxisdirectionxyz#1#2#3{\pgfplots@evalute@tikz@coord@system@interface[ noshift]{#1},{#2},{#3},\pgfplots@coord@end}%

% rel axis cs:
\tikzdeclarecoordinatesystem{rel axis}{\edef\pgfplots@loc@TMPa{#1}\expandafter\pgfplots@evalute@tikz@coord@system@interface@rel\pgfplots@loc@TMPa,\pgfplots@coord@end}
\def\pgfplotspointrelaxisxy#1#2{\pgfplots@evalute@tikz@coord@system@interface@rel{#1},{#2},\pgfplots@coord@end}%
\def\pgfplotspointrelaxisxyz#1#2#3{\pgfplots@evalute@tikz@coord@system@interface@rel{#1},{#2},{#3},\pgfplots@coord@end}%

% axis description cs:
\tikzdeclarecoordinatesystem{axis description}{\edef\pgfplots@loc@TMPa{#1}\expandafter\pgfplots@evalute@tikz@coord@system@interface@axis@description\pgfplots@loc@TMPa\pgfplots@coord@end}
\def\pgfplots@evalute@tikz@coord@system@interface@axis@description#1,#2\pgfplots@coord@end{\pgfplotspointdescriptionxy{#1}{#2}}

\def\pgfplotstransformcoordinatex#1{\pgfplots@evalute@tikz@coord@system@interface@for[]{x}{#1}}%
\def\pgfplotstransformcoordinatey#1{\pgfplots@evalute@tikz@coord@system@interface@for[]{y}{#1}}%
\def\pgfplotstransformcoordinatez#1{\pgfplots@evalute@tikz@coord@system@interface@for[]{z}{#1}}%

\def\pgfplotstransformdirectionx#1{\pgfplots@evalute@tikz@coord@system@interface@for[ noshift]{x}{#1}}%
\def\pgfplotstransformdirectiony#1{\pgfplots@evalute@tikz@coord@system@interface@for[ noshift]{y}{#1}}%
\def\pgfplotstransformdirectionz#1{\pgfplots@evalute@tikz@coord@system@interface@for[ noshift]{z}{#1}}%

\def\pgfplots@declare@mathfunctions{%
	\pgfmathdeclarefunction{transformdirectionx}{1}{\pgfplotstransformdirectionx{##1}}%
	\pgfmathdeclarefunction{transformdirectiony}{1}{\pgfplotstransformdirectiony{##1}}%
	\pgfmathdeclarefunction{transformdirectionz}{1}{\pgfplotstransformdirectionz{##1}}%
	%
	\pgfmathdeclarefunction{transformcoordinatex}{1}{\pgfplotstransformcoordinatex{##1}}%
	\pgfmathdeclarefunction{transformcoordinatey}{1}{\pgfplotstransformcoordinatey{##1}}%
	\pgfmathdeclarefunction{transformcoordinatez}{1}{\pgfplotstransformcoordinatez{##1}}%
}%

% Assigns \pgfmathresult := canvas coordinate (#3) for axis #2.
%
% A "canvas coordinate" here means an argument for \pgfplotsqpointxyz.
%
% #1: a command suffix which will be handed over to the datascale
% #2: an axis (x,y, or z)
% #3: the high-level coordinate which should be transformed
% trafo (typically an empty string)
\long\def\pgfplots@evalute@tikz@coord@system@interface@for[#1]#2#3{%
	\pgfkeysgetvalue{/pgfplots/#2 coord trafo/.@cmd}\pgfplots@loc@TMPc
	\ifx\pgfplots@loc@TMPc\pgfplots@empty@command@key
		\edef\pgfmathresult{#3}% do not expand it - might contain unexpandable input for coord trafo.
	\else
		\pgfplots@loc@TMPc{#3}\pgfeov
	\fi
	\ifpgfplots@plot@coords@mathparser
		\pgfplotscoordmath{default}{parse}{\pgfmathresult}%
	\fi
	\let\pgfplots@loc@TMPc=\pgfmathresult% FIXME: is that necessary? I doubt it... but just to make sure...
	\csname ifpgfplots@#2islinear\endcsname
		\pgfplotscoordmath{#2}{parsenumber}{\pgfplots@loc@TMPc}%
		\pgfplots@if{pgfplots@apply@datatrafo@#2}{%
			\pgfplotscoordmath{#2}{datascaletrafo#1}{\pgfmathresult}%
		}{}%
	\else
		\pgfplotscoordmath{#2}{log}{\pgfplots@loc@TMPc}%
	\fi
}

\long\def\pgfplots@evalute@tikz@coord@system@interface@for@normalized[#1]#2#3{%
	\edef\pgfmathresult{#3}%
	\pgfplotscoordmath{default}{parse}{\pgfmathresult}%
	\let\pgfplots@loc@TMPc=\pgfmathresult% FIXME: is that necessary? I doubt it... but just to make sure...
	\pgfplotscoordmath{#2}{parsenumber}{\pgfplots@loc@TMPc}%
	\csname ifpgfplots@#2islinear\endcsname
		\pgfplots@if{pgfplots@apply@datatrafo@#2}{%
			\pgfplotscoordmath{#2}{datascaletrafo#1}{\pgfmathresult}%
		}{}%
	\else
		% OK, assume it *is* in the normalized format.
	\fi
}

\def\pgfplots@evalute@tikz@coord@system@interface{%
	\begingroup
	\pgfutil@ifnextchar[%
		{\pgfplots@evalute@tikz@coord@system@interface@x}%
		{\pgfplots@evalute@tikz@coord@system@interface@x[]}%
}
\def\pgfplots@evalute@tikz@coord@system@interface@x[#1]#2,{%
	\def\pgfplots@evaluate@tikz@coord@opts{#1}%
	\def\pgfplots@evaluate@tikz@coord@x{#2}%
	\pgfplots@evalute@tikz@coord@system@interface@xy%
}%

\def\pgfplots@evalute@tikz@coord@system@interface@xy#1,{%
	\def\pgfplots@evaluate@tikz@coord@y{#1}%
	\pgfutil@ifnextchar\pgfplots@coord@end{%
		% ah - we have no Z component. ok.
		\let\pgfplots@evaluate@tikz@coord@z\pgfutil@empty
		% jump to the end of the state machine:
		\pgfplots@evalute@tikz@coord@system@interface@@@@@
	}{%
		\pgfplots@evalute@tikz@coord@system@interface@xyz
	}%
}%

\def\pgfplots@evalute@tikz@coord@system@interface@xyz#1,{%
	\def\pgfplots@evaluate@tikz@coord@z{#1}%
	\pgfplots@evalute@tikz@coord@system@interface@@@@@
}%

% equals only itsself in \ifx:
\def\pgfplots@coord@end{\pgfplots@coord@end}

\long\def\pgfplots@evalute@tikz@coord@system@interface@@@@@#1\pgfplots@coord@end{%
	%\begingroup <--- has already been opened at the beginning of the state machine
	\pgfplots@evalute@tikz@coord@system@interface@tocoords[\pgfplots@evaluate@tikz@coord@opts]%
	\xdef\pgfplots@glob@TMPa{\pgfplots@evaluate@tikz@coord@x}%
	\xdef\pgfplots@glob@TMPb{\pgfplots@evaluate@tikz@coord@y}%
	\xdef\pgfplots@glob@TMPc{\pgfplots@evaluate@tikz@coord@z}%
	\endgroup
	\ifx\pgfplots@glob@TMPc\pgfutil@empty
		\pgfplotsqpointxy{\pgfplots@glob@TMPa}{\pgfplots@glob@TMPb}%
	\else
		\pgfplotsqpointxyz{\pgfplots@glob@TMPa}{\pgfplots@glob@TMPb}{\pgfplots@glob@TMPc}%
	\fi
}

% Defines \pgfplots@evaluate@tikz@coord@[xyz]
\def\pgfplots@evalute@tikz@coord@system@interface@tocoords[#1]{%
	\def\pgfplots@evalute@tikz@coord@@##1##2{%
		\pgfplots@evalute@tikz@coord@system@interface@for[#1]{##2}{##1}%
	}%
	\expandafter\pgfplots@evalute@tikz@coord@@\expandafter{\pgfplots@evaluate@tikz@coord@x}{x}%
	\let\pgfplots@evaluate@tikz@coord@x=\pgfmathresult
	\expandafter\pgfplots@evalute@tikz@coord@@\expandafter{\pgfplots@evaluate@tikz@coord@y}{y}%
	\let\pgfplots@evaluate@tikz@coord@y=\pgfmathresult
	%
	\ifx\pgfplots@evaluate@tikz@coord@z\pgfutil@empty
	\else
		\expandafter\pgfplots@evalute@tikz@coord@@\expandafter{\pgfplots@evaluate@tikz@coord@z}{z}%
		\let\pgfplots@evaluate@tikz@coord@z=\pgfmathresult
	\fi
}%

\def\pgfplots@evalute@tikz@coord@system@interface@rel{%
	\begingroup
	\let\pgfplots@evalute@tikz@coord@system@interface@@@@@=\pgfplots@evalute@tikz@coord@system@interface@@@@@rel
	\pgfutil@ifnextchar[%
		{\pgfplots@evalute@tikz@coord@system@interface@x}%
		{\pgfplots@evalute@tikz@coord@system@interface@x[]}%
}

\long\def\pgfplots@evalute@tikz@coord@system@interface@@@@@rel#1\pgfplots@coord@end{%
	%\begingroup <--- has already been opened at the beginning of the state machine
	\pgfkeys{/pgf/fpu=false}%
	\pgfmathparse{\pgfplots@evaluate@tikz@coord@x}%
	\let\pgfplots@evaluate@tikz@coord@x=\pgfmathresult
	\pgfmathparse{\pgfplots@evaluate@tikz@coord@y}%
	\let\pgfplots@evaluate@tikz@coord@y=\pgfmathresult
	\ifx\pgfplots@evaluate@tikz@coord@z\pgfutil@empty
	\else
		\pgfmathparse{\pgfplots@evaluate@tikz@coord@z}%
		\let\pgfplots@evaluate@tikz@coord@z=\pgfmathresult
	\fi
	%
	\pgfplotspointxaxis
	\pgf@xx=\pgf@x
	\pgf@xy=\pgf@y
	%
	\pgfplotspointyaxis
	\pgf@yx=\pgf@x
	\pgf@yy=\pgf@y
	%
	\ifpgfplots@allow@reversal@of@rel@axis@cs
		\if\pgfkeysvalueof{/pgfplots/x dir/value}r%
			\pgf@xa=-\pgfplots@evaluate@tikz@coord@x pt
			\advance\pgf@xa by1pt
			\edef\pgfplots@evaluate@tikz@coord@x{\pgf@sys@tonumber\pgf@xa}%
		\fi
		\if\pgfkeysvalueof{/pgfplots/y dir/value}r%
			\pgf@xa=-\pgfplots@evaluate@tikz@coord@y pt
			\advance\pgf@xa by1pt
			\edef\pgfplots@evaluate@tikz@coord@y{\pgf@sys@tonumber\pgf@xa}%
		\fi
	\fi
	%
	\ifx\pgfplots@evaluate@tikz@coord@z\pgfutil@empty
		\pgfpointadd
			{\pgfplotspointminminmin}%
			{\pgfplotsqpointxy{\pgfplots@evaluate@tikz@coord@x}{\pgfplots@evaluate@tikz@coord@y}}%
	\else
		\ifpgfplots@allow@reversal@of@rel@axis@cs
			\if\pgfkeysvalueof{/pgfplots/z dir/value}r%
				\pgf@xa=-\pgfplots@evaluate@tikz@coord@z pt
				\advance\pgf@xa by1pt
				\edef\pgfplots@evaluate@tikz@coord@z{\pgf@sys@tonumber\pgf@xa}%
			\fi
		\fi
		\pgfplotspointzaxis
		\pgf@zx=\pgf@x
		\pgf@zy=\pgf@y
		\pgfpointadd
			{\pgfplotspointminminmin}%
			{\pgfplotsqpointxyz{\pgfplots@evaluate@tikz@coord@x}{\pgfplots@evaluate@tikz@coord@y}{\pgfplots@evaluate@tikz@coord@z}}%
	\fi
	\pgf@process{}%
	\endgroup
}

\def\pgfplots@evalute@tikz@coord@system@interface@normalized{%
	\begingroup
	\let\pgfplots@evalute@tikz@coord@system@interface@for=\pgfplots@evalute@tikz@coord@system@interface@for@normalized
	\pgfutil@ifnextchar[%
		{\pgfplots@evalute@tikz@coord@system@interface@x}%
		{\pgfplots@evalute@tikz@coord@system@interface@x[]}%
}

% In case of (semi-) logplots, this command will 
% - assign a filter which invokes \pgfmathlog@{} for each coordinate
% - replace any user-specified coordinate by its log.
%
% All subsequent commands will then work with logarithmic coordinates.
%
% PRECONDITION: 
% - The user input options have been set correctly, 
% - the options have been set, but are not applied
%
% POSTCONDITION: 
% - any user input has been parsed
% - any user input for log-axis has been replaced by its log if
%   necessary
% - coordinate filters are prepared
%
% See also:
%     \pgfplots@check@and@apply@datatrafo@for
\def\pgfplots@prepare@coord@filtering@for#1{%
	\pgfkeysgetvalue{/pgfplots/#1 coord trafo/.@cmd}\pgfplots@loc@TMPc
	\expandafter\let\csname pgfplots@highlevel@trafo@#1\endcsname=\pgfplots@loc@TMPc
	\ifx\pgfplots@loc@TMPc\pgfplots@empty@command@key
		% no high-level external coord trafos.
		% Simply use identity:
		\expandafter\def\csname pgfplots@prepare@#1coord\endcsname##1{%
			\edef\pgfmathresult{##1}%
		}%
	\else
		% Apply external coordinate trafo to all input values:
		\expandafter\edef\csname pgfplots@prepare@#1coord\endcsname##1{%
			% do not expand it here - might contain unexpandable
			% material which is processed by the #1 coord trafo:
			% FIXME : this might produce an endless loop if ##1 = \pgfmathresult! 
			\noexpand\def\noexpand\pgfmathresult{##1}%
			% this becomes 
			\expandafter\noexpand\csname pgfplots@highlevel@trafo@#1\endcsname{##1}\noexpand\pgfeov
			%
			% ensure that it is expanded.
			\noexpand\edef\noexpand\pgfmathresult{\noexpand\pgfmathresult}%
		}%
		%
		% The transformation is now \pgfplots@loc@TMPc
		%
		% any user-specified axis limits:
		\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@#1min\endcsname
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\expandafter\pgfplots@loc@TMPc\expandafter{\pgfplots@loc@TMPa}\pgfeov%
			\expandafter\global\expandafter\let\csname pgfplots@#1min\endcsname=\pgfmathresult
		\fi
		\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@#1max\endcsname
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\expandafter\pgfplots@loc@TMPc\expandafter{\pgfplots@loc@TMPa}\pgfeov%
			\expandafter\global\expandafter\let\csname pgfplots@#1max\endcsname=\pgfmathresult
		\fi
		%
		% any user-specified tick limits:
		\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@#1tickmin\endcsname
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\expandafter\pgfplots@loc@TMPc\expandafter{\pgfplots@loc@TMPa}\pgfeov%
			\expandafter\global\expandafter\let\csname pgfplots@#1tickmin\endcsname=\pgfmathresult
		\fi
		\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@#1tickmax\endcsname
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\expandafter\pgfplots@loc@TMPc\expandafter{\pgfplots@loc@TMPa}\pgfeov%
			\expandafter\global\expandafter\let\csname pgfplots@#1tickmax\endcsname=\pgfmathresult
		\fi
		%
		% any user specified axis ticks:
		\edef\pgfplots@loc@TMPa{\csname pgfplots@#1tick\endcsname}%
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\def\pgfplots@loc@TMPb{data}%
			\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
				% #1tick=data is handled elsewhere...
			\else
				\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@#1tick\endcsname
				\expandafter\pgfplots@filter@input@ticks@with@highleveltrafo\expandafter{\pgfplots@loc@TMPa}{\pgfplots@loc@TMPc}%
				\expandafter\edef\csname pgfplots@#1tick\endcsname{\pgfmathresult}%
			\fi
		\fi
		%
		\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@extra@#1tick\endcsname
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\expandafter\pgfplots@filter@input@ticks@with@highleveltrafo\expandafter{\pgfplots@loc@TMPa}{\pgfplots@loc@TMPc}%
			\expandafter\edef\csname pgfplots@extra@#1tick\endcsname{\pgfmathresult}%
		\fi
		%
		\pgfkeysgetvalue{/pgfplots/minor #1tick}\pgfplots@loc@TMPa
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\expandafter\pgfplots@filter@input@ticks@with@highleveltrafo\expandafter{\pgfplots@loc@TMPa}{\pgfplots@loc@TMPc}%
			\pgfkeyslet{/pgfplots/minor #1tick}\pgfmathresult
		\fi
	\fi
	%
	\pgfkeysgetvalue{/pgfplots/#1filter}\pgfplots@loc@TMPa
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
	\else
		\expandafter\let\csname pgfplots@#1filter@backwcompat\endcsname=\pgfplots@loc@TMPa
		\t@pgfplots@tokc={/pgfplots/#1filter is deprecated. Please use /pgfplots/#1 filter/.code={\def\pgfmathresult{\#1}}}%
		\pgfplots@warning{\the\t@pgfplots@tokc}%
		\pgfkeys{/pgfplots/#1 filter/.code={\csname pgfplots@#1filter@backwcompat\endcsname{##1}\to\pgfmathresult}}%
	\fi
	\csname ifpgfplots@#1islinear\endcsname
		\pgfplotssetcoordmathfor{#1}{float}%
		\csname pgfplots@apply@datatrafo@#1true\endcsname
		\pgfplots@apply@datatrafotrue
		\ifpgfplots@apply@datatrafo
			% Check for any existing axis limits:
			\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@#1min\endcsname
			\ifx\pgfplots@loc@TMPa\pgfutil@empty
			\else
				\pgfplotscoordmath{#1}{parse}{\pgfplots@loc@TMPa}%
				\expandafter\global\expandafter\let\csname pgfplots@#1min\endcsname=\pgfmathresult
			\fi
			\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@#1max\endcsname
			\ifx\pgfplots@loc@TMPa\pgfutil@empty
			\else
				\pgfplotscoordmath{#1}{parse}{\pgfplots@loc@TMPa}%
				\expandafter\global\expandafter\let\csname pgfplots@#1max\endcsname=\pgfmathresult
			\fi
			% Check for any existing tick limits:
			\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@#1tickmin\endcsname
			\ifx\pgfplots@loc@TMPa\pgfutil@empty
			\else
				\pgfplotscoordmath{#1}{parse}{\pgfplots@loc@TMPa}%
				\expandafter\global\expandafter\let\csname pgfplots@#1tickmin\endcsname=\pgfmathresult
			\fi
			\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@#1tickmax\endcsname
			\ifx\pgfplots@loc@TMPa\pgfutil@empty
			\else
				\pgfplotscoordmath{#1}{parse}{\pgfplots@loc@TMPa}%
				\expandafter\global\expandafter\let\csname pgfplots@#1tickmax\endcsname=\pgfmathresult
			\fi
		\fi
	\else
		\pgfplotssetcoordmathfor{#1}{pgfbasic}%
		%
		% This here could be done using a high level coord trafo as
		% well! However, I don't want to risk accidentally overwritten
		% keys, so I replicate it here.
		\pgfplots@if{pgfplots@disablelogfilter@#1}{\relax}{%
			% Prepare the log to use for axis '#1'.
			%
			\pgfkeysgetvalue{/pgfplots/log basis #1}\pgfplots@loc@TMPa%
			\edef\pgfplots@loc@TMPa{\pgfplots@loc@TMPa}%
			\def\pgfplots@loc@TMPb{e}%
			\ifx\pgfplots@loc@TMPb\pgfplots@loc@TMPa
				% log basis x=e : same as empty value.
				\let\pgfplots@loc@TMPa=\pgfutil@empty
			\fi
			\ifx\pgfplots@loc@TMPa\pgfutil@empty
				% log basis x={} (initial setting:)
			\else
				% use a different basis.
				\pgfplotscoordmath{#1}{set log basis}{\pgfplots@loc@TMPa}%
				%
				% generate default ticks in the 'log basis', not base 10:
				\pgfplotsset{/pgfplots/log basis ticks=#1}%
				% 
				\ifdim\pgfkeysvalueof{/pgfplots/log basis #1}pt=10pt
				\else
					\pgfplots@identify@log@minor@tick@posfalse
					\csname pgfplots@#1minorticksfalse\endcsname
					\csname pgfplots@#1minorgridsfalse\endcsname
					\expandafter\def\csname pgfplots@#1minortickstrue\endcsname{\pgfplots@error{Sorry, minor ticks are not supported for this log basis.}}%
					\expandafter\def\csname pgfplots@#1minorgridstrue\endcsname{\pgfplots@error{Sorry, minor grid lines are not supported for this log basis.}}%
				\fi
				\pgfkeyslet{/pgfplots/log basis #1/.@cmd}\pgfplots@cant@set@in@this@context
				%%%
				% Ok, now, I have prepared everything for the new
				% log basis!
			\fi
			%
			% any user-specified axis limits:
			\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@#1min\endcsname
			\ifx\pgfplots@loc@TMPa\pgfutil@empty
			\else
				\pgfplotscoordmath{default}{parse}{\pgfplots@loc@TMPa}%
				\pgfplotscoordmath{#1}{log}{\pgfmathresult}%
				\pgfplotscoordmath{#1}{if is bounded}{\pgfmathresult}{%
				}{%
					\pgfplotswarning{illegal user argument in log axis}{#1min}{\csname pgfplots@#1min\endcsname}\pgfeov%
				}%
				\expandafter\global\expandafter\let\csname pgfplots@#1min\endcsname=\pgfmathresult
			\fi
			\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@#1max\endcsname
			\ifx\pgfplots@loc@TMPa\pgfutil@empty
			\else
				\pgfplotscoordmath{default}{parse}{\pgfplots@loc@TMPa}%
				\pgfplotscoordmath{#1}{log}{\pgfmathresult}%
				\pgfplotscoordmath{#1}{if is bounded}{\pgfmathresult}{%
				}{%
					\pgfplotswarning{illegal user argument in log axis}{#1max}{\csname pgfplots@#1max\endcsname}\pgfeov%
				}%
				\expandafter\global\expandafter\let\csname pgfplots@#1max\endcsname=\pgfmathresult
			\fi
			%
			% any user-specified tick limits:
			\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@#1tickmin\endcsname
			\ifx\pgfplots@loc@TMPa\pgfutil@empty
			\else
				\pgfplotscoordmath{#1}{log}{\pgfplots@loc@TMPa}%
				\expandafter\global\expandafter\let\csname pgfplots@#1tickmin\endcsname=\pgfmathresult
			\fi
			\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@#1tickmax\endcsname
			\ifx\pgfplots@loc@TMPa\pgfutil@empty
			\else
				\pgfplotscoordmath{#1}{log}{\pgfplots@loc@TMPa}%
				\expandafter\global\expandafter\let\csname pgfplots@#1tickmax\endcsname=\pgfmathresult
			\fi
			%
			% any user specified axis ticks:
			\edef\pgfplots@loc@TMPa{\csname pgfplots@#1tick\endcsname}%
			\ifx\pgfplots@loc@TMPa\pgfutil@empty
			\else
				\def\pgfplots@loc@TMPb{data}%
				\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
					% #1tick=data is handled elsewhere...
				\else
					\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@#1tick\endcsname
					\expandafter\pgfplots@filter@input@ticks@with@log\expandafter{\pgfplots@loc@TMPa}{#1}%
					\expandafter\edef\csname pgfplots@#1tick\endcsname{\pgfmathresult}%
				\fi
			\fi
			\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@extra@#1tick\endcsname
			\ifx\pgfplots@loc@TMPa\pgfutil@empty
			\else
				\expandafter\pgfplots@filter@input@ticks@with@log\expandafter{\pgfplots@loc@TMPa}{#1}%
				\expandafter\edef\csname pgfplots@extra@#1tick\endcsname{\pgfmathresult}%
			\fi
			%
			\pgfkeysgetvalue{/pgfplots/minor #1tick}\pgfplots@loc@TMPa
			\ifx\pgfplots@loc@TMPa\pgfutil@empty
			\else
				\expandafter\pgfplots@filter@input@ticks@with@log\expandafter{\pgfplots@loc@TMPa}{#1}%
				\pgfkeyslet{/pgfplots/minor #1tick}\pgfmathresult
			\fi
			%
			% append logarithm to prepare coord.
			%
			\t@pgfplots@toka={%
				\ifx\pgfmathresult\pgfutil@empty
				\else
					\pgfplots@if{pgfplots@disablelogfilter@#1}{%
						\pgfplotscoordmath{#1}{parsenumber}{\pgfmathresult}%
						% FIXME : check for unbounded arguments!
					}{%
						\pgfplotscoordmath{#1}{log}{\pgfmathresult}%
						\pgfplotscoordmath{#1}{if is bounded}{\pgfmathresult}{}{%
							\def\pgfplots@unbounded@dir{#1}%
						}%
					}%
				\fi
			}%
			\pgfkeysgetvalue{/pgfplots/#1 coord trafo/.@cmd}\pgfplots@loc@TMPc
			\ifx\pgfplots@loc@TMPc\pgfplots@empty@command@key
				\expandafter\edef\csname pgfplots@prepare@#1coord\endcsname##1{%
					\noexpand\edef\noexpand\pgfmathresult{##1}%
					\the\t@pgfplots@toka
				}%
			\else
				% This is a bit complicated... but it works: APPEND
				% the log stuff to the existing prepare method.
				\t@pgfplots@tokb=\expandafter\expandafter\expandafter{%
					\csname pgfplots@prepare@#1coord\endcsname{##1}%
				}%
				\expandafter\edef\csname pgfplots@prepare@#1coord\endcsname##1{%
					\the\t@pgfplots@tokb
					\the\t@pgfplots@toka
				}%
			\fi
		}%
	\fi
}

\def\pgfplots@create@axis@descriptions{%
	\begingroup
		%
		\pgfplots@change@pgfpoints@to@descriptioncs
		%
		\pgfplots@create@axis@descriptions@
	\endgroup
}

\def\pgfplots@create@axis@descriptions@{%
	\begingroup
	\ifpgfplots@hide@x
	\else
				  \ifpgfplots@units@use%
						\pgfplots@show@label{x}{\pgfplots@label@units{x}}%
				  \else%
						\pgfkeysgetvalue{/pgfplots/xlabel}{\pgfplots@label@}%
						\ifx\pgfplots@label@\pgfutil@empty
						\else
							  \pgfplots@show@label{x}{\pgfplots@label@}%
						\fi
				  \fi
	\fi
	\ifpgfplots@hide@y
	\else
				  \ifpgfplots@units@use%
						\pgfplots@show@label{y}{\pgfplots@label@units{y}}%
				  \else%
						\pgfkeysgetvalue{/pgfplots/ylabel}{\pgfplots@label@}%
						\ifx\pgfplots@label@\pgfutil@empty
						\else
							  \pgfplots@show@label{y}{\pgfplots@label@}%
						\fi
				  \fi  
	\fi
	\ifpgfplots@threedim
		\ifpgfplots@hide@z
		\else
						  \ifpgfplots@units@use%
								\pgfplots@show@label{z}{\pgfplots@label@units{z}}%
						  \else%
								\pgfkeysgetvalue{/pgfplots/zlabel}{\pgfplots@label@}%
								\ifx\pgfplots@label@\pgfutil@empty
								\else
									  \pgfplots@show@label{z}{\pgfplots@label@}%
								\fi
						  \fi
		\fi
	\fi
	\endgroup
	%
	\pgfkeysgetvalue{/pgfplots/title}\pgfplots@loc@TMPa
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
	\else
		\expandafter\pgfplots@show@title\expandafter{\pgfplots@loc@TMPa}%
	\fi
	\pgfplots@createlegend
	%
	\pgfkeysvalueof{/pgfplots/extra description/.@cmd}\pgfeov%
	%
}

% Invokes '#1' foreach key which should be saved by a color bar.
%
% The current key name is available as '##1', the macro under which
% the key is / should be saved as '##2'.
\def\pgfplots@colorbar@foreach@saved@key#1{%
	\def\pgfplots@colorbar@foreach@saved@key@body##1##2{#1}%
	\pgfplotsutilforeachcommasep{%
		{/pgfplots/colorbar/draw/.@cmd}\pgfplots@savedstyle@colorbar@draw,%
		{/pgfplots/every colorbar/.@cmd}\pgfplots@savedstyle@colorbar,%
		{/pgfplots/colorbar shift/.@cmd}\pgfplots@savedstyle@colorbarshift,%
		{/pgfplots/colorbar horizontal/lowlevel/.@cmd}\pgfplots@savedstyle@colorbar@horizontal,%
		{/pgfplots/colorbar vertical/lowlevel/.@cmd}\pgfplots@savedstyle@colorbar@vertical,%
		{/pgfplots/every tick/.@cmd}\pgfplots@savedstyle@tick,%
		{/pgfplots/every minor tick/.@cmd}\pgfplots@savedstyle@minortick,%
		{/pgfplots/every major tick/.@cmd}\pgfplots@savedstyle@majortick,%
		{/pgfplots/every axis grid/.@cmd}\pgfplots@savedstyle@grid,%
		{/pgfplots/every minor grid/.@cmd}\pgfplots@savedstyle@minorgrid,%
		{/pgfplots/every major grid/.@cmd}\pgfplots@savedstyle@majorgrid,%
		{/pgfplots/every tick label/.@cmd}\pgfplots@savedstyle@ticklabel,%
		{/pgfplots/every tick label/.@cmd}\pgfplots@savedstyle@ticklabel%
	}%
		\as\pgfplots@colorbar@foreach@saved@key@@
	{%
		\expandafter\pgfplots@colorbar@foreach@saved@key@body\pgfplots@colorbar@foreach@saved@key@@
	}%
}%
\def\pgfplots@colorbar@restore@saved@keys{%
	\pgfplots@colorbar@foreach@saved@key{%
		\pgfkeyslet{##1}##2%
	}%
}%

% Defines '#1' to be a macro which, upon execution, draws the color
% bar for the current axis. It also handles any required style
% inheritance and option preparation issues.
%
% The important thing is: the macro is expected to be invoked after
% the current TeX group (scope). Thus, the complete state is
% represented inside of '#1' (and maybe some global variables).
\def\pgfplots@colorbar@move@outside@scope@with@globalmacro#1{%
	\pgfplotspointbbdiagonal
	\edef\pgfplots@loc@TMPa{\the\pgf@x}%
	\edef\pgfplots@loc@TMPb{\the\pgf@y}%
	\pgfkeyslet{/pgfplots/parent axis width}{\pgfplots@loc@TMPa}%
	\pgfkeyslet{/pgfplots/parent axis height}{\pgfplots@loc@TMPb}%
	%
	\pgfkeysgetvalue{/pgfplots/colorbar to name}\pgfplots@colorbar@toname
	%
	\pgfnodealias{parent axis}{current axis}%
	%
	% FIXME : 
	% I would really prefer to find a different way to move these
	% variables out of the current scope. But expansion leads to
	% mistakes with '#' characters ... :-(
	\pgfplots@colorbar@foreach@saved@key{%
		\pgfkeysgetvalue{##1}\pgfplots@loc@TMPa
		\global\let##2=\pgfplots@loc@TMPa
	}%
	%
	\toks1={}%
	\ifx\pgfplots@colorbar@toname\pgfutil@empty
	\else
		\toks1={%
			\pgfkeysgetvalue{/pgfplots/at/.@cmd}\pgfplots@at@orig
			\pgfkeyslet{/pgfplots/at/orig/.@cmd}\pgfplots@at@orig
			%
			\pgfkeysgetvalue{/pgfplots/colorbar to name/at/.@cmd}\pgfplots@colorbar@toname@at
			\pgfkeyslet{/pgfplots/at/.@cmd}\pgfplots@colorbar@toname@at
		}%
		\pgfplots@colorbar@foreach@saved@key{%
			\pgfplots@command@with@args@to@string##2\pgfplots@loc@TMPa
			\pgfplots@auxwrite{%
				\noexpand\expandafter
				\noexpand\long
				\noexpand\expandafter
				\noexpand\gdef
				\noexpand\csname pgfplots@colorbar@\pgfplots@colorbar@toname @\noexpand\string\noexpand##2\noexpand\endcsname%
					\pgfplots@loc@TMPa
			}%
			\edef\pgfplots@loc@TMPa{%
				\the\toks1
				\noexpand\expandafter
				\noexpand\let
				\noexpand\expandafter
				\noexpand##2%
					\noexpand\csname pgfplots@colorbar@\pgfplots@colorbar@toname @\noexpand\string\noexpand##2\noexpand\endcsname%
			}%
			\toks1=\expandafter{\pgfplots@loc@TMPa}%
		}%
	\fi
	% %
	% we have to do a lot of work to move *some* of the current
	% settings out of the current TeX group:
	\pgfkeysgetvalue{/pgfplots/colormap name}\pgfplots@loc@TMPa
	\expandafter\pgfplotscolormapserializetomacro\expandafter{\pgfplots@loc@TMPa}{\pgfplots@serializedcolormap}%
	\toks0=\expandafter{\pgfplots@serializedcolormap}%
	%
	\pgfkeysgetvalue{/pgfplots/colorbar addplot}\pgfplots@loc@TMPa
	\toks2=\expandafter{\pgfplots@loc@TMPa}%
	%
	\ifx\pgfplots@colorbar@src@metamin\pgfutil@empty
		\global\let\pgfplots@colorbar@src@metamin=\pgfplots@axiswide@metamin
		\global\let\pgfplots@colorbar@src@metamax=\pgfplots@axiswide@metamax
	\fi
	%
	\ifx\pgfplots@colorbar@src@metamax\pgfplots@invalidrange@metamax
		\pgfplotswarning{colorbar uninitialised}\pgfeov
		\pgfmathfloatparsenumber{0}%
		\global\let\pgfplots@colorbar@src@metamin=\pgfmathresult
		\pgfmathfloatparsenumber{1}%
		\global\let\pgfplots@colorbar@src@metamax=\pgfmathresult
	\fi
	%
	% normalize format:
	\pgfplotscoordmath{meta}{tostring}{\pgfplots@colorbar@src@metamin}%
	\global\let\pgfplots@colorbar@src@metamin=\pgfmathresult
	\pgfplotscoordmath{meta}{tostring}{\pgfplots@colorbar@src@metamax}%
	\global\let\pgfplots@colorbar@src@metamax=\pgfmathresult
	%
	\pgfplots@assemble@ref@picture
		{\pgfplots@colorbar@draw}
		{\tikz[/pgfplots/every colorbar to name picture/.try]{\pgfplots@colorbar@draw}}%
	\toks3=\expandafter{\pgfplotsretval}%
	%
	\xdef#1{%
		\noexpand\begingroup
		\noexpand\def\noexpand\pgfplots@colorbar@draw{%
			\the\toks0 % restore colormap definition
			\noexpand\def\noexpand\pgfplots@colorbar@toname{\pgfplots@colorbar@toname}%
			\the\toks1 % definitions for 'colorbar to name'
			%
			%  restore relevant styles and variables:
			\noexpand\pgfplots@colorbar@restore@saved@keys
			\noexpand\pgfkeyssetvalue{/pgfplots/point meta min}{\pgfplots@colorbar@src@metamin}%
			\noexpand\pgfkeyssetvalue{/pgfplots/point meta max}{\pgfplots@colorbar@src@metamax}%
			\noexpand\pgfkeyssetvalue{/pgfplots/colormap name}{\pgfkeysvalueof{/pgfplots/colormap name}}%
			\noexpand\pgfkeyssetvalue{/pgfplots/parent axis width}{\pgfkeysvalueof{/pgfplots/parent axis width}}%
			\noexpand\pgfkeyssetvalue{/pgfplots/parent axis height}{\pgfkeysvalueof{/pgfplots/parent axis height}}%
			\noexpand\pgfkeyssetvalue{/pgfplots/colorbar/width}{\pgfkeysvalueof{/pgfplots/colorbar/width}}%
			\noexpand\pgfkeyssetvalue{/pgfplots/colorbar addplot}{\the\toks2 }%
			\noexpand\def\noexpand\pgfplots@colormap@access{\pgfplots@colormap@access}%
			\noexpand\pgfkeyssetvalue{/pgfplots/colorbar pos*}{\pgfkeysvalueof{/pgfplots/colorbar pos*}}%
			% just to make sure that colorbar sampled respects it:
			\noexpand\pgfkeyssetvalue{/pgfplots/mark list fill}{\pgfkeysvalueof{/pgfplots/mark list fill}}%
			\noexpand\pgfplots@colorbar@define@hook%
			\noexpand\pgfplots@colorbar@draw@
			\ifx\pgfplots@colorbar@toname\pgfutil@empty
				\noexpand\pgfnodealias{current colorbar axis}{current axis}%
				\noexpand\pgfnodealias{current axis}{parent axis}%
			\fi
		}%
		\the\toks3
		\noexpand\endgroup
	}%
	\ifx\pgfplots@colorbar@toname\pgfutil@empty
	\else
		% finalize the 'colorbar to name' feature
		\toks0=\expandafter{#1}%
		\pgfplots@auxwrite{%
			\noexpand\expandafter
			\noexpand\gdef\noexpand\csname pgfplots@colorbar@to@name@\pgfplots@colorbar@toname\endcsname{\the\toks0}}%
		\xdef#1{}% NOP.
		% 
		% make sure \ref{<colorbarname>} works:
		\pgfplots@label{\pgfplots@colorbar@toname}{pgfplots@colorbar@to@name@}%
	\fi
}%

\newif\ifpgfplotscolorbarCMYKworkaround
\pgfplotscolorbarCMYKworkaroundtrue

\def\pgfplots@colorbar@draw@{%
	\ifpgfplotscolorbarCMYKworkaround
		% the default implementation for colorbars is based on
		% \pgfplotscolormaptoshadingspec.
		% This, in turn, does NOT work for CMYK.
		%
		% This here detects that case and switches to the (visually)
		% equivalent 'colorbar sampled={surf,shader=interp}' style.
		\if1\pgfplotscolormaptoshadingspectorgb
			\pgfkeysgetvalue{/pgfplots/colorbar/draw/.@cmd}\pgfplots@loc@TMPa
			\ifx\pgfplots@loc@TMPa\pgfplots@colorbar@draw@defaultimpl
				\pgfkeysgetvalue{/pgfplots/colormap name}\pgfplots@loc@TMPb
				\pgfplotscolormapgetcolorspace{\pgfplots@loc@TMPb}%
				\def\pgfplots@loc@TMPa{cmyk}%
				\ifx\pgfplots@loc@TMPa\pgfplotsretval
					\pgfutil@ifundefined{pgfplots@colorbar@CMYK@\pgfplots@loc@TMPb}{%
						\pgfplotswarning{colorbar CMYK unsupported}{\pgfplots@loc@TMPb}\pgfeov% 
						\expandafter\gdef\csname pgfplots@colorbar@CMYK@\pgfplots@loc@TMPb\endcsname{1}%
					}{}%
					\pgfplotsset{colorbar sampled={surf,shader=interp}}%
				\fi
			\fi
		\fi
	\fi
	%
	% FIXME : the semicolon after ';' has a fixed catcode, namely
	% the one assigned while pgfplots.code.tex has been read.
	%
	% The \pgfplots@checkandpreparefor@active@semicolon gets
	% confused if the catcodes change... this here is a
	% work-around for babel support.
	\let\pgfplots@checkandpreparefor@active@semicolon\relax
	%
	% make sure that 'every colorbar' is checked by the key-filtering
	% stuff: we want to find 'ymode=log' inside of it.
	% Note that we have to change it here because only the colorbar
	% should expand 'every colorbar' that early in the processing:
	\pgfkeys{/pgfplots/every colorbar/.belongs to family=/pgfplots/scale}%
	%
	\pgfkeysvalueof{/pgfplots/colorbar/draw/.@cmd}\pgfeov
}
\pgfkeysdef{/pgfplots/colorbar to name/at}{%
	% automatically search-and-replace 'parent axis' which
	% is not defined for a detached colorbar:
	\pgfutil@in@{parent axis}{#1}%
	\ifpgfutil@in@
		\pgfplots@invoke@pgfkeyscode{/pgfplots/at/orig/.@cmd}{(0pt,0pt)}%
	\else
		\pgfplots@invoke@pgfkeyscode{/pgfplots/at/orig/.@cmd}{#1}%
	\fi
}%
\let\pgfplots@colorbar@position@hook\relax
\def\pgfplots@colorbar@define@hook{%
	\ifx\pgfplots@colorbar@toname\pgfutil@empty
		\def\pgfplots@colorbar@position@hook{%
			% I patch \pgfplots@at...
			\let\pgfplots@at@orig=\pgfplots@at
			%
			% ... and I patch \pgfplotspointdescriptionxy (but only INSIDE
			% of \pgfplots@at) ...
			\let\pgfplotspointdescriptionxy@orig=\pgfplotspointdescriptionxy
			\let\pgfplotsqpointdescriptionxy@orig=\pgfplotsqpointdescriptionxy
			\def\pgfplots@colorbar@position@prepare@CS{%
				% ... which needs to set up ONLY \pgfplotspoint@bb@@@,
				% nothing more.
				\pgfpointanchor{parent axis}{south west}%
				\edef\pgfplotspoint@bb@@@{%
					{\the\pgf@x}%
					{\the\pgf@y}%
					{\pgfkeysvalueof{/pgfplots/parent axis width}}%
					{\pgfkeysvalueof{/pgfplots/parent axis height}}%
				}%
			}%
			%
			% Install replacements:
			\def\pgfplots@at{%
				\begingroup
				\def\pgfplotspointdescriptionxy########1########2{%
					\pgfplots@colorbar@position@prepare@CS
					\pgfplotspointdescriptionxy@orig{########1}{########2}%
				}%
				\def\pgfplotsqpointdescriptionxy########1########2{%
					\pgfplots@colorbar@position@prepare@CS
					\pgfplotsqpointdescriptionxy@orig{########1}{########2}%
				}%
				\pgfplots@deprecated@anchorsfalse
				\pgfplots@change@pgfpoints@to@descriptioncs
				\pgf@process{\pgfplots@at@orig}%
				\endgroup
			}%
		}%
	\else
		% nothing to do for colorbar to name:
		\let\pgfplots@colorbar@position@hook=\relax
	\fi
}%

% Parses all options in #1 which are known in the currently active families.
%
% The result will be stored back into the TikZ-style named #1 without 
% further processing.
%
% Example:
% \tikzstyle{every axis}=[xmin=0,xmax=1,line width=1pt
% \pgfplots@set@keys@from@tikz@style\tmpmacro{every axis}{/pgfplots}
% 
% - sets axis options 'xmin' and 'xmax'
% - calls \tikzstyle{every axis}={line width=1pt}
% 
% I assume that this method is called within local TeX groups so
% nothing will be destroyed outside.
%
% #1:  A style name.
\def\pgfplots@set@keys@from@tikz@style#1{%
	\let\pgfplots@rmopts=\pgfutil@empty
	\pgfqkeysfiltered{/pgfplots}{/pgfplots/#1}%
	\pgfplots@set@keymacro@to@style\pgfplots@rmopts{#1}%
}

% Invokes \pgfplots@set@keys@from@tikz@style and handles the "on
% layer" key.
%
% More precisely, it stores any "on layer" value found in style "#1"
% in
% /pgfplots/layers for styles/#1.
%
% If there is no such value, it will store the empty string (main
% layer)
\def\pgfplots@set@keys@from@tikz@style@and@handle@layer#1{%
	\pgfkeyslet{/pgfplots/on layer}\pgfutil@empty
	\pgfplots@set@keys@from@tikz@style{#1}%
	\pgfkeysgetvalue{/pgfplots/on layer}\pgfplots@loc@TMPa
	\pgfkeyslet{/pgfplots/layers for styles/#1}\pgfplots@loc@TMPa
}%

% The same as \pgfplots@set@keys@from@tikz@style  but this one appends
% unmatched options to style #2.
%
% #1:  A style name.
% #2:  A style name which will be filled with unprocessed options.
\def\pgfplots@set@keys@from@tikz@style@append@to#1#2{%
	\let\pgfplots@rmopts=\pgfutil@empty
	\pgfqkeysfiltered{/pgfplots}{/pgfplots/#1}%
	\pgfplots@append@keymacro@to@style\pgfplots@rmopts{#2}%
}

% #1:  A sequence of options.
% #2:  A style name which will be filled with unprocessed options.
\def\pgfplots@set@keys@and@append@remaining@to@style#1#2{%
	\let\pgfplots@rmopts=\pgfutil@empty
	\pgfqkeysfiltered{/pgfplots}{#1}%
	\pgfplots@append@keymacro@to@style\pgfplots@rmopts{#2}%
}%

% #1: input macro
\def\pgfplots@setkeys@from@macro#1{%
	\let\pgfplots@rmopts=\pgfutil@empty
	\def\pgfplots@loc@TMPa{\pgfqkeysfiltered{/pgfplots}}%
	\expandafter\pgfplots@loc@TMPa\expandafter{#1}%
}

% #1: macro
% #2: style name
\long\def\pgfplots@append@keymacro@to@style#1#2{%
	\ifx#1\pgfutil@empty
	\else
		\t@pgfplots@toka={#2/.append style=}%
		\t@pgfplots@tokb=\expandafter{#1}%
		\edef\pgfplots@setkeys@TMP{\the\t@pgfplots@toka{\the\t@pgfplots@tokb}}%
		\expandafter\pgfplotsset\expandafter{\pgfplots@setkeys@TMP}%
	\fi
%\pgfplots@message{tikzstyle{#2}+=[#1]}%
}

% #1: macro
% #2: style name
\long\def\pgfplots@set@keymacro@to@style#1#2{%
	\ifx#1\pgfutil@empty
		\pgfplotsset{#2/.code={{}}}%
	\else
		\t@pgfplots@toka={#2/.style=}%
		\t@pgfplots@tokb=\expandafter{#1}%
		\edef\pgfplots@setkeys@TMP{\the\t@pgfplots@toka{\the\t@pgfplots@tokb}}%
		\expandafter\pgfplotsset\expandafter{\pgfplots@setkeys@TMP}%
	\fi
%\pgfplots@message{tikzstyle{#2}=[#1]}%
}

% backwards compatibility:
\let\prettyprintnumber=\pgfmathprintnumber%


\def\pgfplots@set@options@sanitizemode{%
	\pgfkeyslet{/pgfplots/xmode/.@cmd}\pgfplots@cant@set@in@this@context@
	\pgfkeyslet{/pgfplots/ymode/.@cmd}\pgfplots@cant@set@in@this@context@
	\pgfkeyslet{/pgfplots/zmode/.@cmd}\pgfplots@cant@set@in@this@context@
}
\def\pgfplots@set@options@sanitize{%
	\pgfkeyslet{/pgfplots/xmin/.@cmd}\pgfplots@cant@set@in@this@context
	\pgfkeyslet{/pgfplots/ymin/.@cmd}\pgfplots@cant@set@in@this@context
	\pgfkeyslet{/pgfplots/zmin/.@cmd}\pgfplots@cant@set@in@this@context
	\pgfkeyslet{/pgfplots/xmax/.@cmd}\pgfplots@cant@set@in@this@context
	\pgfkeyslet{/pgfplots/ymax/.@cmd}\pgfplots@cant@set@in@this@context
	\pgfkeyslet{/pgfplots/zmax/.@cmd}\pgfplots@cant@set@in@this@context
}%

% This here is the main key filter for pgfplots.
%
% It sets keys if
% ( they have an active key family)
% OR
% ( they have /pgfplots/ key prefix )
% OR
% ( they are a command key which contains \tikz@plot@handler ).
%
% In all other cases, the key filter will postpone the key.
%
% Note that \tikz@plot@handler should be defined before the survey
% phase starts.
\pgfkeysdef{/pgfplots/@@key filter}{%
	\if\pgfkeyscasenumber0%
		\pgfkeysfiltercontinuefalse
	\else
		\if\pgfkeyscasenumber3%
			\pgfkeysgetfamily\pgfkeyscurrentpath\pgfkeyspred@TMP
		\else
			\pgfkeysgetfamily\pgfkeyscurrentkey\pgfkeyspred@TMP
		\fi
		\ifpgfkeyssuccess
			% it has a family. Check it!
			\pgfkeysisfamilyactive{\pgfkeyspred@TMP}%
		\else% Ok, it does not belong to any family.
			% Check if it has /pgfplots/ prefix:
			\expandafter\pgfplots@key@filter@isdescendantof\pgfkeyscurrentkey/pgfplots/\pgf@@eov
		\fi
	\fi
}
\def\pgfplots@key@filter@isdescendantof#1/pgfplots/#2\pgf@@eov{%
	\def\pgfkeyspred@TMP{#1}%
	\ifx\pgfkeyspred@TMP\pgfkeys@empty
		% Ah -- it *has* /pgfplots/ prefix. Use it!
		\pgfkeysfiltercontinuetrue
	\else
		% Hm. Probably a /tikz/ key, but who knows.
		\if1\pgfkeyscasenumber
			% It is a command key.
			% Check if the *body* of the command key contains
			% \tikz@plot@handler.
			\pgfkeysgetvalue{\pgfkeyscurrentkey/.@cmd}\pgfkeyspred@TMP%
			\expandafter\pgfplots@key@filter@isplothandler\pgfkeyspred@TMP 123456789\pgfeov\tikz@plot@handler\pgfplots@EOI
		\else
			% Ok, it's no command key. Skip it directly.
			\pgfkeysfiltercontinuefalse
		\fi
	\fi
}%
\def\pgfplots@key@filter@isplothandler#1\tikz@plot@handler#2\pgfplots@EOI{%
	\def\pgfkeyspred@TMP{#2}%
	\ifx\pgfkeyspred@TMP\pgfkeys@empty
		% I didn't find '\tikz@plot@handler' in the key's body. Ok.
		% key won't be processed.
		\pgfkeysfiltercontinuefalse
	\else
		% Aaah -- it is something like /tikz/ybar! process it.
		\pgfkeysfiltercontinuetrue
	\fi
}%

\def\pgfplots@set@options#1{%
	\pgfplots@check@global@colorspace@overrides
	\pgfplots@bb@isactivetrue
	\pgfplots@curplot@threedimfalse
	\global\pgfplots@threedimfalse
	\pgfutil@ifundefined{tikz@lastx}{%
		% no warning. Its not that important anyway, I think.
		\def\pgfplots@at{\pgfpointorigin}%
	}{%
		\def\pgfplots@at{\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}%
	}%
	%
	% Temporarily assign families to 'name' and 'alias' options.
	% This allows to get the names - they should not be appended to
	% 'every axis'!
	\pgfkeyssetfamily{/tikz/name}{/pgfplots/naming commands}%
	\pgfkeyssetfamily{/tikz/alias}{/pgfplots/naming commands}%
	\pgfkeyssetfamily{/tikz/overlay}{/pgfplots/shared with tikz}%
	\pgfkeyssetfamily{/tikz/variable}{/pgfplots}%
	%
	% ... we need to set these options during the survey phase
	% (because it might be interesting for enlarge limits to depend
	% upon their value):
	\pgfkeysdef{/pgfplots/bar width}{\pgfkeysalso{/pgf/bar width={##1}}}%
	\pgfkeysdef{/pgfplots/bar shift}{\pgfkeysalso{/pgf/bar shift={##1}}}%
	\pgfkeyssetfamily{/pgf/bar width}{/pgfplots}%
	\pgfkeyssetfamily{/pgf/bar shift}{/pgfplots}%
	%
	\pgfkeyssetfamily{/pgf/trig format}{/pgfplots}%
	\pgfkeyssetfamily{/pgf/trig format/deg}{/pgfplots}%
	\pgfkeyssetfamily{/pgf/trig format/rad}{/pgfplots}%
	%
	\pgfkeysinstallkeyfilterhandler{/pgf/key filter handlers/append filtered to}{\pgfplots@rmopts}%
	%
	\let\tikz@alias=\pgfutil@empty
	\let\tikz@fig@name=\pgfutil@empty
	%
	% Step 1: acquire ONLY 'xmode' and 'ymode' (necessary to decide
	% which axis style shall be loaded):
		\let\pgfplots@rmopts=\pgfutil@empty
		\pgfkeysinstallkeyfilter{/pgf/key filters/active families and known}{}%
		%
		\pgfqkeysactivatesinglefamilyandfilteroptions{/pgfplots/scale}%
			{/pgfplots}
			{#1,/pgfplots/every axis post}%
	\let\pgfplots@remaining@input=\pgfplots@rmopts
	%
	\pgfplotssetaxistype{\pgfkeysvalueof{/pgfplots/axis type}}%
	%
	% Step 2: parse any pgfplots options out of styles.
	\pgfkeysactivatefamily{/pgfplots/style commands}%
	%\pgfkeysinstallkeyfilter{/pgf/key filters/active families or descendants of}{/pgfplots}
	\pgfkeysinstallkeyfilter{/pgfplots/@@key filter}{}%
	%
	\pgfkeysactivatefamilies
		{/pgfplots,/pgfplots/naming commands,/pgfplots/tick,/pgfplots/legend,/pgfplots/scale}%/pgfplots/descriptions,}
		{\pgfplots@deactivefamiliescmd}%
		\pgfplots@set@keys@from@tikz@style{every axis}%
		\pgfkeysdeactivatefamily{/pgfplots/scale}%
		%
		\pgfplots@set@keys@from@tikz@style@append@to{every \pgfkeysvalueof{/pgfplots/axis type} axis}{every axis}%
		%
		\ifpgfplots@xislinear
			\ifpgfplots@yislinear
				\pgfplots@set@keys@from@tikz@style@append@to{every linear axis}{every axis}%
			\else
				\pgfplots@set@keys@from@tikz@style@append@to{every semilogy axis}{every axis}%
			\fi
		\else
			\ifpgfplots@yislinear
				\pgfplots@set@keys@from@tikz@style@append@to{every semilogx axis}{every axis}%
			\else
				\pgfplots@set@keys@from@tikz@style@append@to{every loglog axis}{every axis}%
			\fi
		\fi
	\pgfplots@deactivefamiliescmd
	\pgfplots@set@options@sanitizemode
	%
	% Acquire style commands and nameing commands from direct input
	% options '#1' BEFORE the 'every' styles are processed:
	\pgfkeysactivatefamily{/pgfplots/naming commands}%
	\pgfkeysactivatefamily{/pgfplots/shared with tikz}%
		\pgfplots@setkeys@from@macro\pgfplots@remaining@input%
		\let\pgfplots@remaining@input=\pgfplots@rmopts
	\pgfkeysdeactivatefamily{/pgfplots/naming commands}%
	\pgfkeysdeactivatefamily{/pgfplots/shared with tikz}%
	%
	\pgfplots@set@options@of@layered@graphics
	%
	% Now, any 'name' and 'alias' options have been processed. 
	%
	% Remember their current meaning and reset the tikz options!
	\let\pgfplots@fig@name=\tikz@fig@name
	\let\pgfplots@fig@alias=\tikz@alias
	\let\tikz@alias=\pgfutil@empty
	\let\tikz@fig@name=\pgfutil@empty
	%
	% And protocol all named sub-nodes! Their positions need to be
	% updated later.
	\global\let\pgfplots@named@child@node@list=\pgfutil@empty
	\pgfutil@ifundefined{pgfplots@old@name@impl}{%
		\pgfkeysgetvalue{/tikz/name/.@cmd}\pgfplots@old@name@impl
		\pgfkeysgetvalue{/tikz/alias/.@cmd}\pgfplots@old@alias@impl
	}{}%
	\pgfkeysdef{/tikz/name}{%
		\pgfplots@add@named@child@node{##1}%
		\pgfplots@old@name@impl##1\pgfeov
	}%
	\pgfkeysdef{/tikz/alias}{%
		\pgfplots@add@named@child@node{##1}%
		\pgfplots@old@alias@impl##1\pgfeov
	}%
	%
	% Now, continue to process the 'every' styles. Please note that
	% options like 'legend style={}' have already been processed;
	% their values are already inside of the associated 'every'
	% styles.
	%
	% What I am doing here is: set every pgfplots-option directly, and
	% discard it from the every-style. Any non-pgfplots-option will
	% be set in its context.
	%
	\pgfkeysactivatefamily{/pgfplots/legend}%
		% this special treatmeant allows the (otherwise unsupported) construction
		% 'legend style={legend pos=outer north east}':
		\pgfkeysdef{/pgfplots/every axis legend/.append style}{\pgfkeysalso{##1}}%
		%
		\pgfplots@set@keys@from@tikz@style@and@handle@layer{every axis legend}%
		%
		% restore:
		\pgfkeysdef{/pgfplots/every axis legend/.append style}{%
			\pgfkeysalso{/pgfplots/every axis legend/.add code={}{\pgfkeysalso{##1}}}%
		}%
	\pgfkeysdeactivatefamily{/pgfplots/legend}%
	%
	% FIXME : VERIFY!
	% If I am not mistaken, these statements are only useful to allow
	% 'xlabel style={xlabel=$x$}'  --- which is not intuitive anyway.
	%\pgfkeysactivatefamily{/pgfplots/descriptions}%
	%	\pgfplots@set@keys@from@tikz@style{every axis label}%
	%	\pgfplots@set@keys@from@tikz@style{every axis x label}%
	%	\pgfplots@set@keys@from@tikz@style{every axis y label}%
	%	\pgfplots@set@keys@from@tikz@style{every axis title}%
	%\pgfkeysdeactivatefamily{/pgfplots/descriptions}%
	%
	\pgfkeysactivatefamily{/pgfplots/tick}%
		\pgfplots@set@keys@from@tikz@style@and@handle@layer{every tick}%
		\pgfplots@set@keys@from@tikz@style@and@handle@layer{every minor tick}%
		\pgfplots@set@keys@from@tikz@style@and@handle@layer{every major tick}%
		\pgfplots@set@keys@from@tikz@style@and@handle@layer{every axis grid}%
		\pgfplots@set@keys@from@tikz@style@and@handle@layer{every minor grid}%
		\pgfplots@set@keys@from@tikz@style@and@handle@layer{every major grid}%
	\pgfkeysdeactivatefamily{/pgfplots/tick}%
	%
	%--------------------------------------------------
	% \pgfkeysactivatefamily{/pgfplots}%
	% 	\pgfplots@set@keys@from@tikz@style{every axis plot}%
	% \pgfkeysdeactivatefamily{/pgfplots}%
	%-------------------------------------------------- 
	%
	% Attention: do NOT set the description styles here! Setting them
	% must be postponed until |every 3d description| has been set (to
	% ensure that \axis[<options>] take higher precedence).
	%\pgfkeysactivatefamily{/pgfplots/descriptions}%
	\pgfkeysactivatefamily{/pgfplots/tick}%
		\pgfplots@set@keys@from@tikz@style@and@handle@layer{every x tick label}%
		\pgfplots@set@keys@from@tikz@style@and@handle@layer{every y tick label}%
		\pgfplots@set@keys@from@tikz@style@and@handle@layer{every tick label}%
	\pgfkeysdeactivatefamily{/pgfplots/tick}%
	%\pgfkeysdeactivatefamily{/pgfplots/descriptions}%
	%
	% Step 3: Set all remaining options of '#1'. They should have
	% highest precedence.
	\pgfkeysactivatefamilies
		{/pgfplots,/pgfplots/tick,/pgfplots/legend}%,/pgfplots/descriptions}%
		{\pgfplots@deactivefamiliescmd}%
		\expandafter
			\pgfplots@set@keys@and@append@remaining@to@style
		\expandafter
			{\pgfplots@remaining@input}%
			{every axis}%
	\pgfplots@deactivefamiliescmd
%\pgfkeysgetvalue{/pgfplots/every axis/.@cmd}\pgfplots@loc@TMPa
%\message{every axis is now '\meaning\pgfplots@loc@TMPa'}%
	%
	\pgfkeysdeactivatefamily{/pgfplots/style commands}%
	\global\pgfkeysgetvalue{/pgfplots/xmin}{\pgfplots@xmin}%
	\global\pgfkeysgetvalue{/pgfplots/xmax}{\pgfplots@xmax}%
	\global\pgfkeysgetvalue{/pgfplots/ymin}{\pgfplots@ymin}%
	\global\pgfkeysgetvalue{/pgfplots/ymax}{\pgfplots@ymax}%
	\global\pgfkeysgetvalue{/pgfplots/zmin}{\pgfplots@zmin}%
	\global\pgfkeysgetvalue{/pgfplots/zmax}{\pgfplots@zmax}%
	\pgfkeysgetvalue{/pgfplots/xtickmin}{\pgfplots@xtickmin}%
	\pgfkeysgetvalue{/pgfplots/xtickmax}{\pgfplots@xtickmax}%
	\pgfkeysgetvalue{/pgfplots/ytickmin}{\pgfplots@ytickmin}%
	\pgfkeysgetvalue{/pgfplots/ytickmax}{\pgfplots@ytickmax}%
	\pgfkeysgetvalue{/pgfplots/ztickmin}{\pgfplots@ztickmin}%
	\pgfkeysgetvalue{/pgfplots/ztickmax}{\pgfplots@ztickmax}%
	%
	\def\pgfplots@loc@TMPa{data}%
	\pgfplots@collect@firstplot@astickfalse
	\ifx\pgfplots@xtick\pgfplots@loc@TMPa
		\pgfplots@collect@firstplot@asticktrue
	\fi
	\ifx\pgfplots@ytick\pgfplots@loc@TMPa
		\pgfplots@collect@firstplot@asticktrue
	\fi
	\ifx\pgfplots@ztick\pgfplots@loc@TMPa
		\pgfplots@collect@firstplot@asticktrue
	\fi
	\pgfkeysgetvalue{/pgfplots/minor xtick}\pgfplots@loc@TMPb
	\ifx\pgfplots@loc@TMPb\pgfplots@loc@TMPa
		\pgfplots@collect@firstplot@asticktrue
	\fi
	\pgfkeysgetvalue{/pgfplots/minor ytick}\pgfplots@loc@TMPb
	\ifx\pgfplots@loc@TMPb\pgfplots@loc@TMPa
		\pgfplots@collect@firstplot@asticktrue
	\fi
	\pgfkeysgetvalue{/pgfplots/minor ztick}\pgfplots@loc@TMPb
	\ifx\pgfplots@loc@TMPb\pgfplots@loc@TMPa
		\pgfplots@collect@firstplot@asticktrue
	\fi
	\global\let\pgfplots@firstplot@coords@x=\pgfutil@empty
	\global\let\pgfplots@firstplot@coords@y=\pgfutil@empty
	\global\let\pgfplots@firstplot@coords@z=\pgfutil@empty
	\pgfkeysalso{/pgfplots/.search also=/tikz}%
	%
	\pgfkeysifdefined{/tikz/on layer}{}{%
		% make sure assignments 'on layer' in the /tikz/ prefix
		% doesn't hurt.
		% this may happen, for example with 
		% 'x grid style={on layer=...}'
		% because 'x grid style' is not processed by the key filtering
		% above (it is extracted later).
		\pgfkeyslet{/tikz/on layer}\pgfutil@empty%
	}%
	%
	\pgfplots@set@patched@options
	%
	\pgfplots@set@options@sanitize
	\pgfplots@notify@options@are@set
}

\def\pgfplots@set@options@of@layered@graphics{%
	\ifpgfplots@axis@on@top
		\ifpgfplots@layered@graphics
			\pgfplots@log3{the combination of 'axis on top' and 'activate layers' implies 'set layers=axis on top'. Deactivate 'axis on top' if you want other layers.}%
			\pgfplotsset{set layers=axis on top}%
		\fi
	\fi
	% retrieve layer configurations (the one set with 'set layers*').
	\pgfkeysgetvalue{/pgfplots/@set layers arg}\pgfplots@loc@TMPa
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
	\else
		% ah, yes: then set its style:
		\pgfqkeys{/pgfplots/layers}{\pgfplots@loc@TMPa}% note that this here should not need key filtering; it adjusts only styles (hopefully ;) )
	\fi
}%

\def\pgfplots@set@patched@options{%
  	\pgfkeysdef{/pgfplots/@@@tmp}{%
		\let\tikz@intersect@def=\gdef
		\pgfkeys{/tikz/name path={##1}}%
	}%
	\pgfkeysgetvalue{/pgfplots/@@@tmp/.@cmd}\pgfplots@name@path@global@cmd@pgf@two@ten
	%
	\pgfkeysifdefined{/tikz/name path/.@cmd}{%
		% 'name path' does not work inside of a pgfplots axis because
		% pgfplots unnecessarily introduces extra \scopes around each path :-/
		% it needs to be 'name path global'. 
		% PATCH IT:
		\pgfkeysgetvalue{/tikz/name path global/.@cmd}\pgfplots@loc@TMPa%
		\ifx\pgfplots@loc@TMPa\pgfplots@name@path@global@cmd@pgf@two@ten
			% ah - we operate against PGF 2.10 . In this case, we must
			% not indirect from 'name path' to 'name path global' - would lead to
			% an indefinite loop.
			% Patch absolutely:
			\pgfkeysgetvalue{/tikz/name path/.@cmd}\pgfplots@name@path@cmd@pgf@two@ten%
			\pgfkeysdef{/tikz/name path}{%
				% see the value of
				% \pgfplots@name@path@global@cmd@pgf@two@ten to verify
				% this patch:
				\let\tikz@intersect@def=\gdef
				\pgfplots@name@path@cmd@pgf@two@ten{##1}\pgfeov
			}%
		\else
			\pgfkeysdef{/tikz/name path}{\pgfkeysalso{/tikz/name path global={##1}}}%
		\fi
	}{%
		\pgfkeysdef{/tikz/name path}{\pgfplots@error{'name path' is undefined. Please load \string\usetikzlibrary{intersections} or \string\usepgfplotslibrary{fillbetween}}}%
	}%
}

% EMPTY. This will be overridden by tex-engine specific code.
% At the time of this writing, the latex driver will check for xcolor
% configuration options and will override
%   mesh/colorspace explicit color output
% and
%	colormap default colorspace
% if needed.
\def\pgfplots@check@global@colorspace@overrides{%
}%

\def\pgfplots@add@named@child@node#1{%
	\xdef\pgfplots@named@child@node@list{\pgfplots@named@child@node@list,{#1}}%
}%

\def\pgfplots@notify@options@are@set{}%

\def\pgfplots@install@abbrev@commands{
	\let\pgfplots@orig@path=\path
	\let\pgfplots@orig@plot=\plot
	%
	\let\axispath=\pgfplots@path
	\let\pgfplotsinterruptdatabb=\pgfplots@interruptdatabb
	\let\endpgfplotsinterruptdatabb=\endpgfplots@interruptdatabb
	%
	\let\addplot=\pgfplots@addplot
	\let\plot=\addplot
	%
	%
	\def\logten{2.3025851}%
	\def\reciproclogten{0.434294}%
	%
	\def\logi##1{%
		\ifcase##1
		\or0
		\or0.693147
		\or1.098612
		\or1.386294
		\or1.60943791
		\or1.7917594
		\or1.94591014
		\or2.07944154
		\or2.197224
		\fi
	}%
	\def\axisdefaultticklabel{\pgfplots@ticklabel@typeset@arg{\pgfmathprintnumber{\tick}}}%
	\def\axisdefaultticklabellog{%
		\pgfplots@ticklabel@typeset@arg{%
			\pgfkeysgetvalue{/pgfplots/log number format code/.@cmd}\pgfplots@log@label@style
			\expandafter\pgfplots@log@label@style\tick\pgfeov
		}%
	}%
	%
	\let\legend=\pgfplots@command@legend
	\let\addlegendimage=\pgfplots@addlegendimage
	\let\addlegendentry=\pgfplots@addlegendentry
	\let\addlegendentryexpanded=\pgfplots@addlegendentryexpanded
}

\let\pgfplots@late@options=\pgfutil@empty
\def\pgfplotssetlateoptions#1{%
	\t@pgfplots@toka=\expandafter{\pgfplots@late@options}%
	\t@pgfplots@tokb={#1}%
	\xdef\pgfplots@late@options{\the\t@pgfplots@toka,\the\t@pgfplots@tokb}%
}%

\def\pgfplots@environment{%
	\pgfutil@ifnextchar[{%
		\pgfplots@environment@opt
	}{%
		\pgfplots@environment@opt[]%
	}%
}%

% temporary (local) variables inside of axis
\newif\ifpgfplots@autocompute@all@limits
\newif\ifpgfplots@autocompute@xmin
\newif\ifpgfplots@autocompute@xmax
\newif\ifpgfplots@autocompute@ymin
\newif\ifpgfplots@autocompute@ymax
\newif\ifpgfplots@autocompute@zmin
\newif\ifpgfplots@autocompute@zmax
\newif\ifpgfplots@apply@datatrafo@x
\newif\ifpgfplots@apply@datatrafo@y
\newif\ifpgfplots@apply@datatrafo@z
\newif\ifpgfplots@apply@datatrafo
\newif\ifpgfplots@datascaletrafo@initialised

% Extracts single components of an entry of
% \pgfplots@stored@plotlist
%
% They are defined as
% \pgfplots@stored@current@precmd
% \pgfplots@stored@current@cmd
% \pgfplots@stored@current@data
% \pgfplots@stored@current@postcmd
\long\def\pgfplots@stored@plotlist@EXTRACTENTRY#1#2#3#4{%
	% the token register stuff allows '#' inside of arguments.
	\t@pgfplots@tokc={#1}%
	\edef\pgfplots@stored@current@precmd{\the\t@pgfplots@tokc}%
	%
	\t@pgfplots@tokc={#2}%
	\edef\pgfplots@stored@current@cmd{\the\t@pgfplots@tokc}%
	%
	\def\pgfplots@stored@current@data{#3}%
	%
	\t@pgfplots@tokc={#4}%
	\edef\pgfplots@stored@current@postcmd{\the\t@pgfplots@tokc}%
	%
}

\def\pgfplots@init@cleared@structures{%
	\global\pgfplotslistnewempty\pgfplots@plotspeclist
	\global\pgfplotslistnewempty\pgfplots@legend
	\global\pgfplotslistnewempty\pgfplots@stored@plotlist
	\global\pgfplots@numplots=0
	\let\pgfplots@already@computed@legend@node=\pgfutil@empty
}

% Takes a plot style and exports it to a self-contained drawing
% command which can be used outside of the current context.
%
% This macro is used inside for \label{} / \ref{}; it tries to be
% reasonable smart about restoring relevant flags stored in a pgfplots
% axis. If it forgets something... well, it is not too smart. 
%
% #1: the style to export.
% #2: either empty or the fully qualified name of a code key. If #2 is not empty,
% the current value of the code key is remembered. It will be restored
% just before the exported \tikz statement is invoked, and \tikz[#2]
% will be called. The code key should not rely on any arguments (it
% won't be given any)
%
% The exported routine autodetects whether the result is used inside of
% a picture. In that case, the '#2' style will be set inside of a
% scope instead of \tikz[#2].
% 
% Assembles a macro \pgfplotsretval which, upon execution, draws the
% plot style.
%
% As a side effect, it returns the resulting plot style (nothing else) into
% \pgfplotsretvalb
\def\pgfplots@export@legend@image@to@macro#1#2{%
	\begingroup
	% I'd like to get all options which are INDEPENDENT of
	% pgfplots. Idea: expand all /pgfplots-keys and collect
	% everything which belongs NOT to /pgfplots. This is the
	% completely expanded rest. At least, I hope so and it appears
	% to work.
	%
	% FIXME : this was a good approach before. Now, there ARE
	% /pgfplots keys which should be maintained. How shall I do that?
	% I can't handle every option separately... !?
	\pgfkeysinstallkeyfilter
		{/pgf/key filters/and}
			{{/pgf/key filters/is descendant of=/pgfplots}%
			 {/pgf/key filters/defined}}%
	\def\pgfplots@label@tikzopts{}%
	\pgfkeysinstallkeyfilterhandler{/pgf/key filter handlers/append filtered to}{\pgfplots@label@tikzopts}%
	% FIXME : this fails if 'error bars/.cd,/pgfplots/.cd' is used inside of #1 --
	% the second /pgfplots/.cd will be applied, but the error bars
	% command not
	\pgfqkeysfiltered{/tikz}{#1}%
	%
	\pgfkeysgetvalue{/pgfplots/legend image code/.@cmd}{\pgfplots@curlegendcode}%
	\pgfplots@getcurrent@plothandler\pgfplots@basiclevel@plothandler
	\toks0=\expandafter{\pgfplots@curlegendcode\pgfeov}%
	\toks1=\expandafter{\pgfplots@label@tikzopts}%
	\toks3=\expandafter{\pgfplots@basiclevel@plothandler}%
	\def\pgfplots@stylekey{#2}%
	\ifx\pgfplots@stylekey\pgfutil@empty
	\else
		\pgfkeysgetvalue{\pgfplots@stylekey/.@cmd}{\pgfplots@stylekey@}%
		\toks4=\expandafter{\pgfplots@stylekey@\pgfeov}%
	\fi
	\edef\pgfplots@loc@TMPa{%
		{%
			\ifx\pgfplots@stylekey\pgfutil@empty
			\else
				\noexpand\scope[#2]%
			\fi
			%
			\noexpand\pgfplots@draw@image
			%
			\ifx\pgfplots@stylekey\pgfutil@empty
			\else
				\noexpand\endscope%
			\fi
		}{%
			\noexpand\tikz[#2]{%
				\noexpand\pgfplots@draw@image
			}%
		}%
	}%
	\expandafter\pgfplots@assemble@ref@picture\pgfplots@loc@TMPa
	\toks5=\expandafter{\pgfplotsretval}%
	\pgfkeysgetvalue{/pgfplots/every legend image post/.@cmd}\pgfplots@legend@image@post
	\toks6=\expandafter{\pgfplots@legend@image@post\pgfeov}%
	%
	\edef\pgfplotsretval{%
		\noexpand\begingroup
		\noexpand\def\noexpand\pgfplots@draw@image{%
			\noexpand\def\noexpand\tikz@plot@handler{\the\toks3}%
			\noexpand\pgfkeysdef{/pgfplots/legend image code}{\the\toks0}%
			\noexpand\pgfkeysdef{/pgfplots/every legend image post}{\the\toks6 }%
			\noexpand\pgfkeyssetvalue{/pgfplots/mark list fill}{\pgfkeysvalueof{/pgfplots/mark list fill}}%
			\ifx\pgfplots@stylekey\pgfutil@empty
			\else
				\noexpand\pgfkeysdef{#2}{\the\toks4}%
			\fi
			\noexpand\pgfplots@show@small@legendplots{\the\toks1}{}%
		}%
		\the\toks5
		\noexpand\endgroup%
	}%
	\xdef\pgfplots@glob@TMPa{\the\toks1}%
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
	\let\pgfplotsretvalb=\pgfplots@glob@TMPa
}%

% The implementation for \label{foo} after \addplot. It allows to
% \ref{foo} (it inserts the 'legend image code').
%
% With 
% \addplot[scatter/classes={a={}}] ... ;
% \label[a]{my label}  
% you can reference scatter/classes labels.
%
% I only need to overwrite '\label'; the rest is done by LaTeX.
%
% THIS IS INCOMPATIBLE WITH plain TeX and ConTeXt! Don't use it, it
% doesn't hurt.
\def\pgfplots@plot@label{%
	\pgfutil@ifnextchar<{%
		\pgfplots@plot@label@beamer@mode
	}{%
		\pgfutil@ifnextchar[{\pgfplots@plot@label@{}}{\pgfplots@plot@label@{}[]}%
	}%
}%
\def\pgfplots@plot@label@beamer@mode<#1>{
		\pgfutil@ifnextchar[{\pgfplots@plot@label@{<#1>}}{\pgfplots@plot@label@{<#1>}[]}%
}
% #1: optional prefix options, used to support
% \label<...>{<name>} of beamer package
\def\pgfplots@plot@label@#1[#2]#3{%
	\ifpgfplots@has@label@information
		\begingroup
		\expandafter\let\expandafter\pgfplots@loc@TMPb\csname pgfplots@last@plot@style@#2\endcsname
		\expandafter\pgfplots@export@legend@image@to@macro\expandafter{\pgfplots@loc@TMPb}{/pgfplots/every crossref picture}%
		%
		\t@pgfplots@toka=\expandafter{\pgfplotsretval}%
		\t@pgfplots@tokb=\expandafter{\pgfplotsretvalb}%
		% 1. prepare /pgfplots/refstyle={#3}:
		\pgfplots@auxwrite{%
			\noexpand\expandafter\noexpand\gdef
			\noexpand\csname pgfplots@labelstyle@#3\noexpand\endcsname{\the\t@pgfplots@tokb}%
		}%
		% 2. prepare \ref{#3} and \pageref{#3}:
		%
		% There are several nasty things to consider:
		% a) macro expansion. Use \string to allow a safe \write
		% operation.
		%
		% b) \protect . If the resulting \ref{} command occurs within
		% a "moving argument" like \caption or so, we need to use
		% proper '\protect'ion. 
		%
		% this here is the low-level implementation of \ref{#3}. Write it into
		% the .aux file:
		\pgfplots@auxwrite{%
			\noexpand\expandafter\noexpand\gdef
			\noexpand\csname pgfplots@show@ref@#3\noexpand\endcsname{%
				\the\t@pgfplots@toka
			}%
		}%
		% create the \label command:
		\let\label=\pgfplots@original@LaTeX@label
		\pgfplots@label[#1]{#3}{pgfplots@show@ref@}%
		\endgroup
	\else
		\pgfplots@error{Can't create \string\label{#3}: it needs to be called after \string\addplot.}%
	\fi
}%


\def\pgfplots@interruptdatabb{\pgfplots@bb@isactivefalse}
\def\endpgfplots@interruptdatabb{\pgfplots@bb@isactivetrue}

\def\pgfplots@search@also@tikz{%
	% make sure the search path is set.
	% Inside of an axis, this is already ok.
	\pgfkeysifdefined{/pgfplots/.unknown/.@cmd}%
		{\relax}% search path in /pgfplots is already set
		{%
%\message{DEBUG: re-initializing /pgfplots/.search also=/tikz  in current plot style!}%
			\pgfkeysalso{/pgfplots/.search also=/tikz}%
		}%
}%

% A helper method which defines 
%  `/tikz/current plot style' to be {#1}  --- with properly set key
%  search paths.
\def\pgfplots@define@currentplotstyle@as#1{%
	\pgfkeysdef{/tikz/current plot style}{%
		\pgfplots@search@also@tikz
		%
		% Make sure that 
		% \addplot[every mark/.append style={...}]
		% or something like that is interpreted as /tikz/ key:
		\pgfplots@invoke@pgfkeyscode{/handler config/full or existing/.@cmd}{}% restrict
		%
		\pgfkeysdef{/pgfplots/colorbar source}{}% make it NO-OP here. It has already been processed.
		%
		\pgfplots@install@local@bar@handlers% see its docs.
		%
		% set both, pgfplots and tikz keys:
		% the draw is important since \addplot visualizes its stuff
		% with \path coordinates ...
		% -> we need to activate draw mode here.
		\pgfplotsset{/tikz/draw,#1}%
		\pgfplots@invoke@pgfkeyscode{/handler config/all/.@cmd}{}% unrestrict
		%
		% the final plot processing uses
		% foreach stored \addplot command :
		%   \scope[current plot style]
		%   <finalize coord stream>
		%   \draw <finalized coord stream>
		%   \endscope
		% -> the problem: \draw reset the modes 'draw,fill' etc which
		%  have been set in \scope!
		% -> ad-hoc-solution:
		%    restore the modes manually.
		\pgfplots@every@addplot@path@prepare%
		%
		\pgfplots@markers@check@for@default@plot@mark%
		%
		%
		% This is done here. The \pgfplots@drawmodes is ONLY set
		% inside of this scope, so we can check for that particular
		% case:
		\pgfkeys{/tikz/every path/.append code={%
				% FIXME : is that portable!?
				\pgfplots@every@addplot@path
				\pgfplots@every@addplot@firstpath
				\let\pgfplots@every@addplot@firstpath=\pgfutil@empty
			}%
		}%
	}%
}%

\def\pgfplots@every@addplot@path{}
\def\pgfplots@every@addplot@firstpath{}

\def\pgfplots@every@addplot@path@prepare{%
	\let\pgfplots@every@addplot@path=\pgfutil@empty
	\let\pgfplots@every@addplot@firstpath=\pgfutil@empty
	%
	% remember these technical things: they will be
	% reset in \path (see below!), so we will need to re-activate
	% them.
	% The re-activation is done in 'every path'.
	\pgfplots@assert@tikzinternal@exists{tikz@options}%
	\pgfplots@assert@tikzinternal@exists{tikz@mode}%
	\let\pgfplots@drawoptions=\tikz@options
	\let\pgfplots@drawmodes=\tikz@mode
	\pgfplots@everypath@prepare@append{\pgfplots@every@addplot@path}{\pgfplots@restore@drawmodes}%
	%
	\iftikz@decoratepath
		\pgfplots@everypath@prepare@append{\pgfplots@every@addplot@firstpath}{\tikz@decoratepathtrue}%
	\fi
	\pgfplots@everypath@prepare@append@macrorestore{\pgfplots@every@addplot@firstpath}\tikz@preactions
	\pgfplots@everypath@prepare@append@macrorestore{\pgfplots@every@addplot@firstpath}\tikz@postactions
}%
\long\def\pgfplots@everypath@prepare@append#1#2{%
	\t@pgfplots@toka=\expandafter{#1}%
	\t@pgfplots@tokb={#2}%
	\edef#1{\the\t@pgfplots@toka\the\t@pgfplots@tokb}%
}%
\long\def\pgfplots@everypath@prepare@append@macrorestore#1#2{%
	\t@pgfplots@toka=\expandafter{#1}%
	\t@pgfplots@tokb=\expandafter{#2}%
	\edef#1{%
		\the\t@pgfplots@toka
		\noexpand\def\noexpand#2{\the\t@pgfplots@tokb}%
	}%
}%


\newif\ifpgfplots@drawmodes@append

\def\pgfplots@restore@drawmodes{%
	\pgfutil@ifundefined{pgfplots@drawmodes}%
		{\relax}%
		{%
			\ifpgfplots@drawmodes@append
				\t@pgfplots@toka=\expandafter{\tikz@mode}%
				\t@pgfplots@tokb=\expandafter{\pgfplots@drawmodes}%
				\edef\tikz@mode{\the\t@pgfplots@tokb\the\t@pgfplots@toka}%
			\else
				\let\tikz@mode=\pgfplots@drawmodes
			\fi
%			\let\tikz@options=\pgfplots@drawoptions
		}%
}%

\long\def\pgfplotsifissurveyphase#1#2{%
	\if\pgfplots@phase@name s%
		#1\relax
	\else
		#2\relax
	\fi
}%
\long\def\pgfplotsifisvisualizationphase#1#2{\pgfplotsifissurveyphase{#2}{#1}}
\def\pgfplots@phase@name{X}

% Invokes #1 if the statement occurs within \begin{axis}...\end{axis}
% and #2 if not.
\long\def\pgfplotsifinaxis#1#2{%
	\pgfutil@ifundefined{pgfplots@is@in@axis}{#2}{#1}%
}%

%
% \begin{axis}[#1] :
%
% This command prepares the axis for collection. NOTHING will be drawn
% until \end{axis}. During the collect phase, axis limits will be
% computed.
%
% The following variables are accummulated between 
% \begin{axis}
% and
% \end{axis}:
%
% -  \pgfplots@[xyz]min
%    \pgfplots@[xyz]max
%    	- These denote the axis limits. 
%    	- They are always assigned globally.
%    	- For linear axes, they will be computed in floating point.
%    	- For log axes, they will be computed using pgf math engine.
% - \pgfplots@[xyz]min@reg
%   	- A register containing the value of macro \pgfplots@[xyz]min
%   	in pt. It is only valid during \end{axis}.
% - \pgfplots@[xyz]max@reg
%   	- The same for 'max'.
% - \pgfplots@invalidrange@[xyz]min
%   \pgfplots@invalidrange@[xyz]max
%   \pgfplots@invalidrange@meta[max,min]
%   	A value which is used for the axis limits before the
%   	limit computation starts.
% - \pgfplots@data@[xyz]min
%   \pgfplots@data@[xyz]max
%   	- DATA limits. These limits are not affected by limit
%   	restrictions
%   	- They are used to initialise the data scaling trafo.
%   	- They WON'T be assigned for log axes.
%   	- Assigned globally.
% - \pgfplots@[xyz]min@unscaled@as@float
%   	- Assigned during \end{axis} (local variables).
%   	- Contain the value of axis limits as floating point numbers
%   	in the original data range.
% - \pgfplots@metamin
%   \pgfplots@metamax
%   \pgfplots@axiswide@metamin
%   \pgfplots@axiswide@metamax
%   	- if meta data is active, these macros will contain the upper
%   	and lower bound for meta data, the first two on a per-plot
%   	basis the latter to globally for the complete axis.
%   	- will be assigned globally.
%   	- meta data is ALWAYS collected in floating point.
% - \pgfplots@colorbar@src@metamin
% - \pgfplots@colorbar@src@metamax
%   	- these keys are usually empty, unless one provides the
%   	'colorbar source' key for an \addplot command. In that case,
%   	they will be filled (globally) with the point meta min/max
%   	ranges of that particular plot. The colorbar will use the
%   	result for its ranges.
% - \pgfplots@numplots
%   	- A count register indexing the current plot counter. Assigned
%   	globally.
% - \ifpgfplots@apply@datatrafo
%   	A boolean which indicates whether any scaling trafo is
%   	active.
% - \ifpgfplots@apply@datatrafo@[xyz]
%   	Booleans indicating whether for which axes the scaling trafo
%   	is active.
% - \pgfplots@stored@plotlist
%   	- An instance of pgfplotslist.
%   	- It is assigned globally.
%   	- Every \addplot or tikz path command is collected into this
%   	structure.
%   	- The element type is a compound object containing everything
%   	needed to process the plot during \end{axis}.
% - \pgfplots@plotspeclist
%   	- instance of pgfplotslist
%   	- collects every line specification for \addplot.
%   	- Used to assemble legends.
%   	- Assigned globally.
% - \pgfplots@legend
%   	- instance of pgfplotslist
%   	- collects every legend entry.
%   	- Used to assemble legends.
%   	- Assigned globally.
% - \pgfplots@data@scale@trafo@SHIFT@[xyz]
%   \pgfplots@data@scale@trafo@EXPONENT@[xyz]
%   	- For any direction for which the scaling trafo is active,
%   	these macros contain the two parameters for the affine scaling
%   	trafo.
% - \pgfplots@firstplot@coords@[xyz]
%   	- A macro containing a comma separated list
%   	- It is collected if and only if [xyz]tick = 'data'.
%   	- Contains a list of coordinates in floating point
%   	representation if the axis is linear.
%   	- The coordinates are in pgf math notation for log axes.
%   	- Assigned globally.
% - \pgfplots@[xyz]@veclength
%   	- A macro containing the vector length of the [xyz] unit
%   	vector.
%   	- Assigned in \end{axis}
% - \pgfplots@[xyz]@inverseveclength
%   	- A macro containing the INVERSE vector length of the [xyz]
%   	unit vector.
%   	- Assigned in \end{axis}
% - \pgfplotspoint[xyz]axis
%   	- A macro which sets 'pgf@x' and 'pgf@y' to the [xyz] axis.
% - \pgfplotspoint[xyz]axislength
%   	- A macro containing the vector length of the [xyz] axis
%   	(including the 'pt' suffix).
%
% - \ifpgfplots@curplot@threedim
%   	- valid during an '\addplot' preparation step. 
% - \ifpgfplots@threedim
%   	- whether the axis shall be threedimensional.
%
% - \pgfplots@currentplot@firstcoord@[xyz] 
% - \pgfplots@currentplot@lastcoord@[xyz]
%   	- contains the first/last coordinate of the current plot.
%   	- assigned globally.
% - \ifpgfplots@coord@stream@isfirst
%   	- assigned globally during \addplot.
% - \pgfplotssurveyphase@setactiveplothandlers
%   	A macro which is used to implement '\numplotsofactualtype'
%   	see \pgfplots@countplots@advance for details.
%
%
\def\pgfplots@environment@opt[#1]{%
	\begingroup
	\pgfplotsifinaxis{%
		\pgfplots@error{%
			Sorry, nested axis environments are not supported.
			Please move the inner axis environment below \string\end{axis} and
			use alignment options (for example named nodes, see manual) to place it at the desired
			position}%
	}{}%
	\def\pgfplots@is@in@axis{1}%
	\pgfplots@environment@opt@@setup@pgfpoint@restores
	%
	\global\let\pgfplots@late@options=\pgfutil@empty
	\pgfplots@checkandpreparefor@active@semicolon
	%
	\pgfplots@install@abbrev@commands
	\pgfplots@stacked@initialise
	\pgfplotsplothandlers@init
	%
	%
	% The explicit specification of 'x' and 'y' as 1pt is to avoid
	% numeric overflow/underflow during scale computations:
	%
	% The scaling (i.e. proper values for 'x' and 'y') will be
	% determined later-on, dependend on the axis limits.  Since axis
	% limits are implicitly in units of 1pt, it is reasonable to use
	% '1pt' here as well.
	\pgfsetxvec{\pgfqpoint{1pt}{0pt}}%
	\pgfsetyvec{\pgfqpoint{0pt}{1pt}}%
	\pgfsetzvec{\pgfqpoint{0pt}{0pt}}%
	%
	\pgfplots@set@options{#1}%
	%
	%
	%
	% --------------------
	% Allocations:
	% --------------------
	\pgfplots@init@cleared@structures
	%
	% --------------------
	% Option preprocessing
	% --------------------
	\pgfplots@prepare@coord@filtering@for x%
	\pgfplots@prepare@coord@filtering@for y%
	\pgfplots@prepare@coord@filtering@for z%
	\ifpgfplots@apply@datatrafo
		\pgfplots@datascaletrafo@initialisedfalse
	\else
		\pgfplots@datascaletrafo@initialisedtrue% there is no trafo.
	\fi
	%
	\pgfplotsutilforeachcommasep{x,y,z}\as\pgfplots@loc@TMPa{%
		\pgfplotscoordmath \pgfplots@loc@TMPa{min limit}%
		\expandafter\let\csname pgfplots@invalidrange@\pgfplots@loc@TMPa max\endcsname=\pgfmathresult
		\pgfplotscoordmath \pgfplots@loc@TMPa{max limit}%
		\expandafter\let\csname pgfplots@invalidrange@\pgfplots@loc@TMPa min\endcsname=\pgfmathresult
	}%
	%
	\pgfplotscoordmath{meta}{max limit}%
	\let\pgfplots@invalidrange@metamin=\pgfmathresult
	\pgfplotscoordmath{meta}{min limit}%
	\let\pgfplots@invalidrange@metamax=\pgfmathresult
	%
	% These numbers will ONLY be filled for linear axis!
	\global\let\pgfplots@data@xmin=\pgfplots@invalidrange@xmin
	\global\let\pgfplots@data@xmax=\pgfplots@invalidrange@xmax
	\global\let\pgfplots@data@ymin=\pgfplots@invalidrange@ymin
	\global\let\pgfplots@data@ymax=\pgfplots@invalidrange@ymax
	\global\let\pgfplots@data@zmin=\pgfplots@invalidrange@zmin
	\global\let\pgfplots@data@zmax=\pgfplots@invalidrange@zmax
	\global\let\pgfplots@axiswide@metamin=\pgfplots@invalidrange@metamin
	\global\let\pgfplots@axiswide@metamax=\pgfplots@invalidrange@metamax
	\global\let\pgfplots@colorbar@src@metamin=\pgfutil@empty
	\global\let\pgfplots@colorbar@src@metamax=\pgfutil@empty
	%
	\pgfplots@autocompute@all@limitstrue
	\ifx\pgfplots@xmin\pgfutil@empty
		\pgfplots@autocompute@xmintrue
		\global\let\pgfplots@xmin=\pgfplots@invalidrange@xmin
	\else
		\pgfplots@autocompute@all@limitsfalse
	\fi
	\ifx\pgfplots@xmax\pgfutil@empty
		\pgfplots@autocompute@xmaxtrue
		\global\let\pgfplots@xmax=\pgfplots@invalidrange@xmax
	\else
		\pgfplots@autocompute@all@limitsfalse
	\fi
	\ifx\pgfplots@ymin\pgfutil@empty
		\pgfplots@autocompute@ymintrue
		\global\let\pgfplots@ymin=\pgfplots@invalidrange@ymin
	\else
		\pgfplots@autocompute@all@limitsfalse
	\fi
	\ifx\pgfplots@ymax\pgfutil@empty
		\pgfplots@autocompute@ymaxtrue
		\global\let\pgfplots@ymax=\pgfplots@invalidrange@ymax
	\else
		\pgfplots@autocompute@all@limitsfalse
	\fi
	\ifx\pgfplots@zmin\pgfutil@empty
		\pgfplots@autocompute@zmintrue
		\global\let\pgfplots@zmin=\pgfplots@invalidrange@zmin
	\else
		\global\pgfplots@threedimtrue
		\pgfplots@autocompute@all@limitsfalse
	\fi
	\ifx\pgfplots@zmax\pgfutil@empty
		\pgfplots@autocompute@zmaxtrue
		\global\let\pgfplots@zmax=\pgfplots@invalidrange@zmax
	\else
		\global\pgfplots@threedimtrue
		\pgfplots@autocompute@all@limitsfalse
	\fi
	%
	\pgfutil@IfUndefined{pgfmathdeclarefunction}{%
		% SKIP: \pgfmathdeclarefunction is unavailable in pgf 2.00 .
		% UPGRADE TO PGF 2.10 to use these math functions.
	}{%
		\pgfplots@declare@mathfunctions
	}%
	%
	% check for axis-wide 'point meta min' :
	\pgfkeysgetvalue{/pgfplots/point meta min}\pgfplots@loc@TMPa
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\def\pgfplots@axiswide@metamin@autocompute{1}%
	\else
		\def\pgfplots@axiswide@metamin@autocompute{0}%
		\pgfplotscoordmath{meta}{parsenumber}{\pgfplots@loc@TMPa}%
		\global\let\pgfplots@axiswide@metamin=\pgfmathresult
	\fi
	\pgfkeysgetvalue{/pgfplots/point meta max}\pgfplots@loc@TMPa
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\def\pgfplots@axiswide@metamax@autocompute{1}%
	\else
		\def\pgfplots@axiswide@metamax@autocompute{0}%
		\pgfplotscoordmath{meta}{parsenumber}{\pgfplots@loc@TMPa}%
		\global\let\pgfplots@axiswide@metamax=\pgfmathresult
	\fi
	%
	% --------------------
	% Start axis:
	% start survey phase!
	% --------------------
	%
	\ifpgfplots@stackedmode
	\else
		% we have no stacked plots and thus no reversing.
		\pgfplots@stacked@reversefalse
	\fi
	%
	\pgfutil@IfUndefined{label}{\relax}{%
		\let\pgfplots@original@LaTeX@label=\label
		\let\label=\pgfplots@plot@label
	}%
	%
	\global\pgfplots@has@label@informationfalse
	%
	\def\numplots{\the\pgfplots@numplots}%
	\global\let\pgfplotssurveyphase@setactiveplothandlers=\pgfutil@empty
	\let\numplotsofactualtype=\pgfplots@numplotsofactualtype
	%
	% any \path command is invalid inside of an axis.
	% Use \axispath instead:
	\let\path=\pgfplots@replacement@for@tikz@path
	\let\closedcycle=\pgfplots@path@closed@cycle
	%
	% defines \pgfplotsaxisupdatelimitsforcoordinate etc.
	\pgfplots@prepare@axis@API
	\pgfkeysvalueof{/pgfplots/execute at begin axis}%
	\pgfkeysvalueof{/pgfplots/execute at begin axis@@}%
	\def\pgfplots@phase@name{s}%
	%
	\pgfplots@replace@path@commands
	%
	% allow layer changes within the environment; reset:
	\pgfkeyslet{/pgfplots/on layer}\pgfutil@empty
}

% \end{axis} :
%
% This command actually takes all collected (global) variables,
% creates an axis and performs all postponed drawing operations.
\def\endpgfplots@environment@opt{%
	\def\pgfplots@phase@name{v}%
	\pgfutil@IfUndefined{label}{\relax}{%
		% restore.
		\let\label=\pgfplots@original@LaTeX@label
	}%
	\xdef\numplots{\the\pgfplots@numplots}%
	\pgfkeysvalueof{/pgfplots/before end axis/.@cmd}\pgfeov%
	\pgfkeysvalueof{/pgfplots/execute at end axis}%
	\pgfkeysvalueof{/pgfplots/execute at end axis@@}%
	%
	\pgfplots@restore@path@commands
	%
	\pgfplotssurveyphase@setactiveplothandlers
	%
	\expandafter\pgfplotsset\expandafter{\pgfplots@late@options}%
	%
	\pgfplots@prepare@layered@graphics
	%
	\pgfplots@prepare@cell@picture
	%
	%\end{axis}:
	%
	% --------------------
	%  All plotting commands have been read.
	%  -> apply postponed drawing commands!
	% --------------------
	\pgfplots@determinedefaultvalues
	\pgfplots@BEGIN@cell@picture[/pgfplots/every axis]%
		\pgfplots@BEGIN@init@and@draw@axis
		%
		% replace some of tikz's paths (like ellipse and path): make them
		% aware of any transformations:
		\pgfplots@install@path@replacements
		%
		\pgfplots@stacked@initialise
		\pgfplots@markers@visphase@after@axis@prepare
		\ifpgfplots@stacked@reverse
			% This here applies any scaling trafos and assembles a
			% NEW \pgfplots@stored@plotlist!
			\pgfplots@stacked@finalize@stored@plots
		\fi
		%
		% ensure that (1,2) is automatically converted to (axis cs:1,2) :
		\pgfplots@change@pgfpoints@to@axiscs
		%
		% make it ungrouped: we must not destroy group nesting of tikz
		% path instructions at this point.
		\pgfplotslistforeachungrouped\pgfplots@stored@plotlist\as\pgfplots@loc@TMPa{%
			\expandafter\pgfplots@stored@plotlist@EXTRACTENTRY\pgfplots@loc@TMPa
%\message{^^JProcessing stored plot with precommand '\meaning\pgfplots@stored@current@precmd';^^J  pgfplots@plotcmd '\meaning\pgfplots@stored@current@cmd'^^J postcommand '\meaning\pgfplots@stored@current@postcmd'^^J}%
%\message{DATA: '\meaning\pgfplots@stored@current@data';^^J}%
			% The precmd sets all required variables needed to
			% finalize a plot.
			% @see the stream preparation routines.
			\pgfplots@stored@current@precmd
			\ifx\pgfplots@stored@current@cmd\pgfutil@empty
				% Ah: some \pgfplotsextra command like \draw,\path,
				% \node or even \scope or \endscope.
				%
				% do NOT call \pgfplotsonlayer here! We MUST NOT
				% destroy grouping levels here.
				\pgfplots@stored@current@data%
			\else
				%
				% this code here means we REALLY have a plotting
				% command!
				% This is the heart component of the visualization
				% phase.
				\pgfplots@stored@plotlist@visualize@selected@phases{\pgfplots@visphase@names}%
			\fi
			\pgfplots@stored@current@postcmd
		}%
		%
		\pgfplots@restorepgfpoint
		%
		\pgfplots@END@init@and@draw@axis
		%
		\pgfplots@create@axis@descriptions
	%
	% this here does \endtikzpicture\endpgfinterruptpicture 
	% (and stores sizes):
	\pgfplots@END@cell@picture
	%
	\let\tikz@fig@name=\pgfplots@fig@name
	\tikz@fig@mustbenamed
	%
	\edef\pgfplots@shapename{pgfplots@low@level@shape\ifpgfplots@deprecated@anchors @deprecated\fi}%
	\pgfutil@IfUndefined{pgf@anchor@\pgfplots@shapename @\pgfplots@anchorname}{%
		% Oh. Well, suppose \pgfplots@anchorname is associated to an
		% INNER node.
		\def\pgfplots@loc@TMPa##1{%
			\pgftransformshift{%
				% So far, the inner node's position has not been
				% corrected (that happens in 
				% \pgfplots@finally@correct@child@node@positions).
				% Do that here with \pgfplots@saveddimen@picminx:
				\pgfpointdiff
					{\pgfplotspointorigininternal}
					{##1}%
				\global\pgf@x=-\pgf@x \global\pgf@y=-\pgf@y
			}%
		}%
		\expandafter\tikz@scan@one@point\expandafter\pgfplots@loc@TMPa\expandafter(\pgfplots@anchorname)%
		\def\pgfplots@anchorname{image}% that means: no shift!
	}{}%
	%
	\begingroup
	\pgfplots@beforenode
	%
	\ifpgfplots@deprecated@anchors
		\pgfplots@restore@deprecated@lowlevel@shape
		\pgfmultipartnode{\pgfplots@shapename}{\pgfplots@anchorname}{\tikz@fig@name}{\pgfusepath{discard}}%
	\else
		\pgfmultipartnode{\pgfplots@shapename}{\pgfplots@anchorname}{\tikz@fig@name}{\pgfusepath{discard}}%
	\fi
	\endgroup
	\pgfplots@fig@alias
	\pgfnodealias{current axis}{\tikz@fig@name}%
	%
	\pgfplots@finally@correct@child@node@positions
	\pgfplots@stacked@finalize
	%
	\ifpgfplots@colorbar
		\pgfplots@colorbar@move@outside@scope@with@globalmacro{\pgfplots@glob@TMPa}%
	\else
		\global\let\pgfplots@glob@TMPa=\relax
	\fi
	%
	% transport the current layer config - but only if nessary!
	\def\pgfplots@loc@TMPa{0}%
	\ifpgfplots@has@cell@picture
		% layers are used for the cell picture only- no need to
		% communicate them.
	\else
		\ifpgfplots@layered@graphics
			\def\pgfplots@loc@TMPa{1}%
		\else
			% there are no layers.
		\fi
	\fi
	\if1\pgfplots@loc@TMPa
		% Ah - we need to transport the current layer config!
		\pgf@remember@layerlist@globally
		\aftergroup\pgf@restore@layerlist@from@global
	\else
		% Hm. No layers to transport. Make sure that the second
		% \aftergroup does not hurt:
		\aftergroup\pgf@remember@layerlist@globally
	\fi
	\endgroup
	\pgfplots@glob@TMPa
	%
	% once more again - just to be sure that it works with LaTeX which
	% introduces a further grouping level:
	\aftergroup\pgf@restore@layerlist@from@global
	%
	\pgfplots@cell@picture@remembered
	\aftergroup\pgfplots@cell@picture@remembered
}

\def\pgfplots@environment@opt@@setup@pgfpoint@restores{%
	% There are places in pgfplots where the default coordinate system
	% (i.e. the one used whenever one writes (1,2)) needs to be
	% replaced:
	%  - during axis descriptions (see \pgfplots@change@pgfpoints@to@descriptioncs)
	%  - during the visualization phase (where it is substituted by
	%  (axis cs:1,2), compare XXXX)
	%
	% However, as soon as someone writes \pgfsetxvec (or its y/z
	% variants), we want to *restore* the original PGF functionality.
	%
	% Prepare that here:
	\let\pgfpointxy@orig=\pgfpointxy
	\let\pgfqpointxy@orig=\pgfqpointxy
	\let\pgfpointxyz@orig=\pgfpointxyz
	\let\pgfqpointxyz@orig=\pgfqpointxyz
	\let\pgfsetxvec@orig=\pgfsetxvec
	\let\pgfsetyvec@orig=\pgfsetyvec
	\let\pgfsetzvec@orig=\pgfsetzvec
	\let\tikz@checkunit@orig=\tikz@checkunit
	%
	\let\pgfsetxvec=\pgfplots@setxvec@restorepgfpoint
	\let\pgfsetyvec=\pgfplots@setyvec@restorepgfpoint
	\let\pgfsetzvec=\pgfplots@setzvec@restorepgfpoint
}%

\def\pgfplots@restorepgfpoint{%
	\let\pgfpointxy=\pgfpointxy@orig
	\let\pgfqpointxy=\pgfqpointxy@orig
	\let\pgfpointxyz=\pgfpointxyz@orig
	\let\pgfqpointxyz=\pgfqpointxyz@orig
	\let\tikz@checkunit=\tikz@checkunit@orig
}%

\def\pgfplots@setxvec@restorepgfpoint#1{%
	\pgfsetxvec@orig{#1}%
	\pgfplots@restorepgfpoint
}%
\def\pgfplots@setyvec@restorepgfpoint#1{%
	\pgfsetyvec@orig{#1}%
	\pgfplots@restorepgfpoint
}%
\def\pgfplots@setzvec@restorepgfpoint#1{%
	\pgfsetzvec@orig{#1}%
	\pgfplots@restorepgfpoint
}%


\def\pgfplots@replace@path@commands{%
	\let\pgfplots@orig@scope=\scope
	\let\pgfplots@orig@endscope=\endscope
	\let\scope=\pgfplots@replacement@for@scope
	\let\endscope=\pgfplots@replacement@for@endscope
	%
	\let\pgfplots@orig@pgfonlayer=\pgfonlayer
	\let\pgfplots@orig@endpgfonlayer=\endpgfonlayer
	\let\pgfonlayer=\pgfplots@replacement@for@onlayer
	\let\endpgfonlayer=\pgfplots@replacement@for@endonlayer
	%
	\let\pgfplots@orig@pgfplotsonlayer=\pgfplotsonlayer
	\let\pgfplots@orig@endpgfplotsonlayer=\endpgfplotsonlayer
	\let\pgfplotsonlayer=\pgfplots@replacement@for@onlayer
	\let\endpgfplotsonlayer=\pgfplots@replacement@for@endonlayer
}%

\def\pgfplots@restore@path@commands{%
	% restore old \path command:
	\let\path=\pgfplots@orig@path
	\let\plot=\pgfplots@orig@plot
	\let\scope=\pgfplots@orig@scope
	\let\endscope=\pgfplots@orig@endscope
	\let\pgfonlayer=\pgfplots@orig@pgfonlayer
	\let\endpgfonlayer=\pgfplots@orig@endpgfonlayer
	\let\pgfplotsonlayer=\pgfplots@orig@pgfplotsonlayer
	\let\endpgfplotsonlayer=\pgfplots@orig@endpgfplotsonlayer
}

% visualizes selected phases.
%
% #1 a comma-separated list of selected phases. May be empty.
%   This is typically \pgfplots@visphase@names. The content will be
%   expanded, i.e. it can be a macro.
\def\pgfplots@stored@plotlist@visualize@selected@phases#1{%
	\begingroup
	\pgfplotsonlayer{\pgfkeysvalueof{/pgfplots/on layer}}{a plot or graphical element (or inherited from the axis)}%
	\pgfkeysvalueof{/pgfplots/execute at begin plot visualization}%
	\ifpgfplots@threedim
	\else
		% axis = 2d and plot=3d is forbidden here.
		\pgfplots@curplot@threedimfalse
	\fi
	\pgfplots@execute@at@begin@plot@visualization@internal
	%
	\pgfplots@markers@prepare@layered@graphics@marks
	%
	\edef\pgfplots@current@phases{#1}%
	%
	% "boolean shouldExecuteClippedPart = \ifpgfplots@loc@tmp"
	\pgfplots@loc@tmptrue
	\ifx\pgfplots@current@phases\pgfutil@empty
		\ifx\pgfplots@markers@visphase@name\pgfplots@markers@visphase@name@afterpath@clipped
			% some special handling.... ok; start phase.
		\else
			\pgfplots@loc@tmpfalse
		\fi
	\fi
	\ifpgfplots@loc@tmp
		\expandafter\pgfplots@stored@plotlist@visualize@clippedpart\expandafter{\pgfplots@current@phases}%
	\fi
	%
	\ifx\pgfplots@markers@visphase@name\pgfplots@markers@visphase@name@afterpath@unclipped
		\scope[current plot style]%
		\pgfplots@visphase@markers
		\endscope
	\fi
	\pgfplots@execute@at@end@plot@visualization@internal
	\pgfkeysvalueof{/pgfplots/execute at end plot visualization}%
	\endpgfplotsonlayer
	\endgroup
}

% #1: the list of phases to execute. This excludes marker phases.
\def\pgfplots@stored@plotlist@visualize@clippedpart#1{%
	\scope[current plot style] % this does set BOTH pgfplots and tikz options.
	%
	% do this here after options are set.
	\pgfplots@initzerolevelhandler
	%
	% FIXME : what, precisely, was the motivation to use a
	% scope here? It causes a lot of problems and
	% work-arounds. Is it worth the effort!?
	\ifpgfplots@clip
		\if2\pgfplots@clipmode
			% clip=true and 'clip mode=individual'
			\pgfplots@clippath@install{\pgfusepath{clip}}%
		\fi
	\fi
	%
	\def\pgfplots@loc@TMPa{#1}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		% skip. there is a case in which this can happen and makes
		% sense: if
		% \pgfplots@markers@visphase@name=\pgfplots@markers@visphase@name@afterpath@clipped
	\else
		% Standard visualization phases. See
		% \pgfplotssurveyphase@set@visphase@names for a discussion about
		% their intented use-case.
		\pgfplotsutilforeachcommasep{#1}\as\pgfplots@visphase@name{%
			\begingroup
			\pgfutil@ifundefined{pgfplots@visphase@\pgfplots@visphase@name}{%
				\pgfplots@error{Illegal state encountered: unknown visualization phase \pgfplots@visphase@name}%
			}{%
				\csname pgfplots@visphase@\pgfplots@visphase@name\endcsname
			}%
			\endgroup
		}%
	\fi
	%
	% marker visualization phase (one of the available ones):
	\ifx\pgfplots@markers@visphase@name\pgfplots@markers@visphase@name@afterpath@clipped
		\pgfplots@visphase@markers
	\fi
	%
	\endscope
}%

\def\pgfplots@visphase@markers{%
	\begingroup
	\pgfplots@change@pgfpoints@to@axiscs
	\pgfplots@markers@install@plotmark@handler
	\let\pgfplots@visphase@name=\pgfplotsaxis@visphase@name@markers
	\expandafter\pgfplots@coord@stream@finalize@storedcoords@START\pgfplots@stored@current@data\pgfplots@EOI
	\endgroup
}%

% Inside of an axis, the default coordinate system for any draw
% command should be (axis cs:1,2) instead of (1,2). Install that here:
%
% see \pgfplots@restorepgfpoint
\def\pgfplots@change@pgfpoints@to@axiscs{%
	%
	\ifpgfplots@substitute@pgfpoint
		\let\pgfpointxy=\pgfplotspointaxisxy
		\let\pgfpointxyz=\pgfplotspointaxisxyz
		\let\pgfqpointxy=\pgfplotsqpointaxisxy
		\let\pgfqpointxyz=\pgfplotsqpointaxisxyz
		%
		% tikz checks for units before it calls \pgfpointxy . This must
		% not suffer from TeX's math restrictions, so we have to use the
		% FPU for this task. Patch the command as well:
		\let\tikz@checkunit=\pgfplots@checkunit@fpu
	\fi
}%

\def\pgfplots@checkunit@fpu#1{%
	\ifpgfplots@usefpu
		\edef\pgfplots@checkunit@fpu@restore{%
			\pgflibraryfpuifactive{%
				% ok, leave it active
			}{%
				\noexpand\pgfkeys{/pgf/fpu=false}%
			}%
		}%
		\pgfkeys{/pgf/fpu}%
		\tikz@checkunit@orig{#1}%
		\pgfmathfloattofixed{\pgfmathresult}%
		\pgfplots@checkunit@fpu@restore
	\else
		\tikz@checkunit@orig{#1}%
	\fi
}%

\def\pgfplots@execute@at@end@plot@visualization@internal{%
}%

\def\pgfplots@beforenode{%
	\pgfplots@sys@beforenode
}%

% Now, we need to process all named nodes inside of our
% axis-image.
%
% The situation at this point is as follows:
% 1. the complete axis image has been "typeset" into a box. That
% means its coordinate system is LOST up to those variables
% which have been saved explicitly.
%
% 2. the \pgfmultipartnode above knows about all axis anchors and
% saved dimensions.
%
% 3. All sub-nodes don't know about their position any more. Any
% saved anchors are wrong.
%
% The approach:
% 1. we shift each named node's saved anchors such that it's
% coordinate is valid inside of the TeX box.
%
% 2. we also shift each named node's saved anchors to reflect the
% axis' anchor.
%
% Afterwards, everything should be fine.
\def\pgfplots@finally@correct@child@node@positions{%
   \ifx\pgfplots@named@child@node@list\pgfutil@empty%
   \else%
      	\begingroup
		\pgftransformreset% FIXME: what's that for!? Copied from matrix code...
		%
		% Use the 'image' anchor here - the internal anchor
		% transformation matrix already has the shift for
		% \pgfplots@anchorname.
		\pgfpointanchor{\tikz@fig@name}{image}%
		\pgf@xa=\pgf@x
		\pgf@xb=\pgf@y
		\pgf@process{\pgfplotspointorigininternal}%
		\advance\pgf@xa by-\pgf@x
		\advance\pgf@xb by-\pgf@y
		\global\pgf@x=\pgf@xa
		\global\pgf@y=\pgf@xb
		\edef\pgfplots@offset{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
		\pgfplots@finally@correct@remembered@picture@positions
		%
		\pgfutil@for\pgfplots@child@node@name:=\pgfplots@named@child@node@list\do{%
			\ifx\pgfplots@child@node@name\pgfutil@empty
			\else
%\message{Attempting to correct  '\pgfplots@child@node@name' position by \meaning\pgfplots@offset\space (the node is inside of an axis).}%
				\expandafter\ifx\csname pgfplots@child@node@visited@\pgfplots@child@node@name\endcsname\relax%
					\pgfutil@IfUndefined{pgf@sh@nt@\pgfplots@child@node@name}{%
						\pgfplots@warning{could not adjust coordinates of named node '\pgfplots@child@node@name' for reasons I do not understand! After finishing the image, it did no longer exist!? Sorry.}%
					}{%
						\pgf@shift@node{\pgfplots@child@node@name}{\pgfplots@offset}%
						\expandafter\let\csname pgfplots@child@node@visited@\pgfplots@child@node@name\endcsname=\pgfutil@empty%
					}%
				\fi
			\fi
		}%
		\endgroup
    \fi%
}%

% The feature 'remember picture' relies on the global position of
% pgfpictures.
%
% If we have 'remember picture=true' and 'cell picture=true', that
% global position has been shifted as well. We have to correct it.
%
% This, in turn, requires to patch the .aux file.
%
% PRECONDITION: takes the offset \pgf@x,\pgf@y.
\def\pgfplots@finally@correct@remembered@picture@positions{%
	% Note that the cell picture is already closed - but
	% fortunately, we have saved its picture id.
	\ifx\pgfplots@cell@pictureid\pgfutil@empty
		% ah - no cell picture. OK; nothing to do.
	\else
		% ah - there WAS a cell picture ...
		\pgfplots@cell@picture@remembered
		\ifpgfrememberpicturepositiononpage
			% ... AND it had its "remember picture" flag activated.
			%
			% It is task of
			% \pgfplots@finally@correct@child@node@positions to
			% express ALL node locations in terms of \pgfpictureid.
			%
			% So, we can simply replace the (already written) pdfmark
			% of \pgfplots@cell@pictureid by that of \pgfpictureid
			% (which, however, is NOT written because the picture is
			% not finished).
			%
			% It will be written eventually because the outer picture
			% will implicitly inherit
			% \pgfrememberpicturepositiononpagetrue
			% -> see all usages of \pgfplots@cell@picture@remembered
			\begingroup
			\edef\pgfplots@loc@TMPa{%
				\noexpand\noexpand
				\noexpand\pgfplotsreplacepdfmark
					{\pgfplots@cell@pictureid}{\pgfpictureid}%
			}%
			\expandafter\write\expandafter\pgfutil@auxout\expandafter{\pgfplots@loc@TMPa}%
			\endgroup
		\fi
	\fi
}%

% Replaces the pdfmark for #1 by that of #2.
% 
% Note that when this macro is executed (it resides in the .aux file),
% the pdfmark for #2 is typically UNDEFINED.
%
% #1: the pgfpictureid to modify
% #2: the pgfpictureid which contains the correct values
\def\pgfplotsreplacepdfmark#1#2{%
	\pgfsys@getposition{#1}{\pgfplots@loc@TMPa}%
	\ifx\pgfplots@loc@TMPa\relax
		% hm. strange. Perhaps the driver does not support it?
	\else
		% Ok, make a "lazy replace":
		\expandafter\let\expandafter\pgfplots@glob@TMPa\csname pgf@sys@pdf@mark@pos@#1\endcsname
		\expandafter\global\expandafter\let\csname pgf@sys@pdf@mark@pos@#1@old\endcsname=\pgfplots@loc@TMPa%
		% 
		\expandafter\gdef\csname pgf@sys@pdf@mark@pos@#1\endcsname{%
			% this is the lazy replace, assuming knowledge about how
			% pgf calls its internal structures :-/
			%
			% If pgf changes its name, this macro will never be
			% called and we do not hurt someone.
			\pgfsys@getposition{#2}{\pgfplots@loc@TMPa}%
			\ifx\pgfplots@loc@TMPa\relax
				% oh - the picture if for #2 has no remembered name!?
				% Perhaps something failed?
				% try a fall-back. This will most fail (most
				% probably). Issue a warning?
				\csname pgf@sys@pdf@mark@pos@#1@old\endcsname
			\else
				% use #2:
				\pgfplots@loc@TMPa
			\fi
		}%
	\fi
}%

\def\pgfplots@environment@axis{%
	\pgfutil@ifnextchar[{\pgfplots@@environment@axis}{\pgfplots@@environment@axis[]}%
}
\def\endpgfplots@environment@axis{\endpgfplots@environment@opt}
\def\pgfplots@@environment@axis[#1]{%
	\pgfplots@environment@opt[/pgfplots/xmode=linear,/pgfplots/ymode=linear,#1]%
}

\def\pgfplots@environment@semilogxaxis{%
	\pgfutil@ifnextchar[{\pgfplots@@environment@semilogxaxis}{\pgfplots@@environment@semilogxaxis[]}%
}
\def\endpgfplots@environment@semilogxaxis{\endpgfplots@environment@opt}
\def\pgfplots@@environment@semilogxaxis[#1]{%
	\pgfplots@environment@opt[/pgfplots/xmode=log,/pgfplots/ymode=linear,#1]%
}

\def\pgfplots@environment@semilogyaxis{%
	\pgfutil@ifnextchar[{\pgfplots@@environment@semilogyaxis}{\pgfplots@@environment@semilogyaxis[]}%
}
\def\endpgfplots@environment@semilogyaxis{\endpgfplots@environment@opt}
\def\pgfplots@@environment@semilogyaxis[#1]{%
	\pgfplots@environment@opt[/pgfplots/xmode=linear,/pgfplots/ymode=log,#1]%
}

\def\pgfplots@environment@loglogaxis{%
	\pgfutil@ifnextchar[{\pgfplots@@environment@loglogaxis}{\pgfplots@@environment@loglogaxis[]}%
}
\def\endpgfplots@environment@loglogaxis{\endpgfplots@environment@opt}
\def\pgfplots@@environment@loglogaxis[#1]{%
	\pgfplots@environment@opt[/pgfplots/xmode=log,/pgfplots/ymode=log,#1]%
}


\pgfutil@IfUndefined{tikzaddtikzonlycommandshortcutlet}{%
	\def\tikzaddtikzonlycommandshortcutlet#1#2{%
		\expandafter\def\expandafter\tikz@installcommands\expandafter{\tikz@installcommands
			\let#1=#2%
		}%
	}%
}{}

\tikzaddtikzonlycommandshortcutlet\axis\pgfplots@environment@axis
\tikzaddtikzonlycommandshortcutlet\endaxis\endpgfplots@environment@axis

\tikzaddtikzonlycommandshortcutlet\semilogxaxis\pgfplots@environment@semilogxaxis
\tikzaddtikzonlycommandshortcutlet\endsemilogxaxis\endpgfplots@environment@semilogxaxis

\tikzaddtikzonlycommandshortcutlet\semilogyaxis\pgfplots@environment@semilogyaxis
\tikzaddtikzonlycommandshortcutlet\endsemilogyaxis\endpgfplots@environment@semilogyaxis

\tikzaddtikzonlycommandshortcutlet\loglogaxis\pgfplots@environment@loglogaxis
\tikzaddtikzonlycommandshortcutlet\endloglogaxis\endpgfplots@environment@loglogaxis

%\input pgfplots.multiaxis.code.tex

\pgfplotsdefineaxistype{rectangle}{%
	% do nothing, this is the default anyway.
}%

\catcode`\;=\pgfplots@oldcatcodesemicolon

pgfplotscolor.code.tex
%--------------------------------------------
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2007-2013 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------

\pgfkeys{
	/pgfplots/color sequence/reset/.style={
		/pgfplots/color sequence/colorspace,
		/pgfplots/color sequence/default input colorspace,
		/pgfplots/color sequence/every input component/.code=,
		/pgfplots/color sequence/context message,
	},
	/pgfplots/color sequence/colorspace/.initial=auto,
	/pgfplots/color sequence/colorspace/.default=auto,
	/pgfplots/color sequence/default input colorspace/.initial=,
	/pgfplots/color sequence/default input colorspace/.default=\pgfkeysvalueof{/pgfplots/color sequence/colorspace},
	% applied to every INPUT component, i.e. before transforming it to some target color space.
	/pgfplots/color sequence/every input component/.code=,
	/pgfplots/color sequence/context message/.code={\def\pgfplotscolornormalizesequence@context@message{#1}},
	/pgfplots/color sequence/context message/.default=\pgfplotscolornormalizesequence@context@message@default,
	/pgfplots/color sequence/reset,
}

\newif\ifpgfplotscolor@colorspaceknown

% the beginning of a normalized color sequence.
%
% It is to be used like
% \pgfplotscolornormalizesequence[colorspace=rgb]
%
% \pgfplotscolornormalizesequencenext{1,1,1}
% -> \pgfplotsretval = {1,1,1} % uses default colorspace
% \pgfplotscolornormalizesequencenext{color=red}
% -> \pgfplotsretval = {1,0,0}
% \pgfplotscolornormalizesequencenext{color=blue}
% -> \pgfplotsretval = {0,0,1}
% \pgfplotscolornormalizesequencenext{rgb=1,0,0}
% -> \pgfplotsretval = {1,0,0}
% \pgfplotscolornormalizesequencenext{cmyk=1,0,0,1}
% -> \pgfplotsretval = {<converted value>}
%
% \endpgfplotscolornormalizesequence
%
% Every color provided in the sequence will be normalized by
% transforming it to the common color space and by computing the
% separate components representing the color in that space.
%
% These components are available for use in interpolation routines.
%
% #1 : keys in the /pgfplots/color sequence path
\def\pgfplotscolornormalizesequence[#1]{%
	\pgfqkeys{/pgfplots/color sequence}{%
		#1,%
	}%
	\pgfkeysgetvalue{/pgfplots/color sequence/colorspace}\pgfplots@loc@TMPa
	\pgfkeysgetvalue{/pgfplots/color sequence/default input colorspace}\pgfplotscolornormalizesequence@colspace@input
	\edef\pgfplotscolornormalizesequence@colspace@input{\pgfplotscolornormalizesequence@colspace@input}%
	\pgfkeysgetvalue{/pgfplots/color sequence/every input component/.@cmd}\pgfplotscolornormalizesequencenext@every@component
	\edef\pgfplots@loc@TMPa{\pgfplots@loc@TMPa}%
	\def\pgfplots@loc@TMPb{auto}%
	\ifx\pgfplots@loc@TMPb\pgfplots@loc@TMPa
		% colorspace=auto: same as empty.
		\let\pgfplots@loc@TMPa=\pgfutil@empty
	\fi
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		% colorspace=auto:
		\def\pgfplotscolornormalizesequence@colspace{}%
	\else
		\def\pgfplots@loc@TMPb{rgb}%
		\ifx\pgfplots@loc@TMPb\pgfplots@loc@TMPa
			% colorspace=rgb:
			\def\pgfplotscolornormalizesequence@colspace{rgb}%
		\else
			\def\pgfplots@loc@TMPb{cmyk}%
			\ifx\pgfplots@loc@TMPb\pgfplots@loc@TMPa
				% colorspace=cmyk:
				\def\pgfplotscolornormalizesequence@colspace{cmyk}%
			\else
				\def\pgfplots@loc@TMPb{gray}%
				\ifx\pgfplots@loc@TMPb\pgfplots@loc@TMPa
					% colorspace=gray:
					\def\pgfplotscolornormalizesequence@colspace{gray}%
				\else
					\pgfplots@error{Sorry, the choice colorspace=\pgfplots@loc@TMPa\space is unsupported as interpolation colorspace in pgfplots, please use one of 'auto,rgb,cmyk,gray'}%
				\fi
			\fi
		\fi
	\fi
}%

% ends a normalized color sequence and returns the final colorspace
% and its number of components into \pgfplotsretval and
% \pgfplotsretvalb, respectively
\def\endpgfplotscolornormalizesequence{%
	\let\pgfplotsretval=\pgfplotscolornormalizesequence@colspace
	\pgfplotscolor@get@num@components{\pgfplotsretval}{\pgfplotsretvalb}%
	\pgfqkeys{/pgfplots/color sequence}{reset}%
}%

% accepts the next color in a sequence of colors. The color will be
% normalized and the normalized result written to \pgfplotsretval.
%
% SEE \pgfplotscolornormalizesequencenext -- it is MUCH more powerful!
%
% #1 the color space of the color.
% #2 the components of the color, separated by comma.
%
% POSTCONDITION: 
%   \pgfplotsretval contains '{<color space>}{<comma-separated-components>}'
%  -> including the curly braces.
%  
%  \pgfplotsretvalb contains the number of input components in
%  \pgfplotsretval
\def\pgfplotscolornormalizesequencenextbycomponents#1#2{%
	\edef\pgfplotscolornormalizesequence@cur@colspace{#1}%
	\pgfplotscolornormalizesequencenextbycomponents@normalize@components{#2}%
	%
	\ifx\pgfplotscolornormalizesequence@cur@colspace\pgfplotscolornormalizesequence@colspace
	\else
		\ifx\pgfplotscolornormalizesequence@colspace\pgfutil@empty
			\pgfplotscolornormalizesequencenextbycomponents@assign@auto@colspace
		\fi
		%
		\ifx\pgfplotscolornormalizesequence@colspace\pgfplotscolornormalizesequence@cur@colspace
			% Ah, ok - the colorspace is NOW the correct one (because
			% we chose it as the colorspace for this complete color
			% sequence.
		\else
			% Oh. We need to convert the color space!
			\edef\pgfplots@loc@TMPa{{\pgfplotscolornormalizesequence@cur@colspace}{\pgfplotsretval}}%
			\expandafter\pgfutil@convertcolorspec\pgfplots@loc@TMPa
				{\pgfplotscolornormalizesequence@colspace}% target color spaces
				{\pgfplotsretval}% target macro
		\fi
	\fi
	\edef\pgfplotsretval{\pgfplotsretval}%
	\pgfplotscolor@get@num@components{\pgfplotscolornormalizesequence@colspace}{\pgfplotsretvalb}%
}

\def\pgfplotscolornormalizesequencenextbycomponents@assign@auto@colspace{%
	% Ah; we have '/pgfplots/color sequence/colorspace=auto'.
	% Well, check if the current colorspace (stored in
	% \pgfplotscolornormalizesequence@cur@colspace) is suitable.
	%
	% It is suitable if it is rgb or cmyk. In all other cases,
	% we choose either rgb or cmyk. More precisely. 'cmy' is
	% mapped to cmyk. All other cases are treated as rgb.
	%
	\def\pgfplots@loc@TMPa{cmyk}%
	\ifx\pgfplotscolornormalizesequence@cur@colspace\pgfplots@loc@TMPa
		\let\pgfplotscolornormalizesequence@colspace=\pgfplotscolornormalizesequence@cur@colspace
	\else
		\def\pgfplots@loc@TMPa{cmy}%
		\ifx\pgfplotscolornormalizesequence@cur@colspace\pgfplots@loc@TMPa
			\def\pgfplotscolornormalizesequence@colspace{cmyk}%
		\else
			% rgb appears to be the best choice: (1) it is backwards
			% compatible and (2) gray or something like that might fit
			% badly to any other colors in the sequence.
			\def\pgfplotscolornormalizesequence@colspace{rgb}%
		\fi
	\fi
}

% #1: color components
%
% PRECONDITION: \pgfplotscolornormalizesequence@cur@colspace is the
% current color space
%
% POSTCONDITION: \pgfplotsretval contains the normalized color
% components
\def\pgfplotscolornormalizesequencenextbycomponents@normalize@components#1{%
	\pgfutil@ifundefined{pgfplots@colspace@name@\pgfplotscolornormalizesequence@cur@colspace}{%
		\pgfplotscolor@colorspaceknownfalse
	}{%
		\pgfplotscolor@colorspaceknowntrue
	}%
	\edef\pgfplots@loc@TMPb{#1}%
	\def\pgfplotsretval{}%
	\c@pgf@counta=0 %
	\expandafter\pgfplotscolornormalizesequencenext@prepare@loop\pgfplots@loc@TMPb,\pgfplots@EOI,%
}%

% assigns the number of color components for the given colorspace to
% \pgfplotsretval
\def\pgfplotscolorspacegetcomponents#1{%
	\pgfplotscolor@get@num@components{#1}{\pgfplotsretval}%
}%

% Defines \pgfplotsretval to contain the number of components in the
% color space.
\def\pgfplotscolornormalizesequencegetnumcomponents{%
	\ifx\pgfplotscolornormalizesequence@colspace\pgfutil@empty
		\pgfplotsthrow{invalid argument}{\pgfplots@loc@TMPa}{Cannot create color with zero components: no colorspace set for the normalized color sequence.}\pgfeov%
	\fi
	\pgfplotscolorspacegetcomponents{\pgfplotscolornormalizesequence@colspace}%
}%

\def\pgfplotscolor@get@num@components#1#2{%
	\pgfutil@ifundefined{pgfplots@colspace@numcomp@#1}{%
		\pgfplotsthrow{invalid argument}{\pgfplots@loc@TMPa}{The input color has an unsupported color space '#1'}\pgfeov%
	}{%
		\edef#2{\csname pgfplots@colspace@numcomp@#1\endcsname}%
	}%
}%


\def\pgfplots@colspace@numcomp@gray{1}%
\def\pgfplots@colspace@name@gray{gray}%

\def\pgfplots@colspace@numcomp@rgb{3}%
\def\pgfplots@colspace@name@rgb{rgb}%

\def\pgfplots@colspace@numcomp@cmyk{4}%
\def\pgfplots@colspace@name@cmyk{cmyk}%

\def\pgfplots@colspace@numcomp@cmy{3}%
\def\pgfplots@colspace@name@cmy{cmy}%

\def\pgfplots@colspace@numcomp@wave{1}%
\def\pgfplots@colspace@name@wave{wave}%
\pgfutil@namedef{pgfplots@colspace@minaccept@wave@0}{362.998}%
\pgfutil@namedef{pgfplots@colspace@min@wave@0}{363}%
\pgfutil@namedef{pgfplots@colspace@maxaccept@wave@0}{814.001}%
\pgfutil@namedef{pgfplots@colspace@max@wave@0}{814}%

\def\pgfplots@colspace@numcomp@Hsb{3}%
\def\pgfplots@colspace@name@Hsb{Hsb}%
\pgfutil@namedef{pgfplots@colspace@minaccept@Hsb@0}{-0.001}%
\pgfutil@namedef{pgfplots@colspace@min@Hsb@0}{0}%
\pgfutil@namedef{pgfplots@colspace@maxaccept@Hsb@0}{\rangeHsb}%
\pgfutil@namedef{pgfplots@colspace@max@Hsb@0}{\rangeHsb}%

\def\pgfplotscolornormalizesequencenext@prepare@loop#1,{%
	\def\pgfmathresult{#1}%
	\ifx\pgfmathresult\pgfplots@EOI
	\else
		\begingroup
		\pgfkeyslet{/pgf/fpu/handlers/invalid number/.@cmd}\pgfplotscolornormalizesequencenextbycomponents@parsenumber@error
		\expandafter\pgfplotscolornormalizesequencenext@every@component\expandafter{\pgfmathresult}\pgfeov%
		\ifpgfplotscolor@colorspaceknown
			\expandafter\pgfplotscolornormalizesequencenextbycomponents@parsenumber\expandafter{\pgfmathresult}%
		\fi
		\pgfmath@smuggleone\pgfmathresult
		\endgroup
		\ifpgfplotscolor@colorspaceknown
			\expandafter\pgfplotscolornormalizesequencenextbycomponents@sanitize\expandafter{\pgfmathresult}%
		\fi
		\ifx\pgfplotsretval\pgfutil@empty
			\edef\pgfplotsretval{\pgfmathresult}%
		\else
			\edef\pgfplotsretval{\pgfplotsretval,\pgfmathresult}%
		\fi
		\advance\c@pgf@counta by1 %
		\expandafter\pgfplotscolornormalizesequencenext@prepare@loop
	\fi
}

\def\pgfplotscolornormalizesequencenextbycomponents@parsenumber#1{%
	\pgfmathfloatparsenumber{#1}%
	\pgfmathfloattofixed\pgfmathresult
}

\def\pgfplotscolornormalizesequencenextbycomponents@parsenumber@error#1#2\pgfeov{%
	\pgfplotsthrow{invalid color component}{\pgfmathresult}{Sorry, the color component value '#1' is no number. Did you mean 'color=#1'? The error occured near `\pgfplotscolornormalizesequence@context@message'}\pgfeov%
	\pgfmathfloatcreate{0}{0.0}{0}%
}%

% #1 the color component value
\def\pgfplotscolornormalizesequencenextbycomponents@sanitize#1{%
	\pgf@xa=#1pt %
	%
	% check if we have something like 
	%   \csname pgfplots@colspace@minaccept@<colorspace name>@2\endcsname where 2 is component index:
	\edef\pgfplots@loc@TMPc{@\pgfplotscolornormalizesequence@cur@colspace @\the\c@pgf@counta}%
	\pgfutil@ifundefined{pgfplots@colspace@minaccept\pgfplots@loc@TMPc}{%
		% NO - implicitly defined to [0,1]
		\def\pgfplots@colspace@minaccept@@{-0.001}%
		\def\pgfplots@colspace@min@@{-0.001}%
		\def\pgfplots@colspace@maxaccept@@{1.001}%
		\def\pgfplots@colspace@max@@{1}%
	}{%
		% YES - expect all four values:
		\edef\pgfplots@colspace@minaccept@@{\csname pgfplots@colspace@minaccept\pgfplots@loc@TMPc\endcsname}%
		\edef\pgfplots@colspace@min@@{\csname pgfplots@colspace@min\pgfplots@loc@TMPc\endcsname}%
		\edef\pgfplots@colspace@maxaccept@@{\csname pgfplots@colspace@maxaccept\pgfplots@loc@TMPc\endcsname}%
		\edef\pgfplots@colspace@max@@{\csname pgfplots@colspace@max\pgfplots@loc@TMPc\endcsname}%
	}%
	\ifdim\pgf@xa<\pgfplots@colspace@minaccept@@ pt %
		\edef\pgfmathresult{\pgfplots@colspace@min@@}%
		\pgfplotscolor@rangeexception{#1}%
	\else
		\ifdim\pgf@xa>\pgfplots@colspace@maxaccept@@ pt %
			\edef\pgfmathresult{\pgfplots@colspace@max@@}%
			\pgfplotscolor@rangeexception{#1}%
		\else
			% Ah - the common case!
			\edef\pgfmathresult{\pgf@sys@tonumber\pgf@xa}% normalize number (strip trailing zeros etc).
		\fi
	\fi
}

\def\pgfplotscolor@rangeexception#1{%
	\pgfplotsthrow{invalid color component}{\pgfmathresult}{Sorry, the color component value #1 (no. \the\c@pgf@counta) is out of range. The allowed range is 0 <= value  <= 1. The error occured near `\pgfplotscolornormalizesequence@context@message'}\pgfeov%
}


% Same as \pgfplotscolornormalizesequencenextbycomponents but with
% more freedom in the input.
%
% #1 some color.
% Accepted formats:
% 'color=<xcolor value>'
% 	<xcolor value> is any valid expression of the xcolor package.
%
% 'rgb=R,G,B'  
% 	R,G,B are numbers in [0,1]
%
% 'rgb255=R,G,B'
% 	R,G,B are numbers in [0,255]
%
% 'cmyk=C,M,Y,K'
% 	C, M, Y, and K are numbers in [0,1]
%
% 'cmyk255=C,M,Y,K'
% 	C, M, Y, and K are numbers in [0,255]
%
% 'gray=G'
%   G is a gray scale number in [0,1]
%
% 'C1,C2,C3'  
% 	any number of Ci can folow, each is interpreted in the default
% 	colorspace (i.e. the one set before at the beginning of the
% 	sequence)
%
%
% Example:
% \pgfplotscolornormalizesequencenext{color=blue}
% \pgfplotscolornormalizesequencenext{rgb=1,0,0}
% \pgfplotscolornormalizesequencenext{cmyk=1,0,0,1}
% \pgfplotscolornormalizesequencenext{1,0,0} (interpreted in the
% colorspace set at \pgfplotscolornormalizesequence)
%
% POSTCONDITION: see \pgfplotscolornormalizesequencenextbycomponents
\def\pgfplotscolornormalizesequencenext#1{%
	\edef\pgfplotscolornormalizesequence@context@message@default{#1}%
	\expandafter\pgfplotscolornormalizesequencenext@\pgfplotscolornormalizesequence@context@message@default\pgfplots@EOI
}
\def\pgfplotscolornormalizesequencenext@{%
	\pgfutil@ifnextchar c{%
		\pgfplotscolornormalizesequencenext@c
	}{%
		\pgfutil@ifnextchar r{%
			\pgfplotscolornormalizesequencenext@rgb
		}{%
			\pgfutil@ifnextchar g{%
				\pgfplotscolornormalizesequencenext@gray
			}{%
				\pgfplotscolornormalizesequencenext@defaultcolspace
			}%
		}%
	}%
}

\def\pgfplotscolornormalizesequencenext@gray gray=#1\pgfplots@EOI{%
	% FIXME : we might be better off with real support for a gray
	% colorspace!
	\pgfplotscolornormalizesequencenextbycomponents{rgb}{#1,#1,#1}%
}

\def\pgfplotscolornormalizesequencenext@defaultcolspace#1\pgfplots@EOI{%
	\edef\pgfplotsretval{#1}%
	\ifx\pgfplotsretval\pgfutil@empty
		% hm. Ok, simply return the empty input.
		%
		% ... and the number of components.
		\pgfplotscolor@get@num@components{\pgfplotscolornormalizesequence@colspace}{\pgfplotsretvalb}%
		%
	\else
		\expandafter\pgfutil@in@\expandafter=\expandafter{\pgfplotsretval}%
		\ifpgfutil@in@
			\expandafter\pgfplotscolornormalizesequencenext@unknown@colspace\pgfplotsretval\pgfplots@EOI
		\else
			\ifx\pgfplotscolornormalizesequence@colspace@input\pgfutil@empty
				\pgfplotsthrow{invalid argument}{\pgfplots@loc@TMPa}{The input color #1 cannot be interpreted; please assign a default color space first}\pgfeov%
			\fi
			\pgfplotscolornormalizesequencenextbycomponents{\pgfplotscolornormalizesequence@colspace@input}{#1}%
		\fi
	\fi
}

\def\pgfplotscolornormalizesequencenext@unknown@colspace#1=#2\pgfplots@EOI{%
	\pgfplotscolornormalizesequencenextbycomponents{#1}{#2}%
}

\def\pgfplotscolornormalizesequencenext@rgb rgb{%
	\pgfutil@ifnextchar2{%
		\pgfplotscolornormalizesequencenext@rgb@two@five@five
	}{%
		\pgfplotscolornormalizesequencenext@rgb@plain
	}%
}
\def\pgfplotscolornormalizesequencenext@rgb@plain=#1\pgfplots@EOI{%
	\pgfplotscolornormalizesequencenextbycomponents{rgb}{#1}%
}

\def\pgfplotscolorsequence@two@five@five@rescale#1{%
	\pgfmath@basic@multiply@{0.003921568}{#1}%
}%
\def\pgfplotscolornormalizesequencenext@rgb@two@five@five255=#1,#2,#3\pgfplots@EOI{%
	\pgfplotscolorsequence@two@five@five@rescale{#1}%
	\let\pgfplots@loc@TMPa=\pgfmathresult
	\pgfplotscolorsequence@two@five@five@rescale{#2}%
	\let\pgfplots@loc@TMPb=\pgfmathresult
	\pgfplotscolorsequence@two@five@five@rescale{#3}%
	\edef\pgfplots@loc@TMPc{{rgb}{\pgfplots@loc@TMPa,\pgfplots@loc@TMPb,\pgfmathresult}}%
	\expandafter\pgfplotscolornormalizesequencenextbycomponents\pgfplots@loc@TMPc%
}

\def\pgfplotscolornormalizesequencenext@c c{%
	\pgfutil@ifnextchar m{%
		\pgfplotscolornormalizesequencenext@cmyk
	}{%
		\pgfplotscolornormalizesequencenext@color
	}%
}%

\def\pgfplotscolornormalizesequencenext@cmyk myk{%
	\pgfutil@ifnextchar2{%
		\pgfplotscolornormalizesequencenext@cmyk@two@five@five
	}{%
		\pgfplotscolornormalizesequencenext@cmyk@plain
	}%
}%

\def\pgfplotscolornormalizesequencenext@cmyk@plain=#1\pgfplots@EOI{%
	\pgfplotscolornormalizesequencenextbycomponents{cmyk}{#1}%
}%
\def\pgfplotscolornormalizesequencenext@cmyk@two@five@five255=#1,#2,#3,#4\pgfplots@EOI{%
	\pgfplotscolorsequence@two@five@five@rescale{#1}%
	\let\pgfplots@loc@TMPa=\pgfmathresult
	\pgfplotscolorsequence@two@five@five@rescale{#2}%
	\let\pgfplots@loc@TMPb=\pgfmathresult
	\pgfplotscolorsequence@two@five@five@rescale{#3}%
	\let\pgfplots@loc@TMPc=\pgfmathresult
	\pgfplotscolorsequence@two@five@five@rescale{#4}%
	\edef\pgfplots@loc@TMPc{{cmyk}{\pgfplots@loc@TMPa,\pgfplots@loc@TMPb,\pgfplots@loc@TMPc,\pgfmathresult}}%
	\expandafter\pgfplotscolornormalizesequencenextbycomponents\pgfplots@loc@TMPc%
}

% The implementation of \pgfutil@extractcolorspec for plain tex and
% context is ... strange. I prefer one which does the same as the
% xcolor version (which is also what pgf does for latex):
\def\pgfplotsutil@extractcolorspec@xcolor@substitute#1#2{%
  \begingroup
  % this here relies on PGF's emulation of color in plain tex and
  % context. Let's hope it works in the future...
  \def\xcolor@##1##2##3##4{%
	 \edef#2{{##3}{##4}}%
  }%
  \csname\string\color@#1\endcsname
  \global\let\pgfutil@extractcolorspec@@temp=#2%
  \endgroup
  \let#2=\pgfutil@extractcolorspec@@temp
}%

\def\pgfplots@glob@TMPa#1#2{%
	\def#2{{#1}}%
}%

\pgfutil@IfUndefined{extractcolorspec}{%
	% Ah. We do not have a suitable implementation of
	% \extractcolorspec -- \pgfutil@extractcolorspec does not yield
	% the colorspec on context and plain tex.
	\def\pgfplotsutil@extractcolorspec{\pgfplotsutil@extractcolorspec@xcolor@substitute}%
}{%
	\ifx\extractcolorspec\pgfplots@glob@TMPa
		% Same problem as above: pgfutil-plain.def says
		% \let\extractcolorspec=\pgfutil@extractcolorspec and that one
		% is broken.
		% Use my substitute:
		\def\pgfplotsutil@extractcolorspec{\pgfplotsutil@extractcolorspec@xcolor@substitute}%
	\else
		\def\pgfplotsutil@extractcolorspec{\extractcolorspec}%
	\fi
}%

\def\pgfplotscolornormalizesequencenext@color olor=#1\pgfplots@EOI{%
	\pgfutil@colorlet{pgf@tempcol}{#1}%
	\pgfplotsutil@extractcolorspec{pgf@tempcol}{\pgf@tempcolor}%
	\edef\pgfplots@loc@TMPa{\expandafter\pgfutil@firstoftwo\pgf@tempcolor}%
	\edef\pgfplots@loc@TMPb{\expandafter\pgfutil@secondoftwo\pgf@tempcolor}%
	%
	% I expect that \pgf@tempcolor is of the form
	% {<colorspace>}{<comma-separated components>}
	%
	% unfortunately, the <colorspace> has strange catcodes such that
	% we cannot easily compare it by means of \ifx. I normalize it
	% here:
	\pgfutil@ifundefined{pgfplots@colspace@name@\pgfplots@loc@TMPa}{%
		% ohoh. we cannot normalize the name. Let's hope that works out.
		% note that we cannot throw an exception here as we might very well be able 
		% to convert the color to some suitable color space!
	}{%
		\edef\pgfplots@loc@TMPa{%
			\csname pgfplots@colspace@name@\pgfplots@loc@TMPa\endcsname%
		}%
	}%
	\edef\pgf@tempcolor{%
		{\pgfplots@loc@TMPa}%
		{\pgfplots@loc@TMPb}%
	}%
	\expandafter\pgfplotscolornormalizesequencenextbycomponents\pgf@tempcolor%
	%
}%

% Defines \pgfplotsretval to be a "neutral" color, i.e. one in which
% all components are zero.
% @see \pgfplotscolorzero
% @see \pgfplotscoloraddweighted
\def\pgfplotscolornormalizesequencezero{%
	\pgfplotscolornormalizesequencegetnumcomponents
	\pgfplotscolorzero{\pgfplotsretval}%
}

% Defines \pgfplotsretval to be a "neutral" color, i.e. one in which
% all components are zero.
%
% #1: the number of color components to be used (like 3 for rgb)
% @see \pgfplotscoloraddweighted
\def\pgfplotscolorzero#1{%
	\csname pgfplotscolorzero@num@#1\endcsname
}%

\expandafter\def\csname pgfplotscolorzero@num@1\endcsname{\def\pgfplotsretval{0}}
\expandafter\def\csname pgfplotscolorzero@num@2\endcsname{\def\pgfplotsretval{0,0}}
\expandafter\def\csname pgfplotscolorzero@num@3\endcsname{\def\pgfplotsretval{0,0,0}}
\expandafter\def\csname pgfplotscolorzero@num@4\endcsname{\def\pgfplotsretval{0,0,0,0}}

% Defines \pgfplotsretval to be the interpolated color #1 + #2*#3.
% #1 the first color (like 0,0,0)
% #2 a scaling factor (like 4)
% #3 the second color (like 1,0,0.5)
%
% POSTCONDITION: \pgfplotsretval contains the result
%
% @see \pgfplotscolorzero
% @see \pgfplotscoloraddweighted
\def\pgfplotscolornormalizesequenceaddweighted#1#2#3{%
	\begingroup
		\pgfplotscolornormalizesequencegetnumcomponents
		\global\let\pgfplots@glob@TMPd\pgfplotsretval
	\endgroup
	\pgfplotscoloraddweighted{\pgfplots@glob@TMPd}{#1}{#2}{#3}%
}

% Defines \pgfplotsretval to be the interpolated color #2 + #3*#4.
% #1 the number of color components to be used (3 for rgb)
% #2 the first color (like 0,0,0)
% #3 a scaling factor (like 4)
% #4 the second color (like 1,0,0.5)
%
% POSTCONDITION: \pgfplotsretval contains the result
%
% @see \pgfplotscolorzero
\def\pgfplotscoloraddweighted#1#2#3#4{%
	\pgfplots@ifempty{#4}{%
		\pgfplots@error{Illegal input argument encountered while computing colors: 
			one color argument is missing (was empty). Please ensure that you have explicit color values in your input}%
	}{%
		\expandafter\let
		\expandafter\pgfplots@loc@TMPb\csname pgfplotscolornormalizesequencegetnumcomponents@#1\endcsname
		\edef\pgfplots@loc@TMPa{#2:#4\noexpand\relax{#3}}%
		\expandafter\pgfplots@loc@TMPb\pgfplots@loc@TMPa%
	}%
}%

\def\pgfplotscolornormalizesequenceaddweighted@single#1#2#3{%
	\pgf@xa=#1pt %
	\pgf@xb=#3pt %
	\advance\pgf@xa by#2\pgf@xb
	\edef\pgfplotsretval{\pgf@sys@tonumber\pgf@xa}%
}%

\expandafter\def\csname pgfplotscolornormalizesequencegetnumcomponents@1\endcsname#1:#2\relax#3{%
	\pgfplotscolornormalizesequenceaddweighted@single{#1}{#3}{#2}%
}%
\expandafter\def\csname pgfplotscolornormalizesequencegetnumcomponents@3\endcsname#1,#2,#3:#4,#5,#6\relax#7{%
	\pgfplotscolornormalizesequenceaddweighted@single{#1}{#7}{#4}%
	\let\pgfplots@loc@TMPa=\pgfplotsretval
	\pgfplotscolornormalizesequenceaddweighted@single{#2}{#7}{#5}%
	\let\pgfplots@loc@TMPb=\pgfplotsretval
	\pgfplotscolornormalizesequenceaddweighted@single{#3}{#7}{#6}%
	\let\pgfplots@loc@TMPc=\pgfplotsretval
	\edef\pgfplotsretval{\pgfplots@loc@TMPa,\pgfplots@loc@TMPb,\pgfplots@loc@TMPc}%
}%
\expandafter\def\csname pgfplotscolornormalizesequencegetnumcomponents@4\endcsname#1,#2,#3,#4:#5,#6,#7,#8\relax#9{%
	\pgfplotscolornormalizesequenceaddweighted@single{#1}{#9}{#5}%
	\let\pgfplots@loc@TMPa=\pgfplotsretval
	\pgfplotscolornormalizesequenceaddweighted@single{#2}{#9}{#6}%
	\let\pgfplots@loc@TMPb=\pgfplotsretval
	\pgfplotscolornormalizesequenceaddweighted@single{#3}{#9}{#7}%
	\let\pgfplots@loc@TMPc=\pgfplotsretval
	\pgfplotscolornormalizesequenceaddweighted@single{#4}{#9}{#8}%
	\let\pgfplots@loc@TMPd=\pgfplotsretval
	\edef\pgfplotsretval{\pgfplots@loc@TMPa,\pgfplots@loc@TMPb,\pgfplots@loc@TMPc,\pgfplots@loc@TMPd}%
}%

\endinput

pgfplotscolormap.code.tex
%--------------------------------------------
% $Header: /cvsroot/pgfplots/pgfplots/generic/pgfplots/util/pgfplotscolormap.code.tex,v 1.15 2009/07/21 18:18:48 ludewich Exp $
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2007-2013 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------

\input pgfplotscolor.code.tex

\pgfkeyssetvalue{/pgfplots/colormap default colorspace}{auto}

% This package relies on pgfplots temporary registers and its array
% data structure.

% Internal structure:
% the colormap data structure consists of
% - an array 'pgfpl@cm@#1' of RGB color triples,
% - numbers 'pgfpl@cm@#1@h' and 'pgfpl@cm@#1@invh' for the mesh width
%   and inverse mesh width.

% Creates a new colormap.
%
% #1 : the name of the color map as string (not as macro).
% #2 : a <color specification> as is expected for a shading spec of
% pgf. However, the format allows a little bit more freedom:
% 	- it supports 'rgb255' in addition to pgf,
% 	- the length is not required (defaults to 1cm for the first and to
% 	the last length+h for all others).
% 	- the semicolons can be omitted.
%
% Example: 
% \pgfplotscreatecolormap{my map}{rgb(0cm)=(1,0,0); rgb(1cm)=(0,1,0); rgb255(1.5cm)=(128,5,255); rgb(2cm)=(0,0,1); gray(3cm)=(3);  color(4cm)=(green); }
% \pgfplotscreatecolormap{my map}{color=(green); color=(red); color=(blue); color=(yellow)}
\def\pgfplotscreatecolormap#{\pgfplots@createcolormap}%
\def\pgfplots@createcolormap#1#2{%
	\edef\pgfplots@createcolormap@name{pgfpl@cm@#1}%
	\expandafter\pgfplotsarraynewempty\expandafter{\pgfplots@createcolormap@name}%
	\def\pgfplots@createcolormap@MIN{0}% NORMALIZATION: assume that lower-end is 0pt.
	\def\pgfplots@createcolormap@MAX{0}% To be computed.
	\pgfplots@createcolormap@initcolorspace
	\let\pgfplots@createcolormap@LAST=\pgfplots@createcolormap@MIN
	% PARSE IT:
	\edef\pgfplots@loc@TMPa{#2}%
	\let\pgfplots@createcolormap@context=\pgfutil@empty
	% this does also init @H:
	\expandafter\pgfplots@createcolormap@startloop\pgfplots@loc@TMPa\pgfplots@EOI
	\expandafter\pgfplotsarraycheckempty\expandafter{\pgfplots@createcolormap@name}%
	% sanity checking:
	\expandafter\pgfplotsarraysizetomacro\expandafter{\pgfplots@createcolormap@name}\to\pgfplots@loc@TMPa
	\ifcase\pgfplots@loc@TMPa\relax
		\pgfplots@error{Sorry, you need to provide at least two points of a colormap.}%
	\or
		\pgfplots@error{Sorry, you need to provide at least two points of a colormap.}%
	\fi
	% Map the input range [0pt,MAX] linearly to [0,1000]
	\pgfmathdivide@{\pgfplotscolormaprange}{\pgfplots@createcolormap@MAX}%
	\let\pgfplots@loc@TMPb=\pgfmathresult
	\pgfmathmultiply@{\pgfplots@loc@TMPb}{\pgfplots@createcolormap@H}%
	\let\pgfplots@createcolormap@H=\pgfmathresult
	\expandafter\let\csname\pgfplots@createcolormap@name @h\endcsname=\pgfplots@createcolormap@H
	\pgfmathreciprocal@{\pgfplots@createcolormap@H}%
	\expandafter\let\csname\pgfplots@createcolormap@name @invh\endcsname=\pgfmathresult
	%
	\endpgfplotscolornormalizesequence%
	\expandafter\let\csname\pgfplots@createcolormap@name @colspace\endcsname=\pgfplotsretval
	\expandafter\let\csname\pgfplots@createcolormap@name @col@comps\endcsname=\pgfplotsretvalb
%\pgfplots@colormap@showdebuginfofor{#1}%
}


\def\pgfplots@createcolormap@initcolorspace{%
	\pgfplotscolornormalizesequence[
		colorspace=\pgfkeysvalueof{/pgfplots/colormap default colorspace},
		context message=\pgfplots@createcolormap@context,
	]%
}%
\def\pgfplots@createcolormap@seth[#1]{%
	\def\pgfplots@createcolormap@context{[#1]}%
	\pgfmathparse{#1}%
	\let\pgfplots@createcolormap@H=\pgfmathresult
	\pgfplots@createcolormap@
}%

\def\pgfplots@createcolormap@startloop{%
	\pgfutil@ifnextchar[%
		{\pgfplots@createcolormap@seth}%
		{%
			\let\pgfplots@createcolormap@H=\pgfutil@empty
		 	\pgfplots@createcolormap@
		}%
}%
\def\pgfplots@createcolormap@{%
	\pgfutil@ifnextchar\pgfplots@EOI{\pgfutil@gobble}%done!
	{%
		\pgfutil@ifnextchar;{\pgfplots@createcolormap@grabsemicolon}%
		{%
			\expandafter\pgfutil@ifnextchar\pgfplots@activesemicolon{\pgfplots@createcolormap@grabsemicolon@active}%
			{%
				\pgfplots@createcolormap@grabnext
			}%
		}%
	}%
}
\def\pgfplots@createcolormap@error#1#2\pgfplots@EOI{%
	{%
		\t@pgfplots@toka={#1#2}%
		\t@pgfplots@tokb={#1}%
		\pgfplots@error{Illformed colormap specification: I could not read the substring `\the\t@pgfplots@toka' starting at `\the\t@pgfplots@tokb'}%
	}%
}%

\def\pgfplots@createcolormap@grabnext#1({%
	\pgfplots@createcolormap@grabnext@{#1}%
}
\def\pgfplots@createcolormap@grabnext@#1#2){%
	\pgfutil@in@={#1}%
	\ifpgfutil@in@
		% Ah. we do not have a position, i.e. we have
		%   color=(green)
		% or something like this.
		%
		% this here defines \pgfplots@loc@TMPa to contain the
		% colorspace:
		\pgfplots@createcolormap@grabnext@remove@equal@sign#1\pgfplots@EOI
		%
		\pgfplots@createcolormap@grabnext@computenextposition
		\let\pgfplots@loc@TMPb=\pgfmathresult% posisiton
		\def\pgfplots@loc@TMPc{#2}% color data
		\let\pgfplots@loc@TMPd=\pgfplots@createcolormap@grabnext@complete
	\else
		% Ah. We have something like 'color(1cm)' and we did not see
		% the equal sign so far.
		\def\pgfplots@loc@TMPa{#1}% colorspace
		\def\pgfplots@loc@TMPb{#2}% position
		%
		% and collect the color data:
		\def\pgfplots@loc@TMPd{%
			\pgfutil@ifnextchar={%
				\pgfplots@createcolormap@grabnext@@
			}{%
				\pgfplots@createcolormap@error#1(#2)%
			}%
		}%
	\fi
	\pgfplots@loc@TMPd
}%

\def\pgfplots@createcolormap@grabnext@remove@equal@sign#1=#2\pgfplots@EOI{%
	\def\pgfplots@loc@TMPa{#1}%
	%
	% FIXME : what if #2 is not empty!?
}%

\def\pgfplots@createcolormap@grabnext@@={%
	\pgfutil@ifnextchar({%
		\pgfplots@createcolormap@grabnext@@@
	}{%
		\pgfplots@createcolormap@error=%
	}%
}%
\def\pgfplots@createcolormap@grabnext@@@(#1){%
	\def\pgfplots@loc@TMPc{#1}%
	\pgfplots@createcolormap@grabnext@complete
}%

\def\pgfplots@createcolormap@grabnext@complete{%
	\edef\pgfplots@loc@TMPa{%
		{\pgfplots@loc@TMPb}% position
		{%
		\pgfplots@loc@TMPa% colorspace
		=\pgfplots@loc@TMPc% color data
		}%
	}%
	\expandafter\pgfplots@createcolormap@nextcolor\pgfplots@loc@TMPa
	%
	% continue loop:
	\pgfplots@createcolormap@
}%

\def\pgfplots@createcolormap@grabnext@computenextposition{%
	% determine next step size automatically:
	\expandafter\pgfplotsarraycheckempty\expandafter{\pgfplots@createcolormap@name}%
	\ifpgfplotsarrayempty
		% first: must be at 0.
		\def\pgfmathresult{0sp}%
	\else
		% not first:
		\ifx\pgfplots@createcolormap@H\pgfutil@empty
			% ah; we really have to deduce something. We are at the
			% second node:
			\def\pgfmathresult{1cm}%
		\else
			\pgfmathadd@\pgfplots@createcolormap@LAST\pgfplots@createcolormap@H
		\fi
	\fi
}%

\def\pgfplots@createcolormap@grabsemicolon;{\pgfplots@createcolormap@}%

{
	\catcode`\;=13
	\gdef\pgfplots@createcolormap@grabsemicolon@active;{\pgfplots@createcolormap@}%
}

\def\pgfplots@createcolormap@nextcolor@tostring#1=#2\pgfplots@EOI#3{%
	#1(#3)=(#2)%
}%

% #1: h
% #2: a compound element of the form
% '<colorspace>=<comma-separated-color-components>'
%  The format is chosen such that it can be forwarded directly to
%  \pgfplotscolornormalizesequencenext
%
% see  \pgfplotscolornormalizesequencenext for details
\def\pgfplots@createcolormap@nextcolor#1#2{%
	\def\pgfplots@createcolormap@context{\pgfplots@createcolormap@nextcolor@tostring#2\pgfplots@EOI{#1}}%
	%
	\pgfplotscolornormalizesequencenext{#2}%
	\let\pgfplots@createcolormap@col@comps=\pgfplotsretvalb
	%
	\edef\pgfplots@loc@TMPa{{#1}{\pgfplotsretval}}%
	\expandafter\pgfplots@createcolormap@nextcolor@\pgfplots@loc@TMPa%
}%
\def\pgfplots@createcolormap@nextcolor@#1#2{%
%\message{processing color #1=(#2)^^J}%
	% compute 'h':
	\pgfmathparse{#1}%
	\let\pgfplots@createcolormap@MAX=\pgfmathresult
	\expandafter\pgfmathsubtract@\expandafter{\pgfmathresult}{\pgfplots@createcolormap@LAST}%
	\let\pgfplots@createcolormap@H@cur=\pgfmathresult
%\message{found current diff  = \pgfplots@createcolormap@H@cur\ ( from \pgfplots@createcolormap@MAX pt - \pgfplots@createcolormap@LAST pt)^^J}%
	\let\pgfplots@createcolormap@LAST=\pgfplots@createcolormap@MAX
	\ifx\pgfplots@createcolormap@H\pgfutil@empty
		\expandafter\pgfplotsarraycheckempty\expandafter{\pgfplots@createcolormap@name}%
		\ifpgfplotsarrayempty
			\ifdim\pgfplots@createcolormap@MAX pt=0pt
			\else
				\pgfplots@error{Sorry, the left end of a colormap (at 0pt) must be provided explicitly. You cannot start with \pgfplots@createcolormap@MAX pt. The error occured near `\pgfplots@createcolormap@context'}%
				\def\pgfplots@createcolormap@MAX{0}%
			\fi
		\else
			\let\pgfplots@createcolormap@H=\pgfplots@createcolormap@H@cur
%\message{H := \pgfplots@createcolormap@H( from #1).}%
		\fi
	\else
		\pgfmathapproxequalto@{\pgfplots@createcolormap@H}{\pgfplots@createcolormap@H@cur}%
		\ifpgfmathcomparison
		\else
			\pgfmathdivide@{\pgfplots@createcolormap@H@cur}{\pgfplots@createcolormap@H}%
			% after this group, \pgfmathresult is
			% - empty if no reinterpolation is possible,
			% - non-empty if reinterpolation IS possible. In this
			%   case, it contains the integer multiple of H.
			\begingroup
				\afterassignment\pgfplots@createcolormap@nextRGB@consider@reinterpolation
				\c@pgf@counta=\pgfmathresult\relax
				\pgfmath@smuggleone\pgfmathresult
			\endgroup
			\ifx\pgfmathresult\pgfutil@empty
				% I can't do that yet.
			\else
				\let\pgfplots@createcolormap@loop@end=\pgfmathresult
				% interpolate missing values using the already fixed H.
				% This interpolation procedure is stupid because it works
				% only in forward direction - but it works at least.
				% For the backwards direction, you can provide the
				% meshwidth explicitly at
				% \pgfplotscreatecolormap{}{[1pt]}
				\pgfplotsforeachungrouped \c@pgfplots@createcolormap in {1,2,...,\pgfplots@createcolormap@loop@end} {%
					\ifdim\c@pgfplots@createcolormap pt=\pgfplots@createcolormap@loop@end pt %
						% omit the last.
					\else
						\pgfmathparse{\c@pgfplots@createcolormap/\pgfplots@createcolormap@loop@end}%
						\let\pgfplots@createcolormap@scale@current=\pgfmathresult
						\pgfmathparse{1-\pgfplots@createcolormap@scale@current}%
						\let\pgfplots@createcolormap@scale@last=\pgfmathresult
						%
						\pgfplotscolornormalizesequencezero
						\pgfplotscolornormalizesequenceaddweighted
							{\pgfplotsretval}
							{\pgfplots@createcolormap@scale@current}
							{#2}%
						\pgfplotscolornormalizesequenceaddweighted
							{\pgfplotsretval}
							{\pgfplots@createcolormap@scale@last}
							{\pgfplots@createcolormap@last}%
						%
%\message{interpolation step \c@pgfplots@createcolormap = \pgfplotsretval^^J}%
						\edef\pgfplots@loc@TMPa{%
							\noexpand\pgfplotsarraypushback{\pgfplotsretval}%
							\noexpand\to}%
						\expandafter\pgfplots@loc@TMPa\expandafter{\pgfplots@createcolormap@name}%
					\fi
				}%
			\fi
		\fi
	\fi
	\edef\pgfplots@loc@TMPa{\noexpand\pgfplotsarraypushback{#2}\noexpand\to}%
	\expandafter\pgfplots@loc@TMPa\expandafter{\pgfplots@createcolormap@name}%
	\edef\pgfplots@createcolormap@last{#2}%
}%
\def\pgfplots@createcolormap@nextRGB@consider@reinterpolation#1\relax{%
	\pgf@xa=#1pt
	\ifdim\pgf@xa>0.5pt % we have something like 99.995 or so.
		% round up and compute 1 - #1:
		\advance\c@pgf@counta by1
		\pgf@xa=1pt \advance\pgf@xa by-#1pt
	\fi
	%
	% compute relative error:
	\pgf@xb=\the\c@pgf@counta pt
	\divide\pgf@xb by10000
%\message{Checking  H/h = \pgfplots@createcolormap@H@cur pt/\pgfplots@createcolormap@H pt = \the\c@pgf@counta+-\pgf@sys@tonumber\pgf@xa\space:  \the\pgf@xa > \the\pgf@xb\space (relative to \the\c@pgf@counta)?}%
	%
	\ifdim\pgf@xa>\pgf@xb
		\pgfplots@error{Sorry, non-uniform colormaps are only partially implemented, yet: the provided points must be multiples of the mesh width h=\pgfplots@createcolormap@H pt (but I found one with H/h = \pgfplots@createcolormap@H@cur pt/\pgfplots@createcolormap@H pt = \the\c@pgf@counta+-\pgf@sys@tonumber\pgf@xa\space which is no integer). Perhaps it helps to provide the mesh widths as argument as in {<name>}{[1cm] <color arguments>}? The error occured near `\pgfplots@createcolormap@context'}%
		\let\pgfmathresult=\pgfutil@empty
	\else
		\ifnum\c@pgf@counta=0
			\let\pgfmathresult=\pgfutil@empty
		\else
			\edef\pgfmathresult{\the\c@pgf@counta}%
		\fi
	\fi
}%

% Shows debug info about colormap #1 into the console.
\def\pgfplots@colormap@showdebuginfofor#1{%
	\message{Debug info for color map '#1':^^J}%
	\message{(Transformed) Range: [0:\pgfplotscolormaprange];  ^^J}%
	\message{H: \csname pgfpl@cm@#1@h\endcsname;    ^^J}%
	\message{H:^{-1}: \csname pgfpl@cm@#1@invh\endcsname;    ^^J}%
	\pgfplotsarraysizetomacro{pgfpl@cm@#1}\to\pgfplots@loc@TMPa
	\message{Size: \pgfplots@loc@TMPa;    ^^J}%
	\message{Colorspace: \csname pgfpl@cm@#1@colspace\endcsname^^JValues (\csname pgfpl@cm@#1@col@comps\endcsname\space components each): ^^J}%
	\begingroup
	\c@pgf@counta=0
	\pgfplotsarrayforeachungrouped{pgfpl@cm@#1}\as\elem{%
		\message{\#\the\c@pgf@counta: \elem; }%
		\advance\c@pgf@counta by1
	}%
	\message{^^J}%
	\endgroup
}

% Defines \pgfplotsretval to contain the mesh width of colormap #1
\def\pgfplotscolormapgetmeshwidth#1{%
	\expandafter\let\expandafter\pgfplotsretval\csname pgfpl@cm@#1@h\endcsname%
}%

% defines macro #2 to contain a serialized variant of the color
% components (only the color components!)
\def\pgfplotscolormapserializecomponentstomacro#1#2{%
	\pgfplotsapplistXnewempty\pgfplots@serialize@list@
	\pgfplotsarrayforeachungrouped{pgfpl@cm@#1}\as\elem{%
		\expandafter\pgfplotsapplistXpushback\expandafter{\elem},\to\pgfplots@serialize@list@
	}%
	\pgfplotsapplistXlet#2=\pgfplots@serialize@list@
}%

% Copies the contents of the colormap named '#1' into a macro '#2'.
% Invocation of the macro will then re-create the colormap.
%
% #1: color map name
% #2: a macro name
\def\pgfplotscolormapserializetomacro#1#2{%
	\begingroup
		\pgfplotscolormapserializecomponentstomacro{#1}\pgfplots@serialize@list
		\toks0={\expandafter\def\csname pgfpl@cm@#1@h\endcsname}%
		\toks1={\expandafter\def\csname pgfpl@cm@#1@invh\endcsname}%
		\toks2={%
			\pgfplotsarraynewempty{pgfpl@cm@#1}%
			\expandafter\pgfplotsutilforeachcommasep\pgfplots@loc@TMPa\as\pgfplots@loc@TMPb{%
				\ifx\pgfplots@loc@TMPb\pgfutil@empty
				\else
					\expandafter\pgfplotsarraypushback\pgfplots@loc@TMPb\to{pgfpl@cm@#1}%
				\fi
			}%
		}%
		\toks3=\expandafter{\pgfplots@serialize@list}%
		\toks4=\expandafter{\expandafter\def\csname pgfpl@cm@#1@colspace\endcsname}%
		\toks5=\expandafter{\expandafter\def\csname pgfpl@cm@#1@col@comps\endcsname}%
		\xdef\pgfplots@glob@TMPa{%
			\the\toks0 {\csname pgfpl@cm@#1@h\endcsname}%
			\the\toks1 {\csname pgfpl@cm@#1@invh\endcsname}%
			\noexpand\def\noexpand\pgfplots@loc@TMPa{\the\toks3 }%
			\the\toks2
			\the\toks4 {\csname pgfpl@cm@#1@colspace\endcsname}%
			\the\toks5 {\csname pgfpl@cm@#1@col@comps\endcsname}%
		}%
	\endgroup
	\let#2=\pgfplots@glob@TMPa
}%

% this is a CONSTANT! Do NOT change it!
% Just read it -- just in case \pgfplotscolormaptopdffunction will use
% a different upper bound in the future.
\def\pgfplotscolormappdfmax{1}%

% Writes a PDF function of /FunctionType 3 to \pgfplotsretval
%
% The /Domain argument will be set to [ 0 \pgfplotscolormappdfmax ] and bounds will be
% computed accordingly.
%
% #1: the colormap
\def\pgfplotscolormaptopdffunction#1{%
	\begingroup
	\gdef\pgfplotsretval{%
		<< 
			/FunctionType 3 
			/Domain [0 \pgfplotscolormappdfmax] 
	%		/Range [0 1 0 1 0 1] % INCOMPATIBLE WITH ACROBAT 6.0 !
			/Functions [ 
	}%
	\c@pgf@counta=0
	\c@pgf@countb=\pgfplotsarraysizeof{pgfpl@cm@#1} %
	\advance\c@pgf@countb by-1
	\def\pgfplots@loc@TMPa{}%
	\def\pgfplots@loc@TMPb{}%
	\def\pgfplots@loc@TMPc{}%
	\ifnum\csname pgfpl@cm@#1@col@comps\endcsname>4
		\pgfplots@error{Sorry, processing more than 4 color components (as required for color map #1) is unsupported in this context}%
	\fi
	\pgfplotsarrayforeachungrouped{pgfpl@cm@#1}\as\cdata{%
		\edef\cdata{%
			\expandafter
			\expandafter
			\csname pgfplotscolormaptopdffunction@convertcdata@\csname pgfpl@cm@#1@col@comps\endcsname\endcsname
			\cdata\relax
		}%
		\ifnum\c@pgf@counta>0
			\t@pgfplots@toka=\expandafter{\pgfplotsretval}%
			\xdef\pgfplotsretval{%
				\the\t@pgfplots@toka
				<<
					/FunctionType 2
					/Domain [0 \pgfplotscolormappdfmax] 
					/C0 [\pgfplots@loc@TMPa] /C1 [\cdata] /N 1
				>>
			}%
			\ifnum\c@pgf@counta<\c@pgf@countb\relax
				\pgf@xa=\csname pgfpl@cm@#1@h\endcsname pt
				\multiply\pgf@xa by\c@pgf@counta\relax
				\divide\pgf@xa by1000 % we want [ 0 1 ] not [0 1000] as domain
				\edef\pgfplots@loc@TMPb{\pgfplots@loc@TMPb\space \pgf@sys@tonumber\pgf@xa}%
			\fi
			\edef\pgfplots@loc@TMPc{\pgfplots@loc@TMPc\space 0 1}%
		\fi
		\let\pgfplots@loc@TMPa=\cdata
		\advance\c@pgf@counta by1
	}%
	\t@pgfplots@toka=\expandafter{\pgfplotsretval}%
	\xdef\pgfplotsretval{%
			\the\t@pgfplots@toka
			]
			/Bounds [\pgfplots@loc@TMPb]
			/Encode [\pgfplots@loc@TMPc]
		>>
	}%
	\endgroup
}%
\expandafter\def\csname pgfplotscolormaptopdffunction@convertcdata@1\endcsname#1\relax{#1}%
\expandafter\def\csname pgfplotscolormaptopdffunction@convertcdata@2\endcsname#1,#2\relax{#1 #2}%
\expandafter\def\csname pgfplotscolormaptopdffunction@convertcdata@3\endcsname#1,#2,#3\relax{#1 #2 #3}%
\expandafter\def\csname pgfplotscolormaptopdffunction@convertcdata@4\endcsname#1,#2,#3,#4\relax{#1 #2 #3 #4}%

% Invokes '#2' if a color map named '#1' exists and '#3' if no such color map exists.
\def\pgfplotscolormapifdefined#1#2#3{\pgfplotsarrayifdefined{pgfpl@cm@#1}{#2}{#3}}%

\def\pgfplotscolormapassertexists#1{%
	\pgfplotscolormapifdefined{#1}{}{%
		\pgfutil@ifundefined{pgfplotscolormap@errorissued@#1}{%
			\pgfplots@error{The colormap `#1' is undefined! Maybe you misspelled it?}%
		}{}%
		\expandafter\gdef\csname pgfplotscolormap@errorissued@#1\endcsname{1}%
		\pgfplotscreatecolormap{#1}{color(0cm)=(blue); color(1cm)=(yellow)}%
	}%
}

% Convert a colormap into a PGF shading's color specification for use
% in \pgfdeclare*shading.
%
% #1: the colormap's name.
% #2: the PGF "size" of the shading. It is used to set the right end
% of the color specification.
% #3: a macro which will be filled with the result.
%
% Example:
% \pgfplotscolormaptoshadingspec{my colormap}{4cm}{\output}
% \def\tempb{\pgfdeclarehorizontalshading{myshadingA}{1cm}}
% \expandafter\tempb\expandafter{\temp}	
%
% \pgfuseshading{myshadingA}
\def\pgfplotscolormaptoshadingspec#1#2#3{%
	\pgfplotscolormapassertexists{#1}%
	\begingroup
	\def\pgfplots@rgb{rgb}%
	\pgfmathparse{#2}%
	\expandafter\pgfmathdivide@\expandafter{\pgfmathresult}{\pgfplotscolormaprange}%
	\let\pgfplots@loc@TMPb=\pgfmathresult
	\pgfmathmultiply@{\csname pgfpl@cm@#1@h\endcsname}{\pgfplots@loc@TMPb}%
	\pgf@ya=\pgfmathresult pt
	\c@pgf@counta=0
	\let#3=\pgfutil@empty
	\pgfplotsarrayforeachungrouped{pgfpl@cm@#1}\as\pgfplotscolormaptoshadingspec@TMP{%
		\pgf@yb=\c@pgf@counta\pgf@ya
		\edef\pgfplots@colspace{\csname pgfpl@cm@#1@colspace\endcsname}%
		% FIXME : PGF shadings accept only RGB!
		\if1\pgfplotscolormaptoshadingspectorgb
			\ifx\pgfplots@colspace\pgfplots@rgb
			\else
				\pgfutil@ifundefined{pgfpl@cm@#1@warned}{%
					\expandafter\gdef\csname pgfpl@cm@#1@warned\endcsname{1}%
					\pgfplotswarning{lossy colormap rgb conversion}{#1}{\pgfplots@colspace}\pgfeov%
				}{%
				}%
				\edef\pgf@tempcolor{{\pgfplots@colspace}{\pgfplotscolormaptoshadingspec@TMP}}%
				\expandafter\pgfutil@convertcolorspec\pgf@tempcolor{rgb}{\pgfplotscolormaptoshadingspec@TMP}%
				\def\pgfplots@colspace{rgb}%
			\fi
		\fi
		\edef\pgfplots@loc@TMPc{\pgfplots@colspace(\the\pgf@yb)=(\pgfplotscolormaptoshadingspec@TMP)}%
		\ifx#3\pgfutil@empty
			\t@pgfplots@toka={}%
		\else
			\t@pgfplots@toka=\expandafter{#3; }%
		\fi
		\t@pgfplots@tokb=\expandafter{\pgfplots@loc@TMPc}%
		\edef#3{\the\t@pgfplots@toka \the\t@pgfplots@tokb }%
		\advance\c@pgf@counta by1
	}%
	\pgfmath@smuggleone#3%
	\endgroup
}%
\def\pgfplotscolormaptoshadingspectorgb{1}%

% The same as \pgfplotscolormaptoshadingspec, but this here yields the
% *reversed* sequence.
\def\pgfplotscolormapreversedtoshadingspec#1#2#3{%
	\begingroup
	\let\pgfplotsarrayforeachungrouped=\pgfplotsarrayforeachreversedungrouped
	\pgfplotscolormaptoshadingspec{#1}{#2}{#3}%
	\pgfmath@smuggleone#3%
	\endgroup
}%


% Expands to the transformed range's right end of every colormap. The left
% end is fixed to '0'.
\def\pgfplotscolormaprange{1000}

\def\pgfplotscolormapgetcolorspace#1{%
	\edef\pgfplotsretval{\csname pgfpl@cm@#1@colspace\endcsname}%
}%
\def\pgfplotscolormapgetcolorcomps#1{%
	\edef\pgfplotsretval{\csname pgfpl@cm@#1@col@comps\endcsname}%
}%


% Linearly maps the number #4 into the colormap #5 and returns the
% interpolated colors into \pgfmathresult. The result will be a triple
% for an RGB colormap and it will contain four numbers for CMYK. The
% components of the result will be in the range [0:1].
% 
% [#1:#2]  the number range of the data source (i.e. of #4). This is required to
%          map into the colormap.
% [#3]     (optional) the quantity 
% 			 s := \pgfplotscolormaprange / (#2-#1).
% 		   Precomputing this quantity may save a lot of time because
% 		   divisions are expensive in TeX. You can omit [#3] or
% 		   provide an empty string here.
% #4       the number to map.
% #5       the colormap's name. Must be defined with
%          \pgfplotscreatecolormap before.
%
% Example:
% \pgfplotscolormapfind[-1:1]{0.2}{my colormap}
\def\pgfplotscolormapfind[#1:#2]{%
	\pgfutil@ifnextchar[{%
		\pgfplotscolormapfind@precomputed[#1:#2]%
	}{%
		\pgfplotscolormapfind@precomputed[#1:#2][]%
	}%
}%
\def\pgfplotscolormapfind@precomputed[#1:#2][#3]#4#5{%
	\pgfplotscolormapassertexists{#5}%
	\begingroup
	% Step 0: compute #3 if it is missing and write it into
	% \pgfplots@loc@TMPa.
	\def\pgfplots@loc@TMPa{#3}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\pgfmathsubtract@{#2}{#1}%
		\let\pgfplots@loc@TMPb=\pgfmathresult
		\pgfmathdivide@{\pgfplotscolormaprange}{\pgfplots@loc@TMPb}%
		\let\pgfplots@loc@TMPa=\pgfmathresult
	\fi
%\message{mapping '#4' into colormap '#5' ... ^^J}%
	\def\pgfplots@loc@samerange{0:1000}%
	\ifx\pgfplots@loc@TMPa\pgfplots@loc@samerange
		% we have phi(#4) = #4  because #4 in [0:1000].
		\def\pgfmathresult{#4}%
	\else
		% Step 1: perform lookup. Map #4 into the colormap's range
		% using the linear trafo
		% phi(#4) = ( #4 - #1 ) / (#2-#1) * colormaprange(#5).
		% This, determine the INTERVAL number into which #4 falls.
		\pgfmathsubtract@{#4}{#1}%
		\expandafter\pgfmathmultiply@\expandafter{\pgfmathresult}{\pgfplots@loc@TMPa}%
	\fi
	\ifdim\pgfmathresult pt<0pt
		\def\pgfmathresult{0}%
	\else
		\ifdim\pgfmathresult pt>1000pt
			\def\pgfmathresult{1000}%
		\fi
	\fi
	\let\pgfplotscolormapfind@transformedx=\pgfmathresult
	\expandafter\pgfmathmultiply@\expandafter{\pgfmathresult}{\csname pgfpl@cm@#5@invh\endcsname}%
	\let\pgfplotscolormapfind@transformedx@divh=\pgfmathresult
	\expandafter\pgfmathfloor@\expandafter{\pgfmathresult}%
	% assign \pgfplotscolormapfind@intervalno := \pgfmathresult
	% without '.0' suffix:
	\def\pgfplots@discardperiod##1.##2\relax{\def\pgfplotscolormapfind@intervalno{##1}}%
	\expandafter\pgfplots@discardperiod\pgfmathresult\relax
	\pgfmathsubtract@{\pgfplotscolormapfind@transformedx@divh}{\pgfplotscolormapfind@intervalno}%
	\let\pgfplots@loc@factor=\pgfmathresult
	\pgfmathsubtract@{1}{\pgfplots@loc@factor}%
	\let\pgfplots@loc@factor@two=\pgfmathresult
	% Step 2: interpolate the desired RGB value using vector valued
	% interpolation on the identified interval.
	\c@pgf@counta=\pgfplotscolormapfind@intervalno\relax
%\message{mapping [#1,#2] -> [0,\pgfplotscolormaprange]  yielded phi(#4) = \pgfplotscolormapfind@transformedx, situated in interval no \the\c@pgf@counta.^^J}%
	\pgfplotsarrayselect\c@pgf@counta\of{pgfpl@cm@#5}\to\pgfplotscolormapfind@rgb@LEFT
	%
	\pgfplotsarraysize{pgfpl@cm@#5}\to\c@pgf@countb
	\advance\c@pgf@countb-1 %
	\ifnum\c@pgf@counta<\c@pgf@countb
		% Ah: (selected index < length-1)  . That means: we have an interval.
		\advance\c@pgf@counta by1
		\pgfplotsarrayselect\c@pgf@counta\of{pgfpl@cm@#5}\to\pgfplotscolormapfind@rgb@RIGHT
%\message{After lookup: the corresponding RGB interval boundaries are [\pgfplotscolormapfind@rgb@LEFT: \pgfplotscolormapfind@rgb@RIGHT].^^J}%
		%
		%
		% color^m(x) = ( x/h - i ) * ( c_{i+1}^m - c_{i}^m ) + c_i^m 
		%            = s * c_{i+1}^m  + S * c_i^m
		%
		%  s= x_h / h -i 
		%  S = 1 - s
		\pgfplotscolorzero{\csname pgfpl@cm@#5@col@comps\endcsname}%
		\pgfplotscoloraddweighted
			{\csname pgfpl@cm@#5@col@comps\endcsname}
			{\pgfplotsretval}%
			{\pgfplots@loc@factor@two}%
			{\pgfplotscolormapfind@rgb@LEFT}%
		\pgfplotscoloraddweighted
			{\csname pgfpl@cm@#5@col@comps\endcsname}
			{\pgfplotsretval}%
			{\pgfplots@loc@factor}%
			{\pgfplotscolormapfind@rgb@RIGHT}%
		\let\pgfmathresult=\pgfplotsretval
	\else
		% Ah: selected index = last index. Use the rightmost color!
		\let\pgfmathresult=\pgfplotscolormapfind@rgb@LEFT
	\fi
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
%\message{-> got finally mapping(#4, #5) = RGB'\pgfmathresult'.}%
}%


% Performs a direct color access into color map '#2' using an index
% '#1'.
%
% #1: an index in the range 0 ... len(#2)-1.
%  If it does not match, it will be pruned. If #1 is a real number, it
%  will be truncated.
% #2: a color map name.
%
% The resulting RGB value will be written to \pgfmathresult.
\def\pgfplotscolormapgetindex#1#2{%
	\pgfplotscolormapassertexists{#2}%
	\begingroup
	\afterassignment\pgfplots@gobble@until@relax
	\c@pgf@counta=#1\relax
	\ifnum\c@pgf@counta<0
		\c@pgf@counta=0
	\else
		\pgfplotsarraysizetomacro{pgfpl@cm@#2}\to\pgfplotscolormapgetindex@
		\ifnum\c@pgf@counta<\pgfplotscolormapgetindex@\relax
		\else
			\c@pgf@counta=\pgfplotscolormapgetindex@\relax
			\advance\c@pgf@counta by-1
		\fi
	\fi
	\pgfplotsarrayselect\c@pgf@counta\of{pgfpl@cm@#2}\to\pgfmathresult
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}

% Invokes either \pgfplotscolormapfind or \pgfplotscolormapgetindex,
% depending on the value of '/pgfplots/colormap access'.
\def\pgfplotscolormapaccess[#1:#2]{%
	\pgfutil@ifnextchar[{%
		\pgfplotscolormapaccess@precomputed[#1:#2]%
	}{%
		\pgfplotscolormapaccess@precomputed[#1:#2][]%
	}%
}
\def\pgfplotscolormapaccess@precomputed[#1:#2][#3]#4#5{%
	\if m\pgfplots@colormap@access
		\pgfplotscolormapfind@precomputed[#1:#2][#3]{#4}{#5}%
	\else
		\pgfplotscolormapgetindex{#4}{#5}%
	\fi
}%


\pgfutil@definecolor{mapped color}{rgb}{0,0,0}% make sure this color exists. It will be overwritten if needed.
% ATTENTION: replicated in pgfplots.code.tex :
\pgfplotscreatecolormap{hot}{color(0cm)=(blue); color(1cm)=(yellow); color(2cm)=(orange); color(3cm)=(red)}

\def\pgfplotspointmetatransformedrange{0:1000}

% Defines the 'mapped color' on the basis of
% the current color map.
%
% #1: is the value which should be mapped into the color map; it
% is expected in the range [0,1000] (like point meta).
\def\pgfplotscolormapdefinemappedcolor#1{%
	\expandafter\pgfplotscolormapaccess\expandafter[\pgfplotspointmetatransformedrange]
		[1.0]
		{#1}
		{\pgfkeysvalueof{/pgfplots/colormap name}}
%\message{Color for current point is RGB '\pgfmathresult' (determined using meta 'phi(\pgfplotspointmeta) = \pgfplotspointmetatransformed')^^J}%
	\def\pgfplots@loc@TMPb{\pgfutil@definecolor{mapped color}{\csname pgfpl@cm@\pgfkeysvalueof{/pgfplots/colormap name}@colspace\endcsname}}%
	\expandafter\pgfplots@loc@TMPb\expandafter{\pgfmathresult}%
}%


pgfplotscoordprocessing.code.tex
%--------------------------------------------
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2007-2010 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------

% This file contains the code to process coordinates
% - coordinate input: \addplot and its variants,
% - coordinate loops,
% - single coordinate processing
%
%   -> see \pgfplots@addplot


% To be called inside of an axis as soon as the axis is ready and all
% point commands can be invoked.
\def\pgfplotspoint@initialisation{%
	\expandafter\global\expandafter\let\csname pgfplotspointouternormalvectorofaxis@cache@v00\endcsname\relax
	\expandafter\global\expandafter\let\csname pgfplotspointouternormalvectorofaxis@cache@v01\endcsname\relax
	\expandafter\global\expandafter\let\csname pgfplotspointouternormalvectorofaxis@cache@v10\endcsname\relax
	\expandafter\global\expandafter\let\csname pgfplotspointouternormalvectorofaxis@cache@v11\endcsname\relax
	\expandafter\global\expandafter\let\csname pgfplotspointouternormalvectorofaxis@cache@0v0\endcsname\relax
	\expandafter\global\expandafter\let\csname pgfplotspointouternormalvectorofaxis@cache@0v1\endcsname\relax
	\expandafter\global\expandafter\let\csname pgfplotspointouternormalvectorofaxis@cache@1v0\endcsname\relax
	\expandafter\global\expandafter\let\csname pgfplotspointouternormalvectorofaxis@cache@1v1\endcsname\relax
	\expandafter\global\expandafter\let\csname pgfplotspointouternormalvectorofaxis@cache@00v\endcsname\relax
	\expandafter\global\expandafter\let\csname pgfplotspointouternormalvectorofaxis@cache@01v\endcsname\relax
	\expandafter\global\expandafter\let\csname pgfplotspointouternormalvectorofaxis@cache@10v\endcsname\relax
	\expandafter\global\expandafter\let\csname pgfplotspointouternormalvectorofaxis@cache@11v\endcsname\relax
	%
	% Installs e_x, e_y and e_z such that (0,0) is the 'south west'
	% anchor of the axis and (1,1) the 'north east'.
	% It is used inside of descriptions.
	\def\pgfplots@install@description@xyzvec{%
		% this here is also used in color bars!
		\ifpgfplots@deprecated@anchors
			\pgfpointadd{\pgfplotspointxaxis}{\pgfplotspointyaxis}%
		\else
			\pgfplotspointbbdiagonal
		\fi
		\pgf@xa=\pgf@x
		\pgf@ya=\pgf@y
		% do not use \pgfqpoint here - it may have been replaced
		% (compare \pgfplots@change@pgfpoints@to@descriptioncs)
		\pgfsetxvec{\global\pgf@x=\pgf@xa \global\pgf@y=0pt }%
		\pgfsetyvec{\global\pgf@x=0pt     \global\pgf@y=\pgf@ya}%
		\pgfsetzvec{\global\pgf@x=0pt     \global\pgf@y=0pt }%
	}%
	%
	% The \pgfplotsqpointxyz method (or its 2d counterpart) are THE
	% point method. If you override them, all other coordinate systems
	% should inherit the changes as well.
	\edef\pgfplotsplothandlerpointxyz##1##2##3{%
		\ifpgfplots@curplot@threedim
			\noexpand\pgfplotsqpointxyz{##1}{##2}{##3}%
		\else
			\noexpand\pgfplotsqpointxy{##1}{##2}%
		\fi
	}%
	%
	% A point command such that (0,0) is the 'south west' and (1,1)
	% the 'north east' point of an axis.
	\def\pgfplotspointdescriptionxy##1##2{%
		\pgf@process{%
			\pgfplots@install@description@xyzvec
			\pgfpointadd
				{\ifpgfplots@deprecated@anchors
					\pgfplotspointminminmin
				\else
					\pgfplotspointbblowerleft
				\fi}%
				{\pgfpointxy@orig{##1}{##2}}% 
				%I use the '@orig' variant here because descriptions may 
				%\let\pgfpointxy=\pgfplotspointdescriptionxy
		}%
	}%
	% the 'q' variant:
	\def\pgfplotsqpointdescriptionxy##1##2{%
		\pgf@process{%
			\pgfplots@install@description@xyzvec
			\pgfpointadd
				{\ifpgfplots@deprecated@anchors
					\pgfplotspointminminmin
				\else
					\pgfplotspointbblowerleft
				\fi}%
				{\pgfqpointxy@orig{##1}{##2}}% 
		}%
	}%
	\pgfplotspoint@initialisation@axes
	\pgfplotspoint@initialisation@units
	\pgfplotspoint@initialisation@center
	%
	% declare the '[xyz]ticklabel cs'
	\tikzdeclarecoordinatesystem{xticklabel}{\pgfplotspointticklabelcs{x}{##1}}%
	\tikzdeclarecoordinatesystem{yticklabel}{\pgfplotspointticklabelcs{y}{##1}}%
	\tikzdeclarecoordinatesystem{zticklabel}{\pgfplotspointticklabelcs{z}{##1}}%
	\tikzdeclarecoordinatesystem{xticklabel*}{\pgfplotspointticklabelnoshiftcs{x}{##1}}%
	\tikzdeclarecoordinatesystem{yticklabel*}{\pgfplotspointticklabelnoshiftcs{y}{##1}}%
	\tikzdeclarecoordinatesystem{zticklabel*}{\pgfplotspointticklabelnoshiftcs{z}{##1}}%
	%
	% does also declare the 'near xticklabel*' variants.
	\pgfplotsdeclareborderanchorforticklabelaxis{x}{near xticklabel}%
	\pgfplotsdeclareborderanchorforticklabelaxis{y}{near yticklabel}%
	\pgfplotsdeclareborderanchorforticklabelaxis{z}{near zticklabel}%
	%
	\pgfkeysdef{/tikz/sloped like x axis}{\tikz@addtransform{\pgfplotstransformtoaxisdirection[##1]{x}}}%
	\pgfkeysdef{/tikz/sloped like y axis}{\tikz@addtransform{\pgfplotstransformtoaxisdirection[##1]{y}}}%
	\pgfkeysdef{/tikz/sloped like z axis}{\tikz@addtransform{\pgfplotstransformtoaxisdirection[##1]{z}}}%
	%
}%

% Determine final  axes this does also fix the axis' dimension.
% There are the following cases: 
% 1. the user really wants a fixed dimension,
%    i.e. he used 'scale only axis'.
%    Then, we have to work to get the correct dimension!
%
%    Up to now, the scaling mechanism looses to many significant
%    digits such that the final width/height differs by 1-2 pt.
%
%    If I am not mistaken, this does ONLY affect the final size,
%    not the relative plot precision.
%    
%    FIXME : really compute the plot precision!
% 
% 2. The use specified width and/or height, but not 'scale only
%    axis'. Accept inaccurate final widths/heights (see above).
%
% 3. The user supplied 'x' and or 'y'. Simply use them, its
% accurate.
% POSTCONDITION: the macros
% 	\pgfplotspointminminmin
% 	\pgfplotspoint[xyz]axis
% 	\pgfplotspoint[xyz]axislength
%   are defined (globally).
%
\def\pgfplotspoint@initialisation@axes{%
	\begingroup
	\ifpgfplots@threedim
		\def\pgfplotspointmaxminmin{\pgfplotsqpointxyz{\pgfplots@xmax}{\pgfplots@ymin}{\pgfplots@zmin}}%
		\def\pgfplotspointminmaxmin{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymax}{\pgfplots@zmin}}%
		\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymin}{\pgfplots@zmin}%
	\else
		\def\pgfplotspointmaxminmin{\pgfplotsqpointxy{\pgfplots@xmax}{\pgfplots@ymin}}%
		\def\pgfplotspointminmaxmin{\pgfplotsqpointxy{\pgfplots@xmin}{\pgfplots@ymax}}%
		\pgfplotsqpointxy{\pgfplots@xmin}{\pgfplots@ymin}%
	\fi
	\xdef\pgfplotspointminminmin{\noexpand\pgf@x=\the\pgf@x\space\noexpand\pgf@y=\the\pgf@y\space}%
	% ATTENTION: I re-use registers here! Make sure they won't be
	% overwritten! \pgfpointdiff and \pgfplotsqpointxy are ok in this respect.
	\let\pgfplots@xcoordminTEX=\pgf@xb
	\let\pgfplots@ycoordminTEX=\pgf@yb
	\pgfplots@xcoordminTEX=\pgf@x
	\pgfplots@ycoordminTEX=\pgf@y
	%
	%--------------------------------------------------
	% FIXME : WHAT IS THIS HERE FOR? 
	% \pgfplotsqpointxy{\pgfplots@xmax}{\pgfplots@ymax}%
	% \ifx\pgfplots@rectangle@width\pgfutil@empty
	% 	\def\pgfplots@tmp@xmax@ymin{\pgfplotsqpointxy{\pgfplots@xmax}{\pgfplots@ymin}}%
	% \else
	% 	% this 'if' here should only make a difference of about
	% 	% 1-2pt, not more.
	% 	%
	% 	% and I am quite sure that this inaccuracy (and this
	% 	% work-around) only affects the
	% 	% final size, not the relative plot accuracy.
	% 	\pgf@x=\pgfplots@xcoordminTEX
	% 	\advance\pgf@x by\pgfplots@width
	% 	\edef\pgfplots@tmp@xmax@ymin{\noexpand\pgfqpoint{\the\pgf@x}{\noexpand\pgfplots@ycoordminTEX}}%
	% \fi
	% \ifx\pgfplots@rectangle@height\pgfutil@empty
	% 	\def\pgfplots@tmp@xmin@ymax{\pgfplotsqpointxy{\pgfplots@xmin}{\pgfplots@ymax}}%
	% \else
	% 	\pgf@x=\pgfplots@ycoordminTEX
	% 	\advance\pgf@x\pgfplots@height
	% 	\edef\pgfplots@tmp@xmin@ymax{\noexpand\pgfqpoint{\noexpand\pgfplots@xcoordminTEX}{\the\pgf@x}}%
	% \fi
	%-------------------------------------------------- 
	\pgfpointdiff
		{\pgfqpoint{\pgfplots@xcoordminTEX}{\pgfplots@ycoordminTEX}}
		{\pgfplotspointmaxminmin}%
	\xdef\pgfplotspointxaxis{\noexpand\pgf@x=\the\pgf@x\space\noexpand\pgf@y=\the\pgf@y\space}%
	\pgfmathveclen{\pgf@x}{\pgf@y}%
	\xdef\pgfplotspointxaxislength{\pgfmathresult pt}%
	%
	\pgfpointdiff
		{\pgfqpoint{\pgfplots@xcoordminTEX}{\pgfplots@ycoordminTEX}}
		{\pgfplotspointminmaxmin}%
	\xdef\pgfplotspointyaxis{\noexpand\pgf@x=\the\pgf@x\space\noexpand\pgf@y=\the\pgf@y\space}%
	\pgfmathveclen{\pgf@x}{\pgf@y}%
	\xdef\pgfplotspointyaxislength{\pgfmathresult pt}%
	%
	\ifpgfplots@threedim
		\pgfpointdiff
			{\pgfqpoint{\pgfplots@xcoordminTEX}{\pgfplots@ycoordminTEX}}
			{\pgfplotsqpointxyz{\pgfplots@xmin}{\pgfplots@ymin}{\pgfplots@zmax}}%
		\xdef\pgfplotspointzaxis{\noexpand\pgf@x=\the\pgf@x\space\noexpand\pgf@y=\the\pgf@y\space}%
		\pgfmathveclen{\pgf@x}{\pgf@y}%
		\xdef\pgfplotspointzaxislength{\pgfmathresult pt}%
	\else
		\global\let\pgfplotspointzaxis=\pgfpointorigin
		\gdef\pgfplotspointzaxislength{0pt}%
	\fi
	\endgroup
	%
}

% PRECONDITION: called after \pgfplotspoint@initialisation@axes
% POSTCONDITION:
% 	\pgfplotspointcenter is defined.
\def\pgfplotspoint@initialisation@center{%
	\begingroup
	%
	%
	\ifpgfplots@threedim
		%
		\pgfpointscale
			{0.5}%
			{\pgfplotspointxaxis
			\pgf@xa=\pgf@x
			\pgf@xb=\pgf@y
			\pgfplotspointyaxis%
			\advance\pgf@xa by\pgf@x
			\advance\pgf@xb by\pgf@y
			\pgfplotspointzaxis%
			\advance\pgf@xa by\pgf@x
			\advance\pgf@xb by\pgf@y
			\pgf@x=\pgf@xa
			\pgf@y=\pgf@xb
			}%
		\xdef\pgfplotspointcenter{\noexpand\pgf@x=\the\pgf@x\space\noexpand\pgf@y=\the\pgf@y\space}%
	\else
		\pgfpointscale
			{0.5}%
			{\pgfpointadd
				\pgfplotspointxaxis%
				\pgfplotspointyaxis%
			}%
		\xdef\pgfplotspointcenter{\noexpand\pgf@x=\the\pgf@x\space\noexpand\pgf@y=\the\pgf@y\space}%
	\fi
	\endgroup
}

% PRECONDITION:
% 	the unit vectors are set up
%
% POSTCONDITION:
% 	\pgfplotspointunit[xyz]
% 	\pgfplotspointunit[xyz]length
% 	\pgfplotspointunit[xyz]invlength
% 	are all set up.
\def\pgfplotspoint@initialisation@units{%
	\edef\pgfplotspointunitx{\pgf@x=\the\pgf@xx\space\pgf@y=\the\pgf@xy\space}%
	\edef\pgfplotspointunity{\pgf@x=\the\pgf@yx\space\pgf@y=\the\pgf@yy\space}%
	\let\pgfplotsunitxlength=\pgfplots@x@veclength
	\let\pgfplotsunitylength=\pgfplots@y@veclength
	\let\pgfplotsunitxinvlength=\pgfplots@x@inverseveclength
	\let\pgfplotsunityinvlength=\pgfplots@y@inverseveclength
	\ifpgfplots@threedim
		\edef\pgfplotspointunitz{\pgf@x=\the\pgf@zx\space\pgf@y=\the\pgf@zy\space}%
		\let\pgfplotsunitzlength=\pgfplots@z@veclength
		\let\pgfplotsunitzinvlength=\pgfplots@z@inverseveclength
	\fi
}%

% The idea here is the following:
%
% 1. A point coordinate (<x>,<y>) without units should use
% relative axis coordinate system.
%
% 2. Any other point coordinate should not be altered.
%
% Former versions installed a shift and changed e_x, e_y and
% e_z. However, that was misleading as it disabled point 2). 
% So, my idea here is to replace \pgfpointxy and \pgfqpointxy
% such that they install the correct coordinate system before
% doing anything else.
\def\pgfplots@change@pgfpoints@to@descriptioncs{%
	%
	\let\pgfpointxy=\pgfplotspointdescriptionxy
	\let\pgfqpointxy=\pgfplotsqpointdescriptionxy
	% e_z is zero, so the xyz variants ignore z:
	\def\pgfpointxyz##1##2##3{\pgfpointxy{##1}{##2}}%
	\def\pgfqpointxyz##1##2##3{\pgfqpointxy{##1}{##2}}%
	%
}%

% \pgfplotspointticklabelcs{<axis>}{<coordinate>}
% or
% \pgfplotspointticklabelcs[<default shift>]{<axis>}{<coordinate>}
%
% Yields a point in the '<axis>ticklabel cs'.
%
% The 'xticklabel cs' is a coordinate system which expects either one
% or two coordinates. The first is the coordinate on the axis where
% x tick label will be placed (or would be placed). The first
% coordinate '0' means the lower aixs site and the value '1' the upper
% range. The second (optional) coordinate of 'xticklabel cs' is a
% shift in direction of the outer normal vector of the axis. The
% minimum shift is the largest' tick labels dimensions. If the second
% argument is omitted, the <default shift> will be used (0pt if this
% argument has been omitted as well).
%
% \pgfplotspointticklabelcs#1#2: 
% #1 is the axis (either x,y or z)
% #2 is the coordinate (either <relative coord> or <relative coord>,<shift>)
%
% @see \pgfplotsvalueoflargesttickdimen
%
% This command actually boils down to a
% \pgfplotsqpointoutsideofticklabelaxisrel
% invocation which. Thus, you *can* get the *same* effect by using
% basic level commands -- and you are not restricted to the tick label
% axis.
% @see \pgfplotsqpointoutsideofaxisrel
\def\pgfplotspointticklabelcs{\pgfutil@ifnextchar[%
	{\pgfplotspointticklabelcs@opt}%
	{\pgfplotspointticklabelcs@opt[0pt]}%
}%
\def\pgfplotspointticklabelcs@opt[#1]#2#3{%
	\pgfutil@in@{,}{#3}%
	\ifpgfutil@in@
		\edef\pgfplots@loc@TMPa{#3}%
	\else
		\edef\pgfplots@loc@TMPa{#3,#1}%
	\fi
	\def\pgfplots@loc@TMPb##1,##2\relax{%
		% invoke
		% \pgfplotsqpointoutsideofticklabelaxisrel{#2}{##1}{ticklabel dimen + ##2}:
		\begingroup
			\pgfmathparse{##2}%
			\pgf@xa=\pgfmathresult pt\relax
			\advance\pgf@xa by\pgfplotsvalueoflargesttickdimen{#2} %<- keep this space!
			\xdef\pgfplots@glob@TMPa{\pgf@sys@tonumber\pgf@xa}%
		\endgroup
		\def\pgfplots@loc@TMPa{\pgfplotsqpointoutsideofticklabelaxisrel{#2}{##1}}%
		\expandafter\pgfplots@loc@TMPa\expandafter{\pgfplots@glob@TMPa}%
	}%
	\expandafter\pgfplots@loc@TMPb\pgfplots@loc@TMPa\relax
}%

\def\pgfplotspointticklabelnoshiftcs#1#2{%
	\pgfutil@in@{,}{#2}%
	\ifpgfutil@in@
		\edef\pgfplots@loc@TMPa{#2}%
	\else
		\edef\pgfplots@loc@TMPa{#2,0}%
	\fi
	\def\pgfplots@loc@TMPb##1,##2\relax{%
		% invoke
		% \pgfplotsqpointoutsideofticklabelaxisrel{#2}{##1}{##2}:
		\pgfmathparse{##2}%
		\def\pgfplots@loc@TMPa{\pgfplotsqpointoutsideofticklabelaxisrel{#1}{##1}}%
		\expandafter\pgfplots@loc@TMPa\expandafter{\pgfmathresult}%
	}%
	\expandafter\pgfplots@loc@TMPb\pgfplots@loc@TMPa\relax
}%


% Converts a dimen (with unit!) to a corresponding x, y or z
% coordinate.
% The result will be written to \pgfmathresult (without units).
%
% It is possible to use the result within the \pointxyz command(s).
%
% #1: the axis (x,y or z)
% #2: the dimen
%
% example:
% \pgfplotsconvertunittocoordinate{x}{5pt}
\def\pgfplotsconvertunittocoordinate#1#2{%
	\begingroup
	\pgf@xa=#2\relax
	\pgf@xa=\csname pgfplots@#1@inverseveclength\endcsname\pgf@xa
	\edef\pgfmathresult{\pgf@sys@tonumber\pgf@xa}%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%

% This is the same as using \pgfplotsconvertunittocoordinate for each
% component #1, #2 and #3. The results are directly communicated to
% \pgfplotsqpointxyz.
%
% Expects #1, #2 and #3 to be numbers with units and issues a \pgfplotsqpointxyz 
\def\pgfplotsqpointxyzabsolutesize#1#2#3{%
	\begingroup
	\pgf@xa=#1\relax
	\pgf@xa=\pgfplots@x@inverseveclength\pgf@xa
	\pgf@xb=#2\relax
	\pgf@xb=\pgfplots@y@inverseveclength\pgf@xb
	\pgf@ya=#3\relax
	\pgf@ya=\pgfplots@z@inverseveclength\pgf@ya
	\xdef\pgfplots@glob@TMPa{{\pgf@sys@tonumber\pgf@xa}{\pgf@sys@tonumber\pgf@xb}{\pgf@sys@tonumber\pgf@ya}}%
	\endgroup
	\expandafter\pgfplotsqpointxyz\pgfplots@glob@TMPa
}%

% Denotes a point in a twodimensional hyperplane. The hyperplane is
% one of the six planes of the threedimensional axis cube.
% 
% The meaning of coordinates #1 and #2 will be redefined depending on
% which surface we are currently processing. You can get the axis
% names for '#1' (a) and '#2' (b) using the macros
% \pgfplotspointonorientedsurfaceA (one of the characters x,y or z)
% and
% \pgfplotspointonorientedsurfaceB.
% The surface normal direction is
% \pgfplotspointonorientedsurfaceN.
%
% Example:
% \pgfplotspointonorientedsurfaceabsetupfor xyz
% \pgfplotspointonorientedsurfaceabsetupforsetz{<lower z limit>}{0}
%
% ->
%  \pgfplotspointonorientedsurfaceA = x
%  \pgfplotspointonorientedsurfaceB = y
%  \pgfplotspointonorientedsurfaceN = z
%  \pgfplotspointonorientedsurfacespec = {ab0}
%  \pgfplotspointonorientedsurfacespecunordered = {vv0}
%  \pgfplotspointonorientedsurfaceab{3}{4} =\pgfqpointxyz{3}{4}{<lower z limit>}
%
% \pgfplotspointonorientedsurfaceabsetupfor yxz
% \pgfplotspointonorientedsurfaceabsetupforsetz{<lower z limit>}{0}
% ->
%  \pgfplotspointonorientedsurfaceA = y
%  \pgfplotspointonorientedsurfaceB = x
%  \pgfplotspointonorientedsurfaceN = z
%  \pgfplotspointonorientedsurfacespec = {ba0}
%  \pgfplotspointonorientedsurfacespecunordered = {vv0}
%  \pgfplotspointonorientedsurfaceab{3}{4} =\pgfqpointxyz{4}{3}{<lower z limit>}
%
% @see \pgfplotspointonorientedsurfaceabsetupfor xyz
\def\pgfplotspointonorientedsurfaceab#1#2{%
	\pgfplots@error{Internal logic error: \string\pgfplotspointonorientedsurfaceab\ used although surface has not been declared! You need to call \string\pgfplotspointonorientedsurfaceabsetupfor xyz\ or its friends to do so.}%
}%

% This is a shortcut for 
% \pgfpointadd
% 	{\pgfplotspointonorientedsurfaceab{#1}{#2}}
% 	{<shift in B direction of #3>}
%
% where #3 is a dimension (a number with unit).
\def\pgfplotspointonorientedsurfaceabwithbshift#1#2#3{%
	\begingroup
	\pgf@xa=#3\relax
	\ifdim\pgf@xa=0pt
	\else
		\pgf@xa=\csname pgfplots@\pgfplotspointonorientedsurfaceB @inverseveclength\endcsname\pgf@xa
	\fi
	\advance\pgf@xa by#2pt
	\edef\pgfplots@loc@b{\pgf@sys@tonumber\pgf@xa}%
	\pgf@process{\pgfplotspointonorientedsurfaceab{#1}{\pgfplots@loc@b}}%
	\endgroup
}

\pgfkeyssetvalue{/pgfplots/oriented surf installed}{}

% This macro will be defined after
% \pgfplotspointonorientedsurfaceabsetupfor...
% routines. It expands to a three-character string 
% where the first character contains information about the x axis,
% the second about the y axis and the third about the z axis.
%
% The single characters can be one of
% - 'a'  - the corresponding axis is the PRIMARY direction of the
%   oriented surface.
% - 'b'  - the corresponding axis is the SECONDARY direction of the
%   oriented surface.
% - anything else - the characters provides as second argument for
%   \pgfplotspointonorientedsurfaceabsetupforsetz{}{}, for example.
%   Common choices are '0' for lower limit, '1' for upper limit and
%   '2' for other.
\def\pgfplotspointonorientedsurfacespec{}%

% Similar to \pgfplotspointonorientedsurfacespec, this macro encodes
% the currently active oriented surface.
% However, it only contains the characters 'v', '0' and '1' and '2'.
% The distinction 'v in {a,b}' is eliminated.
\def\pgfplotspointonorientedsurfacespecunordered{}%

% As \pgfplotspointonorientedsurfacespec, this macro contains
% information about the current oriented surface: it contains the
% fixed symbol '0', '1' or '2' describing the only direction which is
% fixed.
\def\pgfplotspointonorientedsurfacespecsymbol{\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol}

\def\pgfplotspointonorientedsurfaceabsetupfor#1#2#3{%
	\pgfutil@ifundefined{pgfplotspointonorientedsurfaceabsetupfor@@#1#2#3}{%
		\pgfplots@error{Sorry, \string\pgfplotspointonorientedsurfaceabsetupfor\space#1#2#3 is not yet implemented.}%
	}{
		\csname pgfplotspointonorientedsurfaceabsetupfor@@#1#2#3\endcsname
	}%
}%
%
% Initialises \pgfplotspointonorientedsurfaceab such that 'a' is the x
% axis and 'b' is the y axis and the z coordinate has been fixed with
% \pgfplotspointonorientedsurfaceabsetupforsetz{}.
%
% The Z value needs to be fixed with 
% \pgfplotspointonorientedsurfaceabsetupforsetz .
\def\pgfplotspointonorientedsurfaceabsetupfor@@xyz{%
	\def\pgfplotspointonorientedsurfaceab##1##2{\pgfplotsqpointxyz{##1}{##2}{\pgfplotspointonorientedsurfaceabsetupfor@fixedz}}%
	\def\pgfplotspointonorientedsurfaceA{x}%
	\def\pgfplotspointonorientedsurfaceB{y}%
	\def\pgfplotspointonorientedsurfaceN{z}%
	\edef\pgfplotspointonorientedsurfacespec{ab\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol}%
	\edef\pgfplotspointonorientedsurfacespecunordered{vv\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol}%
	\pgfkeysvalueof{/pgfplots/oriented surf installed}%
}%
\def\pgfplotspointonorientedsurfaceabsetupfor@@yxz{%
	\def\pgfplotspointonorientedsurfaceab##1##2{\pgfplotsqpointxyz{##2}{##1}{\pgfplotspointonorientedsurfaceabsetupfor@fixedz}}%
	\def\pgfplotspointonorientedsurfaceA{y}%
	\def\pgfplotspointonorientedsurfaceB{x}%
	\def\pgfplotspointonorientedsurfaceN{z}%
	\edef\pgfplotspointonorientedsurfacespec{ba\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol}%
	\edef\pgfplotspointonorientedsurfacespecunordered{vv\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol}%
	\pgfkeysvalueof{/pgfplots/oriented surf installed}%
}%
\def\pgfplotspointonorientedsurfaceabsetupfor@@xzy{%
	\def\pgfplotspointonorientedsurfaceab##1##2{\pgfplotsqpointxyz{##1}{\pgfplotspointonorientedsurfaceabsetupfor@fixedy}{##2}}%
	\def\pgfplotspointonorientedsurfaceA{x}%
	\def\pgfplotspointonorientedsurfaceB{z}%
	\def\pgfplotspointonorientedsurfaceN{y}%
	\edef\pgfplotspointonorientedsurfacespec{a\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol b}%
	\edef\pgfplotspointonorientedsurfacespecunordered{v\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol v}%
	\pgfkeysvalueof{/pgfplots/oriented surf installed}%
}%
\def\pgfplotspointonorientedsurfaceabsetupfor@@zxy{%
	\def\pgfplotspointonorientedsurfaceab##1##2{\pgfplotsqpointxyz{##2}{\pgfplotspointonorientedsurfaceabsetupfor@fixedy}{##1}}%
	\def\pgfplotspointonorientedsurfaceA{z}%
	\def\pgfplotspointonorientedsurfaceB{x}%
	\def\pgfplotspointonorientedsurfaceN{y}%
	\edef\pgfplotspointonorientedsurfacespec{b\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol a}%
	\edef\pgfplotspointonorientedsurfacespecunordered{v\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol v}%
	\pgfkeysvalueof{/pgfplots/oriented surf installed}%
}%
\def\pgfplotspointonorientedsurfaceabsetupfor@@yzx{%
	\def\pgfplotspointonorientedsurfaceab##1##2{\pgfplotsqpointxyz{\pgfplotspointonorientedsurfaceabsetupfor@fixedx}{##1}{##2}}%
	\def\pgfplotspointonorientedsurfaceA{y}%
	\def\pgfplotspointonorientedsurfaceB{z}%
	\def\pgfplotspointonorientedsurfaceN{x}%
	\edef\pgfplotspointonorientedsurfacespec{\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol ab}%
	\edef\pgfplotspointonorientedsurfacespecunordered{\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol vv}%
	\pgfkeysvalueof{/pgfplots/oriented surf installed}%
}%
\def\pgfplotspointonorientedsurfaceabsetupfor@@zyx{%
	\def\pgfplotspointonorientedsurfaceab##1##2{\pgfplotsqpointxyz{\pgfplotspointonorientedsurfaceabsetupfor@fixedx}{##2}{##1}}%
	\def\pgfplotspointonorientedsurfaceA{z}%
	\def\pgfplotspointonorientedsurfaceB{y}%
	\def\pgfplotspointonorientedsurfaceN{x}%
	\edef\pgfplotspointonorientedsurfacespec{\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol ba}%
	\edef\pgfplotspointonorientedsurfacespecunordered{\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol vv}%
	\pgfkeysvalueof{/pgfplots/oriented surf installed}%
}%

% Fixes 'x' to #1 for use in
% \pgfplotspointonorientedsurfaceabsetupfor zyx and 
% \pgfplotspointonorientedsurfaceabsetupfor yzx.
%
% #1: The fixed value for 'x' (a coordinate in transformed range).
% #2: a one-character symbol describing 'x'.
% Command characters are
% 	 0 : x is the lower x-axis range.
% 	 1 : x is the upper x-axis range.
% 	 2 : other.
\def\pgfplotspointonorientedsurfaceabsetupforsetx#1#2{%
	\edef\pgfplotspointonorientedsurfaceabsetupfor@fixedx{#1}%
	\edef\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol{#2}%
}%
\def\pgfplotspointonorientedsurfaceabsetupforsety#1#2{%
	\edef\pgfplotspointonorientedsurfaceabsetupfor@fixedy{#1}%
	\edef\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol{#2}%
}%
\def\pgfplotspointonorientedsurfaceabsetupforsetz#1#2{%
	\edef\pgfplotspointonorientedsurfaceabsetupfor@fixedz{#1}%
	\edef\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol{#2}%
}%

% Helper methods which should be used if no Z component exists (pure
% 2d plots).
\def\pgfplotspointonorientedsurfaceabsetupfor@@xy{%
	\def\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol{0}%
	\def\pgfplotspointonorientedsurfaceab##1##2{\pgfplotsqpointxy{##1}{##2}}%
	\def\pgfplotspointonorientedsurfaceA{x}%
	\def\pgfplotspointonorientedsurfaceB{y}%
	\def\pgfplotspointonorientedsurfaceN{z}%
	\edef\pgfplotspointonorientedsurfacespec{ab\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol}%
	\edef\pgfplotspointonorientedsurfacespecunordered{vv\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol}%
	\pgfkeysvalueof{/pgfplots/oriented surf installed}%
}%
\def\pgfplotspointonorientedsurfaceabsetupfor@@yx{%
	\def\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol{0}%
	\def\pgfplotspointonorientedsurfaceab##1##2{\pgfplotsqpointxy{##2}{##1}}%
	\def\pgfplotspointonorientedsurfaceA{y}%
	\def\pgfplotspointonorientedsurfaceB{x}%
	\def\pgfplotspointonorientedsurfaceN{z}%
	\edef\pgfplotspointonorientedsurfacespec{ba\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol}%
	\edef\pgfplotspointonorientedsurfacespecunordered{vv\pgfplotspointonorientedsurfaceabsetupfor@fixedsymbol}%
	\pgfkeysvalueof{/pgfplots/oriented surf installed}%
}%


% Assuming we have an oriented surface installed, this command defines
% \pgfplotsretval to be the three-char-string such that the 'a' axis
% if the oriented surface takes value '#1', the 'b' axis of the
% oriented surface takes '#2' and the remaining axis has its fixed
% symbol anyway.
\def\pgfplotspointonorientedsurfaceabtolinespec#1#2{%
	\expandafter\pgfplotspointonorientedsurfaceabtolinespec@a\pgfplotspointonorientedsurfacespec\relax#1%
	\expandafter\pgfplotspointonorientedsurfaceabtolinespec@b\pgfplotsretval\relax#2%
}%
\def\pgfplotspointonorientedsurfaceabtolinespec@a#1a#2\relax#3{\edef\pgfplotsretval{#1#3#2}}
\def\pgfplotspointonorientedsurfaceabtolinespec@b#1b#2\relax#3{\edef\pgfplotsretval{#1#3#2}}

% Assuming that an oriented surface has been initialised, say 'a0b',
% we have the following possible axis lines which can be drawn:
% - b=0: 'v00'
% - b=1: 'v01'
% - b=2: 'v02'
%
% To check which of them should be drawn, this macro here converts 'a'
% to 'v' and 'b' to '#1'. The remaining possible character will be
% copied as-is.
%
% The resulting three-character-string is written into '#2'.
%
% #1 : the replacement value which will be inserted instead of 'b' in
% the currently active oriented surface.
% #2 : the macro which will contain the output axis line specification
% (three-char-string).
% 
% Example:
% \pgfplotspointonorientedsurfaceabsetupfor xyz
% \pgfplotspointonorientedsurfaceabsetupforsetz{<lower z limit>}{0}
% -> the oriented surface is 'ab0'
%  ...
% \pgfplotspointonorientedsurfaceabgetcontainedaxisline{0}\pgfplotsretval
% -> \pgfplotsretval = 'v00'
% \pgfplotspointonorientedsurfaceabgetcontainedaxisline{1}\pgfplotsretval
% -> \pgfplotsretval = 'v10'
% \pgfplotspointonorientedsurfaceabgetcontainedaxisline{2}\pgfplotsretval
% -> \pgfplotsretval = 'v20'
\def\pgfplotspointonorientedsurfaceabgetcontainedaxisline#1#2{%
	\expandafter\pgfplotspointonorientedsurfaceabgetcontainedaxisline@\pgfplotspointonorientedsurfacespec\relax{#1}%
	\let#2=\pgfplots@loc@TMPa
}%
% writes into \pgfplots@loc@TMPa:
\def\pgfplotspointonorientedsurfaceabgetcontainedaxisline@#1#2#3\relax#4{%
	\pgfplotspointonorientedsurfaceabgetcontainedaxisline@single{#1}{#4}\to\pgfplots@loc@TMPa
	\pgfplotspointonorientedsurfaceabgetcontainedaxisline@single{#2}{#4}\to\pgfplots@loc@TMPb
	\pgfplotspointonorientedsurfaceabgetcontainedaxisline@single{#3}{#4}\to\pgfplots@loc@TMPc
	\edef\pgfplots@loc@TMPa{\pgfplots@loc@TMPa\pgfplots@loc@TMPb\pgfplots@loc@TMPc}%
}%
\def\pgfplotspointonorientedsurfaceabgetcontainedaxisline@single#1#2\to#3{%
	\if#1a%
		\def#3{v}%
	\else
		\if#1b%
			\def#3{#2}%
		\else
			\def#3{#1}%
		\fi
	\fi
}%


% Finds the two surfaces which are adjacent to an axis line encoded as
% three-character-string.
%
% There are the following possibilities:
% #1 = 'v**' where '*' is not 'v'.
% 	-> #2 = 'vv*'  and #3 = 'v*v'
%
% #1 = '*v*'
% 	-> #2 = 'vv*'  and #3 = '*vv'
%
% #1 = '**v'
% 	-> #2 = 'v*v'  and #3 = '*vv'
\def\pgfplotsgetadjacentsurfsforaxisline#1\to#2#3{%
	\edef\pgfplots@loc@TMPa{#1}%
	\expandafter\pgfplotsgetadjacentsurfsforaxisline@\pgfplots@loc@TMPa\relax{#2}{#3}%
}%
\def\pgfplotsgetadjacentsurfsforaxisline@#1#2#3\relax#4#5{%
	\if#1v%
		\def#4{vv#3}%
		\def#5{v#2v}%
	\else
		\if#2v%
			\def#4{vv#3}%
			\def#5{#1vv}%
		\else
			\def#4{v#2v}%
			\def#5{#1vv}%
		\fi
	\fi
}%

% Executes code '#2' if the axis surface denoted by the
% three-character-string '#1' is a foreground surface and code '#3' if
% the surface '#1' is a background surface.
%
% #1: a three-char-string with the keys 
% 	'v' = 'varying', 
% 	'0' = 'lower axis limit',
% 	'1' = 'upper axis limit'.
% 	The string 'v0v' means that x and z are varying in that surface
% 	and 'y' is fixed to the lower axis limit.
% #2: code to execute if '#1' is foreground.
% #3: code to execute if '#1' is background.
\def\pgfplotsifaxissurfaceisforeground#1#2#3{%
	\pgfutil@ifundefined{pgfplots@surfviewdepth@#1}{%
		\pgfplots@error{\string\pgfplotsifaxissurfaceisforeground{#1}: undefined three-character-string '#1' provided.}%
		#3%
	}{%
		\if f\csname pgfplots@surfviewdepth@#1\endcsname #2\else #3\fi
	}%
}%

% As \pgfplotsifaxissurfaceisforeground, but for axis lines.
%
% #1: a three-character string with the same keys as in
% \pgfplotsifaxissurfaceisforeground. However, there should be only
% one varying direction as we are dealing with an axis line.
% #2: code to execute if '#1' is foreground.
% #3: code to execute if '#1' is background.
%
\def\pgfplotsifaxislineisforeground#1#2#3{%
	\pgfplotsgetadjacentsurfsforaxisline#1\to\pgfplots@loc@TMPb\pgfplots@loc@TMPc
	\pgfplotsifaxissurfaceisforeground{\pgfplots@loc@TMPb}{%
		#2%
	}{%
		\pgfplotsifaxissurfaceisforeground{\pgfplots@loc@TMPc}{%
			#2%
		}{%
			#3%
		}%
	}%
}%
% Executes code '#2' if the axis surface denoted by the
% three-char-string '#1' is on the convex hull of the projected axis
% cube or code '#3' if that is not the case.
%
% The arguments are the same as for \pgfplotsifaxislineisforeground:
% #1: a three-character string with the same keys as in
% \pgfplotsifaxissurfaceisforeground. However, there should be only
% one varying direction as we are dealing with an axis line.
% #2: code to execute if '#1' is foreground.
% #3: code to execute if '#1' is background.
\def\pgfplotsifaxislineisonconvexhull#1#2#3{%
	\pgfplotsgetadjacentsurfsforaxisline#1\to\pgfplots@loc@TMPb\pgfplots@loc@TMPc
	% '#1' is on the convex hull if ONE of the adjacent surfs is
	% foreground and the other one is background.
	\pgfplots@loc@tmpfalse
	\pgfplotsifaxissurfaceisforeground{\pgfplots@loc@TMPb}{%
		\pgfplotsifaxissurfaceisforeground{\pgfplots@loc@TMPc}{%
		}{%
			\pgfplots@loc@tmptrue
		}%
	}{%
	}%
	\pgfplotsifaxissurfaceisforeground{\pgfplots@loc@TMPb}{%
	}{%
		\pgfplotsifaxissurfaceisforeground{\pgfplots@loc@TMPc}{%
			\pgfplots@loc@tmptrue
		}{%
		}%
	}%
	\ifpgfplots@loc@tmp #2\else #3\fi
}%

% Executes code '#2' if the axis line with 'b=#1' on the current
% oriented surface shall be drawn.
% If that is not the case, the code '#3' will be executed.
%
% Example:
% Let's assume the current oriented surface is 'b0a'.
% Then,
%   \pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn{0}{draw it!}{\relax}
% will check whether the line '00v' shall be drawn while
%   \pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn{1}{draw it!}{\relax}
% will check whether the line '10v' shall be drawn.
%
% The check is based on
% 1. foreground/background flags
% 2. the current configuration of the axis lines key(s)
%
% @see \pgfplotspointonorientedsurfaceabgetcontainedaxisline
\def\pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn#1#2#3{%
	\pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn@{#1}{%
		\edef\pgfplots@loc@TMPe{\csname pgfplots@\pgfplotspointonorientedsurfaceA axislinesnum\endcsname}%
		\if0\pgfplots@loc@TMPe
			% boxed axis lines
			#2%
		\else
			\if2\pgfplots@loc@TMPe
				% centered axis lines
				#2%
			\else
				% either the 'left' or 'right' positioned cases.
				% These have exactly one line which is the one where
				% tick labels will be placed. And this, in turn, is
				% already known, even for 3D. Check if we have it:
				\pgfplotspointonorientedsurfaceabtolinespec v#1%
				\edef\pgfplots@loc@TMPe{\csname pgfplots@\pgfplotspointonorientedsurfaceA ticklabelaxisspec\endcsname}%
				\ifx\pgfplots@loc@TMPe\pgfplotsretval
					#2%
				\else
					#3%
				\fi
			\fi
		\fi
	}{%
		#3%
	}%
}%
\def\pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn@allaxislinevariations#1#2#3{%
	\pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn@{#1}{%
		#2%
	}{%
		#3%
	}%
}%

% A sub-part of \pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn
% which is /only/ based on foreground/background flags.
%
% @ATTENTION : this command will be always true for the 2D case. (it
% will be overwritten, see \pgfplots@decide@which@figure@surfaces@are@drawn)
\def\pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn@#1#2#3{%
	\pgfplotspointonorientedsurfaceabgetcontainedaxisline#1\pgfplots@loc@TMPc
	\pgfplotsgetadjacentsurfsforaxisline\pgfplots@loc@TMPc\to\pgfplots@loc@TMPb\pgfplots@loc@TMPc
	\pgfplotsifaxissurfaceisforeground{\pgfplots@loc@TMPb}{%
		\pgfplotsifaxissurfaceisforeground{\pgfplots@loc@TMPc}{%
			#3%
		}{%
			#2%
		}%
	}{%
		#2%
	}%
}%

% Similar to \pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn,
% this thing here execute '#1' if grid lines on the currently
% initialised oriented surfaces shall be drawn and '#2' if not.
%
% This does only handle foreground/background issues; it has NOTHING
% to do with the actual checks if grid lines are active or not.
\def\pgfplots@ifgridlines@onorientedsurf@should@be@drawn#1#2{%
	% grid lines shall be drawn 
	% if and only if BOTH adjacent axis lines shall be drawn:
	\pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn@allaxislinevariations{0}{%
		% remark: this is ALWAYS true for 2D plots.
		\pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn@allaxislinevariations{1}{%
			#1%
		}{%
			#2%
		}%
	}{%
		#2%
	}%
}%

% Checks whether the line specified by a three-character-string '#1'
% is inside of the currently set-up oriented surface.
%
% The return value is encoded as integer into the macro #2 as
% described below.
%
% #1 : a three-character string uniquely identifing an axis line.
%      Each of the three characters can be 'v', '0' or '1'.
%      The value '0' denotes the lower axis range while '1' denotes
%      the upper axis range. The character 'v' stands for 'varying'
%      and indicates the direction in which the line varies. The first
%      character contains the values for the 'x' axis, the second
%      character for the 'y' axis and the third character for the 'z'
%      axis.
%      Example:
%      	'v01' is the axis line with 'y=lower y limit' and 'z=upper z limit'
%      	'10v' is the axis line with 'x=upper x limit' and 'y=lower y limit'
%      The 'v' character indicates the varying component. There may be
%      only one 'v'.
% #2 : a macro name. It will be empty if the line is NOT on the
% 		current surface. If will be non-empty if it IS on the current
% 		surface.
% 		To be more precise, If the line IS on the current surface, '#2' will be set to
% 		the character in '#1' which belongs to the second oriented
% 		surface axis (which is called the 'b' axis).
% 		Thus, the following values for '#2' can be expected:
% 		- '' (empty) if the line is not on the surface,
% 		- 'v' if the line IS on the surface, and '#1' contains a 'v' 
% 		in direction of the surface's 'b' axis.
% 		- '0' if the line IS on the surface and '#1' contains a '0' in
% 		direction of the surface's 'b' axis,
% 		- '1' if the line IS on the surface and '#1' contains a '1' in
% 		direction of the surface's 'b' axis.
% 		No other values are possible.
%
% 		Example:
% 		\pgfplotspointonorientedsurfaceabsetupforsetz{\zmax}{1}
% 		\pgfplotspointonorientedsurfaceabsetupfor yxz
% 		\pgfplotspointonorientedsurfaceabmatchaxisline{v01}{\result}
% 		-> \result will be 'v' because 'x=v' in '{v01}
%
% 		\pgfplotspointonorientedsurfaceabsetupforsety{\ymin}{0}
% 		\pgfplotspointonorientedsurfaceabsetupfor xzy
% 		\pgfplotspointonorientedsurfaceabmatchaxisline{v01}{\result}
% 		-> \result will be '1' because 'z=1' in '{v01}
%
% 		\pgfplotspointonorientedsurfaceabsetupforsety{\ymax}{1}
% 		\pgfplotspointonorientedsurfaceabsetupfor xzy
% 		\pgfplotspointonorientedsurfaceabmatchaxisline{v01}{\result}
% 		-> \result will be empty because 'y=0' in '{v01}
%
% 		\pgfplotspointonorientedsurfaceabsetupforsetx{\xmax}{1}
% 		\pgfplotspointonorientedsurfaceabsetupfor yzx
% 		\pgfplotspointonorientedsurfaceabmatchaxisline{10v}{\result}
% 		-> \result will be 'v' because 'z=v' in '{10v}
\def\pgfplotspointonorientedsurfaceabmatchaxisline#1#2{%
	\pgfplotsmatchcubeparts{#1}{\pgfplotspointonorientedsurfacespec}{#2}%
}%

% Checks whether the line or surface specified by a three-character-string '#1'
% is inside of the surface designated by the three-character-string '#2'.
%
%
% Arguments:
% #1  a cube-part (axis line or surface) encoded as three character
%     string. Can be '0v1' or 'vv0' or so (see above).
% #2  a surface, also  encoded as three character string. Maybe
%     oriented.
% #3  The return value is encoded as char into the macro #3 as
%     described in \pgfplotspointonorientedsurfaceabmatchaxisline:
%     '#3' will be EMPTY if '#1' is NOT in '#2'.
%     '#3' will be NON-EMPTY if '#1' IS in '#2'.
\def\pgfplotsmatchcubeparts#1#2#3{%
	\edef\pgfplots@loc@TMPa{#1:#2}%
	\expandafter\pgfplotspointonorientedsurfaceabmatchaxisline@\pgfplots@loc@TMPa\pgfplots@EOI
	\let#3=\pgfplots@loc@TMPa
}%

% IMPLEMENTATION: 
% The return value is 'yes, #1#2#3 is on the oriented surface #4#5#6'
% if and only if for all three character pairs, the following single
% relations hold.
% Input char   oriented surface char
%  'v' :         is either a or b or v
%  '0' :         is either 0, a, b, v or 2 (i.e. NOT 1) FIXME : is the '2' correct here!?
%  '1' :         is either 1, a, b, v or 2 (i.e. NOT 0)
%  '2' :         is either 2, a, b, v (i.e. NOT 0 or 1)
% That's all. 
%
% If the 'oriented surface char' is 'v', then we actually don't have
% an oriented surface but just a surface.
% So, 'a0b' is the same surface as 'v0v', but the first choice has
% designated orientations.
%
% @POST \pgfplots@loc@TMPa contains the return value macro.
%   More precisely, \pgfplots@loc@TMPa will be EMPTY is #1#2#3 is NOT
%   on #4#5#6 . It will contain the value on the surface if it IS on
%   the surface
\def\pgfplotspointonorientedsurfaceabmatchaxisline@#1#2#3:#4#5#6\pgfplots@EOI{%
	% Search for the 'b' character:
	\if#4b%
		\def\pgfplots@loc@TMPa{#1}%
	\else
		\if#5b%
			\def\pgfplots@loc@TMPa{#2}%
		\else
			\if#6b%
				\def\pgfplots@loc@TMPa{#3}%
			\else
				\def\pgfplots@loc@TMPa{v}% FALLBACK solution.
			\fi
		\fi
	\fi
	% Now, check whether we need to clear the return value (i.e.
	% return false)
	\pgfplotspointonorientedsurfaceabmatchaxisline@single{#1}{#4}%
	\pgfplotspointonorientedsurfaceabmatchaxisline@single{#2}{#5}%
	\pgfplotspointonorientedsurfaceabmatchaxisline@single{#3}{#6}%
%\message{\string\pgfplotspointonorientedsurfaceabmatchaxisline@#1#2#3:#4#5#6 = '\pgfplots@loc@TMPa'.^^J}%
}
\def\pgfplotspointonorientedsurfaceabmatchaxisline@single#1#2{%
	\if#1v%
		\if#2a%
		\else
			\if#2b%
			\else
				\if#2v%
				\else
					\let\pgfplots@loc@TMPa=\pgfutil@empty
				\fi
			\fi
		\fi
	\else
		\if0#1%
			\if1#2%
				\let\pgfplots@loc@TMPa=\pgfutil@empty
			\fi
		\else
			\if1#1%
				\if0#2%
					\let\pgfplots@loc@TMPa=\pgfutil@empty
				\fi
			\else
				\if2#1%
					\if0#2%
						\let\pgfplots@loc@TMPa=\pgfutil@empty
					\fi
					\if1#2%
						\let\pgfplots@loc@TMPa=\pgfutil@empty
					\fi
				\else
					% return TRUE.
					% I admit I am not sure at all if this works in all
					% cases
					\pgfplotspointonorientedsurfaceabmatchaxisline@warn{#1}%
				\fi
			\fi
		\fi
	\fi
}%
\def\pgfplotspointonorientedsurfaceabmatchaxisline@warn#1{%
	\pgfplots@warning{The internal implementation is suspicious that something is wrong: \string\pgfplotspointonorientedsurfaceabmatchaxisline@warn:  the character '#1' in a three-character axis line or surface description might not be fully supported...}%
}%

% Provides a point on an arbitrary axis (identified by a
% three-character-string) which can take any value on that axis and
% which is shifted in the direction of the outer normal vector. 
%
% #1: a three-character-string denoting the desired axis
% #2: the coordinate on that axis (the coordinate for the 'v'
% direction in '#1'). It needs to be given as it would be supplied to
% an \addplot or 'axis cs' coordinate; any logs or data
% transformations will be applied.
% #3: the distance (a dimension) describing how much we should move
% away from that axis. This points to the outside normal vector of the
% axis cube.
%
% @see \pgfplotsqpointoutsideofticklabelaxis
%
% If, in addition, the boolean \ifpgfslopedattime is true, the same
% transformations which would have been applied by
% \pgftransformlineattime will be applied, that means the 'sloped'
% feature of tikz is applied. FIXME : is that up-to-date!?
%
% @see \pgftransformlineattime -- it is quite similar.
\def\pgfplotsqpointoutsideofaxis#1#2#3{%
	\begingroup
	\def\pgfplotspointoutsideofaxis@plug@trafo##1##2{\csname pgfplotstransformcoordinate##1\endcsname{##2}}%
	\let\pgfplotspointoutsideofaxis@plug@getlimit=\pgfplotspointoutsideofaxis@getlimit@
	\edef\pgfplots@loc@TMPa{#1}%
	\expandafter\pgfplotspointoutsideofaxis@\pgfplots@loc@TMPa\relax{#2}{#3}%
}%

% A variant of \pgfplotsqpointoutsideofaxis with relative values for
% #2.
% That means  
%   '#2 = 0' === lower axis limit 
% and 
%   '#2 = 1' === upper axis limit.
\def\pgfplotsqpointoutsideofaxisrel#1#2#3{%
	\begingroup
	\def\pgfplotspointoutsideofaxis@plug@trafo##1##2{%
		\begingroup
			% compute ##1min + ##2 * (##1max - ##1min) :
			%
			\afterassignment\pgfplots@gobble@until@relax
			\pgf@xa=##2pt\relax
			\edef\pgfplots@loc@TMPa{\pgf@sys@tonumber\pgf@xa}%
			%
			\pgf@xa=\csname pgfplots@##1min\endcsname pt %
			\pgf@xb=\csname pgfplots@##1max\endcsname pt %
			\pgf@xc=\pgf@xb
			\ifpgfplots@allow@reversal@of@rel@axis@cs
				\if\pgfkeysvalueof{/pgfplots/##1 dir/value}r%
					% reverse: exchange min and max.
					\pgf@xb=\pgf@xa
					\pgf@xa=\pgf@xc
					\pgf@xc=\pgf@xb
				\fi
			\fi
			\advance\pgf@xc by-\pgf@xa
			\pgf@xc=\pgfplots@loc@TMPa\pgf@xc
			\advance\pgf@xc by\pgf@xa
			\edef\pgfmathresult{\pgf@sys@tonumber\pgf@xc}%
			\pgfmath@smuggleone\pgfmathresult
		\endgroup
	}%
	\let\pgfplotspointoutsideofaxis@plug@getlimit=\pgfplotspointoutsideofaxis@getlimit@
	\edef\pgfplots@loc@TMPa{#1}%
	\expandafter\pgfplotspointoutsideofaxis@\pgfplots@loc@TMPa\relax{#2}{#3}%
}%

% A variant of \pgfplotsqpointoutsideofaxis which accepts transformed
% values for '#2' (i.e. any data transformations and logs are already
% applied).
\def\pgfplotsqpointoutsideofaxistransformed#1#2#3{%
	\begingroup
	\def\pgfplotspointoutsideofaxis@plug@trafo##1##2{\def\pgfmathresult{##2}}%
	\let\pgfplotspointoutsideofaxis@plug@getlimit=\pgfplotspointoutsideofaxis@getlimit@
	\edef\pgfplots@loc@TMPa{#1}%
	\expandafter\pgfplotspointoutsideofaxis@\pgfplots@loc@TMPa\relax{#2}{#3}%
}%

% Computes the unit outer normal vector of the axis identified by a
% three-character-string '#1'.
%
% This is the same normal vector which is used inside of
% \pgfplotsqpointoutsideofaxis and its variants.
%
% The output of this command will be cached and re-used during the
% lifetime of an axis.
%
% The returned normal vector has length 1 (computed with
% \pgfpointnormalised).
%
% NOTE: some specialized axis types support non-linear axes (for
% example, polar axes). In that case, the outer normal vector *varies*
% along the `v' direction (of the three-character-string `#1').
% The value of `v' can be set using
% \pgfplotspointouternormalvectorofaxissetv{<axis three char string>}{<transformed coordinate>}
\def\pgfplotspointouternormalvectorofaxis#1{%
	\pgfplotspointouternormalvectorofaxis@ifdependson@v{#1}{%
		\expandafter\global\expandafter\let\csname pgfplotspointouternormalvectorofaxis@cache@#1\endcsname\relax
	}{%
	}%
	\expandafter\ifx\csname pgfplotspointouternormalvectorofaxis@cache@#1\endcsname\relax
		\begingroup
		\edef\pgfplots@loc@TMPa{#1}%
		\expandafter\pgfplotspointouternormalvectorofaxis@\pgfplots@loc@TMPa\relax%
		% \endgroup in \pgfplotspointouternormalvectorofaxis@.
		\expandafter\xdef\csname pgfplotspointouternormalvectorofaxis@cache@#1\endcsname{\global\pgf@x=\the\pgf@x\space\global\pgf@y=\the\pgf@y\space}%
	\else
		\csname pgfplotspointouternormalvectorofaxis@cache@#1\endcsname
	\fi
}%

% Fixes the "v" value for successive calls to
% \pgfplotspointouternormalvectorofaxis{#1}.
%
% #1 the three-character-string of an axis or the empty string.
% If #1 is empty, the actual configuration of oriented surfaces may be
% used to check which normal vector is intented.
%
% #2 the "v" value to store. It should be a transformed coordinate.
\def\pgfplotspointouternormalvectorofaxissetv#1#2{%
	\edef\pgfplots@loc@TMPa{#1}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\expandafter\edef\csname pgfplotspointouternormalvectorofaxis@v@\pgfplotspointonorientedsurfaceA\endcsname{#2}%
	\else
		\expandafter\edef\csname pgfplotspointouternormalvectorofaxis@v@#1\endcsname{#2}%
	\fi
}%

% Defines \pgfplotsretval to contain the 'v' value for an outer normal
% vector (if there is one known). If there is no such value,
% \pgfplotsretval will be empty.
% #1 a three-character-string
\def\pgfplotspointouternormalvectorofaxisgetv#1{%
	\edef\pgfplots@loc@TMPa{#1}%
	\expandafter\pgfplotspointouternormalvectorofaxisgetv@\pgfplots@loc@TMPa\relax\relax\relax\relax
}
\def\pgfplotspointouternormalvectorofaxisgetv@#1#2#3\relax{%
	\pgfutil@ifundefined{pgfplotspointouternormalvectorofaxis@v@#1#2#3}{%
		% no value found so far.
		\if#1v%
			\def\pgfplotsretval{x}%
		\else
			\if#2v%
				\def\pgfplotsretval{y}%
			\else
				\def\pgfplotsretval{z}%
			\fi
		\fi
		\pgfutil@ifundefined{pgfplotspointouternormalvectorofaxis@v@\pgfplotsretval}{%
			\let\pgfplotsretval\pgfutil@empty
		}{%
			\edef\pgfplotsretval{\csname pgfplotspointouternormalvectorofaxis@v@\pgfplotsretval\endcsname}%
		}%
	}{%
		\edef\pgfplotsretval{\csname pgfplotspointouternormalvectorofaxis@v@#1#2#3\endcsname}%
	}%
}%

% invokes #2 if the outer normal for the axis #1 (identified by a
% three-character-string) depends on a coordinate on that axis and #3
% otherwise.
%
% Overwrite in subclasses if necessary.
\def\pgfplotspointouternormalvectorofaxis@ifdependson@v#1#2#3{#3}

\def\pgfplotspointouternormalvectorofaxis@#1#2#3\relax{%
	\if v#1%
		\def\pgfplots@loc@point@orthogonal@to@v##1##2{%
			\pgfplotsqpointxyz{0}{##1}{##2}%
		}%
		\def\pgfplots@loc@char@for@baxis{#2}%
		\def\pgfplots@loc@char@for@naxis{#3}%
		\def\pgfplots@loc@vaxis{x}%
		\def\pgfplots@loc@baxis{y}%
		\def\pgfplots@loc@naxis{z}%
	\else
		\if v#2%
			\def\pgfplots@loc@point@orthogonal@to@v##1##2{%
				\pgfplotsqpointxyz{##1}{0}{##2}%
			}%
			\def\pgfplots@loc@char@for@baxis{#1}%
			\def\pgfplots@loc@char@for@naxis{#3}%
			\def\pgfplots@loc@vaxis{y}%
			\def\pgfplots@loc@baxis{x}%
			\def\pgfplots@loc@naxis{z}%
		\else
			\def\pgfplots@loc@point@orthogonal@to@v##1##2{%
				\pgfplotsqpointxyz{##1}{##2}{0}%
			}%
			\def\pgfplots@loc@char@for@baxis{#1}%
			\def\pgfplots@loc@char@for@naxis{#2}%
			\def\pgfplots@loc@vaxis{z}%
			\def\pgfplots@loc@baxis{x}%
			\def\pgfplots@loc@naxis{y}%
		\fi
	\fi
	%
	\pgfplotspointouternormalvectorofaxis@get@otheraxis@sign{\pgfplots@loc@vaxis}{\pgfplots@loc@baxis}{\pgfplots@loc@char@for@baxis}%
	\let\pgfplots@loc@baxissign=\pgfplotsretval
	%
	\pgfplotspointouternormalvectorofaxis@get@otheraxis@sign{\pgfplots@loc@vaxis}{\pgfplots@loc@naxis}{\pgfplots@loc@char@for@naxis}%
	\let\pgfplots@loc@naxissign=\pgfplotsretval
	%
	%
	% ok, compute vector scales:
	\pgfplotsmath@ifzero{\csname pgfplots@\pgfplots@loc@baxis @veclength\endcsname}{%
		\def\pgfplots@loc@baxissign{0}%
		\def\pgfplots@loc@baxisscale{0}%
	}{%
		\edef\pgfplots@loc@baxisscale{\pgfplots@loc@baxissign\csname pgfplots@\pgfplots@loc@baxis @inverseveclength\endcsname}%
	}%
	\pgfplotsmath@ifzero{\csname pgfplots@\pgfplots@loc@naxis @veclength\endcsname}{%
		\def\pgfplots@loc@naxissign{0}%
		\def\pgfplots@loc@naxisscale{0}%
	}{%
		\edef\pgfplots@loc@naxisscale{\pgfplots@loc@naxissign\csname pgfplots@\pgfplots@loc@naxis @inverseveclength\endcsname}%
	}%
	%
	% Ok, compute and normalize the vector:
	\pgf@process{%
		\pgfpointnormalised
			{\pgfplots@loc@point@orthogonal@to@v{\pgfplots@loc@baxisscale}{\pgfplots@loc@naxisscale}}%
	}%
	\endgroup
}%

% #1: the axis for which we want the "outer normal".
% #2: the "other axis" for which we seek the sign.
% #3: the entry in the three-char-identifier which corresponds to
% "other axis".
\def\pgfplotspointouternormalvectorofaxis@get@otheraxis@sign#1#2#3{%
	\ifcase#3\relax%
		% case 0:
		% this means : the '##1' direction of the surface
		% orthogonal to the 'v' vector is on the lower axis
		% limit. Since I need a vector pointing to the OUTSIDE of
		% the axis, I need sign = -1
		\def\pgfplotsretval{-}%
	\or
		% case 1:
		% in this case, the OUTSIDE area requires a plus sign - the b
		% axis already points to the inside.
		\def\pgfplotsretval{+}%
	\or
		% case 2: we have the 'axis lines=centered' case.
		%
		% This case is complicated. The problem is that we do not know
		% if we are at the top or bottom limit.
		%
		% BUT: we know what we would have done if this would be a
		% normal boxed axis!
		%
		% The idea is to return the same normal vector as if this would be a boxed axis.
		% To this end, we have to access the "ticklabel axis spec"
		% which would have been used in this case. 
		%
		% We computed it at startup. Might be a hack ... :-(
		\edef\pgfplots@loc@TMPb{\csname pgfplots@#1ticklabelaxisspec@box\endcsname}%
		%
		% decode it: we have to replace '#3' by the value that it has
		% in that boxed ticklabel axis spec!
		\def\pgfplots@loc@TMPa##1##2##3{%
			% search for the correct entry.
			\if x#2\def\pgfplotsretval{##1}\fi
			\if y#2\def\pgfplotsretval{##2}\fi
			\if z#2\def\pgfplotsretval{##3}\fi
		}%
		\expandafter\pgfplots@loc@TMPa\pgfplots@loc@TMPb
		%
		\if 2\pgfplotsretval
			\pgfplots@error{internal assertion failed.}%
		\fi
		%
		% invoke it again!
		\pgfplotspointouternormalvectorofaxis@get@otheraxis@sign{#1}{#2}{\pgfplotsretval}%
	\fi
}

% very-low-level internal routine. Never invoke it directly.
% @PRECONDITION:
% 	an \begingroup has been opened.
% @POSTCONDITION
% 	an \endgroup has been closed and \pgf@x and \pgf@y are assigned.
%
% This grouping stuff has the intention to keep the "plug" things
% local.
%
% #1#2#3 are the three characters for the line, delimited by \relax.
% #4: the argument supplied as coordinate on that axis.
% #5: the shift along the outer unit normal.
\def\pgfplotspointoutsideofaxis@#1#2#3\relax#4#5{%
	\if v#1%
		\pgfplotspointoutsideofaxis@plug@getlimit{y}{#2}\let\pgfplots@loc@TMPa=\pgfmathresult
		\pgfplotspointonorientedsurfaceabsetupforsety{\pgfplots@loc@TMPa}{#2}%
		%
		\pgfplotspointonorientedsurfaceabsetupfor xzy%
		\pgfplotspointoutsideofaxis@plug@trafo{x}{#4}\let\pgfplots@loc@A=\pgfmathresult
		\ifpgfplots@threedim
			\pgfplotspointoutsideofaxis@plug@getlimit{z}{#3}\let\pgfplots@loc@B=\pgfmathresult
		\else
			\def\pgfplots@loc@B{0}%
		\fi
	\else
		\if v#2%
			\ifpgfplots@threedim
				\pgfplotspointoutsideofaxis@plug@getlimit{z}{#3}\let\pgfplots@loc@TMPa=\pgfmathresult
			\else
				\def\pgfplots@loc@TMPa{0}%
			\fi
			\pgfplotspointonorientedsurfaceabsetupforsetz{\pgfplots@loc@TMPa}{#3}%
			%
			\pgfplotspointonorientedsurfaceabsetupfor yxz%
			\pgfplotspointoutsideofaxis@plug@trafo{y}{#4}\let\pgfplots@loc@A=\pgfmathresult
			\pgfplotspointoutsideofaxis@plug@getlimit{x}{#1}\let\pgfplots@loc@B=\pgfmathresult
		\else
			\pgfplotspointoutsideofaxis@plug@getlimit{x}{#1}\let\pgfplots@loc@TMPa=\pgfmathresult
			\pgfplotspointonorientedsurfaceabsetupforsetx{\pgfplots@loc@TMPa}{#1}%
			%
			\pgfplotspointonorientedsurfaceabsetupfor zyx%
			\ifpgfplots@threedim
				\pgfplotspointoutsideofaxis@plug@trafo{z}{#4}\let\pgfplots@loc@A=\pgfmathresult
			\else
				\def\pgfplots@loc@A{0}%
			\fi
			\pgfplotspointoutsideofaxis@plug@getlimit{y}{#2}\let\pgfplots@loc@B=\pgfmathresult
		\fi
	\fi
	%
	% read dimen argument #5:
	\afterassignment\pgfplots@gobble@until@relax
	\pgf@xa=#5pt\relax
	\edef\pgfplots@loc@distalong@normal{\pgf@sys@tonumber\pgf@xa}%
	%
%\message{pgfplotspointoutsideofaxis{#1#2#3}{#4}{#5}: A = \pgfplots@loc@A, B = \pgfplots@loc@B.^^J}%
	%
	\pgf@process{%
		\pgfpointadd
			{\pgfplotspointonorientedsurfaceab{\pgfplots@loc@A}{\pgfplots@loc@B}}
			{%
				\pgfplotspointouternormalvectorofaxissetv{#1#2#3}{\pgfplots@loc@A}%
				\pgfqpointscale
					{\pgfplots@loc@distalong@normal}%
					{\pgfplotspointouternormalvectorofaxis{#1#2#3}}%
			}%
	}%
	\endgroup
}%
%--------------------------------------------------
% \def\pgfplotspointoutsideofaxis@#1#2#3\relax#4#5{%
% 	\if v#1%
% 		\def\pgfplots@loc@point@orthogonal@to@v{%
% 			\pgfplotspointoutsideofaxis@plug@trafo{x}{#4}\let\pgfplots@loc@TMPa=\pgfmathresult
% 			\pgfplotspointoutsideofaxis@plug@getlimit{y}{#2}\let\pgfplots@loc@TMPb=\pgfmathresult
% 			\ifpgfplots@threedim
% 				\pgfplotspointoutsideofaxis@plug@getlimit{z}{#3}\let\pgfplots@loc@TMPc=\pgfmathresult
% 			\else
% 				\def\pgfplots@loc@TMPc{0}%
% 			\fi
% 			\pgfplotsqpointxyz{\pgfplots@loc@TMPa}{\pgfplots@loc@TMPb}{\pgfplots@loc@TMPc}%
% 		}%
% 	\else
% 		\if v#2%
% 			\def\pgfplots@loc@point@orthogonal@to@v{%
% 				\pgfplotspointoutsideofaxis@plug@trafo{y}{#4}\let\pgfplots@loc@TMPa=\pgfmathresult
% 				\pgfplotspointoutsideofaxis@plug@getlimit{x}{#1}\let\pgfplots@loc@TMPb=\pgfmathresult
% 				\ifpgfplots@threedim
% 					\pgfplotspointoutsideofaxis@plug@getlimit{z}{#3}\let\pgfplots@loc@TMPc=\pgfmathresult
% 				\else
% 					\def\pgfplots@loc@TMPc{0}%
% 				\fi
% 				\pgfplotsqpointxyz{\pgfplots@loc@TMPb}{\pgfplots@loc@TMPa}{\pgfplots@loc@TMPc}%
% 			}%
% 		\else
% 			\def\pgfplots@loc@point@orthogonal@to@v{%
% 				\ifpgfplots@threedim
% 					\pgfplotspointoutsideofaxis@plug@trafo{z}{#4}\let\pgfplots@loc@TMPa=\pgfmathresult
% 				\else
% 					\def\pgfplots@loc@TMPa{0}%
% 				\fi
% 				\pgfplotspointoutsideofaxis@plug@getlimit{x}{#1}\let\pgfplots@loc@TMPb=\pgfmathresult
% 				\pgfplotspointoutsideofaxis@plug@getlimit{y}{#2}\let\pgfplots@loc@TMPc=\pgfmathresult
% 				\pgfplotsqpointxyz{\pgfplots@loc@TMPb}{\pgfplots@loc@TMPc}{\pgfplots@loc@TMPa}%
% 			}%
% 		\fi
% 	\fi
% 	%
% 	% read dimen argument #5:
% 	\afterassignment\pgfplots@gobble@until@relax
% 	\pgf@xa=#5pt\relax
% 	\edef\pgfplots@loc@distalong@normal{\pgf@sys@tonumber\pgf@xa}%
% 	%
% 	%
% 	\pgf@process{%
% 		\pgfpointadd
% 			{\pgfplots@loc@point@orthogonal@to@v}
% 			{%
% 				\pgfqpointscale
% 					{\pgfplots@loc@distalong@normal}%
% 					{\pgfplotspointouternormalvectorofaxis{#1#2#3}}%
% 			}%
% 	}%
% 	\endgroup
% }%
%-------------------------------------------------- 

% Helper method for \pgfplotsqpointoutsideofaxis and its variants.
% #1: an axis (x,y or z)
% #2: o(\pgfplots@loc@TMPa - \pgfplots@loc@TMPb) ne of '0', '1' or '2' where
% 	0 == add lower #1 axis limit,
% 	1 == add upper #1 axis limit,
% 	2 == add nothing.
% #3: the value to add.
\def\pgfplotspointoutsideofaxis@getlimit@#1#2{%
	\if#20%
		\expandafter\let\expandafter\pgfmathresult\csname pgfplots@#1min\endcsname
	\else
		\if#21%
			\expandafter\let\expandafter\pgfmathresult\csname pgfplots@#1max\endcsname
		\else
			\expandafter\let\expandafter\pgfmathresult\csname pgfplots@logical@ZERO@#1\endcsname
		\fi
	\fi
}%

\newif\ifpgfplots@sloped
\pgfplots@slopedtrue % its only purpose is to *DEACTIVATE* the sloped transformation after it has been activated.
\newif\ifpgfplots@sloped@resets@nontranslations
\newif\ifpgfplots@sloped@allowupsidedown
\pgfkeys{
	/pgfplots/sloped/true/.code={\pgfplots@slopedtrue},
	/pgfplots/sloped/false/.code={\pgfplots@slopedfalse},
	/pgfplots/sloped/allow upside down/.is if=pgfplots@sloped@allowupsidedown,
	/pgfplots/sloped/allow upside down/.default=true,
	/pgfplots/sloped/execute for upside down/.initial=,
	/pgfplots/sloped/reset nontranslations/.is if=pgfplots@sloped@resets@nontranslations,
	/pgfplots/sloped/reset nontranslations/.default=true,
}
% Installs a rotation transformation matrix such that labels or
% whatever are aligned precisely in direction of one of the two/three
% coordinate directions.
%
% \pgfplotstransformtoaxisdirection[<options>]{<axis char>}
% 
% <axis char>: the coordinate direction (one of x,y or z)
%
% The code is pretty much the same as \pgftransformlineattime, except
% that the computation is considerably simpler as axis directions are
% a well known quantity.
%
% This command uses \ifpgfplots@sloped@allowupsidedown (=false) and
% \ifpgfplots@sloped@resets@nontranslations (= true). The default
% setting is reinitialised before options are processed
\def\pgfplotstransformtoaxisdirection{%
	\pgfutil@ifnextchar[{\pgfplotstransformtoaxisdirection@}{\pgfplotstransformtoaxisdirection@[]}%
}%
\def\pgfplotstransformtoaxisdirection@[#1]#2{%
	\pgfplots@sloped@allowupsidedownfalse
	\pgfplots@sloped@resets@nontranslationstrue
	%
	\def\pgfplots@loc@TMPa{#1}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
	\else
		\pgfqkeys{/pgfplots/sloped}{#1}%
	\fi
	\ifpgfplots@sloped
	%
	\ifpgfplots@sloped@resets@nontranslations
		\pgftransformresetnontranslations
	\fi
	%
	% compute unit length vector pointing into the direction of
	% '#1#2#3':
	\pgfqpointscale{\csname pgfplotsunit#2invlength\endcsname}{\csname pgfplotspointunit#2\endcsname}%
	%
	\ifdim\pgf@x<0pt%   
		% oh. upside down.
		\pgfkeysvalueof{/pgfplots/sloped/execute for upside down}%
		\ifpgfplots@sloped@allowupsidedown
		\else
			% do not allow upside down labels:
			\global\pgf@x=-\pgf@x%
			\global\pgf@y=-\pgf@y%
		\fi
	\fi%
	%
	\pgf@ya=-\pgf@y%
	% set up rotation matrix 
	%  [ cos(alpha) sin(alpha); 
	%   -sin(alpha) cos(alpha) ]
	% where cos(alpha) = n_x and sin(alpha) = n_y:
	\pgftransformcm%
	{\pgf@sys@tonumber{\pgf@x}}{\pgf@sys@tonumber{\pgf@y}}%
	{\pgf@sys@tonumber{\pgf@ya}}{\pgf@sys@tonumber{\pgf@x}}{\pgfpointorigin}%
	\fi
}


% Adds a further, temporary anchor to every node which will be
% processed. The anchor will be named '#3'. It is placed such that
% 1. the node's center is on a line in direction of the inwards normal
% vector of the axis line denoted by '#2' and the 'at' position of the node,
% 2. the node does not intrude the axis.
%
% #1: either x,y or z the direction which varies
% #2: a three-char-string uniquely identifying the axis line.
%   The parameter '#1' is redundand: it is the same as the 'v'
%   character in '#2'.
% #3: the newly defined achor name.
%
% @see \pgfplotsdeclareborderanchorforticklabelaxis
\def\pgfplotsdeclareborderanchorforaxis#1#2#3{%
	%
	%
	\pgfdeclaregenericanchor{#3}{\pgfplots@borderanchor@for@axis{#1}{#2}{##1}}%
	\pgfdeclaregenericanchor{#3 opposite}{\pgfplots@borderanchor@for@axis@{#1}{#2}{##1}{+1}}%
	% 
	% This variant will ALWAYS be placed on the boundary of the node.
	% It is deprecated, I am keeping it for some time....
	\pgfdeclaregenericanchor{#3*}{%
		\csname pgf@anchor@##1@border\endcsname{%
			\pgf@process{%
				%
				% I want to rotate the node FIRST, then 
				% I'd like to get the boundary anchor! 
				%
				% My idea: apply the INVERSE transformation
				% matrix, then compute the boundary anchor.
				%
				% As soon as pgf draws the node, the
				% transformation matrix will be applied and
				% everything is fine.
				\pgfutil@ifundefined{pgfreferencednodename}{%
					% use given transformation matrix.
				}{%
					\ifx\pgfreferencednodename\pgfutil@empty
						% just use the given transformation matrix - we are
						% typesetting an unlabeled node.
					\else
						\pgfsettransform{\csname pgf@sh@nt@\pgfreferencednodename\endcsname}%
					\fi
				}%
				\pgftransforminvert
				%
				% This here is the anchor as such.
				\pgfqpointscale{-1}{\pgfplotspointouternormalvectorofaxis{#2}}%
				%
				\pgf@pos@transform\pgf@x\pgf@y
			}%
		}%
	}%
}%

% this does the work for \pgfplotsdeclareborderanchorforaxis.
%
% It depends on \pgfplotspointunit[xyz] and
% \pgfplotspointouternormalvectorofaxis
%
% #1: either x,y or z the direction which varies
% #2: a three-char-string uniquely identifying the axis line.
%   The parameter '#1' is redundand: it is the same as the 'v'
%   character in '#2'.
% #3: the shape, provided as argument by the pgf routine invoking the
% anchor.
\def\pgfplots@borderanchor@for@axis#1#2#3{%
	\pgfplots@borderanchor@for@axis@{#1}{#2}{#3}{-1}%
}
% same as \pgfplots@borderanchor@for@axis{#1}{#2}{3} except that #4 is
% the SIGN for the outer normal.
%
% #4: the sign for the outer normal. #4=-1 means "use inner normal"
% and +1 means "use outer normal"
\def\pgfplots@borderanchor@for@axis@#1#2#3#4{%
	\begingroup
	\pgfutil@ifundefined{pgfreferencednodename}{%
		% use given transformation matrix.
	}{%
		\ifx\pgfreferencednodename\pgfutil@empty
			% just use the given transformation matrix - we are
			% typesetting an unlabeled node.
		\else
			\pgfsettransform{\csname pgf@sh@nt@\pgfreferencednodename\endcsname}%
		\fi
	}%
	% I only need to apply the trafo matrix to direction vectors. Eliminate
	% shifts.
	\pgf@pt@x=0pt %
	\pgf@pt@y=0pt %
	%
	% I'll apply the inverse transformation matrix to direction
	% vectors. To ensure the relative position of these vectors
	% and the anchors of the node, I have to invert the matrix:
	\pgftransforminvert
	%
	%
	% This here is the normal direction (points to the axis)
	\pgfqpointscale{#4}{\pgfplotspointouternormalvectorofaxis{#2}}%
	%
	% we apply the inverse CM onto it here:
	\pgf@pos@transform\pgf@x\pgf@y
	\edef\pgfplots@tmp@normaldir{\global\pgf@x=\the\pgf@x\space\global\pgf@y=\the\pgf@y\space}%
	% 
	\pgfplots@borderanchor@snap@to@nearest@anchor{}% takes \pgf@x and \pgf@y
	\let\pgfplots@anchor=\pgfplotsretval
	%
	% Now, I'd like the 'center' of the node on one line with the
	% 'at={}' coordinate at which it shall be placed!
	% This can be done as follows:
	%
	% Compute two lines:
	% 1. a line parallel to the #1 axis which goes
	% through our recently identified anchor,
	%   { x = x_a + r_1 * (#1 axis direction)
	% 2. a line from center in direction of the normal,
	% 	{ x = x_c + r_2 n, r in R }
	%
	% Calculate the intersection point and return it! This
	% involves a lot of arithmetics :-(
	%
	% UPDATE: I realized that using the 'center' anchor might be too
	% restrictive. See the 'near ticklabel align' key.
	%
	% Note that this is actually too much work for the 2d case - I
	% guess it would be more efficient without it. But for 3d, it
	% really rocks.
	%
	% compute (unit#1 - normal):
	\pgfplots@tmp@normaldir
	\pgf@xb=\pgf@x
	\pgf@yb=\pgf@y
	%
	% and the axis direction (in fact, I use -axis dir. But that
	% doesn't matter for the intersection of two lines).
	% Scale unit vector to length 1 to improve conditioning:
	\pgfqpointscale
		{\csname pgfplotsunit#1invlength\endcsname}
		{\csname pgfplotspointunit#1\endcsname}%
	% FIXME : shouldn't the values be copied AFTER the CM!?
	\pgf@xa=\pgf@x
	\pgf@ya=\pgf@y
	\pgf@pos@transform\pgf@xa\pgf@ya
	%
	\ifcase\pgfplots@borderanchor@align\relax
		% near ticklabel align=inside:
		% make sure that we are close to the beginning of the axis
		% direction vector.
		\pgfplots@borderanchor@snap@to@nearest@anchor{%
			\if\pgfkeysvalueof{/pgfplots/#1 dir/value}n%
				% simply take \pgf@x and \pgf@y as-is.
			\else
				\global\pgf@x=-\pgf@x
				\global\pgf@y=-\pgf@y
			\fi
		}%
	\or
		% near ticklabel align=center:
		\def\pgfplotsretval{center}% Ah. simple.
	\or
		% near ticklabel align=outside:
		% make sure that we are far away from the beginning of the
		% axis direction vector.
		\pgfplots@borderanchor@snap@to@nearest@anchor{%
			\if\pgfkeysvalueof{/pgfplots/#1 dir/value}n%
				\global\pgf@x=-\pgf@x
				\global\pgf@y=-\pgf@y
			\else
				% simply take \pgf@x and \pgf@y as-is.
			\fi
		}%
	\fi
	\let\pgfplots@anchor@inner=\pgfplotsretval
	%
	%
	% verify that |n^T d | 
	\pgf@xc=\pgf@sys@tonumber\pgf@xa\pgf@xb
	\advance\pgf@xc by\pgf@sys@tonumber\pgf@ya\pgf@yb
	\ifdim\pgf@xc<0pt \pgf@xc=-\pgf@xc \fi
	\ifdim\pgf@xc<0.8pt
		% ok. 'n' and 'd' are not parallel.
		%
		\edef\pgfplots@LEQ{%
		% solve linear system
		% 	a11 a12
		% 	a21 a22
			{\pgf@sys@tonumber\pgf@xb}{\pgf@sys@tonumber\pgf@xa}%
			{\pgf@sys@tonumber\pgf@yb}{\pgf@sys@tonumber\pgf@ya}%
		}%
		% 
		% This here controls the anchor! Changing it might be more
		% useful than I thought in the first place...
		\pgf@sh@reanchor{#3}{\pgfplots@anchor@inner}%
		\edef\pgfplots@loc@center{\global\pgf@x=\the\pgf@x\space\global\pgf@y=\the\pgf@y\space}%
		%
		% apply inverse matrix to right-hand-side (and compute RHS):
		\pgfpointdiff% {<start>}{<end>} -> computes <end> - <start>
			{\pgfplots@loc@center}%
			{\pgf@sh@reanchor{#3}{\pgfplots@anchor}}%
		\edef\pgfplots@RHS{{\pgf@sys@tonumber\pgf@x}{\pgf@sys@tonumber\pgf@y}}%
		%
		\pgfutilsolvetwotwoleq{\pgfplots@LEQ}{\pgfplots@RHS}%
		\def\pgfplots@extract##1##2{%
			\def\pgfplots@r{##1}%
		}%
		\expandafter\pgfplots@extract\pgfmathresult
		% GOT IT!
		%
		% compute x_c + r*n:
		\pgfpointadd
			{\pgfplots@loc@center}%
			{\pgfqpointscale{\pgfplots@r}{\pgfplots@tmp@normaldir}}%
	\else
		\pgfplotswarning{ticklabel anchor undetermined}{#1}{\the\pgf@xb,\the\pgf@yb}{\the\pgf@xa,\the\pgf@ya}{\the\pgf@xc}\pgfeov
		% Something went awry: normal and unit#1 are almost parallel!?
		% just use the determined anchor.
		\def\pgfplots@r{0}%
		\pgf@sh@reanchor{#3}{\pgfplots@anchor}%
	\fi
%\message{==========>>>>>>>>>> I got finally (\the\pgf@x,\the\pgf@y). <<<<<<<<<===================}%
	\pgf@process{}% <- transport outside of group
	\endgroup
}%

% #1: a direction vector.
%
% assigns the resulting anchor to \pgfplotsretval
\def\pgfplots@borderanchor@snap@to@nearest@anchor#1{%
	\begingroup
	#1%
	% Now:
	% auto-determine the canonical (north, north east etc) anchor
	% at which the node touches the axis (remember: the axis is to
	% be found in direction of the normal vector).  
	%
	% This is kind of a snap-to-nearest-existing-anchor feature. But
	% it tends to move the node too far away. It is used as starting
	% point; we will refine it in the next step.
	%
	% This is a heuristicial procedure.
	%
	% Note that it does not hurt if there are "multiple best matches"
	% (for example because they lie on the same line).
	% The code below will move the final anchor point.
	%
	\def\pgfplots@thresh{0.17pt }% 80 degrees
	%\def\pgfplots@thresh{0.3pt }%
	%\def\pgfplots@thresh{0.707pt }% 45 degrees
	\ifdim\pgf@y>0pt
		\ifdim\pgf@y>\pgfplots@thresh
			% only north anchor
			\def\pgfplots@ycomp{north}%
		\else
			\def\pgfplots@ycomp{}%
		\fi
	\else
		\ifdim\pgf@y<-\pgfplots@thresh
			\def\pgfplots@ycomp{south}%
			% south anchor
		\else
			\def\pgfplots@ycomp{}%
		\fi
	\fi
	\ifdim\pgf@x>0pt
		\ifdim\pgf@x>\pgfplots@thresh
			\def\pgfplots@xcomp{east}%
		\else
			\def\pgfplots@xcomp{}%
		\fi
	\else
		\ifdim\pgf@x<-\pgfplots@thresh
			\def\pgfplots@xcomp{west}%
		\else
			\def\pgfplots@xcomp{}%
		\fi
	\fi
	\edef\pgfplotsretval{%
		\pgfplots@ycomp
		\ifx\pgfplots@ycomp\pgfutil@empty
		\else
			\ifx\pgfplots@xcomp\pgfutil@empty
			\else
				\space
			\fi
		\fi
		\pgfplots@xcomp
	}%
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}

\def\pgfplotspointviewdir{%
	%\pgfplotsmathvectordatascaletrafoinverse{\pgfplots@view@dir@threedim}{default}%
	\let\pgfplotsretval=\pgfplots@view@dir@threedim
	\pgfplotspointfromcsvvector{\pgfplotsretval}{default}%
}%

\def\message@pgfplots@units{%
	\begingroup
	\pgfmathparse{veclen(\pgf@zx,\pgf@zy)}\let\Z=\pgfmathresult
	\ifdim\Z pt=0pt
		\def\Z{1}%
	\fi
	\pgfmathparse{veclen(\pgf@xx,\pgf@xy)/\Z}\let\X=\pgfmathresult
	\pgfmathparse{veclen(\pgf@yx,\pgf@yy)/\Z}\let\Y=\pgfmathresult
	\expandafter\ifx\csname pgfplots@view@dir@threedim\endcsname\relax
		\def\normal{view = (---),^^J}%
	\else
		\pgfplotsmathvectortostring{\pgfplots@view@dir@threedim}{default}%
		\edef\normal{view = (\pgfplotsretval),^^J}%
	\fi
	\message{^^J 
		x = (\the\pgf@xx,\the\pgf@xy),^^J 
		y =(\the\pgf@yx,\the\pgf@yy),^^J 
		z = (\the\pgf@zx,\the\pgf@zy),^^J 
		\normal
		unit vector ratio=[\X\space\Y\space 1],^^J}%
	\endgroup
}%


% ==================================================================================
% 
% COORDINATE MATH.
%
% ==================================================================================

% Declares a new "subclass" to perform coordinate math.
%
% Coordinate math usually needs a more powerful number format than the pgf
% basic layer, or at least a powerful mapping into the pgf basic
% layer. Both cases are realized by the coordinate math class.
%
% Different coordinates can use different instances, and it is also
% possible to use yet a further instance for point meta (or whatever).
%
% Coordinate math is used to compute axis limits and to map the range
% into the pgf number format. 
%
% It is *not* necessarily used for \pgfmathparse, since switching
% the number format of \pgfmathparse is quite involved (at the time of
% this writing). Instead, it is used for *single* operations (like
% max, min, multiply, add).
%
% #1: the name of the coord math class
% #2: methods to override the default.
%
% The available methods are documented and shown below in the
% \pgfqkeys listing. 
%
% @see the predefined examples, also shown below.
\def\pgfplotsdeclarecoordmath#1#2{%
	\edef\pgfplotsdeclarecoordmath@{@#1@}%
	\pgfqkeys{/pgfplots/@declare coord math}{%
		initialise=,
		parse=\edef\pgfmathresult{##1}\expandafter\pgfmathparse\expandafter{\pgfmathresult},
		parsenumber=\pgfmathfloatparsenumber{##1}\pgfmathfloattofixed{##1},%
		zero=		\pgfplotscoordmath{\pgfplotscoordmathid}{parsenumber}{0},
		one=		\pgfplotscoordmath{\pgfplotscoordmathid}{parsenumber}{1},
		-one=		\pgfplotscoordmath{\pgfplotscoordmathid}{parsenumber}{-1},
		log e=		\pgfmathlog@{##1},%
		log to display log=\pgfmath@basic@multiply@{##1}{2.3025851},% * log(10)
		log from display log=\pgfmath@basic@multiply@{##1}{0.434294},% / log(10)
		log unsigned int={%
			\edef\pgfmathresult{%
				\ifcase##1
				\or0
				\or0.693147
				\or1.098612
				\or1.386294
				\or1.60943791
				\or1.7917594
				\or1.94591014
				\or2.07944154
				\or2.197224
				\fi
			}%
		},
		set log basis=\edef\pgfmathresult{{#1}{##1}}\expandafter\pgfplotscoordmath@log@set@basis\pgfmathresult,
		exp e={%
			% make sure the exponential can be represented, i.e. use
			% 'float' in the default repr:
			\pgfmathfloatparsenumber{##1}%
			\pgfmathfloatexp@\pgfmathresult%
			\pgfplotscoordmath{\pgfplotscoordmathid}{parsenumber}{\pgfmathresult}%
		},
		tofixed=	\edef\pgfmathresult{##1},%
		tostring=	\edef\pgfmathresult{##1},%
		max=		\pgfplotsmathmax{##1}{##2},%
		min=		\pgfplotsmathmin{##1}{##2},%
		min limit=	\def\pgfmathresult{-16300},%
		max limit=	\def\pgfmathresult{16300},%
		if less than=	{\pgfplotsmathlessthan{##1}{##2}\ifpgfmathfloatcomparison ##3\else ##4\fi},
		if is=	{%
			\if##20
				\ifdim##1pt=0pt ##2\else ##3\fi
			\else
				\if##2+\ifdim##1pt>0pt ##2\else ##3\fi
				\else
					\if##2-\ifdim##1pt<0pt ##2\else ##3\fi
					\else
						\def\pgfplots@loc@TMPd{##1}\ifx\pgfplots@loc@TMPd\pgfutil@empty ##2\else ##3\fi
					\fi
				\fi
			\fi
		},%
		if is bounded=\edef\pgfplotsretval{##1}\ifx\pgfplotsretval\pgfutil@empty ##3\else ##2\fi,
		suffix=		#1,%
		datascaletrafo set params=,
		datascaletrafo get params=	\def\pgfmathresult{{0}{0}}\def\pgfplotsretval{0}\def\pgfplotsretvalb{0},
		datascaletrafo=				\edef\pgfmathresult{##1},
		datascaletrafo inverse=		\edef\pgfmathresult{##1},
		datascaletrafo noshift inverse=		\edef\pgfmathresult{##1},
		datascaletrafo inverse to fixed=	\edef\pgfmathresult{##1},
		datascaletrafo noshift inverse to fixed=	\edef\pgfmathresult{##1},
		datascaletrafo noshift=		\edef\pgfmathresult{##1},
		datascaletrafo undo shift=	\edef\pgfmathresult{##1},
		datascaletrafo redo shift=	\edef\pgfmathresult{##1},
		#2%
	}%
	\expandafter\edef\csname pgfpmth\pgfplotsdeclarecoordmath@ op\endcsname##1##2{%
		\noexpand\edef\noexpand\pgfplotscoordmath@{##2}%
		\noexpand\expandafter\noexpand\expandafter\noexpand\csname pgfmath\csname pgfpmth@#1@suffix\endcsname ##1@\noexpand\endcsname\noexpand\pgfplotscoordmath@
	}%
	%
	%
	% these log function depend on the first argument of
	% \pgfplotscoordmath{}, which is available as
	% \pgfplotscoordmathid.
	\pgfplotsutilforeachcommasep{%
		exp,%
		log,%
		log to display log,%
		log from display log,%
		log to log 10,%
		log unsigned int}\as\pgfplots@loc@TMPa
	{%
		\expandafter\edef\csname pgfpmth\pgfplotsdeclarecoordmath@\pgfplots@loc@TMPa\endcsname{%
			% invoke \pgfpmth@#1@@<name>@<function>
			% for example
			% \pgfpmth@pgfbasic@@y@log
			\noexpand\csname pgfpmth\pgfplotsdeclarecoordmath@ @\noexpand\pgfplotscoordmathid @\pgfplots@loc@TMPa\noexpand\endcsname
		}%
	}%
	%
	\pgfutil@ifundefined{pgfpmth\pgfplotsdeclarecoordmath@ tmpl@log}{%
		\pgfutil@namelet
			{pgfpmth\pgfplotsdeclarecoordmath@ tmpl@log}
			{pgfpmth\pgfplotsdeclarecoordmath@ log e}%
	}{}%
	\pgfutil@ifundefined{pgfpmth\pgfplotsdeclarecoordmath@ tmpl@exp}{%
		\pgfutil@namelet
			{pgfpmth\pgfplotsdeclarecoordmath@ tmpl@exp}
			{pgfpmth\pgfplotsdeclarecoordmath@ exp e}%
	}{}%
	\pgfplotscoordmath@def@log@to@log@ten{#1}{}{tmpl}% empty arg
	%
}%
\pgfqkeys{/pgfplots/@declare coord math}{%
	initialise/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ initialise\endcsname{#1%
			\pgfplotscoordmath@initialise@logs
		}},%
	% takes a number literal as input and defines \pgfmathresult to be
	% the parsed result.
	parsenumber/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ parsenumber\endcsname##1{#1}},%
	%
	zero/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ zero\endcsname{#1}},%
	one/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ one\endcsname{#1}},%
	-one/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ -one\endcsname{#1}},%
	%
	% Calls pgfmathparse. Note that this might need to switch to the
	% required math library (which is not necessarily cheap)
	parse/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ parse\endcsname##1{#1}},%
	%
	% takes a parsed number and returns a fixed point number:
	tofixed/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ tofixed\endcsname##1{#1}},%
	%
	% chooses a human readable string (which can be processed by parsenumber):
	tostring/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ tostring\endcsname##1{#1}},%
	%
	% defines a max routine which returns the max of *exactly* two numbers:
	max/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ max\endcsname##1##2{#1}},%
	%
	% counterpart for max:
	min/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ min\endcsname##1##2{#1}},%
	%
	% defines \pgfmathresult to be the largest supported number.
	max limit/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ max limit\endcsname{#1}},%
	%
	% defines \pgfmathresult to be the smallest supported number.
	min limit/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ min limit\endcsname{#1}},%
	%
	% computes ##1 < ##2 and invokes ##3 in the true case and ##4 in
	% the false case.
	if less than/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ if less than\endcsname##1##2##3##4{#1}},%
	% checks if ##1 is 0, positive, negative or unbounded
	% ##1: the number to check
	% ##2: either 0 or + or - or u (u = unbounded)
	% ##3: true code
	% ##4: false code
	if is/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ if is\endcsname##1##2##3##4{#1}},%
	%
	% Checks if the argument ##1 is bounded and invokes ##2 in that
	% case. IF the argument is unbounded, it invokes #3.
	if is bounded/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ if is bounded\endcsname##1##2##3{#1}},%
	%
	% applies the natural logarithm. If the log is not defined, the
	% argument is "unbounded", see 'if is bounded'
	%
	% 'log' is special in that it accepts a number literal which may
	% be OUTSIDE of the accepted number format. The result, however, is
	% then in the accepted number format.
	log e/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ log e\endcsname##1{#1}},%
	%
	% Similar, but the log basis can be set with 'set log basis'.
	% This allows \pgfplotscoordmath{x}{log}{} to use a different log
	% basis thatn \pgfplotscoordmath{y}{log}{} (with special handling)
	log/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ tmpl@log\endcsname##1{#1}},%
	% applies a *scale* from the actual log basis to the actual
	% *display* log basis. The display log basis is usually 10, unless
	% the log basis has been changed.
	log to display log/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ tmpl@log to display log\endcsname##1{#1}},%
	% applies a *scale* from the displau log basis to the actual
	% log basis (the inverse of `log to display log').
	log from display log/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ tmpl@log from display log\endcsname##1{#1}},%
	log to log 10/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ tmpl@log to log 10\endcsname##1{#1}},%
	% returns log(i) where i \in {1,2,3,...,basis-1}
	% currently, it is only invoked for log basis 10
	log unsigned int/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ tmpl@log unsigned int\endcsname##1{#1}},%
	% sets (changes) the actual log basis.
	set log basis/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ set log basis\endcsname##1{#1}},%
	%
	% The inverse to 'log e '. 
	exp e/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ exp e\endcsname##1{#1}},%
	%
	% The inverse to 'log'. It also uses the correct log basis.
	exp/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ tmpl@exp\endcsname##1{#1}},%
	%
	% A macro taking two parameters:
	% #1: the EXPONENT (as integer)
	% #2: the SHIFT (as fixed point number)
	%
	% After any change, \pgfplotscoordmathnotifydatascalesetfor{<id>} will be
	% invoked where <id> is the argument to
	% \pgfplotscoordmath{<id>}...
	datascaletrafo set params/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ datascaletrafo set params\endcsname##1##2{%
			#1\relax\pgfplotscoordmathnotifydatascalesetfor{\pgfplotscoordmathid}%
		 }},%
	datascaletrafo set shift/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ datascaletrafo set shift\endcsname##1{%
			#1\relax\pgfplotscoordmathnotifydatascalesetfor{\pgfplotscoordmathid}%
		 }},%
	% 
	% Defines \pgfmathresult to contain the two parameters in the form
	% {#1}{#2} required for 'datascaletrafo set params':
	% #1: the EXPONENT (as integer)
	% #2: the SHIFT (as fixed point number)
	% AND \pgfplotsretval as the EXPONENT and \pgfplotsretvalb as the SHIFT
	datascaletrafo get params/.code={%
		\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ datascaletrafo get params\endcsname{#1}%
	},%
	datascaletrafo/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ datascaletrafo\endcsname##1{#1}},%
	datascaletrafo inverse/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ datascaletrafo inverse\endcsname##1{#1}},%
	datascaletrafo noshift inverse/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ datascaletrafo noshift inverse\endcsname##1{#1}},%
	datascaletrafo inverse to fixed/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ datascaletrafo inverse to fixed\endcsname##1{#1}},%
	datascaletrafo noshift inverse to fixed/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ datascaletrafo noshift inverse to fixed\endcsname##1{#1}},%
	datascaletrafo noshift/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ datascaletrafo noshift\endcsname##1{#1}},%
	datascaletrafo noshift/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ datascaletrafo noshift\endcsname##1{#1}},%
	datascaletrafo undo shift/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ datascaletrafo undo shift\endcsname##1{#1}},%
	datascaletrafo redo shift/.code=
		{\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ datascaletrafo redo shift\endcsname##1{#1}},%
	%
	% defines a suffix such that
	% 	\csname pgfmath<suffix><op>@\endcsname
	% exists. Example: <suffix>=float  --> \pgfmathfloatmultiply@ for <op>=multiply
	suffix/.code=
		{\expandafter\edef\csname pgfpmth\pgfplotsdeclarecoordmath@ suffix\endcsname{#1}},%
}%

\def\pgfplotscoordmath@initialise@logs{%
	\edef\pgfplotsdeclarecoordmath@{@\pgfplotscoordmathclassfor{\pgfplotscoordmathid}@}%
	\pgfutil@ifundefined{pgfpmth\pgfplotsdeclarecoordmath@ @\pgfplotscoordmathid @log}{%
		\pgfplotsutilforeachcommasep{%
			exp,%
			log,%
			log to display log,%
			log from display log,%
			log to log 10,%
			log unsigned int}\as\pgfplots@loc@TMPa
		{%
			\pgfutil@namelet
				{pgfpmth\pgfplotsdeclarecoordmath@ @\pgfplotscoordmathid @\pgfplots@loc@TMPa}
				{pgfpmth\pgfplotsdeclarecoordmath@ tmpl@\pgfplots@loc@TMPa}%
		}%
	}{}%
}%

% shared implementation for 'set log basis' It works for every
% subclass.
\def\pgfplotscoordmath@log@set@basis#1#2{%
	\edef\pgfplotsdeclarecoordmath@{@#1@}%
	%
	\pgfplotscoordmath{\pgfplotscoordmathid}{log e}{#2}%
	\let\pgfplots@loc@TMPa=\pgfmathresult% TMPa = log_e(#2)
	\pgfplotscoordmath{\pgfplotscoordmathid}{op}{reciprocal}{{\pgfmathresult}}%
	\let\pgfplots@loc@TMPb=\pgfmathresult% TMPb = 1/log_e(#2)
	%
	% log_a(x) = log_e(x) / log_e(a)
	\expandafter\edef\csname pgfpmth\pgfplotsdeclarecoordmath@ @\pgfplotscoordmathid @log\endcsname##1{%
		\noexpand\pgfplotscoordmath{\pgfplotscoordmathid}{log e}{##1}%
		\noexpand\ifx\noexpand\pgfmathresult\noexpand\pgfutil@empty
		\noexpand\else
			\noexpand\pgfplotscoordmath{\pgfplotscoordmathid}{op}{multiply}{%
				{\noexpand\pgfmathresult}%
				{\pgfplots@loc@TMPb}%
			}%
		\noexpand\fi
	}%
	%
	% a^x = exp(log_e(a^x)) = exp(x*log_e(a))
	\expandafter\edef\csname pgfpmth\pgfplotsdeclarecoordmath@ @\pgfplotscoordmathid @exp\endcsname##1{%
		\noexpand\edef\noexpand\pgfmathresult{##1}%
		\noexpand\ifx\noexpand\pgfmathresult\noexpand\pgfutil@empty
		\noexpand\else
			\noexpand\pgfplotscoordmath{\pgfplotscoordmathid}{op}{multiply}{%
				{\noexpand\pgfmathresult}%
				{\pgfplots@loc@TMPa}%
			}%
			\noexpand\pgfplotscoordmath{\pgfplotscoordmathid}{exp e}{\noexpand\pgfmathresult}%
		\noexpand\fi
	}%
	\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ @\pgfplotscoordmathid @log to display log\endcsname##1{\edef\pgfmathresult{##1}}%
	\expandafter\def\csname pgfpmth\pgfplotsdeclarecoordmath@ @\pgfplotscoordmathid @log from display log\endcsname##1{\edef\pgfmathresult{##1}}%
	%
	% compute 'log unsigned int' for the new basis.
	%
	% Idea: re-scale the old implementation (of basis e for i = 1,...,9)
	% and re-compute i>=10 :
	\begingroup
		\expandafter\let\expandafter\logi\csname pgfpmth\pgfplotsdeclarecoordmath@ tmpl@log unsigned int\endcsname
		\let\logscale=\pgfplots@loc@TMPb
		%
		\logi{1}%
		\pgfplotscoordmath{\pgfplotscoordmathid}{op}{multiply}{{\pgfmathresult}{\logscale}}%
		\expandafter\let\csname logi@@1\endcsname=\pgfmathresult
		%
		\logi{2}%
		\pgfplotscoordmath{\pgfplotscoordmathid}{op}{multiply}{{\pgfmathresult}{\logscale}}%
		\expandafter\let\csname logi@@2\endcsname=\pgfmathresult
		%
		\logi{3}%
		\pgfplotscoordmath{\pgfplotscoordmathid}{op}{multiply}{{\pgfmathresult}{\logscale}}%
		\expandafter\let\csname logi@@3\endcsname=\pgfmathresult
		%
		\logi{4}%
		\pgfplotscoordmath{\pgfplotscoordmathid}{op}{multiply}{{\pgfmathresult}{\logscale}}%
		\expandafter\let\csname logi@@4\endcsname=\pgfmathresult
		%
		\logi{5}%
		\pgfplotscoordmath{\pgfplotscoordmathid}{op}{multiply}{{\pgfmathresult}{\logscale}}%
		\expandafter\let\csname logi@@5\endcsname=\pgfmathresult
		%
		\logi{6}%
		\pgfplotscoordmath{\pgfplotscoordmathid}{op}{multiply}{{\pgfmathresult}{\logscale}}%
		\expandafter\let\csname logi@@6\endcsname=\pgfmathresult
		%
		\logi{7}%
		\pgfplotscoordmath{\pgfplotscoordmathid}{op}{multiply}{{\pgfmathresult}{\logscale}}%
		\expandafter\let\csname logi@@7\endcsname=\pgfmathresult
		%
		\logi{8}%
		\pgfplotscoordmath{\pgfplotscoordmathid}{op}{multiply}{{\pgfmathresult}{\logscale}}%
		\expandafter\let\csname logi@@8\endcsname=\pgfmathresult
		%
		\logi{9}%
		\pgfplotscoordmath{\pgfplotscoordmathid}{op}{multiply}{{\pgfmathresult}{\logscale}}%
		\expandafter\let\csname logi@@9\endcsname=\pgfmathresult
		%
		\xdef\pgfplots@glob@TMPa##1{%
			\noexpand\ifcase##1
			\noexpand\def\noexpand\pgfmathresult{}%
			\noexpand\or\noexpand\def\noexpand\pgfmathresult{\csname logi@@1\endcsname}%
			\noexpand\or\noexpand\def\noexpand\pgfmathresult{\csname logi@@2\endcsname}%
			\noexpand\or\noexpand\def\noexpand\pgfmathresult{\csname logi@@3\endcsname}%
			\noexpand\or\noexpand\def\noexpand\pgfmathresult{\csname logi@@4\endcsname}%
			\noexpand\or\noexpand\def\noexpand\pgfmathresult{\csname logi@@5\endcsname}%
			\noexpand\or\noexpand\def\noexpand\pgfmathresult{\csname logi@@6\endcsname}%
			\noexpand\or\noexpand\def\noexpand\pgfmathresult{\csname logi@@7\endcsname}%
			\noexpand\or\noexpand\def\noexpand\pgfmathresult{\csname logi@@8\endcsname}%
			\noexpand\or\noexpand\def\noexpand\pgfmathresult{\csname logi@@9\endcsname}%
			\noexpand\else
				\noexpand\pgfplotscoordmath{\pgfplotscoordmathid}{log}{##1}%
			\noexpand\fi
		}%
	\endgroup
	\expandafter\let\csname pgfpmth\pgfplotsdeclarecoordmath@ @\pgfplotscoordmathid @log unsigned int\endcsname=\pgfplots@glob@TMPa
	\pgfplotscoordmath@def@log@to@log@ten{#1}\pgfplots@loc@TMPa{\pgfplotscoordmathid}%
	%
	\pgfutil@namelet
		{pgfpmth\pgfplotsdeclarecoordmath@ @\pgfplotscoordmathid @log to log 10}
		{pgfpmth\pgfplotsdeclarecoordmath@ tmpl@log to log 10}%
}%
% #1: the coord math class
% #2: either empty (basis e) or 1/ln(basis)
% #3: either 'tmpl' or '\pgfplotscoordmathid. It defines the target
% macro name (see the source code)
\def\pgfplotscoordmath@def@log@to@log@ten#1#2#3{%
	\csname pgfpmth@#1@parsenumber\endcsname{0.434294}%
	\edef\pgfplots@loc@TMPa{#2}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		% log basis e ---> log basis 10
		% log_10 x = log x / log(10)
	\else
		% log basis a ---> log basis 10
		%
		% log_a x = log x / log a 
		% log_10 x =  log_a x * log a / log(10) = log x / log(10) [OK]
		\csname pgfpmth@#1@op\endcsname{multiply}{{#2}{\pgfmathresult}}%
	\fi
	\expandafter\edef\csname pgfpmth@#1@#3@log to log 10\endcsname##1{%
		\noexpand\pgfplotscoordmath{\noexpand\pgfplotscoordmathid}{op}{multiply}{{##1}{\pgfmathresult}}%
	}%
}%

% Assumes that #2 is a macro, parses it as number with "coord math choice" #1, and overwrites it with the result.
\def\pgfplotscoordmathparsemacro#1#2{%
	\pgfplotscoordmath{#1}{parsenumber}{#2}\let#2=\pgfmathresult
}%


\pgfplotsdeclarecoordmath{pgfbasic}{%
	parsenumber={%
		\pgfmathfloatparsenumber{#1}%
		\expandafter\pgfmathfloatgetflagstomacro\expandafter{\pgfmathresult}\pgfplotsretval
		\ifnum\pgfplotsretval>2 
			\let\pgfmathresult=\pgfutil@empty
		\else
			\pgfmathfloattofixed\pgfmathresult
		\fi
	},
	suffix=@basic@,
	zero=\def\pgfmathresult{0},
	one=\def\pgfmathresult{1},
	-one=\def\pgfmathresult{-1},
}
\pgfplotsdeclarecoordmath{float}{%
	initialise=
		\pgfutil@ifundefined{pgfplots@data@scale@trafo@EXPONENT@\pgfplotscoordmathid}{%
			\expandafter\edef\csname pgfplots@data@scale@trafo@EXPONENT@\pgfplotscoordmathid\endcsname{0}%
			\expandafter\edef\csname pgfplots@data@scale@trafo@SHIFT@\pgfplotscoordmathid\endcsname{0}%
		}{},
	parsenumber=\pgfmathfloatparsenumber{#1},
	parse={%
		\begingroup 
		\pgfkeys{/pgf/fpu}%
		\edef\pgfmathresult{#1}%
		\expandafter\pgfmathparse\expandafter{\pgfmathresult}%
		\pgfmath@smuggleone\pgfmathresult
		\endgroup
	},
	zero=\pgfmathfloatcreate{0}{0.0}{0},%
	one=\pgfmathfloatcreate{1}{1.0}{0},%
	-one=\pgfmathfloatcreate{2}{1.0}{0},%
	tofixed=\pgfmathfloattofixed{#1},
	tostring=\pgfmathfloattosci{#1},
	max=\pgfplotsmathfloatmax{#1}{#2},%
	min=\pgfplotsmathfloatmin{#1}{#2},%
	max limit=\pgfmathfloatcreate{1}{1.0}{2147483645},%
	min limit=\pgfmathfloatcreate{2}{1.0}{2147483645},%
	log e=\pgfmathfloatparsenumber{#1}\pgfmathfloatln@{\pgfmathresult},%
	if less than=\pgfmathfloatlessthan@{#1}{#2}\ifpgfmathfloatcomparison #3\else #4\fi,
	if is bounded=%
		\expandafter\pgfmathfloatgetflagstomacro\expandafter{#1}\pgfplotsretval
		\ifnum\pgfplotsretval>2 #3\else #2\fi,
	if is=%
		\pgfmathfloatifflags{#1}{#2}{#3}{#4},
	log=\pgfmathlog@float{#1},%
	datascaletrafo set params={%
		\expandafter\edef\csname pgfplots@data@scale@trafo@EXPONENT@\pgfplotscoordmathid\endcsname{#1}%
		\expandafter\edef\csname pgfplots@data@scale@trafo@SHIFT@\pgfplotscoordmathid\endcsname{#2}%
	},%
	datascaletrafo set shift={%
		\expandafter\edef\csname pgfplots@data@scale@trafo@SHIFT@\pgfplotscoordmathid\endcsname{#1}%
	},%
	datascaletrafo get params={%
		\edef\pgfplotsretval{\csname pgfplots@data@scale@trafo@EXPONENT@\pgfplotscoordmathid\endcsname}%
		\edef\pgfplotsretvalb{\csname pgfplots@data@scale@trafo@SHIFT@\pgfplotscoordmathid\endcsname}%
		\edef\pgfmathresult{%
			{\pgfplotsretval}%
			{\pgfplotsretvalb}%
		}%
	},%
	datascaletrafo={%
		\edef\pgfmathresult{#1}%
		\pgfmathfloatshift@\pgfmathresult{\csname pgfplots@data@scale@trafo@EXPONENT@\pgfplotscoordmathid\endcsname}%
		\pgfmathfloattofixed\pgfmathresult
		\expandafter\pgfmath@basic@subtract@\expandafter{\pgfmathresult}{\csname pgfplots@data@scale@trafo@SHIFT@\pgfplotscoordmathid\endcsname}%
	},%
	datascaletrafo noshift={%
		\edef\pgfmathresult{#1}%
		\pgfmathfloatshift@\pgfmathresult{\csname pgfplots@data@scale@trafo@EXPONENT@\pgfplotscoordmathid\endcsname}%
		\pgfmathfloattofixed{\pgfmathresult}%
	},%
	datascaletrafo undo shift=
		\pgfmath@basic@subtract@{#1}{\csname pgfplots@data@scale@trafo@SHIFT@\pgfplotscoordmathid\endcsname},%
	datascaletrafo redo shift=\pgfmath@basic@add@{#1}{\csname pgfplots@data@scale@trafo@SHIFT@\pgfplotscoordmathid\endcsname},%
	datascaletrafo inverse={%
		\pgfplotscoordmath@float@datascaletrafo@inverse{#1}%
	},%
	datascaletrafo inverse to fixed={%
		\pgfplotscoordmath@float@datascaletrafo@inverse{#1}%
		\pgfmathfloattofixed\pgfmathresult
	},%
	datascaletrafo noshift inverse={%
		\pgfmathfloatparsenumber{#1}%
		\pgfmathfloatshift@{\pgfmathresult}{-\csname pgfplots@data@scale@trafo@EXPONENT@\pgfplotscoordmathid\endcsname}%
	},%
	datascaletrafo noshift inverse to fixed={%
		\pgfmathfloatparsenumber{#1}%
		\pgfmathfloatshift@{\pgfmathresult}{-\csname pgfplots@data@scale@trafo@EXPONENT@\pgfplotscoordmathid\endcsname}%
		\pgfmathfloattofixed\pgfmathresult
	},%
}

\def\pgfplotscoordmath@float@datascaletrafo@inverse#1{%
	\pgfmath@basic@add@{#1}{\csname pgfplots@data@scale@trafo@SHIFT@\pgfplotscoordmathid\endcsname}%
	\let\pgfplots@inverse@datascaletrafo@@shifted=\pgfmathresult
	\pgfmathapproxequalto@{\pgfplots@inverse@datascaletrafo@@shifted}{0.0}%
	\ifpgfmathcomparison
		\pgfmathfloatcreate{0}{0.0}{0}%
	\else
		\pgfmathfloatparsenumber{\pgfplots@inverse@datascaletrafo@@shifted}%
		\pgfmathfloatshift@{\pgfmathresult}{-\csname pgfplots@data@scale@trafo@EXPONENT@\pgfplotscoordmathid\endcsname}%
	\fi
}%

% Invokes a coordinate math routine.
%
% #1: the axis (x,y or z)
% #2: a method name declared by \pgfplotsdeclarecoordmath (one of
% 'op', 'parsenumber', 'tofixed' etc)
% #3-#9: any further arguments required to perform the call to '#2'.
%
% \pgfplotscoordmath {x}{op}{multiply}{{<a>}{<b>}}
% \pgfplotscoordmath {x}{parsenumber}{<a>}
\def\pgfplotscoordmath#1#2{%
	\edef\pgfplotscoordmathid{#1}%
	\csname pgfpmth@\csname pgfcrdmth@#1\endcsname @#2\endcsname}%

\def\pgfplotscoordmathclassfor#1{\csname pgfcrdmth@#1\endcsname}%

\def\pgfplotscoordmathnotifydatascalesetfor#1{}%

% Enables a particular coordinate math class for the label `#1'.
%
% #1 a label (usually x,y or z)
% #2 the coordinate math class (one prepare by
% \pgfplotsdeclarecoordmath)
%
% From this point on, any call to \pgfplotscoordmath{#1}{...}
% will use the selected math class.
\def\pgfplotssetcoordmathfor#1#2{%
	\pgfutil@ifundefined{pgfpmth@#2@initialise}{%
		\pgfplotsthrow{invalid argument}{\pgfplots@loc@TMPa}{Sorry, \string\pgfplotssetcoordmathfor{#1}{#2} failed since `#2' is unknown. Maybe you misspelled it?}\pgfeov%
	}{%
		\expandafter\edef\csname pgfcrdmth@#1\endcsname{#2}%
		\pgfplotscoordmath{#1}{initialise}%
	}%
}%

% Defines \pgfplotsretval to be the coordmath id for #1
\def\pgfplotsgetcoordmathfor#1{%
	\pgfutil@ifundefined{pgfcrdmth@#1}{%
		\pgfplotsthrow{invalid argument}{\pgfplots@loc@TMPa}{Sorry, \string\pgfplotsgetcoordmathfor{#1} failed since `#1' is unknown. Maybe you misspelled it?}\pgfeov%
	}{%
		\pgfutil@namelet{pgfplotsretval}{pgfcrdmth@#1}%
	}%
}%
\pgfplotssetcoordmathfor{pgfbasic}{pgfbasic}%
\pgfplotssetcoordmathfor{float}{float}%
\pgfplotssetcoordmathfor{meta}{float}%
\pgfplotssetcoordmathfor{default}{float}%



% ==================================================================================



% #1  the name of an input method for point meta. It must have been
% declared by \pgfplotsdeclarepointmetasource first.
% #2  any arguments supplied by the user (maybe empty).
\def\pgfplotssetpointmetainput#1#2{%
	\csname pgfpmeta@#1@initfor\endcsname{#2}%
	%
	\edef\pgfplotspointmetainputhandler{#1}%
}%

% Expands to the current value of 'point meta'.
\def\pgfplotspointmetainputhandler{}

\def\pgfplotsaxisifhaspointmeta#1#2{%
	\ifx\pgfplotspointmetainputhandler\pgfutil@empty #2\else #1\fi
}%

% Invokes '#1' if the axis contains the coordinate designated by
% \pgfplots@current@point@[xyz] and '#2' if not.
\def\pgfplotsaxisifcontainspoint#1#2{%
	\pgf@xa=\pgfplots@current@point@x pt % FIXME : SCOPE REGISTERS!?
	\pgf@ya=\pgfplots@current@point@y pt %
	\ifpgfplots@curplot@threedim
		\pgf@yb=\pgfplots@current@point@z pt %
	\fi
	\def\pgfplots@loc@TMPa{#2}%
	% 
	% I assume that \pgfplots@[xyz]min@reg and min@reg are registers
	% containing the limits.
	\ifdim\pgf@xa<\pgfplots@xmin@reg
	\else
		\ifdim\pgf@xa>\pgfplots@xmax@reg
		\else
			\ifdim\pgf@ya<\pgfplots@ymin@reg
			\else
				\ifdim\pgf@ya>\pgfplots@ymax@reg
				\else
					\ifpgfplots@curplot@threedim
						\ifdim\pgf@yb<\pgfplots@zmin@reg
						\else
							\ifdim\pgf@yb>\pgfplots@zmax@reg
							\else
								\def\pgfplots@loc@TMPa{#1}%
							\fi
						\fi
					\else
						\def\pgfplots@loc@TMPa{#1}%
					\fi
				\fi
			\fi
		\fi
	\fi
	\pgfplots@loc@TMPa%
}

% Declares a routine which can be used to get point meta input.
%
% Such a routine is invoked in a context where point coordinates are
% processed, i.e. during 'plot coordinates', 'plot table' or the like.
%
% The routine is called `#1'. It consists of several methods, which
% are described below, in the key definitions.
%
% #1: the name of the input routine.
% #2: a sequence of key-value pairs which can be used to overwrite
% 'assign', 'initfor' or the other components.
% 	See the definitions below for examples.
\def\pgfplotsdeclarepointmetasource#1#2{%
	\expandafter\def\csname pgfpmeta@#1@assign\endcsname{\let\pgfplots@current@point@meta=\pgfutil@empty}%
	\expandafter\def\csname pgfpmeta@#1@initfor\endcsname##1{}%
	\expandafter\def\csname pgfpmeta@#1@issymbolic\endcsname{0}%
	\expandafter\def\csname pgfpmeta@#1@explicitinput\endcsname{0}%
	\expandafter\def\csname pgfpmeta@#1@activate\endcsname{}%
	\edef\pgfplotsdeclarepointmetasource@{#1}%
	\pgfqkeys{/pgfplots/@declare point meta src}{#2}%
}%
\pgfqkeys{/pgfplots/@declare point meta src}{%
	%
	% 		a macro used to initialise the point meta source when it is
	% 		selected.
	% 		This macro body is invoked by pgfplots when someone types 
	%		'point meta=x' -> will invoke 'pgfpmeta@x@initfor{}'.
	%		The first argument to initfor can be supplied by the user.
	%		PRECONDITION for 'initfor':
	%			- it will be invoked just before
	%			'\pgfplotspointmetainputhandler' will be changed.
	%	Default is to do nothing.
	initfor/.code=
		{\expandafter\def\csname pgfpmeta@\pgfplotsdeclarepointmetasource@ @initfor\endcsname##1{#1}},%
	%
	% Called during the survey phase before the first 'assign' call.
	% It is usually empty.
	activate/.code=
		{\expandafter\def\csname pgfpmeta@\pgfplotsdeclarepointmetasource@ @activate\endcsname{#1}},%
	%
	% 	During the survey phase, this macro is expected to assign
	% 	\pgfplots@current@point@meta
	%	if it is a numeric input method, it should return a
	%	floating point number.
	%	It is allowed to return an empty string to say "there is no point
	%	meta".
	%	PRECONDITION for '@assign':
	%		- the coordinate input method has already assigned its
	%		'\pgfplots@current@point@meta' (probably as raw input string).
	%		- the other input coordinates are already read.
	%	POSTCONDITION for '@assign':
	%		- \pgfplots@current@point@meta is ready for use:
	%		- EITHER a parsed floating point number 
	%		- OR an empty string,
	%		- OR a symbolic string (if the issymbolic boolean is true)
	%	The default implementation is
	%	\let\pgfplots@current@point@meta=\pgfutil@empty
	%
	assign/.code=
		{\expandafter\def\csname pgfpmeta@\pgfplotsdeclarepointmetasource@ @assign\endcsname{#1}},%
	%
	%    expands to either '1' or '0'
	% 		A numeric source will be processed numerically in float
	% 		arithmetics. Thus, the output of the @assign routine should be
	% 		a macro \pgfplots@current@point@meta in float format.
	%
	%		The output of a numeric point meta source will result in meta
	%		limit updates and the final map to [0,1000] will be
	%		initialised automatically.
	%
	% 		A symbolic input routine won't be processed.
	% 	Default is '0'
	%
	issymbolic/.code=
		{\expandafter\def\csname pgfpmeta@\pgfplotsdeclarepointmetasource@ @issymbolic\endcsname{#1}},%
	%
	%   expands to either
	%   '1' or '0'. In case '1', it expects explicit input from the
	%   coordinate input routines. For example, 'plot file' will look for
	%   further input after the x,y,z coordinates.
	%   Default is '0'
	%
	explicitinput/.code=
		{\expandafter\def\csname pgfpmeta@\pgfplotsdeclarepointmetasource@ @explicitinput\endcsname{#1}},%
}%

% An empty one. This is simple to check with
% \ifx\pgfplotspointmetainputhandler\pgfutil@empty:
\pgfplotsdeclarepointmetasource{}{}
\pgfplotsdeclarepointmetasource{x}{assign={%
		\let\pgfplots@current@point@meta=\pgfplots@current@point@x
		\pgfplotscoordmath{meta}{parsenumber}{\pgfplots@current@point@meta}%
		\let\pgfplots@current@point@meta=\pgfmathresult
		}}
\pgfplotsdeclarepointmetasource{y}{assign={%
		\let\pgfplots@current@point@meta=\pgfplots@current@point@y
		\pgfplotscoordmath{meta}{parsenumber}{\pgfplots@current@point@meta}%
		\let\pgfplots@current@point@meta=\pgfmathresult
		}}
\pgfplotsdeclarepointmetasource{z}{assign={%
		\let\pgfplots@current@point@meta=\pgfplots@current@point@z
		\pgfplotscoordmath{meta}{parsenumber}{\pgfplots@current@point@meta}%
		\let\pgfplots@current@point@meta=\pgfmathresult
	}}

\pgfplotsdeclarepointmetasource{explicit}{%
	assign={%
		\ifx\pgfplots@current@point@meta\pgfutil@empty
		\else
			\pgfplotscoordmath{meta}{parsenumber}{\pgfplots@current@point@meta}%
			\let\pgfplots@current@point@meta=\pgfmathresult
		\fi
	},
	explicitinput=1%
}%
\pgfplotsdeclarepointmetasource{explicit symbolic}{%
	assign={},% no math, simply collect.
	explicitinput=1,%
	issymbolic=1%
}%

\pgfplotsdeclarepointmetasource{expr}{%
	assign={%
		\csname pgfpmeta@\pgfpmeta@expr@origchoice @assign\endcsname
		%
		\pgfkeysgetvalue{/pgfplots/point meta/expr}\pgfplots@loc@TMPa
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\pgfmathparse{\pgfplots@loc@TMPa}%
			\pgfplotscoordmath{meta}{parsenumber}{\pgfmathresult}%
			\let\pgfplots@current@point@meta=\pgfmathresult
		\fi
	},%
	initfor={%
		\pgfkeyssetvalue{/pgfplots/point meta/expr}{#1}%
		\def\pgfplots@loc@TMPa{expr}%
		\ifx\pgfplots@loc@TMPa\pgfplotspointmetainputhandler
		\else
			\let\pgfpmeta@expr@origchoice\pgfplotspointmetainputhandler
		\fi
		\ifx\pgfpmeta@expr@origchoice\pgfplots@loc@TMPa
			\let\pgfpmeta@expr@origchoice\pgfutil@empty
		\fi
	},
}%
\pgfkeyssetvalue{/pgfplots/point meta/expr}{}%

\pgfplotsdeclarepointmetasource{f(x)}{%
	activate={%
		\ifpgfplots@curplot@threedim
			\def\pgfplotspointmetainputhandler{z}%
		\else
			\def\pgfplotspointmetainputhandler{y}%
		\fi
		\csname pgfpmeta@\pgfplotspointmetainputhandler @activate\endcsname
	},
}%

\pgfplotsdeclarepointmetasource{TeX code}{%
	assign={%
		\begingroup
		\let\pgfplotspointmeta=\pgfutil@empty
		\pgfplots@invoke@pgfkeyscode{/pgfplots/point meta/code/.@cmd}{}%
		\pgfplotscoordmath{meta}{parsenumber}{\pgfplotspointmeta}%
		\let\pgfplots@current@point@meta=\pgfmathresult
		\pgfmath@smuggleone\pgfplots@current@point@meta
		\endgroup
	},%
	initfor={%
		\pgfkeysdef{/pgfplots/point meta/code}{#1}%
	},
}%
\pgfplotsdeclarepointmetasource{TeX code symbolic}{%
	assign={%
		\begingroup
		\let\pgfplotspointmeta=\pgfutil@empty
		\pgfplots@invoke@pgfkeyscode{/pgfplots/point meta/code/.@cmd}{}%
		\let\pgfplots@current@point@meta=\pgfplotspointmeta
		\pgfmath@smuggleone\pgfplots@current@point@meta
		\endgroup
	},%
	initfor={%
		\pgfkeysdef{/pgfplots/point meta/code}{#1}%
	},
	issymbolic=1%
}%
\pgfkeysdef{/pgfplots/point meta/code}{}%

% Internal stream methods.
%
% Please overwrite 
% - \pgfplots@coord@stream@start@,
% - \pgfplots@coord@stream@end@ and 
% - \pgfplots@coord@stream@coord@
% if you implement streams.
%
% REMARK:
% 	- the stream methods automatically collect first and last
% 	coordinates.
% 	- I have experimented with global \addplot accumulation to reduce
% 	copy operations. That experiment was not successfull (it was not
% 	faster :-(  ). However, the streaming methods still assign their
% 	things globally...
\def\pgfplots@coord@stream@start{%
	\let\pgfplots@current@point@x=\pgfutil@empty
	\let\pgfplots@current@point@y=\pgfutil@empty
	\let\pgfplots@current@point@z=\pgfutil@empty
	\let\pgfplots@current@point@meta=\pgfutil@empty
	\let\pgfplots@current@point@error@x@plus=\pgfutil@empty
	\let\pgfplots@current@point@error@x@minus=\pgfutil@empty
	\let\pgfplots@current@point@error@y@plus=\pgfutil@empty
	\let\pgfplots@current@point@error@y@minus=\pgfutil@empty
	\let\pgfplots@current@point@error@z@plus=\pgfutil@empty
	\let\pgfplots@current@point@error@z@minus=\pgfutil@empty
	\pgfplots@coord@stream@start@}%
\def\pgfplots@coord@stream@end{\pgfplots@coord@stream@end@}

% Will be invoked for every point coordinate.
%
% It invokes \pgfplots@coord@stream@coord@.
%
% Arguments:
% \pgfplots@current@point@[xyz]
% \pgfplots@current@point@[xyz]@error (if in argument list)
% \pgfplots@current@point@meta
\def\pgfplots@coord@stream@coord{%
	\pgfplots@coord@stream@coord@%
}%
\def\pgfplotscoordstream@firstlast@init{%
	\global\let\pgfplots@currentplot@firstcoord@x=\pgfutil@empty
	\global\let\pgfplots@currentplot@firstcoord@y=\pgfutil@empty
	\global\let\pgfplots@currentplot@firstcoord@z=\pgfutil@empty
	\global\let\pgfplots@currentplot@lastcoord@x=\pgfutil@empty
	\global\let\pgfplots@currentplot@lastcoord@y=\pgfutil@empty
	\global\let\pgfplots@currentplot@lastcoord@z=\pgfutil@empty
}%
\def\pgfplotscoordstream@firstlast@update{%
	\ifx\pgfplots@current@point@x\pgfutil@empty
		% only one \if is enough as ONE empty coordinate causes all
		% others to be reset as well.
	\else
		\ifx\pgfplots@currentplot@firstcoord@x\pgfutil@empty
			\global\let\pgfplots@currentplot@firstcoord@x=\pgfplots@current@point@x
			\global\let\pgfplots@currentplot@firstcoord@y=\pgfplots@current@point@y
			\global\let\pgfplots@currentplot@firstcoord@z=\pgfplots@current@point@z
		\fi
		\global\let\pgfplots@currentplot@lastcoord@x=\pgfplots@current@point@x
		\global\let\pgfplots@currentplot@lastcoord@y=\pgfplots@current@point@y
		\global\let\pgfplots@currentplot@lastcoord@z=\pgfplots@current@point@z
	\fi
}%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Scanline management. The idea is to handle complete sequences of
% input coordinates, which are usually separated by a blank line.
%
% This allows a simple syntax to provide matrix input - by means of scanlines.
% Furthermore, 2d plots can use it to interrupt the display.
%
% An empty line in 'addplot coordinates {}' indicates the end of a
% scan line. Similarly, an empty line in 'addplot file' or 'table'
% also indicates the end of a scan line.
%
% The steps taken whenever a scan line is complete depend on the
% configuration of the /pgfplots/empty line choice key (queried in
% \pgfplotsscanlinelengthinitzero).
%
%
% The following methods constitute the scanline interface.
%
% Usage:
%
% \pgfplotsscanlinelengthinitzero
%
% \pgfplotsscanlinelengthincrease
% <process point>
% \pgfplotsscanlinelengthincrease
% <process point>
% \pgfplotsscanlinelengthincrease
% <process point>
% \pgfplotsscanlinecomplete
% \pgfplotsscanlinelengthincrease
% <process point>
% \pgfplotsscanlinelengthincrease
% <process point>
% \pgfplotsscanlinelengthincrease
% <process point>
% \pgfplotsscanlinecomplete
% \pgfplotsscanlinelengthincrease
% <process point>
% \pgfplotsscanlinelengthincrease
% <process point>
% \pgfplotsscanlinelengthincrease
% <process point>
% \pgfplotsscanlinecomplete
%
% \pgfplotsscanlinelengthcleanup
%
% In other words, the \pgfplotsscanlinelengthincrease routine is
% invoked *before* the point is processed. That's important.
%
% Now, \pgfplotsscanlinelength expands to either 
% a) a negative number in which case there is no 
%  unique scanline length.
%  	More precisely, -1 means "there was no end-of-scanline marker"
%  	-2 means "there where end-of-scanline markers, but the scanlines
%  	had different lengths.
% b) the scanline length.
\def\pgfplotsscanlinelengthinitzero{%
	\def\pgfplotsscanlinelength{-1}%
	\pgfkeysgetvalue{/pgfplots/empty line}\pgfplots@loc@TMPa%
	\edef\pgfplots@loc@TMPa{\pgfplots@loc@TMPa}%
	\def\pgfplots@loc@TMPb{auto}%
	\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
		\pgfplotsdetermineemptylinehandler
		\pgfkeysgetvalue{/pgfplots/empty line}\pgfplots@loc@TMPa%
	\fi
	\def\pgfplots@loc@TMPb{jump}%
	\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
		\def\pgfplots@loc@TMPa{nan}% alias for jump
	\fi
	\def\pgfplots@loc@TMPb{no op}%
	\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
		\def\pgfplots@loc@TMPa{none}% alias for no op
	\fi
	\pgfutil@ifundefined{pgfplotsscanlinelength@\pgfplots@loc@TMPa @initzero}{%
		\pgfplots@error{Sorry, the choice `empty line=\pgfkeysvalueof{/pgfplots/empty line}' is unknown. Maybe you misspelled it}%
	}{}%
	\expandafter\let\expandafter\pgfplotsscanlinelength@initzero	\csname pgfplotsscanlinelength@\pgfplots@loc@TMPa @initzero\endcsname
	\expandafter\let\expandafter\pgfplotsscanlinelengthincrease		\csname pgfplotsscanlinelength@\pgfplots@loc@TMPa @increase\endcsname
	\edef\pgfplotsscanlinecomplete{%
		\expandafter\noexpand\csname pgfplotsscanlinelength@\pgfplots@loc@TMPa @complete\endcsname
		\noexpand\pgfplotsplothandlernotifyscanlinecomplete
	}%
	\expandafter\let\expandafter\pgfplotsscanlinelengthcleanup		\csname pgfplotsscanlinelength@\pgfplots@loc@TMPa @cleanup\endcsname
	\pgfplotsscanlinelength@initzero
}%

\newif\ifpgfplots@emptyline@compat

% Invoked for 'empty line=auto'. 
%
% @POSTCONDITION: '/pgfplots/empty line' is set to something useful
% (not auto)
\def\pgfplotsdetermineemptylinehandler{%
	\if n\pgfplots@meshmode
		% no mesh/surf plot:
		\pgfkeyssetvalue{/pgfplots/empty line}{jump}%
		\ifpgfplots@emptyline@compat
			\pgfkeyssetvalue{/pgfplots/empty line}{none}% do nothing for backwards compatibility with 2D processing.
		\fi
	\else
		% it is a mesh or surf plot; use scanline:
		\pgfkeyssetvalue{/pgfplots/empty line}{scanline}%
	\fi
}%
\def\pgfplotsscanlinedisablechanges{%
	\let\pgfplotsscanlinecomplete=\relax
	\let\pgfplotsscanlinelengthincrease=\relax
	\let\pgfplotsscanlinelengthcleanup=\relax
	\let\pgfplotsscanlinelengthinitzero=\relax
	\let\pgfplotsscanlineendofinput=\relax
}%

% -------------------------------------------------------------------------------
% empty line=scanline
% class:
\def\pgfplotsscanlinelength@scanline@initzero{%
	\c@pgfplots@scanlineindex=0
	\def\pgfplots@scanlinelength{-1}%
}
\def\pgfplotsscanlinelength@scanline@increase{%
	\advance\c@pgfplots@scanlineindex by1
}
\def\pgfplotsscanlinelength@scanline@complete{%
	\ifnum\pgfplots@scanlinelength>0
		\ifnum\c@pgfplots@scanlineindex=0
			% 
			% \pgfplotsscanlinecomplete
			% \pgfplotsscanlinecomplete
			% \pgfplotsscanlinecomplete
			% should have the same effect as a single statement. Do
			% nothing here.
		\else
			\ifnum\pgfplots@scanlinelength=\c@pgfplots@scanlineindex\relax
			\else
%\message{Found inconsistent scan line length: \pgfplots@scanlinelength\space vs. \the\c@pgfplots@scanlineindex\space near line \pgfplotstablelineno.}%
				% special marker which means 'inconsistent scan line length found'
				\def\pgfplots@scanlinelength{-2}%
			\fi
		\fi
	\else
		\ifnum\pgfplots@scanlinelength=-2
		\else
			\edef\pgfplots@scanlinelength{\the\c@pgfplots@scanlineindex}%
		\fi
	\fi
	\c@pgfplots@scanlineindex=0
}
\def\pgfplotsscanlinelength@scanline@cleanup{%
	\ifnum\c@pgfplots@scanlineindex=0
		% I assume the last scan line is already complete.
	\else
		\pgfplotsscanlinecomplete
	\fi
	\let\pgfplotsscanlinelength=\pgfplots@scanlinelength
}
% -------------------------------------------------------------------------------
%
% empty line=none   class:
% 
\let\pgfplotsscanlinelength@none@initzero=\pgfutil@empty
\let\pgfplotsscanlinelength@none@increase=\relax
\let\pgfplotsscanlinelength@none@complete=\relax
\let\pgfplotsscanlinelength@none@cleanup=\relax
% -------------------------------------------------------------------------------
%
% empty line=nan   class:
\def\pgfplotsscanlinelength@nan@initzero{%
	\def\pgfplotsscanlinelength@nan@isfirst{1}%
	\let\pgfplotsscanlinelength@nan@pendingwork=\relax
	\pgfplotsifinaxis{}{\let\pgfplotsaxisserializedatapoint=\relax}%
}%
\def\pgfplotsscanlinelength@nan@increase{%
	\def\pgfplotsscanlinelength@nan@isfirst{0}%
	\pgfplotsscanlinelength@nan@pendingwork
}%
\def\pgfplotsscanlinelength@nan@complete{%
	\if1\pgfplotsscanlinelength@nan@isfirst
	\else
		\def\pgfplotsscanlinelength@nan@pendingwork{%
			% this will be executed when the next point has been
			% found.
			\def\pgfplots@current@point@x{}%
			\def\pgfplots@current@point@y{}%
			\def\pgfplots@current@point@z{}%
			% simply serialize an empty point. That works -- the
			% visualization phase checks if the coordinates are empty and
			% visualizes them as "jump"
			%
			% Note that \pgfplotsplothandlersurveypoint is not a good
			% choice here unless one employs its 'unbounded coords=jump'
			% feature
			\def\pgfplotsaxisplothasjumps{1}%
			\pgfplotsaxisserializedatapoint
			%
			\let\pgfplotsscanlinelength@nan@pendingwork=\relax
		}%
	\fi
	\def\pgfplotsscanlinelength@nan@isfirst{1}%
}%
\let\pgfplotsscanlinelength@nan@cleanup=\relax
% 
% -------------------------------------------------------------------------------


\def\pgfplotsaxisfilteredcoordsaway{0}%
\def\pgfplotsaxisplothasjumps{0}%
\newif\ifpgfplotsaxisparsecoordinateok

% Initialises 
% \pgfplots@coord@stream@start
% \pgfplots@coord@stream@coord
% \pgfplots@coord@stream@end
% such that a following coordinate stream is processed properly. The
% following coordinate stream may come from different input methods.
%
% This coordinate stream is the first time a coordinate will be
% reported and processed by pgfplots. The task of this first pass is
% to
% - compute and update any axis limits,
% - collect and prepare ranges for color data,
% - handle stacked plots and error bars,
% - store the complete state of the plot's preprocessing in an
%   internal datastructure for later completion.
%   This involves a serialization of all processed points (i.e. the
%   generation of a long coordinate list)
%
% Any \addplot command should issue \pgfplots@PREPARE@COORD@STREAM
% eventually.
%
% Arguments:
% #1:  any trailing path commands after the 'plot' command as such,
%      for example \addplot plot coordinates {...} -- (0,0);
%      would yield #1 =' -- (0,0)'
%
% PRECONDITION:
% 	- needs to be called inside of \addplot.
% 	- \pgfplots@addplot@survey@@optionlist contains the <options>
% 	provided to \addplot (all of them, including automatically
% 	determined ones)
%
% REMARK:
% 	The following code is permissable:
% 		\pgfplots@PREPARE@COORD@STREAM{...}
% 		\pgfplots@coord@stream@start
% 		...
% 		\pgfplots@coord@stream@coord
% 		..
%		\pgfplots@coord@stream@coord
%		..
% 		\pgfplots@coord@stream@end
% 	-> All need to be the SAME LEVEL OF SCOPING! The '@coord' commands
% 	may not be scoped deeper than 'begin' and 'end'!
% 	- I had a version which allowed that. it was actually slower!
% 	- For now, the following things are global / local:
% 		- point coordinate list: local
% 		- meta data limits: global,
% 		- what about stacked plot stuff: appears to be a combination
% 		of local/global.
% 		- all that will be serialized and written into
% 		\pgfplots@stored@plotlist in \pgfplots@coord@stream@end.
% 	This list is global, so, if I am not mistaken, the scoping
% 	level of the complete stream operation from setup to @end can
% 	be as deep as necessary - as long as all operations have the
% 	same level of scoping.
%
% @see the detailed documentation in pgfplotsplothandlers.code.tex
\long\def\pgfplots@PREPARE@COORD@STREAM#1{%
	\ifpgfplots@curplot@threedim
		\global\pgfplots@threedimtrue
	\fi
	\def\pgfplotsaxisfilteredcoordsaway{0}%
	\def\pgfplotsaxisplothasjumps{0}%
	%
	% FIXME : these macros should not be redefined! They are defined
	% in \pgfplots@prepare@axis@API right during \begin{axis}... they
	% probably shouldn't be changed.
	\ifpgfplots@curplot@threedim
		\let\pgfplotsaxisupdatelimitsforcoordinate=\pgfplotsaxisupdatelimitsforcoordinatethreedim
		\let\pgfplotsaxisparsecoordinate=\pgfplotsaxisparsecoordinatethreedim
	\else
		\let\pgfplotsaxisupdatelimitsforcoordinate=\pgfplotsaxisupdatelimitsforcoordinatetwodim
		\let\pgfplotsaxisparsecoordinate=\pgfplotsaxisparsecoordinatetwodim
	\fi
	\begingroup
	%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	\let\E=\noexpand
	% 
%\message{Assembled update-limits \ifpgfplots@curplot@threedim 3D\else 2D\fi macro to {\meaning\pgfplotsaxisupdatelimitsforcoordinate}}%
	\ifpgfplots@bb@isactive
	\else
		% we are inside of 
		% \pgfplotsinterruptdatabb 
		% ..
		% \endpgfinterruptboundingbox
		% -> don't change data limits!
		\gdef\pgfplotsaxisupdatelimitsforcoordinate##1##2##3{}%
	\fi
	%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	%
	%
	% Takes a coordinate which is already parsed and applies steps
	% such that it becomes its final values.
	%
	% This implements the stacked plot feature currently.
	%
	% PRECONDITION:
	% 	\pgfplotsaxisparsecoordinate has already been called.
	%
	% POSTCONDITION:
	% 	the point has its final coordinates; the axis won't change it
	% 	anymore.
	\xdef\pgfplotsaxispreparecoordinate{%
		\E\ifpgfplotsaxisparsecoordinateok
			% All following routines (limit updating/stacking/error
			% bars) will use float numerics if necessary (controlled
			% by ifs).
			\E\pgfplotsaxistransformfromdatacs
			\ifpgfplots@stackedmode
				\E\pgfplots@stacked@preparepoint@inmacro%
			\fi
		\E\fi
	}%
	%
	% A macro which should be called once for every data point during the
	% survey phase.
	%
	% The caller is the plot handler's point survey routine.
	%
	% A data point might be a complicated thing which contains
	% multiple coordinates. You need to invoke
	% \pgfplotsaxisparsecoordinate and 
	% \pgfplotsaxispreparecoordinate for each of them. But
	% \pgfplotsaxisdatapointsurveyed is invoked once for the complete
	% set.
	% 
	% @PRECONDITION
	% 	- \pgfplots@current@point@[xyz] contain final coordinates
	% 	(i.e. output of \pgfplotsaxispreparecoordinate)
	%
	% @POSTCONDITION
	% 	- stacked plot things, 
	% 	- error bars,
	% 	- xtick=data
	% 	are all processed.
	%
	\xdef\pgfplotsaxisdatapointsurveyed{%
		\E\ifpgfplotsaxisparsecoordinateok
			% All following routines (limit updating/stacking/error
			% bars) will use float numerics if necessary (controlled
			% by ifs).
			%
			% Prepare \pgfplots@current@point@meta (see the preparation
			% routine above):
			\E\pgfplotsaxissurveysetpointmeta
			%
			\ifpgfplots@errorbars@enabled
				\E\pgfplots@errorbars@survey@point
			\fi
			%
			\ifpgfplots@collect@firstplot@astick
				\ifnum\pgfplots@numplots=0
					\E\ifx\E\pgfplots@firstplot@coords@x\E\pgfutil@empty
						\E\t@pgfplots@tokc={}%
					\E\else
						\E\t@pgfplots@tokc=\E\expandafter{\E\pgfplots@firstplot@coords@x,}%
					\E\fi
					\E\xdef\E\pgfplots@firstplot@coords@x{\E\the\E\t@pgfplots@tokc\E\pgfplots@current@point@x}%
					\E\ifx\E\pgfplots@firstplot@coords@y\E\pgfutil@empty
						\E\t@pgfplots@tokc={}%
					\E\else
						\E\t@pgfplots@tokc=\E\expandafter{\E\pgfplots@firstplot@coords@y,}%
					\E\fi
					\E\xdef\E\pgfplots@firstplot@coords@y{\E\the\E\t@pgfplots@tokc\E\pgfplots@current@point@y}%
					%
					\ifpgfplots@curplot@threedim
						\E\ifx\E\pgfplots@firstplot@coords@z\E\pgfutil@empty
							\E\t@pgfplots@tokc={}%
						\E\else
							\E\t@pgfplots@tokc=\E\expandafter{\E\pgfplots@firstplot@coords@z,}%
						\E\fi
						\E\xdef\E\pgfplots@firstplot@coords@z{\E\the\E\t@pgfplots@tokc\E\pgfplots@current@point@z}%
					\fi
				\fi
			\fi
			\E\pgfplotscoordstream@firstlast@update
			\E\pgfplotsaxisserializedatapoint
		\E\else
			% COORDINATE HAS BEEN FILTERED AWAY:
			%
			% make ALL empty to simplify special case checking:
			\E\let\E\pgfplots@current@point@x=\E\pgfutil@empty
			\E\let\E\pgfplots@current@point@y=\E\pgfutil@empty
			\E\let\E\pgfplots@current@point@z=\E\pgfutil@empty
			% check whether we have UNBOUNDED or just unfiltered
			% coords:
			\if\pgfplots@unbounded@handler d% unbounded coords=discard
				\E\def\E\pgfplotsaxisfilteredcoordsaway{1}%
				\ifpgfplots@warn@for@filter@discards
					\E\pgfplots@message{%
						NOTE: coordinate (\E\pgfplots@current@point@x@unfiltered,\E\pgfplots@current@point@y@unfiltered\ifpgfplots@curplot@threedim,\E\pgfplots@current@point@z@unfiltered\fi)
						has been dropped because 
						\E\ifx\E\pgfplots@unbounded@dir\E\pgfutil@empty
							of a coordinate filter.
						\E\else
							it is unbounded (in \E\pgfplots@unbounded@dir).
						\E\fi
						(see also unbounded coords=jump).
					}%
				\fi
			\else
				% unbounded coords=jump
				\E\ifx\E\pgfplots@unbounded@dir\E\pgfutil@empty
					\E\def\E\pgfplotsaxisfilteredcoordsaway{1}%
					\ifpgfplots@warn@for@filter@discards
						\E\pgfplots@message{%
							NOTE: coordinate (\E\pgfplots@current@point@x@unfiltered,\E\pgfplots@current@point@y@unfiltered\ifpgfplots@curplot@threedim,\E\pgfplots@current@point@z@unfiltered\fi)
							has been dropped because of a coordinate filter.
						}%
					\fi
				\E\else
					\E\def\E\pgfplotsaxisplothasjumps{1}%
					\E\pgfplotsaxisserializedatapoint
				\E\fi
			\fi
		\E\fi
		%
		% increase \pgfplots@current@point@coordindex:
		\E\advance\E\c@pgfplots@coordindex by1
	}%
	%
	%
	%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	\endgroup
	%
	\def\pgfplotsaxissurveysetpointmeta{%
		\pgfplotsplothandlersurveybeforesetpointmeta
		\pgfplots@set@perpointmeta
		\pgfplotsplothandlersurveyaftersetpointmeta
	}%
	%
%\message{Prepared macro \string\pgfplots@update@limits@for@one@point: {\meaning\pgfplotsaxisupdatelimitsforcoordinate}}%
%\message{Prepared macro \string\pgfplots@process@one@point: {\meaning\pgfplots@process@one@point}}%
	% 
	\let\pgfplots@coord@stream@start@=\pgfplots@PREPARE@COORD@STREAM@start@
	\def\pgfplots@coord@stream@coord@{%
		\def\pgfplots@set@perpointmeta@done{0}%
		\pgfplotsplothandlersurveypoint
	}%
	\def\pgfplots@coord@stream@end@{\pgfplots@PREPARE@COORD@STREAM@end@{#1}}%
}%

% The \pgfplots@coord@stream@start@ routine used inside of
% \pgfplots@PREPARE@COORD@STREAM.
%
% It prepares everything for the first pass through all input
% coordinates.
\def\pgfplots@PREPARE@COORD@STREAM@start@{%
	% The current implementation of pgfplots stores the preprocessed
	% coordinate stream into a long list of coordinates.
	% Since macro append is an expensive operation, it uses the highly
	% optimized 'applistXX' structure:
	\pgfplotsapplistXXnewempty
	%
	\edef\plotnumofactualtype{\numplotsofactualtype}%
	\csname pgfpmeta@\pgfplotspointmetainputhandler @activate\endcsname
	\pgfplotsplothandlersurveystart
	\pgfplotscoordstream@firstlast@init
	%
	\pgfkeyssetvalue{/data point/x}{\pgfplots@current@point@x}%
	\pgfkeyssetvalue{/data point/y}{\pgfplots@current@point@y}%
	\pgfkeyssetvalue{/data point/z}{\pgfplots@current@point@z}%
	\pgfkeyssetvalue{/data point/meta}{\pgfplots@current@point@meta}%
	%
	\ifpgfplots@stackedmode
		\pgfplots@stacked@beginplot
	\fi
	\ifpgfplots@errorbars@enabled
		% prepare error bar processing.
		\pgfplots@errorbars@survey@begin
	\fi
	%
	%
	\pgfplots@prepare@visualization@dependencies
	%
	% Inside of math expressions, 'x', 'y' and 'z' expand to the
	% current x,y and z coords respectively. Introduce these (and some
	% more) shortcuts:
	\pgfplotsmathdeclarepseudoconstant{x}{\let\pgfmathresult=\pgfplots@current@point@x}%
	\pgfplotsmathdeclarepseudoconstant{y}{\let\pgfmathresult=\pgfplots@current@point@y}%
	\pgfplotsmathdeclarepseudoconstant{z}{\let\pgfmathresult=\pgfplots@current@point@z}%
	\pgfplotsmathdeclarepseudoconstant{rawx}{\let\pgfmathresult=\pgfplots@current@point@x@unfiltered}%
	\pgfplotsmathdeclarepseudoconstant{rawy}{\let\pgfmathresult=\pgfplots@current@point@y@unfiltered}%
	\pgfplotsmathdeclarepseudoconstant{rawz}{\let\pgfmathresult=\pgfplots@current@point@z@unfiltered}%
	\pgfplotsmathdeclarepseudoconstant{meta}{%
		\let\pgfmathresult=\pgfplots@current@point@meta
		\ifx\pgfmathresult\pgfutil@empty
			\pgfplotscoordmath{meta}{parsenumber}{0}%
		\fi
	}%
	%
	% %%%%%%%%%%%%%%
	%
	% Define \pgfplots@set@perpointmeta properly:
	\def\pgfplots@set@perpointmeta{%
		\if0\pgfplots@set@perpointmeta@done
			\csname pgfpmeta@\pgfplotspointmetainputhandler @assign\endcsname
			\def\pgfplots@set@perpointmeta@done{1}%
			\pgfplots@set@perpointmeta@limits
		\fi
	}%
	% append limit updating to \pgfplots@set@perpointmeta :
	\if0\csname pgfpmeta@\pgfplotspointmetainputhandler @issymbolic\endcsname
		% We need to work with per point meta data.
		% So, also compute the data range on a per-plot basis!
		% These limits are important later.
		\pgfkeysgetvalue{/pgfplots/point meta min}\pgfplots@metamin
		\t@pgfplots@tokb={}%
		\ifx\pgfplots@metamin\pgfutil@empty
			\global\let\pgfplots@metamin=\pgfplots@invalidrange@metamin
			\t@pgfplots@tokb=\expandafter{\the\t@pgfplots@tokb
				\pgfplotscoordmath{meta}{min}{\pgfplots@metamin}{\pgfplots@current@point@meta}%
				\global\let\pgfplots@metamin=\pgfmathresult
			}%
		\else
			\pgfplotscoordmath{meta}{parsenumber}{\pgfplots@metamin}%
			\global\let\pgfplots@metamin=\pgfmathresult
		\fi
		\pgfkeysgetvalue{/pgfplots/point meta max}\pgfplots@metamax
		\ifx\pgfplots@metamax\pgfutil@empty
			\global\let\pgfplots@metamax=\pgfplots@invalidrange@metamax
			\t@pgfplots@tokb=\expandafter{\the\t@pgfplots@tokb
				\pgfplotscoordmath{meta}{max}{\pgfplots@metamax}{\pgfplots@current@point@meta}%
				\global\let\pgfplots@metamax=\pgfmathresult
			}%
		\else
			\pgfplotscoordmath{meta}{parsenumber}{\pgfplots@metamax}%
			\global\let\pgfplots@metamax=\pgfmathresult
		\fi
		%
		\edef\pgfplots@set@perpointmeta@limits{%
			\noexpand\ifx\noexpand\pgfplots@current@point@meta\noexpand\pgfutil@empty
			\noexpand\else
				\the\t@pgfplots@tokb
			\noexpand\fi
		}%
		\def\pgfplotsaxisupdatelimitsforpointmeta##1{%
			\begingroup
			\def\pgfplots@current@point@meta{##1}%
			\pgfplots@set@perpointmeta@limits
			\endgroup
		}%
	\else
		% there is no point meta:
		\global\let\pgfplots@metamin=\pgfutil@empty
		\global\let\pgfplots@metamax=\pgfutil@empty
		\let\pgfplots@set@perpointmeta@limits=\relax
		\def\pgfplotsaxisupdatelimitsforpointmeta##1{}%
	\fi
}%
% This is the \pgfplots@coord@stream@end@ routine which is invoked by
% \pgfplots@PREPARE@COORD@STREAM. 
%
% It finalizes the first pass through the input coordinates and
% remembers the preprocessed \addplot command.
%
% Technical note: The parameters provided to
% \pgfplots@PREPARE@COORD@STREAM
% are needed here. This doesn't fit directly into the framework of
% coordinate streams, see \pgfplots@PREPARE@COORD@STREAM how this
% invocation works.
%
% #1,#2: see \pgfplots@PREPARE@COORD@STREAM
\def\pgfplots@PREPARE@COORD@STREAM@end@#1{%
	\pgfkeysvalueof{/pgfplots/execute at end survey}%
	% FIXME : move this the \pgfplotsplothandlersurveyend of mesh plot
	% handler:
	\pgfkeyssetvalue{/pgfplots/mesh/num points}{\pgfplots@current@point@coordindex}%
	%
	\pgfplotsplothandlersurveyend
	\ifx\pgfplots@metamin\pgfutil@empty
	\else
		\if\pgfplots@axiswide@metamin@autocompute1%
			\pgfplotscoordmath{meta}{min}{\pgfplots@axiswide@metamin}{\pgfplots@metamin}%
			\global\let\pgfplots@axiswide@metamin=\pgfmathresult
		\fi
		\if\pgfplots@axiswide@metamax@autocompute1%
			\pgfplotscoordmath{meta}{max}{\pgfplots@axiswide@metamax}{\pgfplots@metamax}%
			\global\let\pgfplots@axiswide@metamax=\pgfmathresult
		\fi
	\fi
	\if1\pgfplots@colorbar@set@src% this 0|1 switch is set in \pgfplots@start@plot@with@behavioroptions
		\ifx\pgfplots@metamin\pgfutil@empty
			\pgfplotsthrow{no such element}{\pgfplots@loc@TMPa}{Sorry, `colorbar source' can't be processed: the current \string\addplot\space command doesn't have point meta. Ignoring it.}\pgfeov%
		\else
			\global\let\pgfplots@colorbar@src@metamin=\pgfplots@metamin
			\global\let\pgfplots@colorbar@src@metamax=\pgfplots@metamax
		\fi
	\fi
	\ifpgfplots@autocompute@all@limits
		\global\let\pgfplots@data@xmin=\pgfplots@xmin
		\global\let\pgfplots@data@xmax=\pgfplots@xmax
		\global\let\pgfplots@data@ymin=\pgfplots@ymin
		\global\let\pgfplots@data@ymax=\pgfplots@ymax
		\global\let\pgfplots@data@zmin=\pgfplots@zmin
		\global\let\pgfplots@data@zmax=\pgfplots@zmax
	\fi
	\ifpgfplots@errorbars@enabled
		\pgfplots@errorbars@survey@end
	\fi
	\ifpgfplots@stackedmode
		\pgfplots@stacked@survey@endplot
	\fi
	\ifx\pgfplots@currentplot@firstcoord@x\pgfutil@empty
		\pgfplotswarning{plot without coordinates}\pgfeov%
	\else
		% Idea: use
		%   \scope[plot specification]
		%   <any paths for error bars>
		%   \endscope
		%   \draw plot coordinates {...};
		% to share plot specifications between error bars and plot
		% coordinates. Unfortunately, it is NOT sufficient to use
		% \tikzset
		\pgfplotspreparemeshkeydefaults%
		\pgfplots@PREPARE@COORD@STREAM@end@determinecoordsorting x%
		\pgfplots@PREPARE@COORD@STREAM@end@determinecoordsorting y%
		%
		\pgfplots@remember@survey@option@list
		%
		% warning: rememberplotspec calls list macros which
		% overwrite \t@pgfplots@toka
		\t@pgfplots@toka=\expandafter{\pgfplots@addplot@survey@@optionlist}%
		% ATTENTION: do NOT call list macros from here on!
		%
		\pgfplotsplothandlerserializestateto\pgfplots@loc@TMPa
		\t@pgfplots@tokb=\expandafter{\pgfplots@loc@TMPa}%
		%
		\pgfplots@markers@survey@set@visphasename
		\let\pgfplots@markers@visphase@name=\pgfplotsretval
		%
		\pgfplotssurveyphase@set@visphase@names{#1}%
		\let\pgfplots@visphase@names=\pgfplotsretval
		%
		%
		% SERIALIZE RESULT:
		%
		% everything which has been accumulated so far (including the
		% preprocessed coordinates) will be serialized into the
		% structure \pgfplots@stored@plotlist (globally).
		%
		% assemble a \pgfplots@addplot@enqueue@coords command ...
		% BEGIN HERE ...
		% vvvvvvvvvv
		\xdef\pgfplots@glob@TMPa{%
			\noexpand\pgfplots@addplot@enqueue@coords
			{% precommand(s):
				\expandafter\noexpand\csname pgfplots@curplot@threedim\ifpgfplots@curplot@threedim true\else false\fi\endcsname
				\noexpand\def\noexpand\plotnum{\the\pgfplots@numplots}%
				%
				% store \plotnumofactualtype
				\noexpand\def\noexpand\plotnumofactualtype{\plotnumofactualtype}%
				% ... and make sure that it 
				% remains the same type even if some plot handler uses
				% other plot handlers internally:
				\noexpand\def\noexpand\pgfplotsplothandlername@actual{\pgfplotsplothandlername@actual}%
				\noexpand\let\noexpand\numplotsofactualtype\noexpand\pgfplots@numplotsofactualtype@duringplot
				%
				\noexpand\def\noexpand\numcoords{\pgfplots@current@point@coordindex}%
				% \pgfplots@current@point@coordindex will always contain the current index.
				% Maybe overwritten if not provided using \c@pgfplots@coordindex.
				\noexpand\def\noexpand\pgfplots@current@point@coordindex{\noexpand\the\noexpand\c@pgfplots@coordindex}%
				\noexpand\def\noexpand\coordindex{\noexpand\pgfplots@current@point@coordindex}% valid inside of \addplot
				%
				\ifpgfplots@stackedmode
					\pgfplots@stacked@serialized@commands
				\fi
				%
				% save the possibly prepare/adjusted plot
				% variables [FIXME: move after \pgfplots@define@currentplotstyle@as ?]:
				\noexpand\pgfkeyssetvalue{/pgfplots/samples}{\pgfplots@plot@samples}%
				\noexpand\pgfkeyssetvalue{/pgfplots/domain}{\pgfplots@plot@domain}%
				\noexpand\pgfkeyssetvalue{/pgfplots/samples at}{\pgfplots@plot@samples@at}%
				\noexpand\pgfkeyssetvalue{/pgfplots/mesh/rows}{\pgfkeysvalueof{/pgfplots/mesh/rows}}%
				\noexpand\pgfkeyssetvalue{/pgfplots/mesh/cols}{\pgfkeysvalueof{/pgfplots/mesh/cols}}%
				\noexpand\pgfkeyssetvalue{/pgfplots/mesh/num points}{\pgfkeysvalueof{/pgfplots/mesh/num points}}%
				% either '+' or '-' :
				\noexpand\pgfkeyssetvalue{/pgfplots/x coord sorting}{\pgfkeysvalueof{/pgfplots/x coord sorting}}%
				\noexpand\pgfkeyssetvalue{/pgfplots/y coord sorting}{\pgfkeysvalueof{/pgfplots/y coord sorting}}%
				%
				% remember 'current plot style':
				\noexpand\pgfplots@define@currentplotstyle@as{%
					\the\t@pgfplots@toka
				}%
				% per-point meta data ranges which apply only to
				% this plot:
				\noexpand\xdef\noexpand\pgfplots@metamin{\pgfplots@metamin}%
				\noexpand\xdef\noexpand\pgfplots@metamax{\pgfplots@metamax}%
				\noexpand\def\noexpand\pgfplotspointmetainputhandler{\pgfplotspointmetainputhandler}%
				\noexpand\def\noexpand\pgfplots@serialized@state@plothandler{\the\t@pgfplots@tokb}%
				\noexpand\def\noexpand\pgfplots@markers@visphase@name{\pgfplots@markers@visphase@name}%
				\noexpand\def\noexpand\pgfplots@visphase@names{\pgfplots@visphase@names}%
				\noexpand\def\noexpand\pgfplotsaxisfilteredcoordsaway{\pgfplotsaxisfilteredcoordsaway}%
				\noexpand\def\noexpand\pgfplotsaxisplothasjumps{\pgfplotsaxisplothasjumps}%
				\noexpand\pgfkeyssetvalue{/pgfplots/on layer}{\pgfkeysvalueof{/pgfplots/on layer}}%
			}%
			{% draw command:
				\noexpand\path%
			}%
		}%
		\pgfplotsapplistXXlet\pgfplots@coord@stream@recorded
		\pgfplotsapplistXXclear
		\t@pgfplots@tokc=\expandafter{\pgfplots@coord@stream@recorded}%
		\t@pgfplots@tokb={#1;}%
		\t@pgfplots@toka=\expandafter{\pgfplots@glob@TMPa}%
		\xdef\pgfplots@glob@TMPa{%
			\the\t@pgfplots@toka
			{% coordinates which need to be processed in \endaxis.
			% See
			% \pgfplots@coord@stream@finalize@storedcoords@START
				normalized coordinates {\the\t@pgfplots@tokc}\the\t@pgfplots@tokb
			}%
		}%
		%
		\pgfplots@glob@TMPa
			{%
				% Post commands are empty here.
			}%
		%^^^^^^^^^^^^ ... END of \pgfplots@addplot@enqueue@coords HERE
	\fi
	\pgfplots@end@plot
}%

\def\pgfplots@remember@survey@option@list{%
	\t@pgfplots@tokc=\expandafter{\pgfplots@addplot@survey@@optionlist,%
		/pgfplots/.cd,/pgfplots/every axis plot post}%
	\edef\pgfplots@addplot@survey@@optionlist{\the\t@pgfplots@tokc}%
	\ifpgfplots@curplot@isirrelevant
		% for \label commands:
		\expandafter\pgfplots@rememberplotspec@for@label\expandafter{\pgfplots@addplot@survey@@optionlist}%
	\else
		\expandafter\pgfplots@rememberplotspec\expandafter{\pgfplots@addplot@survey@@optionlist}%
	\fi
}%

% Defines \pgfplotsretval to contain a comma-separated-list of
% visualization phase names. May be empty.
%
% These names will be stored as \pgfplots@visphase@names during the
% visualization phase.
%
% The role of "visualization phases" is to call the plot
% handler, and perhaps further visualization phases.
%
% This is entirely *independent* of plot marks which have their own,
% very special visualization phase.
%
% It is allowed if a plot has an empty list of visualization phases
% (common for 'only marks').
%
% #1: any tikz path instructions after the \addplot command but before
% the semicolon.
\def\pgfplotssurveyphase@set@visphase@names#1{%
	% 1. check if we need the 'default' visualization phase:
	\pgfplots@getcurrent@plothandler\pgfplots@basiclevel@plothandler
	\ifx\pgfplots@basiclevel@plothandler\pgfplothandlerdiscard
		% Ah - "only marks". In this case, we rely on the (special)
		% marker visualization phase - there is no need for a further
		% phase.
		\pgfplotsutil@trim{#1}%
		\ifx\pgfplotsretval\pgfutil@empty
			% OK, we do not have after-path instructions.
			% No need for this phase.
			\let\pgfplotsretval=\pgfutil@empty
		\else
			% Hm. We found after-path instructions! These *need* to be
			% done during the standard visualization phase. Ok, then
			% do it, even if it has no uses otherwise!
			\let\pgfplotsretval=\pgfplotsaxis@visphase@name@default
		\fi
	\else
		\let\pgfplotsretval=\pgfplotsaxis@visphase@name@default
	\fi
	%
	% 2. error bar phase:
	\ifpgfplots@errorbars@enabled
		\ifx\pgfplotsretval\pgfutil@empty
		\else
			\edef\pgfplotsretval{\pgfplotsretval,}%
		\fi
		%
		\edef\pgfplotsretval{\pgfplotsretval \pgfplotsaxis@visphase@name@errorbars}%
	\fi
	%
	% markers have the special phase \pgfplots@markers@visphase@name .
}%

\def\pgfplotsaxis@visphase@name@default{default}
\def\pgfplotsaxis@visphase@name@markers{markers}

% This defines \pgfplots@visphase@default:
\expandafter\def\csname pgfplots@visphase@\pgfplotsaxis@visphase@name@default\endcsname{%
	\expandafter\pgfplots@coord@stream@finalize@storedcoords@START\pgfplots@stored@current@data\pgfplots@EOI
}%

% A routine which transforms the current set of
% \pgfplots@current@point@[xyz] values to the coordinate system
% accepted by the actual axis.
\def\pgfplotsaxistransformfromdatacs{%
	\pgfkeyslet{/data point/x}\pgfplots@current@point@x
	\pgfkeyslet{/data point/y}\pgfplots@current@point@y
	\pgfkeyslet{/data point/z}\pgfplots@current@point@z
	\pgfplotsaxistransformcs
		{\pgfkeysvalueof{/pgfplots/data cs}}
		{\pgfkeysvalueof{/pgfplots/@expected axis cs}}%
	\pgfkeysgetvalue{/data point/x}\pgfplots@current@point@x
	\pgfkeysgetvalue{/data point/y}\pgfplots@current@point@y
	\pgfkeysgetvalue{/data point/z}\pgfplots@current@point@z
}%

% Changes '/data point/[xyz]' to the new coordinate system
% (cs) designated by '#2'.
%
% #1: the actual coordinate system's name
% #2: the desired coordinate system's name
%
% PRECONDITION: '/data point/[xyz]' contain the current
% point's coordinates in the '#1' system. The z coordinate is ignored for 2d plots (or
% for coordinate systems which are inherently two-dimensional).
%
% POSTCONDITION: 'data point/[xyz]' contain same point as
% before, but represented in the '#2' system.
%
% The coordinate system transformations must be defined,
% see \pgfplotsdefinecstransform.
%
% Example:
% \pgfkeyssetvalue{/data point/x}{90}
% \pgfkeyssetvalue{/data point/y}{1}
% \pgfplotsaxistransformcs{polar}{cart}
% -->
%  \pgfkeysvalueof{/data point/x}= 0
%  \pgfkeysvalueof{/data point/y}= 1
\def\pgfplotsaxistransformcs#1#2{%
	\edef\pgfplots@loc@TMPa{#1}%
	\edef\pgfplots@loc@TMPb{#2}%
	\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
		% nothing to do
	\else
		\pgfutil@ifundefined{pgfp@transform@\pgfplots@loc@TMPa @to@\pgfplots@loc@TMPb}{%
			\pgfutil@ifundefined{pgfp@transform@\pgfplots@loc@TMPa @to@cart}{%
				\pgfplotsaxistransformcs@error
			}{%
				\pgfplotsaxistransformcs{#1}{cart}%
				\pgfplotsaxistransformcs{cart}{#2}%
			}%
		}{%
			\csname pgfp@transform@\pgfplots@loc@TMPa @to@\pgfplots@loc@TMPb\endcsname
		}%
	\fi
}%

% Defines a new coordinate transformation for use in
% \pgfplotsaxistransformcs.
% #1: the source coordinate system
% #2: the target coordinate system
% #3: the transformation code. 
%
% @see \pgfplotsaxistransformcs for what #3 should do.
%
% This does also declare a coordinate system for use in 'data cs'.
% The minimal requirements are to define the transformations from and
% to "cart" (cartesian coordinates).
% 
\def\pgfplotsdefinecstransform#1#2#3{%
	\expandafter\def\csname pgfp@transform@#1@to@#2\endcsname{#3}%
}%

\pgfplotsdefinecstransform{polar}{cart}{%
	\pgfplotscoordmath{default}{parsenumber}{\pgfkeysvalueof{/data point/x}}%
	\let\pgfplots@current@point@x=\pgfmathresult
	\pgfplotscoordmath{default}{parsenumber}{\pgfkeysvalueof{/data point/y}}%
	\let\pgfplots@current@point@y=\pgfmathresult
	\pgfplotsmathpoltocart\pgfplots@current@point@x\pgfplots@current@point@y\pgfplots@current@point@x@\pgfplots@current@point@y@
	\pgfplotscoordmath{x}{parsenumber}{\pgfplots@current@point@x@}%
	\pgfkeyslet{/data point/x}\pgfmathresult
	\pgfplotscoordmath{y}{parsenumber}{\pgfplots@current@point@y@}%
	\pgfkeyslet{/data point/y}\pgfmathresult
}%
\pgfplotsdefinecstransform{cart}{polar}{%
	\pgfplotscoordmath{default}{parsenumber}{\pgfkeysvalueof{/data point/x}}%
	\let\pgfplots@current@point@x=\pgfmathresult
	\pgfplotscoordmath{default}{parsenumber}{\pgfkeysvalueof{/data point/y}}%
	\let\pgfplots@current@point@y=\pgfmathresult
	\pgfplotsmathcarttopol\pgfplots@current@point@x\pgfplots@current@point@y\pgfplots@current@point@x@\pgfplots@current@point@y@
	\pgfplotscoordmath{x}{parsenumber}{\pgfplots@current@point@x@}%
	\pgfkeyslet{/data point/x}\pgfmathresult
	\pgfplotscoordmath{y}{parsenumber}{\pgfplots@current@point@y@}%
	\pgfkeyslet{/data point/y}\pgfmathresult
}%

\pgfplotsdefinecstransform{polarrad}{polar}{%
	\pgfplotsgetcoordmathfor{default}\let\pgfplots@coordmath@id=\pgfplotsretval
	\pgfutil@ifundefined{pgfp@polarradscale@\pgfplots@coordmath@id}{%
		\pgfplotscoordmath{default}{parsenumber}{57.2957795130823}%
		\expandafter\global\expandafter\let\csname pgfp@polarradscale@\pgfplots@coordmath@id\endcsname=\pgfmathresult
	}{}%
	%
	\pgfplotscoordmath{default}{parsenumber}{\pgfkeysvalueof{/data point/x}}%
	\pgfplotscoordmath{default}{op}{multiply}{{\pgfmathresult}{\csname pgfp@polarradscale@\pgfplots@coordmath@id\endcsname}}%
	\pgfkeyslet{/data point/x}\pgfmathresult
}%
\pgfplotsdefinecstransform{polar}{polarrad}{%
	\pgfplotsgetcoordmathfor{default}\let\pgfplots@coordmath@id=\pgfplotsretval
	\pgfutil@ifundefined{pgfp@polarradiscale@\pgfplots@coordmath@id}{%
		\pgfplotscoordmath{default}{parsenumber}{0.0174532925199433}%
		\expandafter\global\expandafter\let\csname pgfp@polarradiscale@\pgfplots@coordmath@id\endcsname=\pgfmathresult
	}{}%
	%
	\pgfplotscoordmath{default}{parsenumber}{\pgfkeysvalueof{/data point/x}}%
	\pgfplotscoordmath{default}{op}{multiply}{{\pgfmathresult}{\csname pgfp@polarradiscale@\pgfplots@coordmath@id\endcsname}}%
}%
\pgfplotsdefinecstransform{polarrad}{cart}{%
	\pgfplotsaxistransformcs{polarrad}{polar}%
	\pgfplotsaxistransformcs{polar}{cart}%
}%
\pgfplotsdefinecstransform{cart}{polarrad}{%
	\pgfplotsaxistransformcs{cart}{polar}%
	\pgfplotsaxistransformcs{polar}{polarrad}%
}%

\def\pgfplotsaxistransformcs@error{%
	\pgfplotsthrow{invalid argument}{\pgfplots@loc@TMPa}{Sorry, I do not know how to transform the coordinate system '\pgfplots@loc@TMPa' to '\pgfplots@loc@TMPb'. Maybe you misspelled the 'data cs'? Or perhaps the feature is not yet implemented?}\pgfeov%
}%

% Takes the current point and serializes it into \pgfplotsretval.
%
% The serialization includes the coordinates (as returned by the
% current plot handler), the point meta, and any "visualization
% depends on" keys.
%
% See \pgfplotsaxisdeserializedatapointfrom
%
% POSTCONDITION:
%  \pgfplotsretval contains everything that is needed to restore the
%  current coordinate. This includes
%    - the coordinate values for x,y, and z
%    - any special coordinate values reported by the plot handler
%    (like u,v,w for quiver plots)
%    - the point meta
%    - any 'visualization depends on' value
%    - anything which is needed for other purposes (stacked plots have
%    a  plugin).
%
%   The result has an EXTRA SET OF BRACES which needs to be dealt with.
%
% Example:
% \pgfplotsaxisserializedatapointtostring
%
% \expandafter\pgfplotsaxisdeserializedatapointfrom\pgfplotsretval
%
% -> note the absence of extra braces for the deserialization!
\def\pgfplotsaxisserializedatapointtostring{%
	\pgfplotsplothandlerserializepointto\pgfplotsaxisserializedatapoint@val
	\pgfplotsaxisserializedatapoint@private
	\t@pgfplots@toka=\expandafter{\pgfplotsaxisserializedatapoint@val}%
	\t@pgfplots@tokb=\expandafter{\pgfplotsretval}%
	\edef\pgfplotsretval{{\the\t@pgfplots@tokb;\the\t@pgfplots@toka}}%
}%

\def\pgfplotsaxisserializedatapoint{%
	\pgfplotsaxisserializedatapointtostring
	\expandafter\pgfplotsapplistXXpushback\expandafter{\pgfplotsretval}%
}%
\def\pgfplotsaxisserializedatapoint@private{%
	\let\pgfplotsretval=\pgfplots@current@point@meta
}%
\def\pgfplotsaxisdeserializedatapointfrom@private#1{%
	\def\pgfplots@current@point@meta{#1}%
}%
% Restores the variables serialized in '#1'.
%
% As a side--effect, the macro
% \pgfplotsaxisdeserializedatapointfrom@private@lastvalue will contain
% the serialized part which is specific to pgfplots (i.e. the private
% parts which can be read with
% \pgfplotsaxisdeserializedatapointfrom@private)
\def\pgfplotsaxisdeserializedatapointfrom#1{%
	\expandafter\pgfplotsaxisdeserializedatapointfrom@#1\pgfplots@EOI
}%
\def\pgfplotsaxisdeserializedatapointfrom@#1;#2\pgfplots@EOI{%
	\def\pgfplotsaxisdeserializedatapointfrom@private@lastvalue{#1}%
	\pgfplotsaxisdeserializedatapointfrom@private{#1}%
	\pgfplotsplothandlerdeserializepointfrom{#2}%
}%

% Handle User-defined parts which should be serialized as well.
% This preparation tool should be called at the start of both, survey
% and visualization phase.
% 
% @PRECONDITION
% 	- the macros 
% 	\pgfplotsaxisserializedatapoint@private
% 	\pgfplotsaxisdeserializedatapointfrom@private
% 	are known and valid.
% 	- '/pgfplots/visualization depends on' contains its correct value.
%
% @POSTCONDITION
% 	Both,
% 	\pgfplotsaxisserializedatapoint@private
% 	and
% 	\pgfplotsaxisdeserializedatapointfrom@private
% 	have been patched to incorporate the '/pgfplots/visualization
% 	depends on' feature.
% 	
\def\pgfplots@prepare@visualization@dependencies{%
	\pgfkeysgetvalue{/pgfplots/visualization depends on/list}\pgfplots@loc@TMPa
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
	\else
		% SERIALIZATION format:
		% visualization depends on={{value1}\as \macro1, {<value2>}\as \macro2,...}
		% ->
		% {<original private data>}<\macro1>{<value1>}<\macro2>{<value2>}...<\macroN>{<valueN>}
		%
		% prepare
		% \t@pgfplots@tokb={<\macro1>{<value1>}<\macro2>{<value2>}...<\macroN>{<valueN>}}
		\t@pgfplots@tokb={}%
		%
		% prepare
		% \t@pgfplots@tokc={<\macro1><\macro2><\macro3>...}
		\t@pgfplots@tokc={}% 
		\expandafter\pgfplotsutilforeachcommasep\expandafter{\pgfplots@loc@TMPa}\as\pgfplots@loc@TMPa{%
			\ifx\pgfplots@loc@TMPa\pgfutil@empty
			\else
				\expandafter\pgfplots@prepare@visualization@depends@on\pgfplots@loc@TMPa\pgfplots@EOI%
			\fi
		}%
		% Step 1: modify the SERIALIZATION method:
		\t@pgfplots@toka=\expandafter{\pgfplotsaxisserializedatapoint@private}%
		\edef\pgfplotsaxisserializedatapoint@private{%
			\the\t@pgfplots@tokc
			\the\t@pgfplots@toka
			% nothing is expanded here, only \t@pgfplots@tokb
			\noexpand\t@pgfplots@toka=\noexpand\expandafter{\noexpand\pgfplotsretval}%
			\noexpand\edef\noexpand\pgfplotsretval{{\noexpand\the\t@pgfplots@toka},\the\t@pgfplots@tokb}%
		}%
		% Step 2: modify the DESERIALIZATION method:
		\let\pgfplotsaxisdeserializedatapointfrom@private@orig=\pgfplotsaxisdeserializedatapointfrom@private
		\let\pgfplotsaxisdeserializedatapointfrom@private=\pgfplotsaxisdeserializedatapointfrom@private@withdeplist
	\fi
	%
	\pgfkeysgetvalue{/pgfplots/execute for finished point}\pgfplots@loc@TMPa
	\ifx\pgfplots@loc@TMPa\pgfplots@empty@command@key
	\else
		\expandafter\def\expandafter\pgfplotsaxisserializedatapoint@private\expandafter{%
			\pgfplotsaxisserializedatapoint@private
			\pgfkeysvalueof{/pgfplots/execute for finished point}%
		}%
	\fi
}%
\def\pgfplots@prepare@visualization@depends@on#1\pgfplots@EOI{%
	\pgfutil@in@\as{#1}%
	\ifpgfutil@in@
		% ok, we have the '<content>\as<\macro>' syntax:
		\pgfplots@prepare@visualization@depends@on@#1\pgfplots@EOI
	\else
		\pgfplots@prepare@visualization@depends@on@preparetype@checkvalue#1value\pgfplots@EOI
		\ifpgfutil@in@
			% ok, then it should be 'value <\macro>'.
			% extract the <\macro>:
			\def\pgfplots@loc@TMPa value{\pgfplots@loc@TMPb}%
			\def\pgfplots@loc@TMPb##1{\pgfplots@loc@TMPc ##1}% this step should remove leading white spaces
			\def\pgfplots@loc@TMPc##1\pgfplots@EOI{%
				% sanitize: check if ##1 is a defined macro:
				\begingroup
					\escapechar=-1
					\xdef\pgfplots@glob@TMPa{\string##1}%
				\endgroup
				\pgfutil@ifundefined{\pgfplots@glob@TMPa}{%	
					\begingroup
					\t@pgfplots@toka={##1}%
					\pgfplotsthrow{invalid argument}
						{\pgfplots@loc@TMPa}%
						{Sorry, `visualization depends on=value <\string\macro>' expected a defined control sequence name instead of `\the\t@pgfplots@toka'. Please make sure `\the\t@pgfplots@toka' is a properly defined macro or use the `visualization depends on=value <content> \string\as <\string\macro>' syntax instead}%
						\pgfeov
					\endgroup
				}{%
					\def\pgfplots@loc@TMPa{%
						\pgfplots@prepare@visualization@depends@on@ value}%
					\expandafter\pgfplots@loc@TMPa##1\as##1\pgfplots@EOI
				}%
			}%
			\pgfplots@loc@TMPa#1\pgfplots@EOI
		\else
			% then, I expect '<\macro>'.
			% sanitize: check if #1 is a defined macro:
			\begingroup
				\escapechar=-1
				\xdef\pgfplots@glob@TMPa{\string#1}%
			\endgroup
			\pgfutil@ifundefined{\pgfplots@glob@TMPa}{%	
				\begingroup
				\t@pgfplots@toka={#1}%
				\pgfplotsthrow{invalid argument}
					{\pgfplots@loc@TMPa}%
					{Sorry, `visualization depends on' expected a defined control sequence name instead of `\the\t@pgfplots@toka'. Please make sure `\the\t@pgfplots@toka' is a properly defined macro or use the `visualization depends on=<expression> \string\as <\string\macro>' syntax instead}%
					\pgfeov
				\endgroup
			}{%
				\expandafter\pgfplots@prepare@visualization@depends@on@#1\as#1\pgfplots@EOI
			}%
		\fi
	\fi
}%
\def\pgfplots@prepare@visualization@depends@on@#1\as#2\pgfplots@EOI{%
	\pgfplots@prepare@visualization@depends@on@preparetype{#1}\as{#2}%
	% prepare the serialization:
	\t@pgfplots@tokb=\expandafter{\the\t@pgfplots@tokb\noexpand#2{\csname\string#2@value\endcsname}}%
	\t@pgfplots@tokc=\expandafter{\the\t@pgfplots@tokc\csname assign@\string#2\endcsname}%
}%

% task: define a macro '\csname assign@\string#2\endcsname' which, when executed, 
% defines \csname\string#2@value\endcsname such that it expands
% to a the correct value.
\def\pgfplots@prepare@visualization@depends@on@preparetype#1\as#2{%
	\pgfplots@prepare@visualization@depends@on@preparetype@checkvalue#1value\pgfplots@EOI
	\ifpgfutil@in@
		\pgfplots@prepare@visualization@depends@on@preparetype@value#1\as{#2}% no braces here.
	\else
		\pgfplots@prepare@visualization@depends@on@preparetype@expr{#1}\as{#2}%
	\fi
}%
\def\pgfplots@prepare@visualization@depends@on@preparetype@expr#1\as#2{%
	\pgflibraryfpuifactive{%
		\expandafter\def\csname assign@\string#2\endcsname{%
			\pgfmathparse{#1}%
			\pgfmathfloattofixed{\pgfmathresult}%
			\expandafter\let\csname \string#2@value\endcsname=\pgfmathresult
		}%
	}{%
		\expandafter\def\csname assign@\string#2\endcsname{%
			\pgfmathparse{#1}%
			\expandafter\let\csname \string#2@value\endcsname=\pgfmathresult
		}%
	}%
}
\def\pgfplots@prepare@visualization@depends@on@preparetype@checkvalue#1value#2\pgfplots@EOI{%
	\def\pgfplots@loc@TMPa{#1}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\pgfutil@in@true
	\else
		\pgfutil@in@false
	\fi
}%
\def\pgfplots@prepare@visualization@depends@on@preparetype@value value#1\as#2{%
	% remove spaces from #1:
	\pgfkeys@spdef\pgfplots@loc@TMPa{#1}%
	%
	% ok, prepare the value.
	\def\pgfplots@loc@TMPb{#2}%
	\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
		% oh - a special case! We have value\macro\as\macro. 
		\expandafter\def\csname\string#2@value\endcsname{#2}%
		% 
		% this is special; we do not need to EXECUTE assign@\string#2 to arrive at its value.
		% But we need to define #2@value as that will be stored.
		\expandafter\let\csname assign@\string#2\endcsname=\relax
	\else
		\begingroup
		\t@pgfplots@toka=\expandafter{\pgfplots@loc@TMPa}%
		\t@pgfplots@tokb=\expandafter{\csname\string#2@value\endcsname}%
		\xdef\pgfplots@glob@TMPa{%
			\noexpand\def\the\t@pgfplots@tokb{\the\t@pgfplots@toka}%
		}%
		\endgroup
		\expandafter\let\csname assign@\string#2\endcsname=\pgfplots@glob@TMPa
	\fi
}

\def\pgfplotsaxisdeserializedatapointfrom@private@withdeplist#1{%
	\pgfplotsaxisdeserializedatapointfrom@private@withdeplist@#1\pgfplots@EOI
}%
\def\pgfplotsaxisdeserializedatapointfrom@private@withdeplist@#1,{%
	\pgfplotsaxisdeserializedatapointfrom@private@orig{#1}%
	\pgfplotsaxisdeserializedatapointfrom@private@withdeplist@@
}%
\def\pgfplotsaxisdeserializedatapointfrom@private@withdeplist@@#1{%
	\def\pgfplots@loc@TMPa{#1}%
	\ifx\pgfplots@loc@TMPa\pgfplots@EOI
	\else
		\afterassignment\pgfplotsaxisdeserializedatapointfrom@private@withdeplist@@
		\expandafter\def\expandafter#1%
	\fi
}%

% PRECONDITION: must be called inside of
% \pgfplots@PREPARE@COORD@STREAM@end@.
%
% POSTCONDITION:
% 	assigns '/pgfplots/#1 coord sorting=[+-]' 
% 	i.e. whether #1 (x or y or z) coordinates are in ascending (+) ordering or in
% 	descending order (-).
\def\pgfplots@PREPARE@COORD@STREAM@end@determinecoordsorting#1{%
	\pgfplotscoordmath{#1}{if less than}
			{\csname pgfplots@currentplot@firstcoord@#1\endcsname}%
			{\csname pgfplots@currentplot@lastcoord@#1\endcsname}%
			{\pgfkeyssetvalue{/pgfplots/#1 coord sorting}{+}}%
			{\pgfkeyssetvalue{/pgfplots/#1 coord sorting}{-}}%
}%

% Defines the linear transformation macro \pgfplots@perpointmeta@trafo,
%
% phi : [meta_min,meta,max] -> [0,10^k]
%
% which operates on the per-point meta data (if any).
% The trafo will be skipped if there is no such data.
%
% The trafo is expected to prepare meta information before it is used
% as input to \pgfplotscolormapaccess (or
% \pgfplotscolormapdefinemappedcolor). Thus, the 10^k is chosen to be 
% the same as \pgfplotscolormaprange (which is 1000 per default).
%
% If there is no data range (for example because meta information is
% not available or is not of numeric type), the trafo will simply
% copy the input argument symbolically.
%
% Note: it does not hurt to call it multiple times. It checks automatically whether it already is up-to-date.
\def\pgfplots@perpointmeta@preparetrafo{%
	\def\pgfplotspointmetarangeexponent{1}% pre-fill
	\pgfutil@ifundefined{pgfplots@perpointmeta@trafo}{%
		\let\pgfplots@current@point@meta=\pgfutil@empty
		\pgfutil@ifundefined{pgfplots@metamax}{\let\pgfplots@metamax=\pgfutil@empty}{}
		\ifpgfplots@warn@for@filter@discards
			\global\let\pgfplots@perpointmeta@unboundedwarning@stop=\relax
			\def\pgfplots@perpointmeta@unboundedwarning##1{%
				\ifx\pgfplots@perpointmeta@unboundedwarning@stop\relax
					\begingroup
						\pgfplotscoordmath{meta}{tostring}{##1}%
						\pgfplotswarning{point meta unbounded}{\pgfmathresult}{##1}\pgfeov
					\endgroup
					\gdef\pgfplots@perpointmeta@unboundedwarning@stop{1}%
				\fi
			}%
		\else
			\def\pgfplots@perpointmeta@unboundedwarning##1{}%
		\fi
		\if m\pgfplots@colormap@access
			% colormap access=map
			\ifx\pgfplots@metamax\pgfutil@empty
				\def\pgfplots@perpointmeta@trafo##1{%
					\pgfplotscoordmath{meta}{if is}{##1}{u}
					{%
						\def\pgfmathresult{0}%
						\pgfplots@perpointmeta@unboundedwarning{##1}%
					}{%
						\pgfplotscoordmath{meta}{tofixed}{##1}%
					}%
				}%
				\def\pgfplots@perpointmeta@traforange{0:1000}%
				\edef\pgfplotspointmetarange{0:1000}%
			\else
				% The transformation is
				%
				% phi(m) = ( m- meta_min) * 1000/ (meta_max-meta_min).
				%
				% -> precompute the scaling factor!
				\edef\pgfplots@loc@TMPa{\pgfplotscolormaprange}%
				\ifnum\pgfplots@loc@TMPa=1000
				\else
					\pgfplots@error{LOGIC ERROR: sorry, I have hard-coded the assumption \string\pgfplotscolormaprange = 1000, but now it is \pgfplots@loc@TMPa.}%
				\fi
				\if\pgfplots@perpointmeta@rel@choice0%
					% point meta rel=axis wide:
					\pgfplots@perpointmeta@preparetrafo@initfrom{pgfplots@axiswide@}%
				\else
					\pgfplots@perpointmeta@preparetrafo@initfrom{pgfplots@}%
				\fi
			\fi
		\else
			% colormap access=direct
			\def\pgfplots@perpointmeta@trafo##1{%
				\pgfplotscoordmath{meta}{if is}{##1}{u}{%
					\def\pgfmathresult{0}%
					\pgfplots@perpointmeta@unboundedwarning{##1}%
				}{%
					\pgfplotscoordmath{meta}{tofixed}{##1}%
				}%
			}%
			\def\pgfplots@perpointmeta@traforange{0:0}%
			\edef\pgfplotspointmetarange{\pgfplots@metamin:\pgfplots@metamax}%
		\fi
		\edef\pgfplotspointmetatransformedrange{\pgfplots@perpointmeta@traforange}%
	}{}%
}%

% Employs \csname #1metamin\endcsname and its metamax counterpart to
% initialize the trafo.
%
% This unifies the approaches for \pgfplots@axiswide@metamax and
% \pgfplots@metamax.
\def\pgfplots@perpointmeta@preparetrafo@initfrom#1{%
	\edef\pgfplotspointmetarange{\csname #1metamin\endcsname:\csname #1metamax\endcsname}%
	% Now, prepare the trafo as such.
	% It assigns \pgfmathresult (in fixed point).
	\def\pgfplots@perpointmeta@trafo##1{%
		\pgfplotscoordmath{meta}{if is}{##1}{u}{%
			\def\pgfmathresult{0}%
			\pgfplots@perpointmeta@unboundedwarning{##1}%
		}{%
			\pgfplotscoordmath{meta}{op}{subtract}{{##1}{\csname #1metamin\endcsname}}%
			\pgfplotscoordmath{meta}{op}{multiply}{{\pgfmathresult}{\pgfplots@perpointmeta@trafo@factor}}%
			\pgfplots@perpointmeta@trafo@clipresult
			\pgfplotscoordmath{meta}{tofixed}{\pgfmathresult}%
		}%
	}%
	\pgfplotscoordmath{meta}{op}{subtract}{{\csname #1metamax\endcsname}{\csname #1metamin\endcsname}}%
	\let\pgfplots@loc@TMPa=\pgfmathresult
	\pgfplotscoordmath{meta}{zero}%
	\let\pgfplots@perpointmeta@lowerrange=\pgfmathresult
	\pgfplotscoordmath{meta}{parsenumber}{1000}%
	\let\pgfplots@perpointmeta@upperrange=\pgfmathresult
	\pgfplotscoordmath{meta}{op}{divide}{{\pgfmathresult}{\pgfplots@loc@TMPa}}%
	\let\pgfplots@perpointmeta@trafo@factor=\pgfmathresult
	%
	% Expands to the transformation range as 'a:b':
	\def\pgfplots@perpointmeta@traforange{0:1000}%
	%
	\expandafter\let\expandafter\pgfplots@loc@TMPa\csname #1metamax\endcsname
	\pgfplotscoordmath{meta}{tostring}{\pgfplots@loc@TMPa}%
	\pgfmathfloatparsenumber\pgfmathresult
	\pgfmathfloatgetexponent\pgfmathresult\c@pgf@countd
	\edef\pgfplotspointmetarangeexponent{\the\c@pgf@countd}%
}

\def\pgfplots@perpointmeta@trafo@clipresult{%
	\let\pgfplots@loc@TMPa=\pgfmathresult
	\pgfplotscoordmath{meta}{if less than}{\pgfplots@loc@TMPa}{\pgfplots@perpointmeta@upperrange}{%
		\pgfplotscoordmath{meta}{if less than}{\pgfplots@loc@TMPa}{\pgfplots@perpointmeta@lowerrange}{%
			\let\pgfmathresult=\pgfplots@perpointmeta@lowerrange
		}{%
			\let\pgfmathresult=\pgfplots@loc@TMPa
		}%
	}{%
		\let\pgfmathresult=\pgfplots@perpointmeta@upperrange
	}%
}%

% define it globally - this simplifies some mesh plots.
\pgfplotscoordmath{meta}{one}%
\let\pgfplotspointmeta=\pgfmathresult
\def\pgfplotspointmetatransformed{1000}% use the maximum because it is usually divided by 1000

% A command which is readily available during the visualization phase of each plot.
% 
% It takes existing point meta data and transforms it, i.e. it defines
% \pgfplotspointmetatransformed.
%
% The command won't be invoked automatically, it is task of a plot
% handler to decide if it is needed. It's application is relatively
% fast, however.
%
% PRECONDITION:
% 	- point meta has been set up during the survey phase (i.e. the
% 	/pgfplots/point meta!=none),
% 	- there *is* point meta data for the current data point.
%
% POSTCONDITION:
% 	- the macros \pgfplotspointmeta and \pgfplotspointmetatransformed
% 	are defined.
%
% @see also \pgfplotsaxisifhaspointmeta
\def\pgfplotsaxisvisphasetransformpointmeta{%
	\if1\csname pgfpmeta@\pgfplotspointmetainputhandler @issymbolic\endcsname
		% symbolic point meta may be empty.
		\let\pgfplotspointmeta=\pgfplots@current@point@meta
		\let\pgfplotspointmetatransformed=\pgfplotspointmeta
	\else
		% numeric point meta may NOT be empty.
		\ifx\pgfplots@current@point@meta\pgfutil@empty%
			\pgfplots@error{could not access the 'point meta' (used for example by scatter plots and color maps). Maybe you need to add '\string\addplot[point meta=y]' or something like that?}%
			\pgfplotscoordmath{meta}{one}%
			\let\pgfplotspointmeta=\pgfmathresult
			\def\pgfplotspointmetatransformed{1.0}%
		\else
			% prepare arguments:
			\let\pgfplotspointmeta=\pgfplots@current@point@meta
			\pgfplots@perpointmeta@trafo{\pgfplotspointmeta}%
			\let\pgfplotspointmetatransformed=\pgfmathresult
		\fi
	\fi
}%

\def\pgfplotsaxisvisphasetransformpointmetaifany{%
	\pgfplotsaxisifhaspointmeta{\pgfplotsaxisvisphasetransformpointmeta}{}%
}

% A looping method which applies
% \pgfplots@coord@stream@start
% for each coordinate '(x,y)'  or '(x,y) +- (ex,ey)',
%    assign \pgfplots@current@point@[xyz]
%    assign \pgfplots@current@point@[xyz]@error (if in argument list)
%    assign \pgfplots@current@point@meta
%    call \pgfplots@coord@stream@coord
% \pgfplots@coord@stream@end
%
% #1 a sequence of coordinates of the form 
%   '(x,y)' or '(x,y,z)'
%   or
%   '(x,y[,z]) +- (ex,ey)'
%   or
%   '(x,y[,z]) += (ex+,ey+) -= (ex-,ey-)'
%   or
%   '(x,y) [meta]'
%   or
%   '(x,y) +- (ex,ey) [meta]'
%   separated by white-space.
%
\long\def\pgfplots@coord@stream@foreach#1{%
	\pgfplots@coord@stream@start
	\pgfplotsscanlinelengthinitzero
	\pgfplots@foreach@plot@coord@ITERATE#1\pgfplots@EOI%
	\pgfplotsscanlinelengthcleanup
	\pgfplots@coord@stream@end
}%

\begingroup
\def\\{\global\let\pgfplots@let@space@token= } \\ % now, \pgfplots@let@space@token is a space token
\endgroup


% A looping command to loop through plot coordinates.
% For every point, \pgfplots@coord@stream@coord will be invoked.
%
% No scoping is used during this operation, so you can access outer
% variables.
\def\pgfplots@foreach@plot@coord@ITERATE{%
	\futurelet\pgfplots@foreach@plot@coord@ITERATE@tok\pgfplots@foreach@plot@coord@ITERATE@
}%
\long\def\pgfplots@foreach@plot@coord@ITERATE@#1{%
	\ifx\pgfplots@foreach@plot@coord@ITERATE@tok(%
		\pgfplotsscanlinelengthincrease
		\let\pgfplots@loop@next=\pgfplots@foreach@plot@coord@NEXT%
	\else
		\ifx\pgfplots@foreach@plot@coord@ITERATE@tok\pgfplots@let@space@token
			\def\pgfplots@loop@next{\pgfplots@foreach@plot@coord@ITERATE#1}%
		\else
			\ifx\pgfplots@foreach@plot@coord@ITERATE@tok\pgfplots@EOI
				% ok, do nothing more
				\let\pgfplots@loop@next=\relax
			\else
				\ifx\pgfplots@foreach@plot@coord@ITERATE@tok\par
					\pgfplotsscanlinecomplete
					\let\pgfplots@loop@next=\pgfplots@foreach@plot@coord@ITERATE
				\else
					\if\noexpand\pgfplots@foreach@plot@coord@ITERATE@tok\noexpand\anymacro
						% Ah. #1 has the same character (!) code as \anymacro,
						% that means it is a macro! Expand it:
						\def\pgfplots@loop@next{\expandafter\pgfplots@foreach@plot@coord@ITERATE#1}%
					\else
						\def\pgfplots@loop@next{\pgfplots@foreach@plot@coord@error#1}%
					\fi
				\fi
			\fi
		\fi
	\fi
	\pgfplots@loop@next
}

\long\def\pgfplots@foreach@plot@coord@error#1\pgfplots@EOI{%
	\def\pgfplots@loc@TMPa{#1}%
	\pgfplots@command@to@string\pgfplots@loc@TMPa\pgfplots@loc@TMPa
	\pgfplots@error{Sorry, I could not read the plot coordinates near '\pgfplots@loc@TMPa'. Please check for format mistakes}%
}%
\def\pgfplots@foreach@plot@coord@NEXT#1,#2){%
	\ifpgfplots@plot@coords@mathparser
		\pgfmathparse{#1}\let\pgfplots@current@point@x=\pgfmathresult
		\pgfmathparse{#2}\let\pgfplots@current@point@y=\pgfmathresult
	\else
		\def\pgfplots@current@point@x{#1}%
		\def\pgfplots@current@point@y{#2}%
	\fi
	\let\pgfplots@current@point@error@x@plus=\pgfutil@empty
	\let\pgfplots@current@point@error@x@minus=\pgfutil@empty
	\let\pgfplots@current@point@error@y@plus=\pgfutil@empty
	\let\pgfplots@current@point@error@y@minus=\pgfutil@empty
	\let\pgfplots@current@point@meta=\pgfutil@empty
	\pgfplots@foreach@plot@coord@NEXT@cont
}
\def\pgfplots@foreach@plot@coord@NEXT@cont{%
	\pgfutil@ifnextchar+{%
		\pgfplots@foreach@plot@coord@NEXT@plus%
	}{%
		\pgfutil@ifnextchar-{%
			\pgfplots@foreach@plot@coord@NEXT@minus%
		}{%
			\pgfutil@ifnextchar[{%
				\pgfplots@foreach@plot@coord@NEXT@meta
			}{%
				\pgfplots@coord@stream@coord
				\pgfplots@foreach@plot@coord@ITERATE
			}%
		}%
	}%
}
\def\pgfplots@foreach@plot@coord@NEXT@meta[#1]{%
	\def\pgfplots@current@point@meta{#1}%
	\pgfplots@coord@stream@coord
	\pgfplots@foreach@plot@coord@ITERATE
}%
\def\pgfplots@foreach@plot@coord@NEXT@plus+{%
	\pgfutil@ifnextchar={%
		\pgfplots@foreach@plot@coord@NEXT@pluseq%
	}{%
		\pgfplots@foreach@plot@coord@NEXT@plusminus%
	}%
}
\def\pgfplots@foreach@plot@coord@NEXT@minus-=#1({%
	\def\pgfplots@foreach@plot@coord@state{-}%
	\pgfplots@foreach@plot@coord@NEXT@WITH@ERRORRANGE@
}
\def\pgfplots@foreach@plot@coord@NEXT@pluseq=#1({%
	\def\pgfplots@foreach@plot@coord@state{+}%
	\pgfplots@foreach@plot@coord@NEXT@WITH@ERRORRANGE@
}
\def\pgfplots@foreach@plot@coord@NEXT@plusminus-#1({%
	\def\pgfplots@foreach@plot@coord@state{B}%
	\pgfplots@foreach@plot@coord@NEXT@WITH@ERRORRANGE@
}

% processing something like '(x,y) +- (error_x,error_y)'
\def\pgfplots@foreach@plot@coord@NEXT@WITH@ERRORRANGE@#1,#2){%
	\ifpgfplots@plot@coords@mathparser
		\pgfmathparse{#1}%
		\let\pgfplots@loc@TMPb=\pgfmathresult
		\pgfmathparse{#2}%
		\let\pgfplots@loc@TMPc=\pgfmathresult
	\else
		\def\pgfplots@loc@TMPb{#1}%
		\def\pgfplots@loc@TMPc{#2}%
	\fi
	%
	\if +\pgfplots@foreach@plot@coord@state
		% ah, it was a "+=" item:
		\let\pgfplots@current@point@error@x@plus=\pgfplots@loc@TMPb
		\let\pgfplots@current@point@error@y@plus=\pgfplots@loc@TMPc
	\else
		\if -\pgfplots@foreach@plot@coord@state
			% ah, it was a "-=" item:
			\let\pgfplots@current@point@error@x@minus=\pgfplots@loc@TMPb
			\let\pgfplots@current@point@error@y@minus=\pgfplots@loc@TMPc
		\else
			% ah, it was a "+-" item:
			\let\pgfplots@current@point@error@x@plus=\pgfplots@loc@TMPb
			\let\pgfplots@current@point@error@x@minus=\pgfplots@loc@TMPb
			\let\pgfplots@current@point@error@y@plus=\pgfplots@loc@TMPc
			\let\pgfplots@current@point@error@y@minus=\pgfplots@loc@TMPc
		\fi
	\fi
	%
	\pgfplots@foreach@plot@coord@NEXT@cont
}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
% The same for three dim coords:
\long\def\pgfplots@coord@stream@foreach@threedim#1{%
	\pgfplots@coord@stream@start
	\pgfplotsscanlinelengthinitzero
	\pgfplots@foreach@plot@coord@threedim@ITERATE#1\pgfplots@EOI%
	\pgfplotsscanlinelengthcleanup
	\pgfplots@coord@stream@end
}%
\def\pgfplots@foreach@plot@coord@threedim@ITERATE{%
	\futurelet\pgfplots@foreach@plot@coord@threedim@ITERATE@tok\pgfplots@foreach@plot@coord@threedim@ITERATE@
}%
\long\def\pgfplots@foreach@plot@coord@threedim@ITERATE@#1{%
	\ifx\pgfplots@foreach@plot@coord@threedim@ITERATE@tok(%
		\pgfplotsscanlinelengthincrease
		\let\pgfplots@loop@next=\pgfplots@foreach@plot@coord@threedim@NEXT%
	\else
		\ifx\pgfplots@foreach@plot@coord@threedim@ITERATE@tok\pgfplots@let@space@token
			\def\pgfplots@loop@next{\pgfplots@foreach@plot@coord@threedim@ITERATE#1}%
		\else
			\ifx\pgfplots@foreach@plot@coord@threedim@ITERATE@tok\pgfplots@EOI
				% ok, do nothing more
				\let\pgfplots@loop@next=\relax
			\else
				\ifx\pgfplots@foreach@plot@coord@threedim@ITERATE@tok\par
					\pgfplotsscanlinecomplete
					\let\pgfplots@loop@next=\pgfplots@foreach@plot@coord@threedim@ITERATE
				\else
					\if\noexpand\pgfplots@foreach@plot@coord@threedim@ITERATE@tok\noexpand\anymacro
						% Ah. #1 has the same character (!) code as \anymacro,
						% that means it is a macro! Expand it:
						\def\pgfplots@loop@next{\expandafter\pgfplots@foreach@plot@coord@threedim@ITERATE#1}%
					\else
						\def\pgfplots@loop@next{\pgfplots@foreach@plot@coord@error#1}%
					\fi
				\fi
			\fi
		\fi
	\fi
	\pgfplots@loop@next
}
\def\pgfplots@foreach@plot@coord@threedim@NEXT#1,#2,#3){
	\ifpgfplots@plot@coords@mathparser
		\pgfmathparse{#1}\let\pgfplots@current@point@x=\pgfmathresult
		\pgfmathparse{#2}\let\pgfplots@current@point@y=\pgfmathresult
		\pgfmathparse{#3}\let\pgfplots@current@point@z=\pgfmathresult
	\else
		\def\pgfplots@current@point@x{#1}%
		\def\pgfplots@current@point@y{#2}%
		\def\pgfplots@current@point@z{#3}%
	\fi
	\let\pgfplots@current@point@error@x@plus=\pgfutil@empty
	\let\pgfplots@current@point@error@x@minus=\pgfutil@empty
	\let\pgfplots@current@point@error@y@plus=\pgfutil@empty
	\let\pgfplots@current@point@error@y@minus=\pgfutil@empty
	\let\pgfplots@current@point@error@z@plus=\pgfutil@empty
	\let\pgfplots@current@point@error@z@minus=\pgfutil@empty
	%
	\let\pgfplots@current@point@meta=\pgfutil@empty
	%
	\pgfplots@foreach@plot@coord@threedim@NEXT@cont
}
\def\pgfplots@foreach@plot@coord@threedim@NEXT@cont{%
	\pgfutil@ifnextchar+{%
		\pgfplots@foreach@plot@coord@threedim@NEXT@plus%
	}{%
		\pgfutil@ifnextchar-{%
			\pgfplots@foreach@plot@coord@threedim@NEXT@minus%
		}{%
			\pgfutil@ifnextchar[{%
				\pgfplots@foreach@plot@coord@threedim@NEXT@meta
			}{%
				\pgfplots@coord@stream@coord
				\pgfplots@foreach@plot@coord@threedim@ITERATE
			}%
		}%
	}%
}
\def\pgfplots@foreach@plot@coord@threedim@NEXT@meta[#1]{%
	\def\pgfplots@current@point@meta{#1}%
	\pgfplots@coord@stream@coord
	\pgfplots@foreach@plot@coord@threedim@ITERATE
}%

\def\pgfplots@foreach@plot@coord@threedim@NEXT@plus+{%
	\pgfutil@ifnextchar={%
		\pgfplots@foreach@plot@coord@threedim@NEXT@pluseq%
	}{%
		\pgfplots@foreach@plot@coord@threedim@NEXT@plusminus%
	}%
}
\def\pgfplots@foreach@plot@coord@threedim@NEXT@minus-=#1({%
	\def\pgfplots@foreach@plot@coord@state{-}%
	\pgfplots@foreach@plot@coord@threedim@NEXT@WITH@ERRORRANGE@
}
\def\pgfplots@foreach@plot@coord@threedim@NEXT@pluseq=#1({%
	\def\pgfplots@foreach@plot@coord@state{+}%
	\pgfplots@foreach@plot@coord@threedim@NEXT@WITH@ERRORRANGE@
}
\def\pgfplots@foreach@plot@coord@threedim@NEXT@plusminus-#1({%
	\def\pgfplots@foreach@plot@coord@state{B}%
	\pgfplots@foreach@plot@coord@threedim@NEXT@WITH@ERRORRANGE@
}
% processing something like '(x,y) +- (error_x,error_y)'
\def\pgfplots@foreach@plot@coord@threedim@NEXT@WITH@ERRORRANGE@#1,#2,#3){%
	\ifpgfplots@plot@coords@mathparser
		\pgfmathparse{#1}\let\pgfplots@loc@TMPb=\pgfmathresult
		\pgfmathparse{#2}\let\pgfplots@loc@TMPc=\pgfmathresult
		\pgfmathparse{#3}\let\pgfplots@loc@TMPd=\pgfmathresult
	\else
		\def\pgfplots@loc@TMPb{#1}%
		\def\pgfplots@loc@TMPc{#2}%
		\def\pgfplots@loc@TMPd{#3}%
	\fi
	%
	\if +\pgfplots@foreach@plot@coord@state
		% ah, it was a "+=" item:
		\let\pgfplots@current@point@error@x@plus=\pgfplots@loc@TMPb
		\let\pgfplots@current@point@error@y@plus=\pgfplots@loc@TMPc
		\let\pgfplots@current@point@error@z@plus=\pgfplots@loc@TMPd
	\else
		\if -\pgfplots@foreach@plot@coord@state
			% ah, it was a "-=" item:
			\let\pgfplots@current@point@error@x@minus=\pgfplots@loc@TMPb
			\let\pgfplots@current@point@error@y@minus=\pgfplots@loc@TMPc
			\let\pgfplots@current@point@error@z@minus=\pgfplots@loc@TMPd
		\else
			% ah, it was a "+-" item:
			\let\pgfplots@current@point@error@x@plus=\pgfplots@loc@TMPb
			\let\pgfplots@current@point@error@x@minus=\pgfplots@loc@TMPb
			\let\pgfplots@current@point@error@y@plus=\pgfplots@loc@TMPc
			\let\pgfplots@current@point@error@y@minus=\pgfplots@loc@TMPc
			\let\pgfplots@current@point@error@z@plus=\pgfplots@loc@TMPd
			\let\pgfplots@current@point@error@z@minus=\pgfplots@loc@TMPd
		\fi
	\fi
	%
	\pgfplots@foreach@plot@coord@threedim@NEXT@cont
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
%
% A coordinate stream which works like this:
% 
% -------------
% \pgfplots@coord@stream@start
%
% foreach encoded coordinate:
%   \def\pgfplots@coord@stream@foreach@NORMALIZED@curencoded{<encoded data>}%
%   \def\pgfplots@coord@stream@foreach@NORMALIZED@curencoded@braced{{<encoded data>}}% note the extra braces.
%   \pgfplotsaxisdeserializedatapointfrom{<encoded data>}
% 	\pgfplots@coord@stream@coord
%
% \pgfplots@coord@stream@end
% -------------
%
% The format of #1 is
%  {<datapoint>}{<datapoint>}...{<datapoint>}
% Each data point is decoded with
% \pgfplotsaxisserializedatapoint
% and then, \pgfplots@coord@stream@coord will be called.
\long\def\pgfplots@coord@stream@foreach@NORMALIZED#1{%
	\pgfplots@coord@stream@start
	\pgfplotscoordstream@firstlast@init
	\pgfplots@foreach@plot@coord@NORMALIZED@ITERATE#1\pgfplots@EOI%
	\pgfplots@coord@stream@end
}%
% No scoping is used during this operation, so you can access outer
% variables.
\def\pgfplots@foreach@plot@coord@NORMALIZED@ITERATE#1{%
	\def\pgfplots@coord@stream@foreach@NORMALIZED@curencoded{#1}%
	\ifx\pgfplots@coord@stream@foreach@NORMALIZED@curencoded\pgfplots@EOI
	\else
		\def\pgfplots@coord@stream@foreach@NORMALIZED@curencoded@braced{{#1}}%
		\pgfplotsaxisdeserializedatapointfrom{#1}%
		\pgfplots@coord@stream@coord
		\pgfplotsplothandlerifcurrentpointcanbefirstlast{%
			\pgfplotscoordstream@firstlast@update
		}{}%
		\expandafter\pgfplots@foreach@plot@coord@NORMALIZED@ITERATE
	\fi
}

% A common routine which resets internal data structures for the
% survey phase, i.e. it is the shared implementation for all \addplot
% variations.
% 
% It takes all options which are provided to \addplot, sets them (at
% least partially) and remembers them for the command serialization.
%
% #1:  arguments to \addplot plot[#1]
%   -> these are called 'behavior' options in the manual; they are set
%   immediately.
%
% PRECONDITION:
%	\pgfplots@addplotimpl@plot@withoptions has already been invoked
%
% POSTCONDITION:
% 	- internal datastructures are initialised (coordinate indexing, fpu)
% 	- all keys which are required for the current plot are determined
% 	(and set if necessary).
% 	They are stored into 
% 	\pgfplots@addplot@survey@@optionlist.
%    
\def\pgfplots@start@plot@with@behavioroptions#1{%
	%\begingroup%<-- has been moved to \pgfplots@addplotimpl@plot@withoptions
	\c@pgfplots@coordindex=0
	\def\pgfplots@current@point@coordindex{\the\c@pgfplots@coordindex}% can be used inside of coordinate filters.
	\def\coordindex{\pgfplots@current@point@coordindex}% valid inside of \addplot
	\def\pgfplots@addplot@running{1}%
	%
	\def\pgfplots@colorbar@set@src{0}%
	\pgfkeysdef{/pgfplots/colorbar source}{%
		\pgfplotsutilifstringequal{##1}{true}{%
			\def\pgfplots@colorbar@set@src{1}%
		}{%
			\pgfplotsutilifstringequal{##1}{false}{%
				\def\pgfplots@colorbar@set@src{0}%
			}{%
				\pgfplots@error{Sorry, I don't know the value `colorbar source={##1}' and I am going to ignore it. Maybe you misspelled it?}%
			}%
		}%
	}%
	%
	\pgfplots@start@plot@with@behavioroptions@setkeys{#1}%
	%
	% enable FPU after any \pgfplotsset operations. Otherwise things like
	% linewidth=... which use the math parser might fail.
	\ifpgfplots@usefpu
		\pgfkeys{/pgf/fpu=true}%
	\fi
	%
	% make sure it is reset, just in case it is not supported by the
	% input method. 
	\pgfplotsscanlinelengthinitzero
	%
	\pgfplots@getcurrent@plothandler\pgfplots@basiclevel@plothandler
	\pgfplotsresetplothandler
	\pgfplots@basiclevel@plothandler
	%
	\pgfplots@countplots@init
	%
	% hooks:
	\pgfkeysvalueof{/pgfplots/execute at begin plot@@}%
	\pgfkeysvalueof{/pgfplots/execute at begin plot}%
	%
	\if1\pgfplots@colorbar@set@src
		\t@pgfplots@tokc={/pgfplots/point meta rel=per plot}%
		\t@pgfplots@toka=\expandafter{\pgfplots@addplot@survey@@optionlist}%
		\edef\pgfplots@addplot@survey@@optionlist{\the\t@pgfplots@tokc,\the\t@pgfplots@toka}%
	\fi
	%
	%
	\pgfplots@validate@plot@domain@arguments
}

\def\pgfplots@disable@non@survey@keys{%
	%
	% this here would try to compute something. DON'T DO THIS DURING
	% SURVEY!
	\pgfkeysdef{/tikz/name intersections}{}%
	\pgfkeysdef{/tikz/intersection segments}{}%
	%
}%

\def\pgfplots@start@plot@with@behavioroptions@setkeys#1{%
	% these styles may contain behavior options (error bars,
	% samples,... ) activate them!
	%
	% As of february 20, 2009,  #1 will contain BOTH, /pgfplots
	% and /tikz options. The /tikz ones are primarily for drawing
	% and are UNIMPORTANT at this stage of processing.
	% In  fact, transparency etc. will only confuse everything.
	%
	% So: ignore them and set only /pgfplots keys here:
	% This may actually redefine styles, for example
	% \addplot[every mark/.append style={}] will use
	% /pgfplots/every mark/.append style.
	% But that doesn't hurt here.
	%
	% there are some exceptions like /tikz/id etc. These
	% exceptions need special styles in the /pgfplots root - or I
	% need to change the .unknown handler. See the available
	% compatibility styles!
	%
%	\pgfkeysdef{/pgfplots/.unknown}{%
%\message{In \string\addplot[#1]: I am silently ignoring key `\pgfkeyscurrentkeyRAW' during the preparation phase.}%
%	}%
	% ATTENTION:
	% as of january 30, 2010, I will set /tikz keys as well. This won't hurt
	% too much, I hope... there are no graphics operations anyway. But it *is*
	% necessary since I *need* the plot handler for the new version. And the plot
	% handler is, most likely, a /tikz key.
	%
	% it is possible that '#1' contains 'forget plot'. So, we need to
	% set the options before checking \ifpgfplots@curplot@isirrelevant:
	\pgfplots@disable@non@survey@keys
	\pgfplotsset{/pgfplots/every axis plot,#1}%
	%
	\ifpgfplots@curplot@isirrelevant
		\def\pgfplots@addplot@survey@@optionlist{/pgfplots/every axis plot,/pgfplots/every forget plot}%
		\pgfplotsset{/pgfplots/every forget plot,/pgfplots/every axis plot post}%
	\else
		\edef\pgfplots@addplot@survey@@optionlist{/pgfplots/every axis plot,/pgfplots/every axis plot no \the\pgfplots@numplots/.try}%
		\pgfplotsset{/pgfplots/every axis plot no \the\pgfplots@numplots/.try,/pgfplots/every axis plot post}%
	\fi
	%
	\t@pgfplots@tokc=\expandafter{\pgfplots@addplot@survey@@optionlist,#1}% this allows '#' inside of '#1'
	\edef\pgfplots@addplot@survey@@optionlist{\the\t@pgfplots@tokc}%
	%
	\pgfplots@set@trig@format@plots
}

\long\def\pgfplotssurveyphaseaddoptionsbeforesurveybegins#1{%
	\pgfplotsset{%
		/pgfplots/execute at end survey/.add={}{%
			\t@pgfplots@tokc=\expandafter{\pgfplots@addplot@survey@@optionlist,#1}% this allows '#' inside of '#1'
			\edef\pgfplots@addplot@survey@@optionlist{\the\t@pgfplots@tokc}%
		},%
		#1%
	}%
}%
\long\def\pgfplotsplothandlersurveyaddoptions#1{%
	\t@pgfplots@tokc=\expandafter{\pgfplots@addplot@survey@@optionlist,#1}% this allows '#' inside of '#1'
	\edef\pgfplots@addplot@survey@@optionlist{\the\t@pgfplots@tokc}%
	\pgfplotsset{#1}%
}%


% The main interface to draw a plot into an axis.
%
% Usage:
% \addplot 
% 	plot coordinates {
% 		(0,0)
% 		(1,1)
% 	};
% 
% or
%
% \addplot[color=blue,mark=*]
% 	plot coordinates {
% 		(0,0)
% 		(1,1)
% 	};
%
% or one of the other input types.
% 
% The first syntax will use the next plot specification in the list
% \autoplotspeclist
% and the first will use blue color and * markers. 
%
% \addplot [<style options>]  plot[<behavior options>]  <input type and args> <post plot path> ;
% \addplot3[<style options>]  plot[<behavior options>]  <input type and args> <post plot path> ;
% 
% The complete accumulation is done GLOBALLY. It should be safe to put
% '\addplot' into local groups.
%
%
% The linespec. will be used in the legend.
%
% Low-level implementation:
%
% \pgfplots@addplot 
% \pgfplots@addplotimpl
% \pgfplots@start@plot@with@behavioroptions <--- \begingroup
% ...
% ... remember options GLOBALLY
% ... update limits GLOBALLY
% ... \pgfplots@addplot@enqueue@coords GLOBALLY
% ...
% \pgfplots@end@plot <--- \endgroup
\def\pgfplots@addplot{%
	\pgfutil@ifnextchar3{%
		\pgfplots@curplot@threedimtrue
		\pgfplots@addplot@three
	}{%
		\pgfplots@curplot@threedimfalse
		\pgfplots@addplot@
	}%
}
\def\pgfplots@addplot@three3{\pgfplots@addplot@}%
\def\pgfplots@addplot@{%
	\pgfutil@ifnextchar+{%
		\pgfplots@getautoplotspec into\nextplotspec
		\pgfplots@addplotimplAPPEND
	}{%
		\pgfutil@ifnextchar[{%
			\pgfplots@addplotimpl%
		}{%
			\pgfplots@getautoplotspec into\nextplotspec
			% the space after ']' is required here:
			% FIXME: 
			% - \addplot[]plot coordinates is NOT allowed!?
			\expandafter\pgfplots@addplotimpl\expandafter[\nextplotspec]%
		}%
	}%
}

\def\pgfplots@addplotimplAPPEND+{\pgfutil@ifnextchar[{\pgfplots@addplotimplAPPEND@}{\pgfplots@addplotimplAPPEND@[]}}% this allows to gobble spaces and to skip the '[]'
\def\pgfplots@addplotimplAPPEND@[{%
	\expandafter\pgfplots@addplotimpl\expandafter[\nextplotspec,%
}

\long\def\pgfplots@addplotimpl[#1]{%
	\pgfplotsutil@ifnextchar p{%
		\pgfplots@addplotimpl@plot{#1}%
	}{%
		\pgfplots@addplotimpl@plot{#1}plot
	}%
}

\long\def\pgfplots@addplotimpl@plot#1plot{%
	\pgfplotsutil@ifnextchar[{%
		\pgfplots@addplotimpl@plot@withoptions{#1}%
	}{%
		\pgfplots@addplotimpl@plot@withoptions{#1}[]%
	}%
}

\long\def\pgfplots@addplotimpl@plot@withoptions#1[#2]{
	\begingroup% <-- This groups ends in \pgfplots@end@plot
	%
	\pgfplotsutil@ifnextchar c{%
		\pgfplots@addplotimpl@coordinates{#1}{#2}plot 
	}{%
		\pgfplotsutil@ifnextchar f{%
			\pgfplots@addplotimpl@f{#1}{#2}%
		}{%
			\pgfplotsutil@ifnextchar t{%
				\def\pgfplotssurveyphaseinputclass{table}%
				\pgfplots@start@plot@with@behavioroptions{#1,/pgfplots/.cd,#2}%
				\pgfplots@addplotimpl@table{#1,#2}%
			}{%
				\pgfplotsutil@ifnextchar ({%
					\pgfplots@addplotimpl@expression{#1}{#2}%
				}{%
					\pgfplotsutil@ifnextchar\bgroup{%
						\pgfplots@addplotimpl@expression@curly{#1}{#2}%
					}{%
						\pgfplotsutil@ifnextchar e{%
							\pgfplots@addplotimpl@expression@e{#1}{#2}%
						}{%
							\pgfplotsutil@ifnextchar g{%
								\pgfplots@addplotimpl@g{#1}{#2}%
							}{%
								\pgfplotsutil@ifnextchar s{%
									\pgfplots@addplotimpl@shell{#1}{#2}%
								}{%

									\pgfplots@error{Sorry, the supplied plot command is unknown or unsupported by pgfplots! Ignoring it.}%
									\pgfplots@gobble@until@semicolon
								}%
							}%
						}%
					}%
				}%
			}%
		}%
	}%
}
\long\def\pgfplots@addplotimpl@f#1#2f{%
	\pgfplotsutil@ifnextchar i{%
		\pgfplots@addplotimpl@fil{#1}{#2}%
	}{%
		\pgfplots@addplotimpl@function{#1}{#2}%
	}%
}%

\long\def\pgfplots@addplotimpl@fil#1#2il{%
	\pgfplotsutil@ifnextchar e{%
		\pgfplots@addplotimpl@file{#1}{#2}%
	}{%
		\pgfplots@addplotimpl@fillbetween{#1}{#2}%
	}%
}%

\def\pgfplots@addplotimpl@fillbetween#1#2l between{%
	\pgfplotsutil@ifnextchar[{%
		\pgfplots@addplotimpl@fillbetween@opt{#1}{#2}%
	}{%
		\pgfplots@addplotimpl@fillbetween@opt{#1}{#2}[]%
	}%
}
% \addplot[#1] [#2] fill between[#3] #4;
\long\def\pgfplots@addplotimpl@fillbetween@opt#1#2[#3]#4;{\pgfplots@addplotimpl@fillbetween@opt@{#1}{#2}{#3}{#4}}%

\long\def\pgfplots@addplotimpl@fillbetween@opt@#1#2#3#4{%
	\pgfkeysifdefined{/tikz/fill between/of/.@cmd}{%
		\pgfplotslibraryfillbetween@addplot{#1,#2}{#3}{#4}%
	}{%	
		\pgfplotsthrow{invalid argument}
		{\pgfplots@loc@TMPa}%
		{Please load \string\usepgfplotslibrary{fillbetween} in order to use `\string\addplot\space fill between'.}%
		\pgfeov
	}%
	%
	\pgfplots@end@plot%
}%

\def\pgfplots@gobble@until@semicolon#1;{}

% PRECONDITION:
% 	the key-value sets have all been set in the current scope.
% 
% POSTCONDITION:
% 	1. the following macros are initialised and sanitized:
% 	\pgfplots@plot@domain
% 	\pgfplots@plot@ydomain (will be set to \pgfplots@plot@domain if empty)
% 	\pgfplots@plot@samples@at
% 	\pgfplots@plot@samples@y (will be set to the x variant if empty)
% 	\tikz@plot@var (will become a macro like '\x')
% 	\pgfplots@plot@var@nonmacro (the same as \tikz@plot@var, but without backslash)
% 	\pgfplots@plot@var@y (like \tikz@plot@var, but for y)
% 	\pgfplots@plot@var@y@nonmacro (like \pgfplots@plot@var@nonmacro, but for y)
% 	2. the following key-value things are set:
% 		/pgfplots/mesh/rows
% 		/pgfplots/mesh/cols
% 		/pgfplots/samples y (will contain a value )
% 	3. the macro 
% 		\b@pgfplots@should@sample@LINE 
% 		will be 
% 		\def\b@pgfplots@should@sample@LINE{1}
% 		if the expression plotter should sample a line
% 		and
% 		\def\b@pgfplots@should@sample@LINE{0}
% 		if it should sample a mesh.
\def\pgfplots@plot@expression@preparekeys{%
	\pgfkeysgetvalue{/pgfplots/domain}\pgfplots@plot@domain
	\pgfkeysgetvalue{/pgfplots/samples y}\pgfplots@plot@samples@y
	\pgfkeysgetvalue{/pgfplots/samples at}\pgfplots@plot@samples@at
	\pgfkeysgetvalue{/pgfplots/variable y}\pgfplots@plot@var@y
	% 
	% \tikz@plot@var is '\x' be default:
	\pgfplots@gettikzinternal@keyval{variable}{tikz@plot@var}{\x}%
	%
	\begingroup
		\escapechar=-1
		\xdef\pgfplots@glob@TMPa{\expandafter\string\tikz@plot@var}%
		\xdef\pgfplots@glob@TMPb{\expandafter\string\pgfplots@plot@var@y}%
	\endgroup
	% \pgfplots@plot@var@nonmacro is the value '\tikz@plot@var'
	% without the '\', i.e. 'x' by default:
	\let\pgfplots@plot@var@nonmacro=\pgfplots@glob@TMPa
	\let\pgfplots@plot@var@y@nonmacro=\pgfplots@glob@TMPb
	%
	% make sure the 'plot vars' have a backslash (as it was in tikz
	% plot expression):
	\edef\pgfplots@loc@TMPa{\expandafter\string\tikz@plot@var}%
	\ifx\pgfplots@plot@var@nonmacro\pgfplots@loc@TMPa
		\edef\tikz@plot@var{\expandafter\noexpand\csname \tikz@plot@var\endcsname}%
	\fi
	%
	\edef\pgfplots@loc@TMPa{\expandafter\string\pgfplots@plot@var@y}%
	\ifx\pgfplots@plot@var@y@nonmacro\pgfplots@loc@TMPa
		\edef\pgfplots@plot@var@y{\expandafter\noexpand\csname \pgfplots@plot@var@y\endcsname}%
	\fi
	%
	% Check if we have to sample a line or a matrix.
	% 
	\pgfkeysgetvalue{/pgfplots/sample dim}\pgfplots@loc@TMPa
	\def\pgfplots@loc@TMPb{auto}%
	\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
		\ifpgfplots@curplot@threedim
			\def\b@pgfplots@should@sample@LINE{0}%
		\else
			\def\b@pgfplots@should@sample@LINE{1}%
		\fi
	\else
		\ifcase\pgfplots@loc@TMPa\relax
			% sample dim=0 not useful!?
			\def\b@pgfplots@should@sample@LINE{1}%
		\or
			\def\b@pgfplots@should@sample@LINE{1}%
		\or
			\def\b@pgfplots@should@sample@LINE{0}%
		\else
			\pgfplots@error{Sorry, sample dim=\pgfplots@loc@TMPa\space is unsupported (use either 1 or 2)}%
		\fi
	\fi
	%
	\if0\b@pgfplots@should@sample@LINE
		% sample a matrix. Check the keys; if they are one
		% dimensional, switch back to line sampling:
		\pgfkeysgetvalue{/pgfplots/y domain}{\pgfplots@plot@ydomain}%
		\edef\pgfplots@plot@ydomain{\pgfplots@plot@ydomain}%
		\def\pgfplots@loc@TMPa{0:0}%
		\ifx\pgfplots@plot@ydomain\pgfplots@loc@TMPa
			\def\b@pgfplots@should@sample@LINE{1}%
		\fi
		\ifx\pgfplots@plot@ydomain\pgfutil@empty
			\let\pgfplots@plot@ydomain=\pgfplots@plot@domain
			\pgfkeyssetvalue{/pgfplots/y domain}{\pgfkeysvalueof{/pgfplots/domain}}%
		\fi
		\ifx\pgfplots@plot@samples@y\pgfutil@empty
		\else
			\ifnum\pgfplots@plot@samples@y<2
				\def\b@pgfplots@should@sample@LINE{1}%
			\fi
		\fi
	\else
		\def\b@pgfplots@should@sample@LINE{1}%
	\fi
	\ifx\pgfplots@plot@samples@y\pgfutil@empty
		\pgfkeyssetvalue{/pgfplots/samples y}{\pgfkeysvalueof{/pgfplots/samples}}%
		\pgfkeysgetvalue{/pgfplots/samples y}\pgfplots@plot@samples@y
	\fi
	%
	\iftikz@plot@raw@gnuplot
		% FIXME : verify this case
	\else
		\pgfkeyssetvalue{/pgfplots/mesh/rows}{\pgfkeysvalueof{/pgfplots/samples y}}%
		\pgfkeyssetvalue{/pgfplots/mesh/cols}{\pgfkeysvalueof{/pgfplots/samples}}%
	\fi
	\if1\b@pgfplots@should@sample@LINE
		\pgfkeyssetvalue{/pgfplots/sample dim}{1}%
		\pgfkeyssetvalue{/pgfplots/mesh/cols}{1}%
	\else
		\pgfkeyssetvalue{/pgfplots/sample dim}{2}%
	\fi
	%
}%

% Plot expression. It invokes the pgf math parser and a customized
% pgfplots point sampling routine. Combined with the 'fixed point
% library' of pgf, it results in highly accurate plots.
%
%
\long\def\pgfplots@addplotimpl@expression#1#2(#3,#4)#5;{\pgfplots@addplotimpl@expression@{#1}{#2}{#3}{#4}{#5}}%
% \addplot[#1] [#2] (#3,#4) #5;
\long\def\pgfplots@addplotimpl@expression@#1#2#3#4#5{%
	\pgfplots@addplotimpl@expression@set@options{#1}{#2}%
	\pgfplots@addplotimpl@expression@@{#3}{#4}{#5}%
}

\long\def\pgfplots@addplotimpl@expression@set@options#1#2{%
	\def\pgfplotssurveyphaseinputclass{expression}%
	\pgfplots@start@plot@with@behavioroptions{#1,/pgfplots/.cd,#2,/pgfplots/mesh input=lattice,/pgfplots/mesh/ordering/x varies}%
	\pgfplots@plot@expression@preparekeys
}%

% \addplot (#1,#2) #3;
\long\def\pgfplots@addplotimpl@expression@@#1#2#3{%
	%
	\pgfplots@PREPARE@COORD@STREAM{#3}%
	%
	% Determine whether the x range is parameterized or uniform and
	% prepare a macro which assigns \pgfplots@current@point@x:
	\def\pgfplots@addplotimpl@expression@prepare@x{%
		\pgfmathparse{#1}%
		\let\pgfplots@current@point@x=\pgfmathresult
	}%
	\def\pgfplots@addplotimpl@expression@hasuniform@x{0}%
	\def\pgfplots@loc@TMPa{#1}%
	% do we have '\x' as x coordinate?
	\expandafter\def\expandafter\pgfplots@loc@TMPb\expandafter{\tikz@plot@var}%
	\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
		\def\pgfplots@addplotimpl@expression@hasuniform@x{1}%
	\else
		\def\pgfplots@loc@TMPb{x}%
		% do we have 'x' as x coordinate?
		\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
			\def\pgfplots@addplotimpl@expression@hasuniform@x{1}%
		\fi
	\fi
	\if\pgfplots@addplotimpl@expression@hasuniform@x1%
		% if '#1' is '\x' or 'x', we don't need the math parser -
		% we can simply take \tikz@plot@var.
		\def\pgfplots@addplotimpl@expression@prepare@x{%
			\edef\pgfplots@current@point@x{\tikz@plot@var}%
		}%
	\fi
	%
	%
	% Now, prepare the loops.
	%
	% I am using \pgfplotsforeachungrouped in favor of
	% \foreach because \foreach does NOT allow extended
	% precision. Besides, \pgfplotsforeachungrouped avoids
	% scoping problems.
	\let\pgfplots@plot@data@notify@next@x=\relax
	\let\pgfplots@plot@data@notify@next@y=\relax
	%
	\ifpgfplots@curplot@threedim
		\def\pgfplots@addplotimpl@expression@split@yz##1,##2\pgfplots@EOI{%
			\def\pgfplots@addplotimpl@expression@yEXPR{##1}%
			\def\pgfplots@addplotimpl@expression@zEXPR{##2}%
		}%
		\pgfplots@addplotimpl@expression@split@yz#2\pgfplots@EOI%
		%
		% we don't have 'samples at' for 3D plots -> use domain!
		\expandafter\pgfplots@domain@to@foreach\pgfplots@plot@domain\relax{\pgfplots@plot@samples}%
		\let\pgfplots@expression@xdomain=\pgfplotsretval
		%
		\if0\b@pgfplots@should@sample@LINE
			% Samples twodimensionally (a lattice):
			\expandafter\pgfplots@domain@to@foreach\pgfplots@plot@ydomain\relax{\pgfplots@plot@samples@y}%
			\let\pgfplots@expression@ydomain=\pgfplotsretval
			%
			% Assemble a 
			% \pgfplots@plot@data##1 -> 
			% 	\foreach \y in {-5,-4.6,...,5} {##1}; 
			% 		\foreach \x in {-5,-4.6,...,5} 
			%  macro:
			\edef\pgfplots@plot@data##1{%
				\noexpand\pgfplotsforeachungrouped\expandafter\noexpand\pgfplots@plot@var@y in {\pgfplots@expression@ydomain} 
					{%
						\pgfplots@plot@data@notify@next@y
						\noexpand\pgfplotsforeachungrouped\expandafter\noexpand\tikz@plot@var in {\pgfplots@expression@xdomain} {%
							\pgfplots@plot@data@notify@next@x
							##1%
						}%
						\noexpand\pgfplotsplothandlernotifyscanlinecomplete
					}%
				}%
		\else
			% sample a line:
			\def\pgfplots@plot@ydomain{0:0}%
			\edef\pgfplots@plot@data##1{%
				\noexpand\pgfplotsforeachungrouped\expandafter\noexpand\tikz@plot@var in {\pgfplots@expression@xdomain} {%
					\pgfplots@plot@data@notify@next@x
					##1%
				}%
			}%
			%
			% If we have (\x,\y,f(x)), use (\x,0,f(x)) instead and
			% suppress the error message which would occur for \y.
			\expandafter\pgfplotsutilifstringequal\expandafter{\pgfplots@addplotimpl@expression@yEXPR}{\pgfplots@plot@var@y}{%
				\def\pgfplots@addplotimpl@expression@yEXPR{0}%
			}{%
				\expandafter\edef\pgfplots@plot@var@y{\pgfplots@plot@var@y@nonmacro}% this provides an error message, see above.
			}%
		\fi
	\else
		% Assemble a 
		% \pgfplots@plot@data##1 -> \foreach \x in {-5,-4.6,...,5} {##1} macro:
		%
		%
		% if( 	
		% 	x is logarithmic && 
		% 	#1 == '\x' && 
		% 	the 'samples at' key has not been used )
		%  -> sample logarithmically!
		\def\pgfplots@samples@logarithmically{0}%
		\ifpgfplots@xislinear
		\else
			\if\pgfplots@addplotimpl@expression@hasuniform@x1%
				\ifx\pgfplots@plot@samples@at\pgfutil@empty
					% we don't have 'samples at' -> use domain!
					\def\pgfplots@samples@logarithmically{1}%
				\fi
			\fi
		\fi
		\if\pgfplots@samples@logarithmically1%
			\def\pgfplotsforeachlogarithmicmathid{x}% use \pgfplotscoordmath{x}
			% sample logarithmically:
			\edef\pgfplots@plot@data##1{%
				\noexpand\pgfplotsforeachlogarithmicungrouped[\pgfplots@plot@samples]
				\expandafter\noexpand\tikz@plot@var/\noexpand\pgfplots@current@point@x@log 
					in {\pgfplots@plot@domain}%
				{%
					\pgfplots@plot@data@notify@next@x
					##1%
				}%
			}%
			%  we have a logarithmic sampling sequence,
			% \pgfplots@current@point@x@log is already available
			% logarithmic! We can safe time and accuracy for the x
			% coordinate by using that one instead of computing
			% log(exp(\x)) numerically:
			\pgfplots@disablelogfilter@xtrue
			\def\pgfplots@addplotimpl@expression@prepare@x{%
				\let\pgfplots@current@point@x=\pgfplots@current@point@x@log
			}%
			\pgflibraryfpuifactive
				{\relax}
				{%
					% ok, if the FPU is NOT active, we should return
					% results as fixed points.
					% We need to configure that for
					% \pgfplotsforeachlogarithmicungrouped manually:
					\pgfplotsforeachlogarithmicformatresultwith{%
						\pgfmathfloattofixed{\pgfmathresult}%
					}%
				}%
		\else
			\ifx\pgfplots@plot@samples@at\pgfutil@empty
				% we don't have 'samples at' -> use domain!
				\expandafter\pgfplots@domain@to@foreach\pgfplots@plot@domain\relax{\pgfplots@plot@samples}%
				\let\pgfplots@loc@TMPa=\pgfplotsretval
			\else
				% use 'samples at':
				\let\pgfplots@loc@TMPa=\pgfplots@plot@samples@at
			\fi
			\edef\pgfplots@plot@data##1{%
				\noexpand\pgfplotsforeachungrouped\expandafter\noexpand\tikz@plot@var in {\pgfplots@loc@TMPa}%
				{%
					\pgfplots@plot@data@notify@next@x
					##1%
				}%
			}%
		\fi
		\expandafter\def\pgfplots@plot@var@y{0}%
		\def\pgfplots@addplotimpl@expression@yEXPR{#2}%
		\def\pgfplots@current@point@z{}%
	\fi
	%
	% START:
	%  (NOTE: this does also define 'x', 'y', and 'z' math
	%  expressions!)
	\pgfplots@coord@stream@start
	%
	% create a backup of the 'x' and 'y' math expressions which 
	% have been defined in \pgfplots@coord@stream@start:
	\let\pgfplots@addplotimpl@expression@pseudoconst@old@x=\pgfmathx@
	\let\pgfplots@addplotimpl@expression@pseudoconst@old@y=\pgfmathy@
	%
	% Prepare 'x' and 'y' as pseudo constants in expressions:
	\gdef\pgfplots@noy@error{%
		\pgfplots@error{Sorry, you can't use 'y' in this context. PGFPlots expected to sample a line, not a mesh. Please use the [mesh] option combined with [samples y>0] and [domain y!=0:0] to indicate a twodimensional input domain}%
		\global\let\pgfplots@noy@error=\relax
	}%
	% Define a "function" x which sets \pgfmathresult := \x :
	\pgfplotsmathdeclarepseudoconstant{\pgfplots@plot@var@nonmacro}{\edef\pgfmathresult{\tikz@plot@var}}%
	\if0\b@pgfplots@should@sample@LINE
		% surface:
		\pgfplotsmathdeclarepseudoconstant{\pgfplots@plot@var@y@nonmacro}{\edef\pgfmathresult{\pgfplots@plot@var@y}}%
	\else
		\pgfplotsmathdeclarepseudoconstant{\pgfplots@plot@var@y@nonmacro}{\pgfplots@noy@error\def\pgfmathresult{0.0}}%
	\fi
	% remember them here:
	\let\pgfplots@addplotimpl@expression@pseudoconst@x=\pgfmathx@
	\let\pgfplots@addplotimpl@expression@pseudoconst@y=\pgfmathy@
	%
%	\if n\pgfplots@meshmode
		% mesh=false : ignore patch type sampling.
%	\else
		\ifpgfplotsplothandlermesh@patch@type@sampling
			\pgfplots@plot@expression@prepare@patch@type@sampling
		\fi
%	\fi
	%
	% Warning for use fpu=false: evaluation '\x^3' might be different from 'x^3' for
	% negative arguments:
	% \x^3 ---> -0.2^3  but x^3 = (-0.2)^3 .
	% This does not happen for use fpu=true.
	% 
	\pgfplots@plot@data{%
		\let\pgfmathx@=\pgfplots@addplotimpl@expression@pseudoconst@x
		\let\pgfmathy@=\pgfplots@addplotimpl@expression@pseudoconst@y
		% eval expressions:
		\pgfplots@addplotimpl@expression@prepare@x%
		\pgfmathparse{\pgfplots@addplotimpl@expression@yEXPR}%
		\let\pgfplots@current@point@y=\pgfmathresult
		\ifpgfplots@curplot@threedim
			\pgfmathparse{\pgfplots@addplotimpl@expression@zEXPR}%
			\let\pgfplots@current@point@z=\pgfmathresult
		\fi
		% restore 'x' and 'y':
		\let\pgfmathx@=\pgfplots@addplotimpl@expression@pseudoconst@old@x
		\let\pgfmathy@=\pgfplots@addplotimpl@expression@pseudoconst@old@y
		%
		%\pgfplots@expression@normalize@floats
		%
		% process coords as usual:
		\pgfplots@coord@stream@coord
	}%
	\pgfplots@coord@stream@end
}%

% Typically, the FPU will generate stuff like '1Y1.0e5'. Since such
% internal representations will be available to API users (especially
% 'x filter' and its variants, we want to simplify its output - by
% normalizing it.
%
% This routine will convert any floats to scientific format, i.e.
% 1.0e5 instead of 1Y1.0e5 (1Y means 'positive float', compare
% pgfmathfloat.code.tex).
\def\pgfplots@expression@normalize@floats{%
	\pgflibraryfpuifactive{%
		\ifx\pgfplots@current@point@x\pgfutil@empty\else
			\pgfmathfloattosci{\pgfplots@current@point@x}\let\pgfplots@current@point@x=\pgfmathresult
		\fi%
		\ifx\pgfplots@current@point@y\pgfutil@empty\else
			\pgfmathfloattosci{\pgfplots@current@point@y}\let\pgfplots@current@point@y=\pgfmathresult
		\fi%
		\ifx\pgfplots@current@point@z\pgfutil@empty\else
			\pgfmathfloattosci{\pgfplots@current@point@z}\let\pgfplots@current@point@z=\pgfmathresult
		\fi%
	}{%
	}%
}%

% \addplot[#1] [#2] {#3} #4;
\long\def\pgfplots@addplotimpl@expression@curly#1#2#3#4;{\pgfplots@addplotimpl@expression@curly@{#1}{#2}{#3}{#4}}%
\long\def\pgfplots@addplotimpl@expression@curly@#1#2#3#4{%
	\pgfplots@addplotimpl@expression@set@options{#1}{#2}%
	\ifpgfplots@curplot@threedim
		\t@pgfplots@toka={,#3}%
		% the \pgfplots@plot@var@y will expand to the current value of
		% '/pgfplots/variable y'.
		% Keep it this way, \pgfplots@addplotimpl@expression@ checks
		% for that special string.
		\edef\pgfplots@loc@TMPb{%
			{\expandafter\noexpand\tikz@plot@var}%
			{\noexpand\pgfplots@plot@var@y\the\t@pgfplots@toka}%
		}%
		\expandafter\pgfplots@addplotimpl@expression@@\pgfplots@loc@TMPb{#4}%
	\else
		\expandafter\pgfplots@addplotimpl@expression@@\expandafter{\tikz@plot@var}{#3}{#4}%
	\fi
}%
% \addplot[#1] [#2] expression[#3] {#4} #5;
\def\pgfplots@addplotimpl@expression@e#1#2expression{%
	\pgfplotsutil@ifnextchar[{%
		\pgfplots@addplotimpl@expression@e@{#1}{#2}%
	}{%
		\pgfplots@addplotimpl@expression@e@{#1}{#2}[]%
	}%
}%
\def\pgfplots@addplotimpl@expression@e@#1#2[#3]{%
	\pgfplots@addplotimpl@expression@curly{#1}{#2,#3}%
}%


% This prepares the implementation for 'patch type sampling':
\def\pgfplots@plot@expression@prepare@patch@type@sampling{%
	\pgfplotssurveyphaseaddoptionsbeforesurveybegins{
		mesh input=patches,%
	}%
	%
	\pgfkeysgetvalue{/pgfplots/patch type}\pgfplotsplothandlermesh@patchclass
	%
	\let\pgfplots@plot@data@@=\pgfplots@plot@data
	\let\pgfplots@plot@data@curx=\pgfutil@empty
	\let\pgfplots@plot@data@cury=\pgfutil@empty
	\let\pgfplots@plot@data@lastx=\pgfutil@empty
	\let\pgfplots@plot@data@lasty=\pgfutil@empty
	\let\pgfplots@plot@data@first@x=\pgfutil@empty
	\let\pgfplots@plot@data@first@y=\pgfutil@empty
	%
	\def\pgfplots@plot@data@notify@next@x{%
		\ifx\pgfplots@plot@data@first@x\pgfutil@empty
			\edef\pgfplots@plot@data@first@x{\tikz@plot@var}%
		\fi
		\let\pgfplots@plot@data@lastx=\pgfplots@plot@data@curx
		\edef\pgfplots@plot@data@curx{\tikz@plot@var}%
	}%
	\def\pgfplots@plot@data@notify@next@y{%
		\ifx\pgfplots@plot@data@first@y\pgfutil@empty
			\edef\pgfplots@plot@data@first@y{\pgfplots@plot@var@y}%
		\fi
		\let\pgfplots@plot@data@lasty=\pgfplots@plot@data@cury
		\edef\pgfplots@plot@data@cury{\pgfplots@plot@var@y}%
	}%
	\def\pgfplots@plot@data##1{%
		%
		\pgfplots@plot@data@@{%
			\let\tikz@plot@var@old=\tikz@plot@var
			\let\pgfplots@plot@var@y@old=\pgfplots@plot@var@y
			%
			%
			%
			% boolean 'if is first row || is first cell':
			\pgfplots@loc@tmpfalse
			\ifx\pgfplots@plot@data@curx\pgfplots@plot@data@first@x
				% ah - we have the first row.
				\pgfplots@loc@tmptrue
			\fi
			\if0\b@pgfplots@should@sample@LINE
				\ifx\pgfplots@plot@data@cury\pgfplots@plot@data@first@y
					% ah - we have the first cell.
					\pgfplots@loc@tmptrue
				\fi
			\fi
			%
			\ifpgfplots@loc@tmp
			\else
				\pgfmathparse{\pgfplots@plot@data@curx-\pgfplots@plot@data@lastx}%
				\let\pgfplots@plot@data@hx=\pgfmathresult
				%
				\if0\b@pgfplots@should@sample@LINE
					\pgfmathparse{\pgfplots@plot@data@cury-\pgfplots@plot@data@lasty}%
					\let\pgfplots@plot@data@hy=\pgfmathresult
				\fi
				%
				\def\pgfplotspatchready{\pgfplotsscanlinecomplete}%
				\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{sample in unit cube}{%
					\pgfmathparse{\pgfplots@plot@data@lastx + \pgfplotspatchclassx*\pgfplots@plot@data@hx}%
					\let\tikz@plot@var=\pgfmathresult
					%
					\if0\b@pgfplots@should@sample@LINE
						\pgfmathparse{\pgfplots@plot@data@lasty + \pgfplotspatchclassy*\pgfplots@plot@data@hy}%
						\let\pgfplots@plot@var@y=\pgfmathresult
					\fi
					%
					##1%
					%
					\let\tikz@plot@var=\tikz@plot@var@old
					\let\pgfplots@plot@var@y=\pgfplots@plot@var@y@old
				}%
			\fi
		}%
	}%
}%

\let\pgfplots@backupof@pgfplotxyfile=\pgfplotxyfile

% the following code 
% results finally in
%
% set format "%.7e";; set samples <...>; plot ...
%
% The windows port of gnuplot doesn't run without the second semicolon
% - for whatever reason.
{
  \catcode`\%=12
  \catcode`\"=12
  \catcode`\;=12
  \xdef\pgfplots@gnuplot@format{set format "%.7e";}
}
\def\pgfplots@addplotimpl@g#1#2g{%
	\pgfplotsutil@ifnextchar r{%
		\pgfplots@addplotimpl@graphics{#1}{#2}%
	}{%
		\pgfplots@addplotimpl@gnuplot{#1}{#2}%
	}%
}%

% |\addplot gnuplot| is an alias to |\addplot function|
\def\pgfplots@addplotimpl@gnuplot#1#2nuplot{\pgfplots@addplotimpl@function{#1}{#2}unction}%

% \addplot[#1] plot[#2] function[#3] {#4} #5;
\def\pgfplots@addplotimpl@function#1#2unction{%
	\pgfplotsutil@ifnextchar[{%
		\pgfplots@addplotimpl@function@opt{#1}{#2}%
	}{%
		\pgfplots@addplotimpl@function@opt{#1}{#2}[]%
	}%
}%
\def\pgfplots@addplotimpl@function@opt#1#2[#3]#4#5;{\pgfplots@addplotimpl@function@opt@{#1}{#2}{#3}{#4}{#5}}%
% \addplot[#1] [#2] function[#3] {#4} #5;
\def\pgfplots@addplotimpl@function@opt@#1#2#3#4#5{%
	% FIXME : what about the key search paths if the user changes
	% them!?
	\def\pgfplotssurveyphaseinputclass{gnuplot}%
	\pgfplots@start@plot@with@behavioroptions{#1,/pgfplots/.cd,#2,/pgfplots/.cd,#3,/pgfplots/mesh/ordering/x varies}%
	%
	\pgfplots@gettikzinternal@keyval{prefix}{tikz@plot@prefix}{\jobname.}%
	\pgfplots@gettikzinternal@keyval{id}{tikz@plot@id}{pgf-plot}%
	\pgfplots@gettikzinternal@keyval{raw gnuplot}{iftikz@plot@raw@gnuplot}{\iffalse}%
	\pgfplots@gettikzinternal@keyval{parametric}{iftikz@plot@parametric}{\iffalse}%
	%
	% determine dummy variables:
	\iftikz@plot@parametric
		\ifpgfplots@curplot@threedim
			\pgfkeysgetvalue{/pgfplots/parametric/var 2d}\pgfplots@gnuplot@dummy%
		\else
			\pgfkeysgetvalue{/pgfplots/parametric/var 1d}\pgfplots@gnuplot@dummy%
		\fi
		\ifx\pgfplots@gnuplot@dummy\pgfutil@empty
		\else
			\expandafter\pgfutil@in@\expandafter,\expandafter{\pgfplots@gnuplot@dummy}%
			\ifpgfutil@in@	
				\def\pgfplots@loc@TMPa##1,##2\pgfeov{\pgfplotsset{variable={##1},variable y={##2}}}%
			\else
				\def\pgfplots@loc@TMPa##1\pgfeov{\pgfplotsset{variable={##1}}}%
			\fi
			\expandafter\pgfplots@loc@TMPa\pgfplots@gnuplot@dummy\pgfeov
		\fi
	\fi
	%
	% prepare domain and samples, normalize dummy variables:
	\pgfplots@plot@expression@preparekeys
	%
	% FIXME: what with 'samples at'!?
	\edef\pgfplots@plot@filename{\tikz@plot@prefix\tikz@plot@id}%
	%
	\def\pgfplots@addplotimpl@gnuplotresult@isthreedim@withtwocoords{0}%
	%
	\edef\pgfplots@gnuplotcode{#4}%
	\ifpgfplots@translategnuplot
		\def\pgfplots@loc@TMPa{\pgfplotsutilstrreplace{^}{**}}%
		\expandafter\pgfplots@loc@TMPa\expandafter{\pgfplots@gnuplotcode}%
		\let\pgfplots@gnuplotcode=\pgfplotsretval
	\fi
	%
	%
	\iftikz@plot@raw@gnuplot%
		\def\pgfplots@plot@data{\pgfplotgnuplot[\pgfplots@plot@filename]{\pgfplots@gnuplot@format;\pgfplots@gnuplotcode}}%
	\else%
		% collect logs:
		\def\pgfplots@gnuplot@logdirs{}%
		\ifpgfplots@xislinear
		\else
			\pgfplots@identify@gnuplot@logbehavior x%
			\expandafter\def\expandafter\pgfplots@gnuplot@logdirs\expandafter{\pgfplots@gnuplot@logdirs x}%
		\fi
		\ifpgfplots@yislinear
		\else
			\pgfplots@identify@gnuplot@logbehavior y%
			\expandafter\def\expandafter\pgfplots@gnuplot@logdirs\expandafter{\pgfplots@gnuplot@logdirs y}%
		\fi
		\ifpgfplots@curplot@threedim
			\ifpgfplots@zislinear
			\else
				\pgfplots@identify@gnuplot@logbehavior z%
				\expandafter\def\expandafter\pgfplots@gnuplot@logdirs\expandafter{\pgfplots@gnuplot@logdirs z}%
			\fi
		\fi
		%
		\ifpgfplots@curplot@threedim
			\if1\b@pgfplots@should@sample@LINE
				\pgfplots@error{Sorry, I do not know how to sample 3D LINE plots with gnuplot... I only know 2D line and 3D mesh. You may want to help the author of pgfplots to improve this feature.}%
			\fi
		\fi
		\def\pgfplots@gnuplot@x{\pgfplots@plot@var@nonmacro}%
		\def\pgfplots@gnuplot@y{\pgfplots@plot@var@y@nonmacro}%
		\def\pgfplots@plot@data{\pgfplotgnuplot[\pgfplots@plot@filename]{%
			\pgfplots@gnuplot@format;
			set samples \pgfkeysvalueof{/pgfplots/samples}\if0\b@pgfplots@should@sample@LINE, \pgfkeysvalueof{/pgfplots/samples y}\fi;
			set dummy \pgfplots@gnuplot@x\if0\b@pgfplots@should@sample@LINE,\pgfplots@gnuplot@y\fi;
			\ifx\pgfplots@gnuplot@logdirs\pgfutil@empty
			\else
				set logscale \pgfplots@gnuplot@logdirs\space 2.71828182845905; 
			\fi
			\iftikz@plot@parametric	set parametric;\fi
			\ifpgfplots@curplot@threedim 
				\if0\b@pgfplots@should@sample@LINE
					% Samples twodimensionally (a lattice):
					% and the isosamples thing confuses me.
					set isosamples \pgfkeysvalueof{/pgfplots/samples}\if0\b@pgfplots@should@sample@LINE, \pgfkeysvalueof{/pgfplots/samples y}\fi;
					splot [\pgfplots@gnuplot@x=\pgfplots@plot@domain] [\pgfplots@gnuplot@y=\pgfplots@plot@ydomain] \pgfplots@gnuplotcode;%
				\else
					% *should* sample a line, but I don't know how.
					splot [\pgfplots@gnuplot@x=\pgfplots@plot@domain] \pgfplots@gnuplotcode;%
				\fi
			\else
				plot [\pgfplots@gnuplot@x=\pgfplots@plot@domain] \pgfplots@gnuplotcode;%
			\fi
			}}%
	\fi%
	\def\pgfplotxyfile{\pgfplots@addplotimpl@gnuplotresult{#5}}%
	\pgfplots@plot@data
	\let\pgfplotxyfile=\pgfplots@backupof@pgfplotxyfile
}%

\def\pgfplots@identify@gnuplot@logbehavior#1{%
	\pgfutil@ifundefined{pgfplots@gnuplot@logscale@writes@log}{%
		\pgfplots@identify@gnuplot@logbehavior@checkversion%
	}{}%
	\if1\pgfplots@gnuplot@logscale@writes@log
		\csname pgfplots@disablelogfilter@#1true\endcsname
	\fi
}%
\def\pgfplots@identify@gnuplot@logbehavior@checkversion{%
	\begingroup
	\immediate\write18{gnuplot -V >\pgfplots@plot@filename.vrs}%
	\openin\r@pgfplots@reada=\pgfplots@plot@filename.vrs\relax
	\ifeof\r@pgfplots@reada
		\pgfplotswarning{gnuplot -V impossible}\pgfeov
		\gdef\pgfplots@gnuplot@logscale@writes@log{1}% something doesn't work. set it somehow.
	\else
		\read\r@pgfplots@reada to\pgfplots@loc@TMPa
		\gdef\pgfplots@gnuplot@logscale@writes@log{1}%
		\t@pgfplots@toka=\expandafter{\pgfplots@loc@TMPa}%
		\immediate\write-1{Package pgfplots: checking gnuplot -V : `\the\t@pgfplots@toka' (if this fails, set `/pgfplots/gnuplot writes logscale=true|false')}%
		\expandafter\pgfplots@identify@gnuplot@logbehavior@checkversion@\pgfplots@loc@TMPa 0 0.0 0\relax
		\if0\pgfplots@gnuplot@logscale@writes@log
			\immediate\write-1{Package pgfplots: I found gnuplot version >= 4.4. This one doesn't write log() coordinates. I will apply log() manually.}%
		\else
			\immediate\write-1{Package pgfplots: I found gnuplot version < 4.4. This one writes log() coordinates. I'll handle it accordingly.}%
		\fi
		\closein\r@pgfplots@reada
	\fi
	\endgroup
}%
\long\def\pgfplots@identify@gnuplot@logbehavior@checkversion@{%
	\pgfutil@ifnextchar\par{%
		\pgfplotswarning{gnuplot -V format unknown}\pgfeov%
		\gdef\pgfplots@gnuplot@logscale@writes@log{1}%
		\pgfplots@identify@gnuplot@logbehavior@checkversion@@@
	}{%
		\pgfplots@identify@gnuplot@logbehavior@checkversion@@
	}%
}%
\long\def\pgfplots@identify@gnuplot@logbehavior@checkversion@@@#1\relax{%
}%
\long\def\pgfplots@identify@gnuplot@logbehavior@checkversion@@#1 #2.#3 #4\relax{%
	% starting with gnuplot 4.4, output files are no longer in
	% logarithmic scale for log plots.
	\ifnum#2<4
		% version 3.X
		\gdef\pgfplots@gnuplot@logscale@writes@log{1}%
	\else
		\ifnum#2>4
			% version 5.X
			\gdef\pgfplots@gnuplot@logscale@writes@log{0}%
		\else
			\ifnum#3<4
				% version 4.2 :
				\gdef\pgfplots@gnuplot@logscale@writes@log{1}%
			\else
				% version 4.4 or later :
				\gdef\pgfplots@gnuplot@logscale@writes@log{0}%
			\fi
		\fi
	\fi
}%

\def\pgfplots@addplotimpl@gnuplotresult#1#2{%
	\begingroup
	\openin\r@pgfplots@reada=#2
	\ifeof\r@pgfplots@reada
		\pgfplots@error{Sorry, the gnuplot-result file '#2' could not be found. Maybe you need to enable the shell-escape feature? For pdflatex, this is '>> pdflatex -shell-escape'. You can also invoke '>> gnuplot <file>.gnuplot' manually on the respective gnuplot file.}%
		\aftergroup\pgfplots@loop@CONTINUEfalse
	\else
		\aftergroup\pgfplots@loop@CONTINUEtrue
	\fi
	\closein\r@pgfplots@reada
	\endgroup
	\ifpgfplots@loop@CONTINUE
		 % Now, invoke 'plot file'.
		 %
		 % I invoke the private '@opt@' method because the semicolon ';' 
		 % character may cause problems due to catcode mismatches.
		 % *sigh*.
		\pgfplots@addplotimpl@file@opt@@{}{}{#2}{#1}% this does not invoke the \pgfplots@start@plot@with@behavioroptions method.
	\else
		\expandafter\pgfplots@end@plot
	\fi
}

% \addplot[#1] plot[#2] shell[#3] {#4} #5;
\def\pgfplots@addplotimpl@shell#1#2shell{%
	\pgfplotsutil@ifnextchar[{%
		\pgfplots@addplotimpl@shell@opt{#1}{#2}%
	}{%
		\pgfplots@addplotimpl@shell@opt{#1}{#2}[]%
	}%
}%
\def\pgfplots@addplotimpl@shell@opt#1#2[#3]#4#5;{\pgfplots@addplotimpl@shell@opt@{#1}{#2}{#3}{#4}{#5}}%
% \addplot[#1] [#2] shell[#3] {#4} #5;
\def\pgfplots@addplotimpl@shell@opt@#1#2#3#4#5{%
	\def\pgfplotssurveyphaseinputclass{shell}%
	\pgfplots@start@plot@with@behavioroptions{#1,/pgfplots/.cd,#2,/pgfplots/.cd,#3}%
	\pgfplots@gettikzinternal@keyval{prefix}{tikz@plot@prefix}{\jobname.}%
	\pgfplots@gettikzinternal@keyval{id}{tikz@plot@id}{pgf-shell}%
	%
	\def\pgfplots@plot@filename{\tikz@plot@prefix\tikz@plot@id}%  
	\def\pgfplots@plot@data{\pgfshell[\pgfplots@plot@filename]{#4}\pgfplotxyfile{\pgfplots@plot@filename.out}}%
	\def\pgfplotxyfile{\pgfplots@addplotimpl@shellresult{#5}}%
	\pgfplots@plot@data
	\let\pgfplotxyfile=\pgfplots@backupof@pgfplotxyfile
}%

\def\pgfplots@addplotimpl@shellresult#1#2{%
	\begingroup
	\openin\r@pgfplots@reada=#2
	\ifeof\r@pgfplots@reada
		\pgfplots@error{Sorry, the shell-result file '#2' could not be found. Maybe you need to enable the shell-escape feature? For pdflatex, this is '>> pdflatex -shell-escape'. You can also invoke '>> sh <file>.sh > <file>.out' manually on the respective shell file.}%
		\aftergroup\pgfplots@loop@CONTINUEfalse
	\else
		\aftergroup\pgfplots@loop@CONTINUEtrue
	\fi
	\closein\r@pgfplots@reada
	\endgroup
	\ifpgfplots@loop@CONTINUE
		 % Now, invoke 'plot file'.
		 %
		 % I invoke the private '@opt@' method because the semicolon ';' 
		 % character may cause problems due to catcode mismatches.
		 % *sigh*.
		\pgfplots@addplotimpl@file@opt@@{}{}{#2}{#1}%
	\else
		\expandafter\pgfplots@end@plot
	\fi
}

% \addplot[#1] [#2] file{#3} #4;
\def\pgfplots@addplotimpl@file#1#2e{%
	\pgfplotsutil@ifnextchar[{%
		\pgfplots@addplotimpl@file@opt{#1}{#2}%
	}{%
		\pgfplots@addplotimpl@file@opt{#1}{#2}[]%
	}%
}

% \addplot[#1] [#2] file[#3] {#4} #5;
\def\pgfplots@addplotimpl@file@opt#1#2[#3]#4#5;{\pgfplots@addplotimpl@file@opt@{#1}{#2}{#3}{#4}{#5}}%
\def\pgfplots@addplotimpl@file@opt@#1#2#3#4#5{%
	% invoke this here - allows to share the 'plot file' impl with
	% 'plot gnuplot'.
	\def\pgfplotssurveyphaseinputclass{file}%
	\pgfplots@start@plot@with@behavioroptions{#1,/pgfplots/.cd,#2}%
	\pgfplots@addplotimpl@file@opt@@{#1,#2}{#3}{#4}{#5}%
}
\def\pgfplots@addplotimpl@file@opt@@#1#2#3#4{%
	\begingroup
	\def\pgfplots@loc@TMPa{#2}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
	\else
		\pgfqkeys{/pgfplots/plot file}{#2}%
	\fi
	\pgfplots@PREPARE@COORD@STREAM{#4}%
	\pgfplots@addplotimpl@file@streamit{#3}%
	\endgroup
}%
% #1: the file name
\def\pgfplots@addplotimpl@file@streamit#1{%
	\pgfplots@coord@stream@start
	\pgfplotsscanlinelengthinitzero
	\openin\r@pgfplots@reada=#1
	\ifeof\r@pgfplots@reada
		\pgfplots@error{sorry, plot file{#1} could not be opened}%
	\else
		\pgfplots@logfileopen{#1}%
		\let\pgfplots@current@point@error@x@plus=\pgfutil@empty
		\let\pgfplots@current@point@error@x@minus=\pgfutil@empty
		\let\pgfplots@current@point@error@y@plus=\pgfutil@empty
		\let\pgfplots@current@point@error@y@minus=\pgfutil@empty
		\let\pgfplots@current@point@error@z@plus=\pgfutil@empty
		\let\pgfplots@current@point@error@z@minus=\pgfutil@empty
		\let\pgfplots@current@point@meta=\pgfutil@empty
		\ifpgfplots@curplot@threedim
			\let\pgfplots@addplotimpl@file@parsesingle=\pgfplots@addplotimpl@file@parsesingle@threedim
			\if1\csname pgfpmeta@\pgfplotspointmetainputhandler @explicitinput\endcsname
				\let\pgfplots@addplotimpl@file@parsesingle=\pgfplots@addplotimpl@file@parsesingle@threedim@andmeta
			\fi
		\else
			\let\pgfplots@addplotimpl@file@parsesingle=\pgfplots@addplotimpl@file@parsesingle@twodim
			\if1\csname pgfpmeta@\pgfplotspointmetainputhandler @explicitinput\endcsname
				\let\pgfplots@addplotimpl@file@parsesingle=\pgfplots@addplotimpl@file@parsesingle@twodim@andmeta
			\fi
		\fi
		\pgfplotstableinstallignorechars%
		\pgfplots@addplotimpl@file@readall
	\fi
	\pgfplotsscanlinelengthcleanup
	\pgfplots@coord@stream@end
}%
\def\pgfplots@addplotimpl@file@readall{%
	\read\r@pgfplots@reada to\pgfplots@file@LINE
	\expandafter\pgfplotstableread@checkspecial@line\pgfplots@file@LINE\pgfplotstable@EOI
	\ifpgfplotstableread@skipline
	\else
		\ifpgfplots@plot@file@skipfirst
			% Silently skip first data row, assuming it is a header.
			\pgfplots@plot@file@skipfirstfalse
		\else
			\pgfplotsscanlinelengthincrease
			\expandafter\pgfplots@addplotimpl@file@parsesingle\pgfplots@file@LINE 0 0 0 0 0\pgfplots@EOI
		\fi
	\fi
	\ifeof\r@pgfplots@reada
	\else
		\expandafter
		\pgfplots@addplotimpl@file@readall
	\fi
}%

\def\pgfplots@addplotimpl@file@parsesingle@threedim#1 #2 #3 #4\pgfplots@EOI{%
	\def\pgfplots@current@point@x{#1}%
	\def\pgfplots@current@point@y{#2}%
	\def\pgfplots@current@point@z{#3}%
	\pgfplots@coord@stream@coord%
}%
\def\pgfplots@addplotimpl@file@parsesingle@twodim#1 #2 #3\pgfplots@EOI{%
	\def\pgfplots@current@point@x{#1}%
	\def\pgfplots@current@point@y{#2}%
	\pgfplots@coord@stream@coord%
}%
\def\pgfplots@addplotimpl@file@parsesingle@threedim@andmeta#1 #2 #3 #4 #5\pgfplots@EOI{%
	\def\pgfplots@current@point@x{#1}%
	\def\pgfplots@current@point@y{#2}%
	\def\pgfplots@current@point@z{#3}%
	\def\pgfplots@current@point@meta{#4}%
	\pgfplots@coord@stream@coord%
}%
\def\pgfplots@addplotimpl@file@parsesingle@twodim@andmeta#1 #2 #3 #4\pgfplots@EOI{%
	\def\pgfplots@current@point@x{#1}%
	\def\pgfplots@current@point@y{#2}%
	\def\pgfplots@current@point@meta{#3}%
	\pgfplots@coord@stream@coord%
}%


\def\pgfplots@addplotimpl@graphics#1#2raphics{%
	\pgfplotsutil@ifnextchar[{%
		\pgfplots@addplotimpl@graphics@{#1}{#2}%
	}{%
		\pgfplots@addplotimpl@graphics@{#1}{#2}[]%
	}%
}%
% \addplot[#1] plot[#2] graphics[#3] {#4} #5;
\long\def\pgfplots@addplotimpl@graphics@#1#2[#3]#4#5;{\pgfplots@addplotimpl@graphics@@{#1}{#2}{#3}{#4}{#5}}%
\long\def\pgfplots@addplotimpl@graphics@@#1#2#3#4#5{%
	\def\pgfplotssurveyphaseinputclass{graphics}%
	\pgfplots@start@plot@with@behavioroptions{%
		/pgfplots/filter discard warning=false,
		/pgfplots/mesh/rows=2,% allow \addplot[surf] graphics ... --> yields a good legend.
		/pgfplots/mesh/cols=2,
		/pgfplots/mesh/check=false,
		#1,/pgfplots/.cd,#2,%
		/pgfplots/plot graphics/@prepare legend,
		/pgfplots/plot graphics,%
		/pgfplots/plot graphics/.cd,%
		#3,%
		/pgfplots/plot graphics/src={#4},%
		/tikz/mark=}%
	\pgfplots@PREPARE@COORD@STREAM{#5}%
	\pgfplots@coord@stream@start
	%
	\pgfkeysgetvalue{/pgfplots/plot graphics/points}{\pgfplots@current@point@points}%
	\ifx\pgfplots@current@point@points\pgfutil@empty
	\else
		\let\pgfplotsplothandlergraphicspointmappoint=\pgfplotsplothandlergraphics@survey@pointmappoint
		\expandafter\pgfplots@plot@handler@graphics@parsepointmap\expandafter{\pgfplots@current@point@points}%
		\ifpgfplots@plot@graphics@autoadjustaxis
			\pgfplotsplothandlergraphicspointmapcomputerequiredview
			\ifx\pgfplotsretval\pgfutil@empty
			\else
				\expandafter\pgfplotssetlateoptions\expandafter{\pgfplotsretval}%
			\fi
		\fi
		%
		\def\pgfplots@addplotimpl@graphics@@error##1{}%
	\fi
	%
	\pgfkeysgetvalue{/pgfplots/plot graphics/xmin}{\pgfplots@current@point@x}%
	\pgfkeysgetvalue{/pgfplots/plot graphics/ymin}{\pgfplots@current@point@y}%
	%
	% these sanity checks do nothing of the 'plot graphics/points' feature has been used:
	\ifx\pgfplots@current@point@x\pgfutil@empty\pgfplots@addplotimpl@graphics@@error{xmin}\fi
	\ifx\pgfplots@current@point@y\pgfutil@empty\pgfplots@addplotimpl@graphics@@error{ymin}\fi
	\ifpgfplots@curplot@threedim
		\pgfkeysgetvalue{/pgfplots/plot graphics/zmin}{\pgfplots@current@point@z}%
	\ifx\pgfplots@current@point@z\pgfutil@empty\pgfplots@addplotimpl@graphics@@error{zmin}\fi
	\fi
	\pgfplots@coord@stream@coord
	%
	\pgfkeysgetvalue{/pgfplots/plot graphics/xmax}{\pgfplots@current@point@x}%
	\pgfkeysgetvalue{/pgfplots/plot graphics/ymax}{\pgfplots@current@point@y}%
	\ifx\pgfplots@current@point@x\pgfutil@empty\pgfplots@addplotimpl@graphics@@error{xmax}\fi
	\ifx\pgfplots@current@point@y\pgfutil@empty\pgfplots@addplotimpl@graphics@@error{ymax}\fi
	\ifpgfplots@curplot@threedim
		\pgfkeysgetvalue{/pgfplots/plot graphics/zmax}{\pgfplots@current@point@z}%
		\ifx\pgfplots@current@point@z\pgfutil@empty\pgfplots@addplotimpl@graphics@@error{zmax}\fi
	\fi
	\pgfplots@coord@stream@coord
	%
	\pgfplots@coord@stream@end
}%
\def\pgfplots@addplotimpl@graphics@@error#1{%
	\begingroup
	\pgfplots@error{Sorry, but 'plot graphics' can't determine where to place the graphics file - (at least) the key '#1' is missing. Please verify that you provided all required limits, for example 'plot graphics[xmin=0,xmax=1,ymin=0,ymax=1] {<graphics>}'.}%
	\endgroup
}%




% \addplot[#1] table[#2] [from] {<\macro>} #4;
% or
% \addplot[#1] table[#2] {<filename>} #4;
%
% The distinction between <\macro> and <filename> is done
% automatically.
%
% Input options can be provided in '#2' using
% - column names, 
%   	for example '/pgfplots/table/x=firstcol' or just 'x=firstcol'
%
% - column indices,
%   	for example '/pgfplots/table/x index=3' or just 'x index=3'
%
% - expressions involving any of the table's data cells in the
%   currently processed cell,
%   	for example '/pgfplots/table/x expr={\columnx * \columny + \thisrow{columnxxx}/2}'
%   During expr, the following (non-exhaustive) list of macros is
%   available:
%   	- \columnx, \columny, \columnz, \columnmeta, \columnerrorx,
%   	\columnerrory, \columnerrorz
%   	Provide access to the cell content which would be used without
%   	'expr'.
%   	The first three access the input coordinate columns, \meta the meta column 
%   	(if any) and the last three the error data (if any). 
%
%		That means it is allowed to provide both, 'x' and 'x expr': 
%		'x expr' can use the (old) value stored in 'x'. the final x
%		coordinate will be that returned of 'x expr'.
%
%   	- \coordindex 
%
%   	- \lineno (physical line numbers including comments etc)
%
%   	- \thisrow{<colname>}
%   		allows access to any columns.
%
%   	- \getthisrow{<colname>}{<\macro>}
%   		this is a fragile command! Don't use it directly inside of
%   		a math expression, prefer \thisrow.
%
%   The FPU will be used to evaluate any expressions.
%
% @REMARKS the implementation for '* expr' differs for the '<\macro>'
% and '<filename>' input types:
% - for '{<filename>}', only the current row is available.
% - for '{<\macro>}', the `create on use' framework of the table
%   package is used - with all its features, including comfortable
%   access to the previous and next row and accumulation features.
\def\pgfplots@addplotimpl@table#1table{%
	\pgfplotsutil@ifnextchar[{%
		\pgfplots@addplotimpl@table@getopts{#1}%
	}{%
		\pgfplots@addplotimpl@table@getopts{#1}[]%
	}%
}%

\def\pgfplots@addplotimpl@table@getopts#1[#2]{%
	% set options outside of the following group.
	% They may contain behavior options.
	\pgfplots@addplotimpl@table@installkeypath
	\pgfplotstableset{#2}%
	%
	\pgfplotsutil@ifnextchar s{%
		\pgfplots@addplotimpl@table@fromshell{#1}{#2}%
	}{%
		\pgfplotsutil@ifnextchar f{%
			\pgfplots@addplotimpl@table@fromstructure@gobble@space{#1}{#2}%
		}{%
			\pgfplots@addplotimpl@table@fromfile@gobble@space{#1}{#2}%
		}%
	}%
}

% this macro simply invokes the "correct" table processing routine.
% The distinction between 'table from {<\macro>}' and 'table
% {<filename>}' is deprecated; it is done automatically now.
%
% \addplot[#1] table[#2] [from] {#3} #4;
\def\pgfplots@addplotimpl@table@startprocessing#1#2#3#4{%
	\pgfplotstable@isloadedtable{#3}{%
		\pgfplots@addplotimpl@table@fromstructure@{#1}{#2}{#3}{#4}%
	}{%
		\pgfplots@addplotimpl@table@fromfile@{#1}{#2}{#3}{#4}%
	}%
}%

% \addplot[#1] table[#2] from {#3} #4;
%
% #1: arguments to \addplot[...]
% #2: arguments to table[...] (already processed!)
% #3: the argument of plot table{...}
% #4: trailing path arguments after plot table{...}#4;
\long\def\pgfplots@addplotimpl@table@fromstructure@gobble@space#1#2from{%
	\pgfplotstablecollectoneargwithpreparecatcodes{%
		\pgfplots@addplotimpl@table@fromstructure{#1}{#2}from%
	}%
}%

\def\pgfplots@addplot@table@fromstructure@preparecolname#1#2#3#4{%
	\pgfkeysgetvalue{/pgfplots/table/#1}{\pgfplots@loc@TMPa}%
	%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\pgfkeysgetvalue{/pgfplots/table/#1 index}{\pgfplots@loc@TMPa}%
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\pgfplotstablegetcolumnnamebyindex\pgfplots@loc@TMPa\of#2\to\pgfplots@loc@TMPa
		\fi
	\fi
	\let#3=\pgfplots@loc@TMPa
	%
	% modify \pgfplots@plot@tbl@{x,y,z,meta} if there are
	% corresponding '#1 expr' statements:
	\pgfplots@addplotimpl@table@fromstructure@prepareexpr@for{#1}{#3}{#4}%
}

% Invokes `#1' if the command is invoked within 
%   \addplot table {<\macro>};
% and `#2' if not.
\def\pgfplotsifinaddplottablestruct#1#2{%
	\pgfutil@ifundefined{pgfplots@plot@tbl@meta}{#2}{#1}%
}%

\long\def\pgfplots@addplotimpl@table@fromstructure#1#2from#3#4;{\pgfplots@addplotimpl@table@startprocessing{#1}{#2}{#3}{#4}}%
% \addplot[#1] table[#2] from {#3} #4 ;
\long\def\pgfplots@addplotimpl@table@fromstructure@#1#2#3#4{%
	\begingroup
	\def\pgfplotstablename{#3}% store the name of the currently processed table.
	\pgfplotstablegetscanlinelength{#3}{\pgfplotsscanlinelength}%
	% FIXME : this thing here has runtime O(N^2) !
	% I fear it is faster to simply reload the data .... !?
	%
	% well, for a lot of columns which are used in different contexts
	% and few rows, this here IS more efficient.
	%
	\pgfplots@addplot@table@fromstructure@preparecolname{x}{#3}\pgfplots@plot@tbl@x\columnx
	\pgfplots@addplot@table@fromstructure@preparecolname{y}{#3}\pgfplots@plot@tbl@y\columny
	\ifpgfplots@curplot@threedim
	\pgfplots@addplot@table@fromstructure@preparecolname{z}{#3}\pgfplots@plot@tbl@z\columnz
	\fi
	\pgfplots@addplot@table@fromstructure@preparecolname{meta}{#3}\pgfplots@plot@tbl@meta\columnmeta
	%
	%
	% high level user interface functions:
	\let\pgfplotstable@coordindex@old=\coordindex
	\def\coordindex{\pgfplotstablerow}%
	\def\lineno{\coordindex}% is the same here
	% These macros are-unfortunately- not accessable here. And the
	% worst is: error messages are impossible either because they are
	% not executed... try to provide useful hints:
	\def\thisrow##1{thisrow_unavailable_load_table_directly}%
	\def\thisrowno##1{thisrowno_unavailable_load_table_directly}%
	% this should work.
	\def\getthisrow##1##2{\pgfplotstablegetelem{\coordindex}{##1}\of{#3}{##2}}%
	\def\getthisrowno##1##2{\pgfplotstablegetelem{\coordindex}{[index]##1}\of{#3}{##2}}%
	%
	\expandafter\pgfplotstablegetcolumnbyname\expandafter{\pgfplots@plot@tbl@x}\of#3\to\addplot@tbl@x
	\expandafter\pgfplotstablegetcolumnbyname\expandafter{\pgfplots@plot@tbl@y}\of#3\to\addplot@tbl@y
	\ifpgfplots@curplot@threedim
		\expandafter\pgfplotstablegetcolumnbyname\expandafter{\pgfplots@plot@tbl@z}\of#3\to\addplot@tbl@z
	\fi
	%
	\let\addplot@tbl@meta=\pgfutil@empty
	\ifx\pgfplots@plot@tbl@meta\pgfutil@empty
	\else
		\expandafter\pgfplotstablegetcolumnbyname\expandafter{\pgfplots@plot@tbl@meta}\of#3\to\addplot@tbl@meta
	\fi
	%
	%
	\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@init x{#3}{plus}%
	\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@init x{#3}{minus}%
	%
	\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@init y{#3}{plus}%
	\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@init y{#3}{minus}%
	%
	\ifpgfplots@curplot@threedim
		\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@init z{#3}{plus}%
		\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@init z{#3}{minus}%
	\fi
	%
	\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@load x{#3}{plus}%
	\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@load x{#3}{minus}%
	%
	\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@load y{#3}{plus}%
	\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@load y{#3}{minus}%
	\ifpgfplots@curplot@threedim
		\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@load z{#3}{plus}%
		\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@load z{#3}{minus}%
	\fi
	%
	\let\coordindex=\pgfplotstable@coordindex@old
	%
	\pgfplots@PREPARE@COORD@STREAM{#4}%
	\pgfplots@coord@stream@start
	\pgfutil@loop
	\pgfplotslistcheckempty\addplot@tbl@x
	\ifpgfplotslistempty
		\pgfplots@loop@CONTINUEfalse
	\else
		% This here is just for sanity checking: if the 'y' column is 
		% - for whatever reasons - invalid; provide good error
		%   recovery.
		\pgfplotslistcheckempty\addplot@tbl@y
		\ifpgfplotslistempty
			\pgfplots@loop@CONTINUEfalse
		\else
			\pgfplots@loop@CONTINUEtrue
		\fi
	\fi
	\ifpgfplots@loop@CONTINUE
		\pgfplotslistpopfront\addplot@tbl@x\to\pgfplots@current@point@x
		\pgfplotslistpopfront\addplot@tbl@y\to\pgfplots@current@point@y
		\ifpgfplots@curplot@threedim
			\pgfplotslistpopfront\addplot@tbl@z\to\pgfplots@current@point@z
		\fi
		\ifx\addplot@tbl@meta\pgfutil@empty
		\else
			\pgfplotslistpopfront\addplot@tbl@meta\to\pgfplots@current@point@meta
		\fi
		\ifpgfplots@errorbars@enabled
			\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@getnext x{plus}%
			\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@getnext x{minus}%
			%
			\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@getnext y{plus}%
			\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@getnext y{minus}%
			%
			\ifpgfplots@curplot@threedim
				\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@getnext z{plus}%
				\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@getnext z{minus}%
			\fi
		\fi
		\pgfplots@coord@stream@coord
	\pgfutil@repeat
	\pgfplots@coord@stream@end
	\pgfmath@smuggleone\pgfplotsscanlinelength
	\endgroup
}

% #1: x, y, or z
% #2: the table name
% #3: either "plus" or "minus"
\def\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@init#1#2#3{%
	\expandafter\let\csname addplot@tbl@error@#1@#3\endcsname=\pgfutil@empty
	\expandafter\let\csname pgfplots@current@point@error@#1@#3\endcsname=\pgfutil@empty
	\ifpgfplots@errorbars@enabled
		% prepare with suitable expansion:
		\def\pgfplots@loc@TMPa{%
			\pgfplots@addplot@table@fromstructure@preparecolname{#1 error #3}{#2}}%
		\edef\pgfplots@loc@TMPb{%
			\expandafter\noexpand\csname pgfplots@plot@tbl@error@#1@#3\endcsname
			% FIXME : these macros are UNDOCUMENTED! I suppose they are dead code...
			\expandafter\noexpand\csname columnerror#1\endcsname
		}%
		% execute prepared statement:
		% = \pgfplots@addplot@table@fromstructure@preparecolname
		% 		{x error plus}{#2}{\pgfplots@plot@tbl@error@x@plus}{\columnerrorx}
		\expandafter\pgfplots@loc@TMPa\pgfplots@loc@TMPb
		%
	\fi
}%

% #1: x, y, or z
% #2: the table name
% #3: either "plus" or "minus"
\def\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@load#1#2#3{%
	\ifpgfplots@errorbars@enabled
		\expandafter\ifx\csname pgfplots@plot@tbl@error@#1@#3\endcsname\pgfutil@empty
			% ok, we do not have this error kind.
		\else
			% assemble the statement
			%  \expandafter\pgfplotstablegetcolumnbyname\expandafter{\pgfplots@plot@tbl@error@x@plus}\of#2\to\addplot@tbl@error@x@plus
			% -> but with suitable expansion restrictions.
			\edef\pgfplots@loc@TMPa{\expandafter\noexpand\csname pgfplots@plot@tbl@error@#1@#3\endcsname}%
			%
			\def\pgfplots@loc@TMPb{%
				\expandafter\pgfplotstablegetcolumnbyname\expandafter{\pgfplots@loc@TMPa}\of#2\to
			}%
			\expandafter\pgfplots@loc@TMPb\csname addplot@tbl@error@#1@#3\endcsname
		\fi
	\fi
}%

% #1: x, y, or z
% #2: either "plus" or "minus"
\def\pgfplots@addplotimpl@table@fromstructure@prepare@errorbar@getnext#1#2{%
	\expandafter\ifx\csname addplot@tbl@error@#1@#2\endcsname\pgfutil@empty
		\expandafter\let\csname pgfplots@current@point@error@#1@#2\endcsname=\pgfutil@empty
	\else
		\expandafter\pgfplotslistpopfront\csname addplot@tbl@error@#1@#2\endcsname\to\pgfplots@loc@TMPa
		\expandafter\let\csname pgfplots@current@point@error@#1@#2\endcsname=\pgfplots@loc@TMPa
	\fi
}%

% A private helper macro which initialises the '#1 expr' keys for plot
% table from structure.
%
% PRECONDITION:
% 	\pgfplots@plot@tbl@#1 contains the column name which would be used
% 	if '#1 expr' is empty.
% 
% POSTCONDITION:
% 	\pgfplots@plot@tbl@#1 will be CHANGED to use the 'expr' column (a
% 	temporary name).
% 	The old value of \pgfplots@plot@tbl@#1 is available as column
% 	alias.
% 	the high level user interface command '#3' will be set correctly.
%
% #1: the key name of the current entity, for example 'x' for
% '/pgfplots/table/x'
% #2: the low level column name representing the data which is already
% defined somehow
% #3: a high level user interface command
\def\pgfplots@addplotimpl@table@fromstructure@prepareexpr@for#1#2#3{%
	% get old column name into a register:
	\t@pgfplots@tokb=\expandafter{#2}%
	%
	% high level user interface command:
	\edef#3{\noexpand\thisrow{\the\t@pgfplots@tokb}}%
	%
	\pgfkeysgetvalue{/pgfplots/table/#1 expr}{\pgfplots@loc@TMPa}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
	\else
		% get expression into register: 
		\t@pgfplots@toka=\expandafter{\pgfplots@loc@TMPa}%
		%
		%
		% assemble pgfkeys statement which expands the names above
		% just one time:
		\edef\pgfplots@loc@TMPa{%
			/pgfplots/table/create on use/#1expr@tempcol/.style={%
				/pgfplots/table/create col/expr={\the\t@pgfplots@toka}%
			},%
			/pgfplots/table/alias/#1/.initial={\the\t@pgfplots@tokb}%
		}%
		\expandafter\pgfkeysalso\expandafter{\pgfplots@loc@TMPa}%
		%
		% tell `plot table' which column should be used for '#1': the
		% temporary column.
		\def#2{#1expr@tempcol}%
	\fi
}%


% \addplot[#1] table[#2] {#3} #4;
%
% This here is the (probably) faster input method from tables.
%
% It has linear complexity in the number of rows (as long as the
% number of rows is less than about 110000).
%
% #1: arguments to \addplot[...]
% #2: arguments to table[...] (already processed!)
% #3: the argument of plot table{...}
% #4: trailing path arguments after plot table{...}#4;
%
\long\def\pgfplots@addplotimpl@table@fromfile@gobble@space#1#2{%
	\pgfplotstablecollectoneargwithpreparecatcodes{%
		\pgfplots@addplotimpl@table@fromfile{#1}{#2}%
	}%
}%
\long\def\pgfplots@addplotimpl@table@fromfile#1#2#3#4;{\pgfplots@addplotimpl@table@startprocessing{#1}{#2}{#3}{#4}}%
% \addplot[#1] table[#2] {#3} {#4};
\long\def\pgfplots@addplotimpl@table@fromfile@#1#2#3#4{%
	\if1\pgfplots@addplotimpl@readcompletely@auto
		\pgfplots@addplotimpl@table@check@createonuse@for{x}%
		\pgfplots@addplotimpl@table@check@createonuse@for{y}%
		\ifpgfplots@curplot@threedim
			\pgfplots@addplotimpl@table@check@createonuse@for{z}%
		\fi
		\pgfplots@addplotimpl@table@check@createonuse@for{x error plus}%
		\pgfplots@addplotimpl@table@check@createonuse@for{x error minus}%
		\pgfplots@addplotimpl@table@check@createonuse@for{y error plus}%
		\pgfplots@addplotimpl@table@check@createonuse@for{y error minus}%
		\ifpgfplots@curplot@threedim
			\pgfplots@addplotimpl@table@check@createonuse@for{z error plus}%
			\pgfplots@addplotimpl@table@check@createonuse@for{z error minus}%
		\fi
		\pgfplots@addplotimpl@table@check@createonuse@for{meta}%
	\fi
	%
	\ifpgfplots@addplotimpl@readcompletely
		\pgfplotstableread{#3}\pgfplots@table
		\pgfplots@addplotimpl@table@fromstructure@{#1}{}{\pgfplots@table}{#4}%
	\else
		\pgfplotsapplistXXglobalnewempty
		%
		% these data pointers will be prepared to allow fast access
		% into the current row while we read rows succesively from
		% disk.
		% Note: their initialisation must be postponed until
		% \pgfplotstableread is running - otherwise, we can't query
		% pointers into the table. See below.
		\let\pgfplots@table@PTR@x=\pgfutil@empty
		\let\pgfplots@table@PTR@y=\pgfutil@empty
		\let\pgfplots@table@PTR@z=\pgfutil@empty
		\let\pgfplots@table@PTR@meta=\pgfutil@empty
		%
		%
		\let\pgfplots@current@point@meta=\pgfutil@empty
		\let\pgfplots@current@point@z=\pgfutil@empty
		%
		% high level user interface functions:
		\def\lineno{\pgfplotstablelineno}%
		\def\columnx{\pgfplotstablereadvalueofptr{\pgfplots@table@PTR@x}}%
		\def\columny{\pgfplotstablereadvalueofptr{\pgfplots@table@PTR@y}}%
		\def\columnz{\pgfplotstablereadvalueofptr{\pgfplots@table@PTR@z}}%
		\def\columnmeta{\pgfplotstablereadvalueofptr{\pgfplots@table@PTR@meta}}%
		%
		\pgfplots@PREPARE@COORD@STREAM{#4}%
		\pgfplots@coord@stream@start
		\ifpgfplots@errorbars@enabled
			% more fast-access pointers for error data:
			\let\pgfplots@table@ERRPTR@x=\pgfutil@empty
			\let\pgfplots@table@ERRPTR@y=\pgfutil@empty
			\let\pgfplots@table@ERRPTR@z=\pgfutil@empty
			%
			% prepare:
			\let\pgfplots@current@point@error@x@plus=\pgfutil@empty
			\let\pgfplots@current@point@error@x@minus=\pgfutil@empty
			\let\pgfplots@current@point@error@y@plus=\pgfutil@empty
			\let\pgfplots@current@point@error@y@minus=\pgfutil@empty
			\let\pgfplots@current@point@error@z@plus=\pgfutil@empty
			\let\pgfplots@current@point@error@z@minus=\pgfutil@empty
			%
			% high level user interface functions:
			% FIXME : these macros are UNDOCUMENTED! I suppose they are dead code...
			\def\columnerrorx{\pgfplotstablereadvalueofptr{\pgfplots@table@ERRPTR@x}}%
			\def\columnerrory{\pgfplotstablereadvalueofptr{\pgfplots@table@ERRPTR@y}}%
			\def\columnerrorz{\pgfplotstablereadvalueofptr{\pgfplots@table@ERRPTR@z}}%
			%
			\pgfplotstableread*{#3} to listener\pgfplots@addplotimpl@table@fromfile@listener@witherrors@COLLECTHIGHLEVEL
		\else
			\pgfplotstableread*{#3} to listener\pgfplots@addplotimpl@table@fromfile@listener@COLLECTNORMALIZED
		\fi
		\pgfplots@coord@stream@end
	\fi
}
\def\pgfplots@addplotimpl@table@check@createonuse@for#1{%
	\pgfkeysgetvalue{/pgfplots/table/#1}\pgfplots@addplotimpl@table@check@createonuse@for@
	\expandafter\pgfplotstableifiscreateonuse\expandafter{\pgfplots@addplotimpl@table@check@createonuse@for@}{%
		\pgfplots@addplotimpl@readcompletelytrue
	}{%
	}%
}%
\def\pgfplots@addplotimpl@table@fromfile@listener@COLLECTNORMALIZED{%
	\pgfplots@addplotimpl@table@fromfile@listener@
	\pgfplots@coord@stream@coord
}
\def\pgfplots@addplotimpl@table@fromfile@listener@PREPARE{%
	% this here is only evaluated ONCE.
	\pgfkeysgetvalue{/pgfplots/table/x}{\pgfplots@plot@tbl@x}%
	\pgfkeysgetvalue{/pgfplots/table/x index}{\pgfplots@plot@tbl@xindex}%
	\pgfkeysgetvalue{/pgfplots/table/y}{\pgfplots@plot@tbl@y}%
	\pgfkeysgetvalue{/pgfplots/table/y index}{\pgfplots@plot@tbl@yindex}%
	\pgfkeysgetvalue{/pgfplots/table/z}{\pgfplots@plot@tbl@z}%
	\pgfkeysgetvalue{/pgfplots/table/z index}{\pgfplots@plot@tbl@zindex}%
	\pgfkeysgetvalue{/pgfplots/table/meta}{\pgfplots@plot@tbl@meta}%
	\pgfkeysgetvalue{/pgfplots/table/meta index}{\pgfplots@plot@tbl@metaindex}%
	%
	\pgfkeysgetvalue{/pgfplots/table/x expr}{\pgfplots@loc@TMPa}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\def\pgfplots@dereferencepointer@and@ASSIGN@x{%
			\pgfplotstablereadevalptr\pgfplots@table@PTR@x\pgfplots@current@point@x
		}%
	\else
		\def\pgfplots@dereferencepointer@and@ASSIGN@x{%
			\pgfmathparse{\pgfkeysvalueof{/pgfplots/table/x expr}}%
			\let\pgfplots@current@point@x=\pgfmathresult
		}%
	\fi
	%
	\pgfkeysgetvalue{/pgfplots/table/y expr}{\pgfplots@loc@TMPa}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\def\pgfplots@dereferencepointer@and@ASSIGN@y{%
			\pgfplotstablereadevalptr\pgfplots@table@PTR@y\pgfplots@current@point@y
		}%
	\else
		\def\pgfplots@dereferencepointer@and@ASSIGN@y{%
			\pgfmathparse{\pgfkeysvalueof{/pgfplots/table/y expr}}%
			\let\pgfplots@current@point@y=\pgfmathresult
		}%
	\fi
	%
	\ifx\pgfplots@plot@tbl@x\pgfutil@empty
		\pgfplotstablereadgetptrtocolindex{\pgfplots@plot@tbl@xindex}{\pgfplots@table@PTR@x}%
	\else
		\pgfplotstablereadgetptrtocolname{\pgfplots@plot@tbl@x}{\pgfplots@table@PTR@x}%
	\fi
	\ifx\pgfplots@plot@tbl@y\pgfutil@empty
		\pgfplotstablereadgetptrtocolindex{\pgfplots@plot@tbl@yindex}{\pgfplots@table@PTR@y}%
	\else
		\pgfplotstablereadgetptrtocolname{\pgfplots@plot@tbl@y}{\pgfplots@table@PTR@y}%
	\fi
	\ifpgfplots@curplot@threedim
		%
		\pgfkeysgetvalue{/pgfplots/table/z expr}{\pgfplots@loc@TMPa}%
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
			\def\pgfplots@dereferencepointer@and@ASSIGN@z{%
				\pgfplotstablereadevalptr\pgfplots@table@PTR@z\pgfplots@current@point@z
			}%
		\else
			\def\pgfplots@dereferencepointer@and@ASSIGN@z{%
				\pgfmathparse{\pgfkeysvalueof{/pgfplots/table/z expr}}%
				\let\pgfplots@current@point@z=\pgfmathresult
			}%
		\fi
		\ifx\pgfplots@plot@tbl@z\pgfutil@empty
			\pgfplotstablereadgetptrtocolindex{\pgfplots@plot@tbl@zindex}{\pgfplots@table@PTR@z}%
		\else
			\pgfplotstablereadgetptrtocolname{\pgfplots@plot@tbl@z}{\pgfplots@table@PTR@z}%
		\fi
	\else
		\let\pgfplots@dereferencepointer@and@ASSIGN@z=\relax
	\fi
	%
	%
	\def\pgfplots@dereferencepointer@and@ASSIGN@meta{%
		\pgfplotstablereadevalptr\pgfplots@table@PTR@meta\pgfplots@current@point@meta
	}%
	\ifx\pgfplots@plot@tbl@meta\pgfutil@empty
		\ifx\pgfplots@plot@tbl@metaindex\pgfutil@empty
			\let\pgfplots@dereferencepointer@and@ASSIGN@meta=\relax
		\else
			\pgfplotstablereadgetptrtocolindex{\pgfplots@plot@tbl@metaindex}{\pgfplots@table@PTR@meta}%
		\fi
	\else
		\pgfplotstablereadgetptrtocolname{\pgfplots@plot@tbl@meta}{\pgfplots@table@PTR@meta}%
	\fi
	\pgfkeysgetvalue{/pgfplots/table/meta expr}{\pgfplots@loc@TMPa}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
	\else
		\def\pgfplots@dereferencepointer@and@ASSIGN@meta{%
			\pgfmathparse{\pgfkeysvalueof{/pgfplots/table/meta expr}}%
			\let\pgfplots@current@point@meta=\pgfmathresult
		}%
	\fi
	\let\pgfplots@addplotimpl@table@fromfile@listener@PREPARE=\relax
}%
\def\pgfplots@addplotimpl@table@fromfile@listener@{%
	\pgfplots@addplotimpl@table@fromfile@listener@PREPARE
	\pgfplots@dereferencepointer@and@ASSIGN@x
	\pgfplots@dereferencepointer@and@ASSIGN@y
	\pgfplots@dereferencepointer@and@ASSIGN@z
	\pgfplots@dereferencepointer@and@ASSIGN@meta
}%

% #1: x, y, or z
% #2: either "plus" or "minus"
\def\pgfplots@addplotimpl@table@fromfile@listener@witherrors@COLLECTHIGHLEVEL@prepare@#1#2{%
	\pgfkeysgetvalue{/pgfplots/table/#1 error #2 index}\pgfplots@plot@tbl@error@index
	\pgfkeysgetvalue{/pgfplots/table/#1 error #2}\pgfplots@plot@tbl@error
	%
	\expandafter\def\csname pgfplots@table@ERRPTR@#1@#2\endcsname{#1 error #2}%
	%
	\expandafter\def\csname pgfplots@dereferencepointer@and@ASSIGN@error@#1@#2\endcsname{%
		\expandafter\pgfplotstablereadevalptr\csname pgfplots@table@ERRPTR@#1@#2\endcsname\pgfmathresult
		\expandafter\let\csname pgfplots@current@point@error@#1@#2\endcsname=\pgfmathresult
	}%
	%
	\ifx\pgfplots@plot@tbl@error\pgfutil@empty
		\ifx\pgfplots@plot@tbl@error@index\pgfutil@empty
			\let\pgfplotsretval=\relax
			\expandafter\let\csname pgfplots@dereferencepointer@and@ASSIGN@error@#1@#2\endcsname=\relax
		\else
			\pgfplotstablereadgetptrtocolindex{\pgfplots@plot@tbl@error@index}{\pgfplotsretval}%
		\fi
	\else
		\pgfplotstablereadgetptrtocolname{\pgfplots@plot@tbl@error}{\pgfplotsretval}%
	\fi
	\expandafter\let\csname pgfplots@table@ERRPTR@#1@#2\endcsname=\pgfplotsretval
	%
	\pgfkeysgetvalue{/pgfplots/table/#1 error #2 expr}{\pgfplots@loc@TMPa}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
	\else
		\expandafter\def\csname pgfplots@dereferencepointer@and@ASSIGN@error@#1@#2\endcsname{%
			\pgfmathparse{\pgfkeysvalueof{/pgfplots/table/#1 error #2 expr}}%
			\expandafter\let\csname pgfplots@current@point@error@#1@#2\endcsname=\pgfmathresult
		}%
	\fi
}%

\def\pgfplots@addplotimpl@table@fromfile@listener@witherrors@COLLECTHIGHLEVEL@prepare{%
	% this here is only evaluated ONCE.
	\pgfplots@addplotimpl@table@fromfile@listener@witherrors@COLLECTHIGHLEVEL@prepare@ x{plus}%
	\pgfplots@addplotimpl@table@fromfile@listener@witherrors@COLLECTHIGHLEVEL@prepare@ x{minus}%
	\pgfplots@addplotimpl@table@fromfile@listener@witherrors@COLLECTHIGHLEVEL@prepare@ y{plus}%
	\pgfplots@addplotimpl@table@fromfile@listener@witherrors@COLLECTHIGHLEVEL@prepare@ y{minus}%
	%
	\ifpgfplots@curplot@threedim
		\pgfplots@addplotimpl@table@fromfile@listener@witherrors@COLLECTHIGHLEVEL@prepare@ z{plus}%
		\pgfplots@addplotimpl@table@fromfile@listener@witherrors@COLLECTHIGHLEVEL@prepare@ z{minus}%
	\else
		\let\pgfplots@dereferencepointer@and@ASSIGN@error@z@plus=\relax
		\let\pgfplots@dereferencepointer@and@ASSIGN@error@z@minus=\relax
	\fi
	\let\pgfplots@addplotimpl@table@fromfile@listener@witherrors@COLLECTHIGHLEVEL@prepare=\relax
}
\def\pgfplots@addplotimpl@table@fromfile@listener@witherrors@COLLECTHIGHLEVEL{%
	\pgfplots@addplotimpl@table@fromfile@listener@
	\pgfplots@addplotimpl@table@fromfile@listener@witherrors@COLLECTHIGHLEVEL@prepare
	%
	\pgfplots@dereferencepointer@and@ASSIGN@error@x@plus
	\pgfplots@dereferencepointer@and@ASSIGN@error@x@minus
	%
	\pgfplots@dereferencepointer@and@ASSIGN@error@y@plus
	\pgfplots@dereferencepointer@and@ASSIGN@error@y@minus
	%
	\ifpgfplots@curplot@threedim
		\pgfplots@dereferencepointer@and@ASSIGN@error@z@plus
		\pgfplots@dereferencepointer@and@ASSIGN@error@z@minus
	\fi
	\pgfplots@coord@stream@coord
}%
\def\pgfplots@addplotimpl@table@installkeypath{%
	\pgfkeysdef{/pgfplots/table/.unknown}{%
		\let\pgfplots@table@curkeyname=\pgfkeyscurrentname
		\pgfqkeys{/pgfplots}{\pgfplots@table@curkeyname=##1}%
	}%
}%

% \addplot[#1] table[#2] shell{#3} #4;
%
% #1: arguments to \addplot[...]
% #2: arguments to table[...]
% #3: the argument of plot table shell{...}
% #4: trailing path arguments after plot table shell{...}#4;
\long\def\pgfplots@addplotimpl@table@fromshell#1#2shell#3#4;{%
	\pgfplots@gettikzinternal@keyval{prefix}{tikz@plot@prefix}{\jobname.}%
	\pgfplots@gettikzinternal@keyval{id}{tikz@plot@id}{pgf-shell}%
	%
	\def\pgfplots@plot@filename{\tikz@plot@prefix\tikz@plot@id}%  
	\pgfshell[\pgfplots@plot@filename]{#3}\pgfplots@addplotimpl@table@fromfile{#1}{#2}{\pgfplots@plot@filename.out}#4;%
}%

% This is a backwards-compatibility method to ensure that
% \axis[ybar]
% and
% \addplot[ybar]
% work as documented.
%
% The problem: earlier versions used /pgfplots/ybar for the global
% setting and /tikz/ybar for the local one. Now, both contexts yield
% /pgfplots/ybar in contradiction to the manual.
%
% So, this macro install special handlers to restore the old setting.
\def\pgfplots@install@local@bar@handlers{%
	\pgfkeysgetvalue{/pgfplots/xbar/.@cmd}\pgfplotskeys@orig@xbar
	\pgfkeysgetvalue{/pgfplots/ybar/.@cmd}\pgfplotskeys@orig@ybar
	\pgfkeysgetvalue{/pgfplots/xbar interval/.@cmd}\pgfplotskeys@orig@xbari
	\pgfkeysgetvalue{/pgfplots/ybar interval/.@cmd}\pgfplotskeys@orig@ybari
	\pgfkeysdef{/pgfplots/xbar}{%
		\ifpgfkeysaddeddefaultpath
			\pgfkeysalso{/tikz/xbar}%
		\else
			\pgfplotskeys@orig@xbar##1\pgfeov
		\fi
	}%
	\pgfkeysdef{/pgfplots/ybar}{%
		\ifpgfkeysaddeddefaultpath
			\pgfkeysalso{/tikz/ybar}%
		\else
			\pgfplotskeys@orig@ybar##1\pgfeov
		\fi
	}%
	\pgfkeysdef{/pgfplots/xbar interval}{%
		\ifpgfkeysaddeddefaultpath
			\pgfkeysalso{/tikz/xbar interval}%
		\else
			\pgfplotskeys@orig@xbari##1\pgfeov
		\fi
	}%
	\pgfkeysdef{/pgfplots/ybar interval}{%
		\ifpgfkeysaddeddefaultpath
			\pgfkeysalso{/tikz/ybar interval}%
		\else
			\pgfplotskeys@orig@ybari##1\pgfeov
		\fi
	}%
}%

\def\pgfplots@end@plot{%
	\ifpgfplots@curplot@isirrelevant
	\else
		\pgfplots@countplots@advance
	\fi
	\pgfkeysvalueof{/pgfplots/execute at end plot@@}%
	\pgfkeysvalueof{/pgfplots/execute at end plot}%
	\endgroup%<-- close the \begingroup of \pgfplots@addplotimpl@plot@withoptions
}

% \numplotsofactualtype
% Expands to the number of plots which have been seen in the current
% axis and which have the same type as the actual plot handler. 
%
% See also \plotnumofactualtype
\def\pgfplots@numplotsofactualtype{%
	\pgfutil@ifundefined{pgfplotssurveyphase@setactiveplothandlers@\pgfplotsplothandlername}{%
		0%
	}{%
		\csname c@pgfplots@numplotsofactualtype@\pgfplotsplothandlername\endcsname
	}%
}%
% use this only inside of \addplot or during the visualization phase
% of a plot.
\def\pgfplots@numplotsofactualtype@duringplot{%
	\pgfutil@ifundefined{pgfplotssurveyphase@setactiveplothandlers@\pgfplotsplothandlername@actual}{%
		0%
	}{%
		\csname c@pgfplots@numplotsofactualtype@\pgfplotsplothandlername@actual\endcsname
	}%
}%
%
%
\def\pgfplots@countplots@init{%
%
	%
	\pgfplotssurveyphase@setactiveplothandlers
	%
	\let\numplotsofactualtype=\pgfplots@numplotsofactualtype@duringplot
	%
	% Store this name during the \addplot command. Thus, even if the
	% plot handler changes, we will keep this one.
	\edef\pgfplotsplothandlername@actual{\pgfplotsplothandlername}%
	%
	\pgfutil@ifundefined{pgfplotssurveyphase@setactiveplothandlers@\pgfplotsplothandlername@actual}{%
		% oh. This is the first time \pgfplotsplothandlername was used
		% in this axis. Set its counter to 0 and remember that it has
		% been initialised.
		\expandafter\xdef\csname c@pgfplots@numplotsofactualtype@\pgfplotsplothandlername@actual\endcsname{0}%
		\t@pgfplots@toka=\expandafter{\pgfplotssurveyphase@setactiveplothandlers}%
		\t@pgfplots@tokb=\expandafter{\pgfplotsplothandlername@actual}%
		\xdef\pgfplotssurveyphase@setactiveplothandlers{%
			\the\t@pgfplots@toka
			\noexpand\expandafter\noexpand\def\noexpand\csname pgfplotssurveyphase@setactiveplothandlers@\the\t@pgfplots@tokb\noexpand\endcsname{1}%
		}%
		\expandafter\def\csname pgfplotssurveyphase@setactiveplothandlers@\the\t@pgfplots@tokb\endcsname{1}%
	}{%
		% ok. do nothing.
	}%
	%
}%
\def\pgfplots@countplots@advance{%
	\global\advance\pgfplots@numplots by1\relax%
	%
	\expandafter\pgfplotsutil@advancestringcounter@global\csname c@pgfplots@numplotsofactualtype@\pgfplotsplothandlername@actual\endcsname
}%

% \addplot[#1] [#2] {#3} #4;
\long\def\pgfplots@addplotimpl@coordinates#1#2plot coordinates#3#4;{\pgfplots@addplotimpl@coordinates@{#1}{#2}{#3}{#4}}%
% \addplot[#1] [#2] coordinates {#3} #4;
\long\def\pgfplots@addplotimpl@coordinates@#1#2#3#4{%
	\def\pgfplotssurveyphaseinputclass{coordinates}%
	\pgfplots@start@plot@with@behavioroptions{#1,/pgfplots/.cd,#2}%
	\pgfplots@PREPARE@COORD@STREAM{#4}%
	\ifpgfplots@curplot@threedim
		\pgfplots@coord@stream@foreach@threedim{#3}%
	\else
		\pgfplots@coord@stream@foreach{#3}%
	\fi
}%

{
	% A block which handles active semicolons.
	%
	% ATTENTION: this block does only work if
	% \pgfplots@addplotimpl.... changes are reflected here!
	%
	\catcode`\;=\active
	\globaldefs=1
	% 'AS' == 'active semicolon'
	% 'IS' == 'inactive semicolon'
	\let\pgfplots@gobble@until@semicolon@IS=\pgfplots@gobble@until@semicolon
	\let\pgfplots@addplotimpl@expression@IS=\pgfplots@addplotimpl@expression
	\let\pgfplots@addplotimpl@expression@curly@IS=\pgfplots@addplotimpl@expression@curly
	\let\pgfplots@addplotimpl@function@opt@IS=\pgfplots@addplotimpl@function@opt
	\let\pgfplots@addplotimpl@file@opt@IS=\pgfplots@addplotimpl@file@opt
	\let\pgfplots@addplotimpl@fillbetween@opt@IS=\pgfplots@addplotimpl@fillbetween@opt
	\let\pgfplots@addplotimpl@table@fromstructure@IS=\pgfplots@addplotimpl@table@fromstructure
	\let\pgfplots@addplotimpl@table@fromfile@IS=\pgfplots@addplotimpl@table@fromfile
	\let\pgfplots@addplotimpl@graphics@IS=\pgfplots@addplotimpl@graphics@
	\let\pgfplots@addplotimpl@coordinates@IS=\pgfplots@addplotimpl@coordinates
	%
	\def\pgfplots@gobble@until@semicolon@AS#1;{}
	\long\def\pgfplots@addplotimpl@expression@AS#1#2(#3,#4)#5;{\pgfplots@addplotimpl@expression@{#1}{#2}{#3}{#4}{#5}}%
	\long\def\pgfplots@addplotimpl@expression@curly@AS#1#2#3#4;{\pgfplots@addplotimpl@expression@curly@{#1}{#2}{#3}{#4}}%
	\def\pgfplots@addplotimpl@function@opt@AS#1#2[#3]#4#5;{\pgfplots@addplotimpl@function@opt@{#1}{#2}{#3}{#4}{#5}}%
	\def\pgfplots@addplotimpl@file@opt@AS#1#2[#3]#4#5;{\pgfplots@addplotimpl@file@opt@{#1}{#2}{#3}{#4}{#5}}%
	\long\def\pgfplots@addplotimpl@fillbetween@opt@AS#1#2[#3]#4;{\pgfplots@addplotimpl@fillbetween@opt@{#1}{#2}{#3}{#4}}%
	\long\def\pgfplots@addplotimpl@table@fromstructure@AS#1#2from#3#4;{\pgfplots@addplotimpl@table@startprocessing{#1}{#2}{#3}{#4}}%
	\long\def\pgfplots@addplotimpl@table@fromfile@AS#1#2#3#4;{\pgfplots@addplotimpl@table@startprocessing{#1}{#2}{#3}{#4}}%
	\long\def\pgfplots@addplotimpl@coordinates@AS#1#2plot coordinates#3#4;{\pgfplots@addplotimpl@coordinates@{#1}{#2}{#3}{#4}}%
	\long\def\pgfplots@addplotimpl@graphics@AS#1#2[#3]#4#5;{\pgfplots@addplotimpl@graphics@@{#1}{#2}{#3}{#4}{#5}}%
	%
	% Checks whether ';' is an active character and, if that is the
	% case, modifies all public macros for it.
	\pgfplots@appendto@activesemicolon@switcher{%
		\let\pgfplots@gobble@until@semicolon=\pgfplots@gobble@until@semicolon@AS
		\let\pgfplots@addplotimpl@expression=\pgfplots@addplotimpl@expression@AS
		\let\pgfplots@addplotimpl@expression@curly=\pgfplots@addplotimpl@expression@curly@AS
		\let\pgfplots@addplotimpl@function@opt=\pgfplots@addplotimpl@function@opt@AS
		\let\pgfplots@addplotimpl@file@opt=\pgfplots@addplotimpl@file@opt@AS
		\let\pgfplots@addplotimpl@fillbetween@opt=\pgfplots@addplotimpl@file@opt@AS
		\let\pgfplots@addplotimpl@table@fromstructure=\pgfplots@addplotimpl@table@fromstructure@AS
		\let\pgfplots@addplotimpl@table@fromfile=\pgfplots@addplotimpl@table@fromfile@AS
		\let\pgfplots@addplotimpl@coordinates=\pgfplots@addplotimpl@coordinates@AS
		\let\pgfplots@addplotimpl@graphics@=\pgfplots@addplotimpl@graphics@AS
	}%
}

\newif\ifpgfplots@update@limits@for@one@point@ISCLIPPED
\def\pgfplots@math@ONE{1.0}%

\def\pgfplots@invoke@prefilter{%
	\pgfkeysvalueof{/pgfplots/pre filter/.@cmd}\pgfeov%
}%
\def\pgfplots@invoke@filter#1#2{%
	\pgfkeysvalueof{/pgfplots/#2 filter/.@cmd}#1\pgfeov%
}%
\def\pgfplots@invoke@filter@xyz{%
	\pgfkeysgetvalue{/pgfplots/filter point/.@cmd}\pgfplots@loc@TMPa
	\ifx\pgfplots@loc@TMPa\pgfplots@empty@command@key
	\else
		\pgfkeyslet{/data point/x}\pgfplots@current@point@x
		\pgfkeyslet{/data point/y}\pgfplots@current@point@y
		\pgfkeyslet{/data point/z}\pgfplots@current@point@z
		\pgfplots@loc@TMPa\pgfeov%
		\pgfkeysgetvalue{/data point/x}\pgfplots@current@point@x
		\pgfkeysgetvalue{/data point/y}\pgfplots@current@point@y
		\pgfkeysgetvalue{/data point/z}\pgfplots@current@point@z
	\fi%
}%

% this is a convenience macro to save storage in the long coordinate
% lists.
\def\pgfplots@stream#1#2{\pgfplotstreampoint{\pgfqpoint{#1}{#2}}}
\def\pgfplots@stream@#1#2#3{\def\pgfplots@current@point@coordindex{#1}\pgfplots@stream{#2}{#3}}
\def\pgfplots@stream@withmeta#1#2#3{\def\pgfplots@current@point@meta{#3}\pgfplotstreampoint{\pgfqpoint{#1}{#2}}}
\def\pgfplots@stream@withmeta@#1#2#3#4{\def\pgfplots@current@point@coordindex{#1}\pgfplots@stream@withmeta{#2}{#3}{#4}}

\def\pgfplots@stream@decode@and@apply#1#2#3#4{%
	\def\pgfplots@current@point@coordindex{#1}%
	\pgfplotsaxisdeserializedatapointfrom@private{#2}%
	\pgfplotstreampoint{\pgfqpoint{#3}{#4}}%
}

% Takes a sequence of PREPARED coordinates which are given in floating
% point representation and applies the data scaling trafo (if
% necessary).
%
% Any coordinate will be plotted with the selected PGF plot handler.
%
% This stream is designed to be done at the end of an axis.
% See \pgfplots@coord@stream@finalize@storedcoords@START
%
\def\pgfplots@coord@stream@INIT@finalize@storedcoords{%
	%
	% Init the plot handlers:
	\pgfplots@getcurrent@plothandler\pgfplots@basiclevel@plothandler
	\pgfplots@gettikzinternal@keyval{mark}{tikz@plot@mark}{}%
	%
	%
	\pgfplots@perpointmeta@preparetrafo
	%
	\ifpgfplots@stackedmode
		\pgfplots@stacked@visphase@beginplot
	\fi
	\ifpgfplots@errorbars@enabled
		\pgfplots@errorbars@visphase@begin
	\fi
	\pgfplots@prepare@visualization@dependencies
	%
	\def\pgfplots@loc@TMPa{0}% <-- if (collectmark positions)
	\ifpgfplots@scatterplotenabled
		\def\pgfplots@loc@TMPa{1}% collect mark positions even if 'mark=none'! scatter might not even use markers.
	\fi
	\ifx\tikz@plot@mark\pgfutil@empty
	\else
		\def\pgfplots@loc@TMPa{1}%
	\fi
	%
	%
	% Now, set up coordinate streams.
	\def\pgfplots@coord@stream@start@{%
		\pgfplotsresetplothandler
		\pgfplots@basiclevel@plothandler
		\expandafter\pgfplotsplothandlerdeserializestatefrom\expandafter{\pgfplots@serialized@state@plothandler}%
		\pgfplotstreamstart
		\let\pgfplots@data@scaletrafo@result=\pgfutil@empty
		\c@pgfplots@coordindex=0
	}%
	\def\pgfplots@coord@stream@end@{%
		\ifpgfplots@stackedmode
			\pgfplots@stacked@visphase@endplot
		\fi
		\ifpgfplots@errorbars@enabled
			\pgfplots@errorbars@visphase@end
		\fi
		\ifpgfplots@apply@datatrafo
			\pgfplots@addplot@get@named@startendpoints@command\pgfplots@loc@TMPa
			\pgfplots@loc@TMPa
		\fi
		\pgfplotstreamend
	}%
	\begingroup
	\let\E=\noexpand
	%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	\pgfplots@coord@stream@INIT@finalize@storedcoords@prepare@scaletrafomacro
	%
	% Will be inserted in one of two possible places below (to collect
	% marker positions)
	% This finalize command maps the logical coordinate into PGF's
	% point space. Furthermore, it collects marker coordinates
	% (properly clipped by position) if markers are required (see
	% above).
	%
	% It is prepared here to eliminate if's.
	\gdef\pgfplots@coord@stream@finalize@currentpt{%
		%
		% NOTE: this here INVALIDATES \pgfplotlastpoint. However, we assign a correct value
		% for that macro after all coordinates have been assigned - and we do it in a way
		% which respects the special coordinates of 'patch plots'.
		%
		\pgfplotstreampoint{}% it will simply take \pgf@x and \pgf@y!
		%
		\advance\c@pgfplots@coordindex by1
	}%
	%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	\endgroup
%
%\message{Prepared macro	\string \pgfplotsaxisvisphasetransformcoordinate {\meaning\pgfplotsaxisvisphasetransformcoordinate}}%
%\message{Prepared macro	\string \pgfplots@coord@stream@finalize@currentpt {\meaning\pgfplots@coord@stream@finalize@currentpt}}%
	\def\pgfplots@coord@stream@coord@{%
		\ifpgfplots@stackedmode
			\pgfplots@stacked@visphase@stream@coord@
		\fi
		\ifx\pgfplots@current@point@x\pgfutil@empty% this implements `unbounded coords=jump', for example
			\pgfplotsplothandlervisualizejump
		\else
			\pgfplotsaxisvisphasegetpoint
			\pgfplots@coord@stream@finalize@currentpt
		\fi
	}%
}

% Takes the current point (defined by a set of macros) as input and defines \pgf@x and \pgf@y 
% as the output point. It also defines
% \pgfplots@current@point@x and its variants to contain the
% transformed canvas coords (those which can be given to
% \pgfplotsqpointxyz).
%
% Furthermore, it defines keys '/data point/x untransformed' to
% contain the untransformed coords.
\def\pgfplotsaxisvisphasegetpoint{%
	\pgfkeyslet{/data point/x untransformed}\pgfplots@current@point@x
	\pgfkeyslet{/data point/y untransformed}\pgfplots@current@point@y
	\pgfkeyslet{/data point/z untransformed}\pgfplots@current@point@z
	\pgfplotsaxisvisphasetransformcoordinate\pgfplots@current@point@x\pgfplots@current@point@y\pgfplots@current@point@z%
	\pgfplotsaxisvisphasepreparedatapoint
	\ifpgfplots@curplot@threedim
		\pgfplotsqpointxyz{\pgfplots@current@point@x}{\pgfplots@current@point@y}{\pgfplots@current@point@z}%
	\else
		\pgfplotsqpointxy{\pgfplots@current@point@x}{\pgfplots@current@point@y}%
	\fi
}%

% Returns the current points into the keys
% /data point/x
% /data point/y
% /data point/z
% /data point/meta
\def\pgfplotspointgetcoordinates{%
	\pgfplotspointgetnormalizedcoordinates
	\pgfplotspointgetcoordinatesfromnormalized
}%

% Same as \pgfplotspointgetcoordinates, but the resulting values are
% for use in 'normalized axis cs'.
\def\pgfplotspointgetnormalizedcoordinates{%
	\pgfkeysgetvalue{/data point/x untransformed}\pgfplots@loc@TMPa
	\pgfkeyslet{/data point/x}\pgfplots@loc@TMPa
	\pgfkeysgetvalue{/data point/y untransformed}\pgfplots@loc@TMPa
	\pgfkeyslet{/data point/y}\pgfplots@loc@TMPa
	\pgfkeysgetvalue{/data point/z untransformed}\pgfplots@loc@TMPa
	\pgfkeyslet{/data point/z}\pgfplots@loc@TMPa
	\pgfkeyslet{/data point/meta}\pgfplots@current@point@meta
	\edef\pgfplots@loc@TMPa{\pgfplots@current@point@coordindex}%
	\pgfkeyslet{/data point/index}\pgfplots@loc@TMPa
}%

% Assumes that we are given normalized coordinates (i.e. those for use
% in 'normalized axis cs') and transforms them into those which are
% for use in 'axis cs'.
%
% Accepts an optional argument in square brackets, namely one or more
% options in the /pgfplots/coords key path (see below).
\def\pgfplotspointgetcoordinatesfromnormalized{%
	\pgfutil@ifnextchar[{\pgfplotspointgetcoordinatesfromnormalized@opt}{\pgfplotspointgetcoordinatesfromnormalized@opt[]}%
}%

% Defines where to expect INPUT coordinates
% \pgfplotspointgetcoordinatesfromnormalized[path=/data point/
% would expect input coordinates 
%   /data point/x
%   /data point/y
%   /data point/z
\pgfkeyssetvalue{/pgfplots/coords/path}{/data point}

% \pgfplotspointgetcoordinatesfromnormalized[target path=/data point/zero/
% would write output coordinates 
%   /data point/zero/x
%   /data point/zero/y
%   /data point/zero/z
\pgfkeyssetvalue{/pgfplots/coords/target path}{\pgfkeysvalueof{/pgfplots/coords/path}}

\def\pgfplotspointgetcoordinatesfromnormalized@opt[#1]{%
	\begingroup
	\pgfqkeys{/pgfplots/coords}{#1}%
	\pgfkeysgetvalue{/pgfplots/coords/path}\pgfplots@path
	\pgfkeysgetvalue{/pgfplots/coords/target path}\pgfplots@path@trg
	\pgfkeysifdefined{\pgfplots@path/x}{}{%
		\pgfplots@error{Illegal argument: '\pgfplots@path' is no valid data point path (\pgfplots@path/x does not exist)}%
	}%
	\pgfkeysgetvalue{\pgfplots@path/x}\pgfplots@loc@x
	\pgfkeysgetvalue{\pgfplots@path/y}\pgfplots@loc@y
	\pgfkeysgetvalue{\pgfplots@path/z}\pgfplots@loc@z
	%
	\pgfplotspointgetcoordinatesfromnormalized@transform x\pgfplots@loc@x%
	\pgfplotspointgetcoordinatesfromnormalized@transform y\pgfplots@loc@y%
	\ifpgfplots@threedim
		\pgfplotspointgetcoordinatesfromnormalized@transform z\pgfplots@loc@z%
	\fi
	\xdef\pgfplots@glob@TMPa{%
		\noexpand\pgfkeyssetvalue{\pgfplots@path@trg/x}{\pgfplots@loc@x}%
		\noexpand\pgfkeyssetvalue{\pgfplots@path@trg/y}{\pgfplots@loc@y}%
		\noexpand\pgfkeyssetvalue{\pgfplots@path@trg/z}{\pgfplots@loc@z}%
	}%
	\endgroup
	\pgfplots@glob@TMPa
}%
\def\pgfplotspointgetcoordinatesfromnormalized@transform#1#2{%
	\pgfplots@if{pgfplots@#1islinear}{%
		\pgfplotscoordmath{#1}{tofixed}{#2}%
	}{%
		\pgfplotscoordmath{#1}{exp}{#2}%
	}%
	\let#2=\pgfmathresult
	\pgfplots@coord@inv@trafo@apply{#1}{#2}%
	\let#2=\pgfmathresult
}%

% Defines an optimized and matching \pgfplotsaxisvisphasetransformcoordinate 
% during the coordinate finalization step in \end{axis}.
\def\pgfplots@coord@stream@INIT@finalize@storedcoords@prepare@scaletrafomacro{%
	\begingroup
	\let\E=\noexpand
	%
	% \pgfplotsaxisvisphasetransformcoordinate
	% Maps a point to the low level xyz coordinate system by applying
	% data scaling transformations.
	%
	% This method should be invoked for every coordinate before it can
	% be drawn.
	%
	% It is prepared here to eliminate if's.
	%
	% Arguments:
	% #1 : a MACRO containing the x value
	% #2 : a MACRO containing the y value
	% #3 : a MACRO containing the z value
	%
	% PRECONDITION:
	% 	- the visualization phase is running.
	% 	- #1,#2,#3 are defined and contain
	% 	values resulting from the survey phase.
	%
	% POSTCONDITION
	% 	- #1,#2,#3 will be redefined to contain data which is
	% 	readily usable by low level pgf plot handlers for
	% 	visualization.
	%
	% @see \pgfplotsaxisvisphasepreparedatapoint
	\xdef\pgfplotsaxisvisphasetransformcoordinate##1##2##3{%
		\ifpgfplots@apply@datatrafo@x
			\E\pgfplotscoordmath{x}{datascaletrafo}{##1}%
			\E\let##1=\E\pgfmathresult
		\fi
		\ifpgfplots@apply@datatrafo@y
			\E\pgfplotscoordmath{y}{datascaletrafo}{##2}%
			\E\let##2=\E\pgfmathresult
		\fi
		\ifpgfplots@curplot@threedim
			\ifpgfplots@apply@datatrafo@z
				\E\pgfplotscoordmath{z}{datascaletrafo}{##3}%
				\E\let##3=\E\pgfmathresult
			\fi
		\fi
	%	\t@pgfplots@tokc=\expandafter{\pgfplots@data@scaletrafo@result}%
	%	\edef\pgfplots@data@scaletrafo@result{\the\t@pgfplots@tokc(\pgfplots@current@point@x,\pgfplots@current@point@y)}%
	}%
	%
	% Just before the visualization phase can call the low level
	% interface, this method is called to handle final changes.
	% It is currently only used by the stacked plot interface.
	\xdef\pgfplotsaxisvisphasepreparedatapoint{%
		\ifpgfplots@stackedmode
			% all these calls work with pgfmath; no more floating point
			% arithmetics are applied.
			\E\pgfplots@stacked@visphasepreparedatapoint%
		\fi
	}%
	%
	\endgroup
}

% Defines \pgfmathresult to contain the transformed coordinate entry
% #1: one of x,y ,or z
% #2: the input value
\def\pgfplotsaxisvisphasetransformcoordinateentry#1#2{%
	\pgfplots@if{pgfplots@apply@datatrafo@#1}{%
		\pgfplotscoordmath{#1}{datascaletrafo}{#2}%
	}{%
		\edef\pgfmathresult{#2}%
	}%
}%

\def\pgfplots@addplot@get@named@startendpoints@command#1{%
	\ifx\pgfplots@currentplot@firstcoord@x\pgfutil@empty
		% empty plot.
		\def#1{%
			\pgfcoordinate{current plot begin}{\pgfplotspointaxisorigin}%
			\pgfcoordinate{current plot end}{\pgfplotspointaxisorigin}%
		}%
	\else
		\ifpgfplots@curplot@threedim
			\edef#1{%
				\noexpand\pgfcoordinate{current plot begin}{\noexpand\pgfplotsqpointxyz{\pgfplots@currentplot@firstcoord@x}{\pgfplots@currentplot@firstcoord@y}{\pgfplots@currentplot@firstcoord@z}}%
				\noexpand\pgfcoordinate{current plot end}{\noexpand\pgfplotsqpointxyz{\pgfplots@currentplot@lastcoord@x}{\pgfplots@currentplot@lastcoord@y}{\pgfplots@currentplot@lastcoord@z}}%
			}%
		\else
			\edef#1{%
				\noexpand\pgfcoordinate{current plot begin}{\noexpand\pgfplotsqpointxy{\pgfplots@currentplot@firstcoord@x}{\pgfplots@currentplot@firstcoord@y}}%
				\noexpand\pgfcoordinate{current plot end}{\noexpand\pgfplotsqpointxy{\pgfplots@currentplot@lastcoord@x}{\pgfplots@currentplot@lastcoord@y}}%
			}%
		\fi
	\fi
}%

% This is the pgfplots implementation for 'node[pos=<fraction>]'.
% Besides modifications of the transformation matrix, it also defines the COORDINATES of the point to
% /data point/x
% /data point/y
% /data point/z
% (or more keys which depend on the plot handler).
\def\pgfplots@plot@timer{%
	\pgfplotstransformplotattime{\tikz@time}%
}

% Installs a transformation matrix such that (0,0) is the point of the
% current plot with fraction #1.
%
% This does actually nothing more than using
% \pgfplotspointplotattime{#1} as shift and using the slope of the
% curve at that point to set up the 'sloped' rotation (if enabled).
\def\pgfplotstransformplotattime#1{%
  \pgftransformshift{\pgfplotspointplotattime{#1}}%
  \ifpgfresetnontranslationattime%
    \pgftransformresetnontranslations%
  \fi%
  \ifpgfslopedattime%
	\pgfplotsplothandlertransformslopedattime{#1}{\pgfplotspointplotattimefirst}{\pgfplotspointplotattimesecond}%
  \fi%
}

\def\pgfplotspointplotattimeclearcache{%
	\global\let\pgfplotspointplotattime@cache=\pgfutil@empty
	\gdef\pgfplotspointplotattime@cachesize{0}%
}%
\pgfplotspointplotattimeclearcache
\def\pgfplotspointplotattime@cachesize@max{20}

% Checks if the cache for \pgfplotspointplotattime has a cached entry for '#1'.
% POSTCONDITION:
%   if \ifpgfplots@loc@tmp is true, the value(s) from the cache have been retrieved successfully.
%   if \ifpgfplots@loc@tmp is false, there is not hit.
\def\pgfplotspointplotattimegetfromcache#1{%
	\pgf@xa=#1pt %
	\pgfplotspointplotattime@cache
	\pgfkeysifdefined{/data point/@pos \the\pgf@xa/segment \pgfkeysvalueof{/tikz/pos segment}}{%
		\pgfkeysvalueof{/data point/@pos \the\pgf@xa/segment \pgfkeysvalueof{/tikz/pos segment}}%
		\pgfplots@loc@tmptrue
	}{%
		\pgfplots@loc@tmpfalse
	}%
}%
\def\pgfplotspointplotattimeaddtocache#1{%
	\pgfplotsutil@advancestringcounter@global\pgfplotspointplotattime@cachesize
	\ifnum\pgfplotspointplotattime@cachesize=\pgfplotspointplotattime@cachesize@max
		\pgfplotspointplotattimeclearcache
	\fi
	\pgf@xa=#1pt %
	\edef\pgfplots@loc@TMPa{%
		\noexpand\gdef\noexpand\pgfplotspointplotattimefirst{\pgfplotspointplotattimefirst}%
		\noexpand\gdef\noexpand\pgfplotspointplotattimesecond{\pgfplotspointplotattimesecond}%
		\noexpand\gdef\noexpand\pgfplotspointplotattimecoords{\pgfplotspointplotattimecoords}%
	}%
	\t@pgfplots@toka=\expandafter{\pgfplotspointplotattime@cache}%
	\t@pgfplots@tokb=\expandafter{\pgfplots@loc@TMPa}%
	\xdef\pgfplotspointplotattime@cache{%
		\the\t@pgfplots@toka
		\noexpand\pgfkeyssetvalue{/data point/@pos \the\pgf@xa/segment \pgfkeysvalueof{/tikz/pos segment}}{\the\t@pgfplots@tokb}%
	}%
}

% Sets (\pgf@x,\pgf@y) to the point of the current plot with fraction #1.
% For #1 = 0, this is the first point.
% For #1 = 1, this is the last point.
% For #1 = 0.5, it is the middle of the plot.
% The argument '#1' is optional: if you leave it away, the current value of the 'pos' key will be used.
% This method will work for most plot handlers, although some of them might be unsupported.
%
% As a side-effect, it defines the (global) macros 
% - \pgfplotspointplotattimefirst  the start coordinate of the line segment containing #1
% - \pgfplotspointplotattimesecond the end   coordinate of the line segment containing #1
% - \pgfplotspointplotattimecoords the coordinates of #1
% The first two are interesting in order to allow the computation of gradients. 
%	\pgfplotsplothandlerpointtokeys{/data point}%
% for the \pgfplotspointplotattimecoords point
% 
% Any of these macros can be decoded using
% \pgfplotsplothandlerdeserializepointfrom\pgfplotspointplotattimesecond
% \pgfplotsaxisvisphasegetpoint
%
% @see \pgfplotsplothandlerpointtokeys
\def\pgfplotspointplotattime{%
	\pgfutil@ifnextchar\bgroup{\pgfplotspointplotattime@}{\pgfplotspointplotattime@{\tikz@time}}%
}
\def\pgfplotspointplotattime@#1{%
	\edef\pgfplots@loc@TMPa{#1}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\pgfplots@error{Sorry, the provided fraction of the plot is empty (maybe the argument of 'pos' has been cleared by the tikz node processing). Please provide a valid 'pos' argument}%
	\else
	\pgfplotspointplotattimegetfromcache{#1}%
	\ifpgfplots@loc@tmp
		% CACHE HIT! 
%\message{CACHE HIT for \string\pgfplotspointplotattime{#1}^^J}%
	\else
%\message{NO cache hit for \string\pgfplotspointplotattime{#1}^^J}%
		\begingroup
		%
		%
		\edef\pgfplots@time{#1}%
		\pgfplotscoordmathparsemacro{default}{\pgfplots@time}%
		\pgfkeysgetvalue{/tikz/pos segment}\pgfplots@pos@segment
		%
\iffalse
	% this here is a simple experiment which finds x or y
	% values. IMPLEMENT IT!
	\def\pgfplotspointattime@do@set@current@value{%
		\pgfplotscoordmath{default}{parsenumber}{\pgfplots@current@point@y}%
		\let\pgfplotspointattime@value@current=\pgfmathresult
	}%
	\def\pgfplotspointattime@do@set@target@value{%
		\let\pgfplotspointattime@value@target=\pgfplots@time
	}%
	\def\pgfplots@ifpointattime@do@set@current@value@accumulates##1##2{##2}%
\fi
		%
		\let\pgfplotspointattime@do=\relax
		\let\pgfplots@coord@stream@start@=\pgfplots@coord@stream@start@plot@at@time
		\let\pgfplots@coord@stream@coord@=\pgfplots@coord@stream@coord@plot@at@time
		\def\pgfplots@coord@stream@end@{}%
		\pgfplots@ifpointattime@do@set@current@value@accumulates{%
			% 1. compute the total length of the plot (by integrating along a linear spline)
			%
			% we need to compute the TOTAL length in order to set the
			% target values.
			\expandafter\pgfplots@coord@stream@foreach@NORMALIZED\expandafter{\pgfplots@plot@timer@args}%
		}{}%
		%
		\pgfplotspointattime@do@set@target@value
		%
		\pgfplotscoordmath{default}{zero}%
		\let\pgfplots@len@last=\pgfmathresult
		\let\pgfplots@len@last@last=\pgfplots@len@last
%\message{plot at time (#1, segment \pgfplots@pos@segment): total length=\pgfplotspointattime@value@current; target len \pgfplotspointattime@value@target\space (#1)^^J}%
		%
		\def\pgfplots@HIT{0}%
		\let\pgfplots@last@last=\pgfutil@empty
		\let\pgfplots@coord@stream@coord@=\pgfplots@coord@stream@coord@plot@at@time
		\let\pgfplotspointattime@do=\pgfplotspointattime@do@find@target@value
		\expandafter\pgfplots@coord@stream@foreach@NORMALIZED\expandafter{\pgfplots@plot@timer@args}%
		\if\pgfplots@HIT0%
			\let\pgfplots@last@processed=\pgfplots@last@last
			\let\pgfplots@len@last=\pgfplots@len@last@last
			\pgfplotspointattime@pointbetween@two
		\fi
		\endgroup
		\pgfplotspointplotattimeaddtocache{#1}%
	\fi
	\pgfplotsplothandlerdeserializepointfrom\pgfplotspointplotattimecoords
	\pgfplotscoordmath{x}{tofixed}{\pgfplots@current@point@x}%
	\pgfplots@coord@inv@trafo@apply{x}{\pgfmathresult}%
	\let\pgfplots@current@point@x=\pgfmathresult
	\pgfplotscoordmath{y}{tofixed}{\pgfplots@current@point@y}%
	\pgfplots@coord@inv@trafo@apply{y}{\pgfmathresult}%
	\let\pgfplots@current@point@y=\pgfmathresult
	\ifpgfplots@curplot@threedim
		\pgfplotscoordmath{z}{tofixed}{\pgfplots@current@point@z}%
		\pgfplots@coord@inv@trafo@apply{z}{\pgfmathresult}%
		\let\pgfplots@current@point@z=\pgfmathresult
	\fi
	\pgfplotsplothandlerpointtokeys{/data point}%
	\fi
}

% coordinate streaming method for use in
% \pgfplotspointplotattime
\def\pgfplots@coord@stream@start@plot@at@time{%
	\ifx\pgfplots@pos@segment\pgfutil@empty
		\let\c@pgfplots@segments=\pgfutil@empty
	\else
		\def\c@pgfplots@segments{0}%
		\c@pgf@countd=\pgfplots@pos@segment\relax
		\edef\pgfplots@pos@segment{\the\c@pgf@countd}%
	\fi
	\pgfplotscoordmath{default}{zero}%
	\let\pgfplotspointattime@value@current=\pgfmathresult
	\let\pgfplots@last@processed=\pgfutil@empty
	\def\pgfplots@last@was@empty{1}%
}%


% coordinate streaming method for use in
% \pgfplotspointplotattime
%
% It invokes \pgfplotspointattime@do{} whenever is has found a line
% segment.
\def\pgfplots@coord@stream@coord@plot@at@time{%
%\message{plot at time (#1, segment \pgfplots@pos@segment): processing (\pgfplots@current@point@x,\pgfplots@current@point@y,\pgfplots@current@point@z)^^J}%
	\ifx\pgfplots@current@point@x\pgfutil@empty
		\if1\pgfplots@last@was@empty
		\else
			% oh. a jump... start new length segment
			\ifx\c@pgfplots@segments\pgfutil@empty
			\else
				\ifx\pgfplots@pos@segment\c@pgfplots@segments
					\let\pgfplots@coord@stream@coord@=\relax
				\fi
				\pgfplotsutil@advancestringcounter\c@pgfplots@segments
			\fi
		\fi
		\let\pgfplots@last@processed=\pgfutil@empty
		\def\pgfplots@last@was@empty{1}%
	\else
		\ifx\pgfplots@pos@segment\c@pgfplots@segments
			\pgfplotsplothandlerserializepointto{\pgfplots@cur}%
			\pgfplotspointattime@do@set@current@value
			%
			\ifx\pgfplots@last@processed\pgfutil@empty
			\else
				\pgfplotspointattime@do
			\fi
			%
			\let\pgfplots@len@last@last=\pgfplots@len@last
			\let\pgfplots@len@last=\pgfplotspointattime@value@current
			\let\pgfplots@last@last=\pgfplots@last@processed
			\let\pgfplots@last@processed=\pgfplots@cur
		\fi
		\def\pgfplots@last@was@empty{0}%
	\fi
}%

% A macro which is invoked whenever \pgfplotspointplotattime found a
% line segment. 
%
% INPUT: 
%  - \pgfplots@cur : serialized current point. This current point's
%     properties are available in the macros
%    \pgfplots@current@point@[xyz] etc.
%  - \pgfplots@last@processed : serialized last point
%  - \pgfplotspointattime@value@current : the accumulated length so far
%
\def\pgfplotspointattime@do{}

% \pgfplots@ifpointattime@do@set@current@value@accumulates{<true code>}{<false code>}
%
% is invokes to test if \pgfplotspointattime@do@set@current@value
% accumulates stuff. If so, it will invoke <true code>. If it does NOT
% accumulate stuff, it will invoke <false code>
\def\pgfplots@ifpointattime@do@set@current@value@accumulates#1#2{%
	% the default "time fraction" implementation accumulates:
	#1\relax
}

\def\pgfplotspointattime@do@set@current@value{%
	\ifx\pgfplots@last@processed\pgfutil@empty
	\else
		\pgfplotsplothandlersurveydifflen{\pgfplots@last@processed}{\pgfplots@cur}%
		\pgfplotscoordmath{default}{op}{add}{{\pgfmathresult}{\pgfplotspointattime@value@current}}%
		\let\pgfplotspointattime@value@current=\pgfmathresult
	\fi
%\message{plot at time (#1, segment \pgfplots@pos@segment): length \pgfplotspointattime@value@current^^J}%
}%

% Needs to define \pgfplotspointattime@value@target .
%
% This value is the search target: once the loop realizes that it
% passed \pgfplotspointattime@value@target, it will report a hit in the current
% interval.
\def\pgfplotspointattime@do@set@target@value{%
	\pgfplotscoordmath{default}{op}{multiply}{{\pgfplots@time}{\pgfplotspointattime@value@current}}%
	\let\pgfplotspointattime@value@target=\pgfmathresult
}%

\def\pgfplotspointattime@do@find@target@value{%
	% compare \pgfplotspointattime@value@target and \pgfplotspointattime@value@current to see if
	% we passed the target interval:
	\pgfplotscoordmath{default}{if less than}
		{\pgfplotspointattime@value@target}
		{\pgfplotspointattime@value@current}
		{% HIT!
			\def\pgfplots@HIT{1}%
			\pgfplotspointattime@pointbetween@two
			%
			% we cannot stop the loop; what we can turn it into no-op:
			\let\pgfplots@coord@stream@coord@=\relax
		}{%
		}%
}%

\def\pgfplotspointattime@pointbetween@two{%
	\pgfplotscoordmath{default}{op}{subtract}{{\pgfplotspointattime@value@target}{\pgfplots@len@last}}%
	\let\pgfplots@tmp=\pgfmathresult
	\pgfplotscoordmath{default}{op}{subtract}{{\pgfplotspointattime@value@current}{\pgfplots@len@last}}%
	\pgfplotscoordmath{default}{op}{divide}{{\pgfplots@tmp}{\pgfmathresult}}%
	\pgfplotscoordmath{default}{tofixed}{\pgfmathresult}%
	\let\pgfplots@time@between@two=\pgfmathresult
%\message{HIT of \pgfplotspointattime@value@target\space between \pgfplots@len@last\space and \pgfplotspointattime@value@current\space (\pgfplots@time@between@two)^^J}%
	\ifx\pgfplots@last@processed\pgfutil@empty
		\pgfplotsplothandlerserializepointto{\pgfplots@cur}%
	\else
		\pgfplotsplothandlersurveypointattime{\pgfplots@time@between@two}{\pgfplots@last@processed}{\pgfplots@cur}%
	\fi
	\pgfplotsplothandlerserializepointto\pgfplots@loc@TMPa
	\global\let\pgfplotspointplotattimecoords=\pgfplots@loc@TMPa
	\pgfplotsaxisvisphasegetpoint
	\global\let\pgfplotspointplotattimefirst=\pgfplots@last@processed
	\global\let\pgfplotspointplotattimesecond=\pgfplots@cur
}%


% #1 : either x,y, or z
% #2 : the argument on which the inv trafo shall be applied. It has to
% be a fixed point number.
\def\pgfplots@coord@inv@trafo@apply#1#2{%
	\edef\pgfmathresult{#2}%
	\pgfkeysgetvalue{/pgfplots/#1 coord inv trafo/.@cmd}\pgfplots@loc@TMPa
	\ifx\pgfplots@loc@TMPa\pgfplots@empty@command@key
	\else
		\expandafter\pgfplots@loc@TMPa\expandafter{\pgfmathresult}\pgfeov
	\fi
}%

% INPUT: 
% 	either floating point or fixed point coordinates (depending on the
% 	state of the \ifpgfplots@apply@datatrafo boolean)
%
\long\def\pgfplots@coord@stream@finalize@storedcoords@START normalized coordinates #1#2;\pgfplots@EOI{%
	% de-activate the FPU here! I fear its number
	% format may cause errors when used in low-level
	% routines.
	\pgfkeys{/pgf/fpu=false}%
	%
	\ifpgfplots@threedim
		\pgfplots@apply@zbuffer{#1}%
		\let\pgfplots@coord@stream@finalize@storedcoords@START@coords=\pgfplotsglobalretval
		\global\let\pgfplotsglobalretval=\relax
	\else
		\def\pgfplots@coord@stream@finalize@storedcoords@START@coords{#1}%
	\fi
	\pgfplots@assert@tikzinternal@exists{tikz@make@last@position}%
	%
	\ifpgfplots@clip
	\else
		% "clip marker paths=true" actually doesn't checks anything --
		% it leaves the checks to the clip path. But since there is no
		% clip path, it is adequate to use it here:
		\pgfplots@clip@marker@pathstrue
	\fi
	%
	\pgfplots@stored@current@cmd%[current plot style] <--- options are already set
	\pgfextra
	\tikzset{every plot/.try}%
	\pgfplots@coord@stream@INIT@finalize@storedcoords%
	\iffalse
	%\ifx\pgfplots@basiclevel@plothandler\pgfplothandlerdiscard
		% discard!? Well, no need to loop through the elements.
		% But there may be a good reason that we entered the phase!
		% keep it.
		% FIXME : this does not work, although it might be desirable.
		% It fails because we need the named start/end points.
		\pgfplots@coord@stream@start
		\pgfplots@coord@stream@end
	\else
		\expandafter\pgfplots@coord@stream@foreach@NORMALIZED\expandafter{\pgfplots@coord@stream@finalize@storedcoords@START@coords}%
	\fi
	%
	% This here ensures that the LAST position of the path is the last plotted point.
	% However, the "last plotted point" is not necessarily the LAST in the sequence.
	% This here is the last plotted point:
	\xdef\pgfplotlastpoint{\noexpand\pgfpointanchor{current plot end}{center}}%
	\tikz@make@last@position{\pgfplotlastpoint}%
	%
	\let\pgfplots@plot@timer@args=\pgfplots@coord@stream@finalize@storedcoords@START@coords
	\pgfplotspointplotattimeclearcache
	\let\tikz@timer=\pgfplots@plot@timer%
	\pgfplotsaxisvisphase@get@afterpath{#2}%
	\expandafter
	\endpgfextra
	\pgfplotsretval
	;
	%
	\pgfplotspointplotattimeclearcache
	%
}%

% Defines \pgfplotsretval to contain the "after path", i.e. the
% standard tikz instructions which are to be carried out after the
% plot path. This depends on the current visualization phase and the
% available visualization phases.
\def\pgfplotsaxisvisphase@get@afterpath#1{%
	\ifx\pgfplots@visphase@name\pgfplotsaxis@visphase@name@default
		% ah - we have the standard visualization phase. Draw them
		% here.
		%
		% Note that the existance of (nontrivial) after path
		% instructions ALWAYS implies the existance of a standard
		% visualization phase (compare \pgfplotssurveyphase@set@visphase@names)
		\def\pgfplotsretval{#1}%
	\else
		\let\pgfplotsretval=\pgfutil@empty
	\fi
}%

	
% This routine is called at the begin of every plot.
% It initialises a zero level stream.
%
% The default is to use '0' as zero level streams.
%
% This method is called as "precommand"; before any Tikz drawing
% commands have been started.
\def\pgfplots@initzerolevelhandler{%
	\ifpgfplots@stackedmode
		% ATTENTION: this thing here says:
		%    "draw zero level coordinates from list XYZ."
		% But at the time of this initialisation, the list will be EMPTY!
		%
		% It will be filled later. That's ok, because 
		% \pgfplots@initzerolevelhandler will be
		% used as 'precommand', that means before Tikz sees any
		% coordinates.
		\pgfplots@stacked@initzerolevelhandler
	\else
		\ifpgfplots@threedim
			\def\pgfplotxzerolevelstreamstart{}%
			\def\pgfplotxzerolevelstreamend{}%
			\def\pgfplotxzerolevelstreamnext{%
				\begingroup
				\pgf@xa=\pgf@y
				\pgfplotsqpointxyz{\pgfplots@logical@ZERO@x}{\pgfplots@current@point@y}{\ifpgfplots@curplot@threedim\pgfplots@current@point@z\else\pgfplots@logical@ZERO@z\fi}%
				\global\pgf@x=\pgf@x
				\global\pgf@y=\pgf@xa
				\endgroup
			}%
			%
			\def\pgfplotyzerolevelstreamstart{}%
			\def\pgfplotyzerolevelstreamend{}%
			\def\pgfplotyzerolevelstreamnext{%
				\begingroup
				\pgf@xa=\pgf@y
				\pgfplotsqpointxyz{\pgfplots@current@point@x}{\pgfplots@current@point@y}{\pgfplots@logical@ZERO@z}%
				\global\pgf@x=\pgf@y
				\global\pgf@y=\pgf@xa
				\endgroup
			}%
		\else
			\pgfplotspointaxisorigin
			\expandafter\pgfplotxzerolevelstreamconstant\expandafter{\the\pgf@x}%
			\expandafter\pgfplotyzerolevelstreamconstant\expandafter{\the\pgf@y}%
		\fi
	\fi
}

% This code is mainly interesting for bar plots.
%
% It precomputes x = 0 and y = 0 - which is not necessarily
% trivial in case of data scaling. Furthermore, it applies
% coordinate clipping to the resulting values and multiplies them
% with x- and y scale vectors.
\def\pgfplots@prepare@ZERO@coordinates{%
	\ifpgfplots@xislinear
		\ifpgfplots@apply@datatrafo@x
			\pgfplotscoordmath{x}{parsenumber}{0}%
			\pgfplotscoordmath{x}{datascaletrafo}{\pgfmathresult}%
			\global\let\pgfplots@logical@ZERO@x=\pgfmathresult
		\else
			\gdef\pgfplots@logical@ZERO@x{0}%
		\fi
		% this works in standard fixed pt math:
		\pgfplotsmathmax{\pgfplots@logical@ZERO@x}{\pgfplots@xmin}%
		\global\let\pgfplots@logical@ZERO@x=\pgfmathresult
		\pgfplotsmathmin{\pgfplots@logical@ZERO@x}{\pgfplots@xmax}%
		\global\let\pgfplots@logical@ZERO@x=\pgfmathresult
	\else
		\if\pgfplots@log@origin@choice@x0%
			\global\let\pgfplots@logical@ZERO@x=\pgfplots@xmin%
		\else
			\gdef\pgfplots@logical@ZERO@x{0}%
		\fi
	\fi
	%
	\ifpgfplots@yislinear
		\ifpgfplots@apply@datatrafo@y
			\pgfplotscoordmath{y}{parsenumber}{0}%
			\pgfplotscoordmath{y}{datascaletrafo}{\pgfmathresult}%
			\global\let\pgfplots@logical@ZERO@y=\pgfmathresult
		\else
			\gdef\pgfplots@logical@ZERO@y{0}%
		\fi
		\pgfplotsmathmax{\pgfplots@logical@ZERO@y}{\pgfplots@ymin}%
		\global\let\pgfplots@logical@ZERO@y=\pgfmathresult
		\pgfplotsmathmin{\pgfplots@logical@ZERO@y}{\pgfplots@ymax}%
		\global\let\pgfplots@logical@ZERO@y=\pgfmathresult
	\else
		\if\pgfplots@log@origin@choice@y0%
			\global\let\pgfplots@logical@ZERO@y=\pgfplots@ymin%
		\else
			\gdef\pgfplots@logical@ZERO@y{0}%
		\fi
	\fi
	%
	\ifpgfplots@threedim
		\ifpgfplots@zislinear
			\ifpgfplots@apply@datatrafo@z
				\pgfplotscoordmath{z}{parsenumber}{0}%
				\pgfplotscoordmath{z}{datascaletrafo}{\pgfmathresult}%
				\global\let\pgfplots@logical@ZERO@z=\pgfmathresult
			\else
				\gdef\pgfplots@logical@ZERO@z{0}%
			\fi
			\pgfplotsmathmax{\pgfplots@logical@ZERO@z}{\pgfplots@zmin}%
			\global\let\pgfplots@logical@ZERO@z=\pgfmathresult
			\pgfplotsmathmin{\pgfplots@logical@ZERO@z}{\pgfplots@zmax}%
			\global\let\pgfplots@logical@ZERO@z=\pgfmathresult
		\else
			\if\pgfplots@log@origin@choice@z0%
				\global\let\pgfplots@logical@ZERO@z=\pgfplots@zmin%
			\else
				\gdef\pgfplots@logical@ZERO@z{0}%
			\fi
		\fi
	\fi
	%
	%
	\ifpgfplots@threedim
		\pgfplotsqpointxyz{\pgfplots@logical@ZERO@x}{\pgfplots@logical@ZERO@y}{\pgfplots@logical@ZERO@z}%
	\else
		\pgfplotsqpointxy{\pgfplots@logical@ZERO@x}{\pgfplots@logical@ZERO@y}%
	\fi
	\xdef\pgfplots@ZERO@x{\the\pgf@x}%
	\xdef\pgfplots@ZERO@y{\the\pgf@y}%
	\xdef\pgfplotspointaxisorigin{\noexpand\global\pgf@x=\pgfplots@ZERO@x\space\noexpand\global\pgf@y=\pgfplots@ZERO@y\space}%
	%
	%
	%--------------------------------------------------
	% \pgfkeyslet{/pgfplots/axis/zero/x}\pgfplots@logical@ZERO@x
	% \pgfkeyslet{/pgfplots/axis/zero/y}\pgfplots@logical@ZERO@y
	% \ifpgfplots@threedim
	% 	\pgfkeyslet{/pgfplots/axis/zero/z}\pgfplots@logical@ZERO@z
	% \fi
	%-------------------------------------------------- 
}%



% the low-level Tikz command which implements 'plot graphics'.
%
% It's current state is described by some pgfkeys options and two
% coordinates.
\def\pgfplotsplothandlergraphics{%
	\def\pgf@plotstreamstart{%
		\gdef\pgfplots@plot@handler@graphics@bb@first{\pgf@x=16000pt \pgf@y=16000pt }%
		\gdef\pgfplots@plot@handler@graphics@bb@second{\pgf@x=-16000pt \pgf@y=-16000pt }%
		\global\let\pgf@plotstreampoint=\pgfplots@plot@handler@graphics@collectbb%
		\global\let\pgf@plotstreamspecial=\pgfutil@gobble%
		\global\let\pgf@plotstreamend=\pgfplots@plot@handler@graphics@finish%
		\def\pgfplotsplothandlervisualizejump{%
			\pgfplots@error{Sorry, plot graphics does not support 'unbounded coords=jump'.}%
		}%
	}%
}%
\def\pgfplots@plot@handler@graphics@collectbb#1{%
	\pgf@process{#1}%
	\pgf@xa=\pgf@x
	\pgf@ya=\pgf@y
	\pgfplots@plot@handler@graphics@bb@first
	\ifdim\pgf@xa<\pgf@x \pgf@x=\pgf@xa\fi
	\ifdim\pgf@ya<\pgf@y \pgf@y=\pgf@ya\fi
	\xdef\pgfplots@plot@handler@graphics@bb@first{\pgf@x=\the\pgf@x\space\pgf@y=\the\pgf@y\space}%
	%
	\pgfplots@plot@handler@graphics@bb@second
	\ifdim\pgf@xa>\pgf@x \pgf@x=\pgf@xa\fi
	\ifdim\pgf@ya>\pgf@y \pgf@y=\pgf@ya\fi
	\xdef\pgfplots@plot@handler@graphics@bb@second{\pgf@x=\the\pgf@x\space\pgf@y=\the\pgf@y\space}%
	%
}%
\def\pgfplots@plot@handler@graphics@finish{%
	\let\pgfplots@plot@handler@graphics@pointmap@B@canvas\pgfutil@empty
	%
	% check if we have a pointmap. If so, the pointmap should be used
	% to place the graphics.
	\pgfkeysgetvalue{/pgfplots/plot graphics/points}\pgfplots@plot@handler@graphics@pointmap
	\ifx\pgfplots@plot@handler@graphics@pointmap\pgfutil@empty
	\else
		\let\pgfplots@plot@handler@graphics@parsepointmap@error=\relax
		\expandafter\pgfplots@plot@handler@graphics@parsepointmap\expandafter{\pgfplots@plot@handler@graphics@pointmap}%
	\fi
	%
	%
	\ifx\pgfplots@plot@handler@graphics@pointmap@B@canvas\pgfutil@empty
		% no pointmap. Good; then squeze graphics into the bounding
		% box:
		\pgfplots@plot@handler@graphics@usebb
	\else
		% oh, a pointmap! Process it.
		\pgfplots@plot@handler@graphics@process@pointmap
	\fi
}%

% Parses the argument of '/pgfplots/plot graphics/points'.
%
% #1: the argument of the key above.
\def\pgfplots@plot@handler@graphics@parsepointmap#1{%
	\let\pgfplots@plot@handler@graphics@pointmap@A@canvas\pgfutil@empty
	\let\pgfplots@plot@handler@graphics@pointmap@A@img\pgfutil@empty
	\let\pgfplots@plot@handler@graphics@pointmap@B@canvas\pgfutil@empty
	\let\pgfplots@plot@handler@graphics@pointmap@B@img\pgfutil@empty
	\let\pgfplots@plot@handler@graphics@pointmap@C@canvas\pgfutil@empty
	\let\pgfplots@plot@handler@graphics@pointmap@C@img\pgfutil@empty
	\let\pgfplots@plot@handler@graphics@pointmap@D@canvas\pgfutil@empty
	\let\pgfplots@plot@handler@graphics@pointmap@D@img\pgfutil@empty
	\pgfplots@plot@handler@graphics@parsepointmap@loop#1\pgfplots@EOI
	\ifpgfplots@plot@graphics@autoadjustaxis
		\ifx\pgfplots@plot@handler@graphics@pointmap@A@img\pgfutil@empty
		\else
			\ifx\pgfplots@plot@handler@graphics@pointmap@D@img\pgfutil@empty
				\def\pgfplots@loc@TMPa{#1}%
				\pgfplots@plot@handler@graphics@parsepointmap@error
			\fi
		\fi
	\fi
}%
\def\pgfplots@plot@handler@graphics@parsepointmap@error{%
	\pgfplots@error{plot graphics/points={\pgfplots@loc@TMPa} cannot be processed: I need at least *four* inner anchor points to automatically adjust the axis, i.e. 4 points of the form (x,y,z) => (imgx,imgy). Use 'plot graphics/auto adjust axis=false' to disable this feature}%
}%
\def\pgfplots@plot@handler@graphics@parsepointmap@loop{%
	\pgfutil@ifnextchar\pgfplots@EOI{%
		\pgfplots@gobble@until@EOI
	}{%
		\pgfplots@plot@handler@graphics@parsepointmap@loop@
	}%
}%
\def\pgfplots@plot@handler@graphics@parsepointmap@loop@(#1,#2){%
	\pgfutil@ifnextchar={%
		\pgfplots@plot@handler@graphics@parsepointmap@loop@@(#1,#2)%
	}{%
		\pgfplots@plot@handler@graphics@parsepointmap@loop@@(#1,#2)=>(,)%
	}%
}%
\def\pgfplots@plot@handler@graphics@parsepointmap@loop@@(#1,#2)=>{%
	\pgfutil@ifnextchar({%
		\pgfplots@plot@handler@graphics@parsepointmap@loop@@@(#1,#2)%
	}{%
		\pgfplots@error{Syntax error for plot graphics/pointmap: expected '(#1,#2) => (...,...)'}%
		\pgfplots@gobble@until@EOI
	}%
}
\def\pgfplots@plot@handler@graphics@parsepointmap@loop@@@(#1,#2)(#3,#4){%
	\def\pgfplotsplothandlergraphicspointmappointindex{}%
	\def\pgfplots@loc@TMPc{#4}%
	\ifx\pgfplots@loc@TMPc\pgfutil@empty
	\else
		\ifx\pgfplots@plot@handler@graphics@pointmap@A@img\pgfutil@empty
			\def\pgfplotsplothandlergraphicspointmappointindex{A}%
		\else
			\ifx\pgfplots@plot@handler@graphics@pointmap@B@img\pgfutil@empty
				\def\pgfplotsplothandlergraphicspointmappointindex{B}%
			\else
				\ifx\pgfplots@plot@handler@graphics@pointmap@C@img\pgfutil@empty
					\def\pgfplotsplothandlergraphicspointmappointindex{C}%
				\else
					\ifx\pgfplots@plot@handler@graphics@pointmap@D@img\pgfutil@empty
						\def\pgfplotsplothandlergraphicspointmappointindex{D}%
					\else
						\def\pgfplotsplothandlergraphicspointmappointindex{*}%
						%\pgfplots@error{Sorry, the argument '(#1,#2) => (#3,#4)' of plot graphics/pointmap is superfluos; ignoring it.}%
					\fi
				\fi
			\fi
		\fi
		\pgfmathparse{#3}%
		\let\pgfplots@loc@TMPb=\pgfmathresult
		%
		\pgfmathparse{#4}%
		\expandafter\edef\csname pgfplots@plot@handler@graphics@pointmap@\pgfplotsplothandlergraphicspointmappointindex @img\endcsname{{\pgfplots@loc@TMPb}{\pgfmathresult}}%
	\fi
	%
	%
	\pgfutil@in@,{#2}%
	\ifpgfutil@in@
		\def\pgfplots@loc@TMPa##1,##2\relax{%
			\expandafter\edef\csname pgfplots@plot@handler@graphics@pointmap@\pgfplotsplothandlergraphicspointmappointindex @logical\endcsname{{#1}{##1}{##2}}%
			%
			\pgfplotsplothandlergraphicspointmappoint(#1,##1,##2)(#3,#4)
		}%
		\pgfplots@loc@TMPa#2\relax
	\else
		\expandafter\edef\csname pgfplots@plot@handler@graphics@pointmap@\pgfplotsplothandlergraphicspointmappointindex @logical\endcsname{{#1}{#2}{}}%
		\pgfplotsplothandlergraphicspointmappoint(#1,#2,)(#3,#4)
	\fi
	\pgfplots@plot@handler@graphics@parsepointmap@loop
}

\def\pgfplotsplothandlergraphics@survey@pointmappoint(#1,#2,#3)(#4,#5){%
	\def\pgfplots@current@point@x{#1}%
	\def\pgfplots@current@point@y{#2}%
	\def\pgfplots@current@point@z{#3}%
	\pgfplots@coord@stream@coord
}%

% PRECONDITION:
% 	\pgfplotsplothandlergraphicspointmappointindex is 
% 	empty if and only if (#4,#5) is empty 
% 	or it is an index among all points with non--empty (#4,#5) image
% 	coordinates.
\def\pgfplotsplothandlergraphicspointmappoint(#1,#2,#3)(#4,#5){%
	\ifx\pgfplotsplothandlergraphicspointmappointindex\pgfutil@empty
	\else
		\def\pgfplots@loc@TMPc{#3}%
		\ifx\pgfplots@loc@TMPc\pgfutil@empty
			\pgfplotspointaxisxy{#1}{#2}%
		\else
			\pgfplotspointaxisxyz{#1}{#2}{#3}%
		\fi
		\expandafter\edef\csname pgfplots@plot@handler@graphics@pointmap@\pgfplotsplothandlergraphicspointmappointindex @canvas\endcsname{\pgf@x=\the\pgf@x\space\pgf@y=\the\pgf@y\space}%
	\fi
}%

% Computes view-related keys which should be communicated to the axis
% in order to render the plot graphics correctly.
%
% @POSTCONDITION: \pgfplotsretval contains any required keys.
\def\pgfplotsplothandlergraphicspointmapcomputerequiredview{%
	\begingroup
	\let\pgfplotsretval=\pgfutil@empty
	\ifx\pgfplots@plot@handler@graphics@pointmap@D@img\pgfutil@empty
	\else
		\pgfkeysgetvalue{/pgfplots/plot graphics/debug}\pgfplots@loc@TMPa
		\def\pgfplots@loc@TMPb{false}%
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
			\let\pgfplots@loc@TMPa=\pgfplots@loc@TMPb
		\fi
		\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
			\def\pgfplotsplothandlergraphicspointmapcomputerequiredview@debug{0}%
		\else
			\def\pgfplotsplothandlergraphicspointmapcomputerequiredview@debug{1}%
		\fi
		% The following implementation computes the 'unit vector
		% ratio' of the IMAGE.
		%
		% It then tells PGFPlots to use the very same unit vector
		% ratio for its axis.
		%
		%
		% The actual implementation is dumb; it requires 4 (!) points for
		% which BOTH, the 3D coordinates and the projected 2D
		% coordinates relative to the image's lower left corner are
		% available.
		%
		% Since the 2D projected coordinates are generated by the map
		%
		% T(x,y,z) = o + x e_x + y e_y + z e_z in R^2
		% with o,e_x,e_y,e_z in R^2,
		%
		% I have 8 degrees of freedom (two for each of the four
		% involved vectors). Thus, a simple approach is to provide 4
		% linearly independend points to get 8 equations.
		%
		% Then, I solve for o,e_x,e_y,e_z 
		%
		\pgfplotsmatrixnewempty\pgfplotsmatrix
		\pgfplotsmatrixresize\pgfplotsmatrix88%
		%
		\pgfplotsarraynewempty\pgfplotsE
		\pgfplotsarrayresize\pgfplotsE8%
		%
		\def\pgfplots@extractimg##1##2{%
			\def\pgfplots@img@x{##1}%
			\def\pgfplots@img@y{##2}%
		}%
		\def\pgfplots@extractlogical##1##2##3{%
			\def\pgfplots@logical@x{##1}%
			\def\pgfplots@logical@y{##2}%
			\def\pgfplots@logical@z{##3}%
		}%
		% Assemble the linear system such that
		% x = [ 
		%  exx 
		%  exy
		%  eyx
		%  eyy
		%  ezx
		%  ezy
		%  ox
		%  oy]
		% are the degrees of freedom.
		\c@pgfplots@coordindex=0
		\pgfplotsutilforeachcommasep{A,B,C,D}\as\pgfplots@loc@TMPa{%
			\expandafter\expandafter\expandafter\pgfplots@extractimg\csname pgfplots@plot@handler@graphics@pointmap@\pgfplots@loc@TMPa @img\endcsname
			\expandafter\expandafter\expandafter\pgfplots@extractlogical\csname pgfplots@plot@handler@graphics@pointmap@\pgfplots@loc@TMPa @logical\endcsname
			\ifx\pgfplots@logical@z\pgfutil@empty
			\else
			%
			\pgfplotsmatrixletentry \the\c@pgfplots@coordindex,0\of\pgfplotsmatrix=\pgfplots@logical@x%
			\pgfplotsmatrixset \the\c@pgfplots@coordindex,1\of\pgfplotsmatrix\to{0}%
			\pgfplotsmatrixletentry \the\c@pgfplots@coordindex,2\of\pgfplotsmatrix=\pgfplots@logical@y%
			\pgfplotsmatrixset \the\c@pgfplots@coordindex,3\of\pgfplotsmatrix\to{0}%
			\pgfplotsmatrixletentry \the\c@pgfplots@coordindex,4\of\pgfplotsmatrix=\pgfplots@logical@z%
			\pgfplotsmatrixset \the\c@pgfplots@coordindex,5\of\pgfplotsmatrix\to{0}%
			\pgfplotsmatrixset \the\c@pgfplots@coordindex,6\of\pgfplotsmatrix\to{1}%
			\pgfplotsmatrixset \the\c@pgfplots@coordindex,7\of\pgfplotsmatrix\to{0}%
			%
			\pgfplotsarrayletentry\c@pgfplots@coordindex\of\pgfplotsE=\pgfplots@img@x
			%
			\advance\c@pgfplots@coordindex by1
			\pgfplotsmatrixset \the\c@pgfplots@coordindex,0\of\pgfplotsmatrix\to{0}%
			\pgfplotsmatrixletentry \the\c@pgfplots@coordindex,1\of\pgfplotsmatrix=\pgfplots@logical@x%
			\pgfplotsmatrixset \the\c@pgfplots@coordindex,2\of\pgfplotsmatrix\to{0}%
			\pgfplotsmatrixletentry \the\c@pgfplots@coordindex,3\of\pgfplotsmatrix=\pgfplots@logical@y%
			\pgfplotsmatrixset \the\c@pgfplots@coordindex,4\of\pgfplotsmatrix\to{0}%
			\pgfplotsmatrixletentry \the\c@pgfplots@coordindex,5\of\pgfplotsmatrix=\pgfplots@logical@z%
			\pgfplotsmatrixset \the\c@pgfplots@coordindex,6\of\pgfplotsmatrix\to{0}%
			\pgfplotsmatrixset \the\c@pgfplots@coordindex,7\of\pgfplotsmatrix\to{1}%
			%
			\pgfplotsarrayletentry\c@pgfplots@coordindex\of\pgfplotsE=\pgfplots@img@y
			%
			\advance\c@pgfplots@coordindex by1
			\fi
		}%
		\ifx\pgfplots@logical@z\pgfutil@empty
		\else
			\if1\pgfplotsplothandlergraphicspointmapcomputerequiredview@debug
				\pgfplotsplothandlergraphics@debug@matrix@to@string
			\fi
			%
			%
			\pgfplotsmatrixsolveLEQS\pgfplotsmatrix=\pgfplotsE
			%
			\edef\pgfmathresult{\pgfplotsarrayvalueofelem0\of\pgfplotsE}%
			\pgfplotscoordmath{default}{tofixed}{\pgfmathresult}%
			\let\pgfplots@xx=\pgfmathresult
			\edef\pgfmathresult{\pgfplotsarrayvalueofelem1\of\pgfplotsE}%
			\pgfplotscoordmath{default}{tofixed}{\pgfmathresult}%
			\let\pgfplots@xy=\pgfmathresult
			\if r\pgfkeysvalueof{/pgfplots/x dir/value}%
				% they will be reversed again during the final
				% processing:
				\edef\pgfplots@xx{-\pgfplots@xx}%
				\edef\pgfplots@xy{-\pgfplots@xy}%
			\fi
			%
			\edef\pgfmathresult{\pgfplotsarrayvalueofelem2\of\pgfplotsE}%
			\pgfplotscoordmath{default}{tofixed}{\pgfmathresult}%
			\let\pgfplots@yx=\pgfmathresult
			\edef\pgfmathresult{\pgfplotsarrayvalueofelem3\of\pgfplotsE}%
			\pgfplotscoordmath{default}{tofixed}{\pgfmathresult}%
			\let\pgfplots@yy=\pgfmathresult
			\if r\pgfkeysvalueof{/pgfplots/y dir/value}%
				% they will be reversed again during the final
				% processing:
				\edef\pgfplots@yx{-\pgfplots@yx}%
				\edef\pgfplots@yy{-\pgfplots@yy}%
			\fi
			%
			\edef\pgfmathresult{\pgfplotsarrayvalueofelem4\of\pgfplotsE}%
			\pgfkeysgetvalue{/pgfplots/plot graphics/snap z}\pgfplots@loc@TMPa
			\ifx\pgfplots@loc@TMPa\pgfutil@empty
			\else
				\let\pgfplots@zx=\pgfmathresult
				\pgfplotscoordmath{default}{op}{veclen}{%
					{\pgfplotsarrayvalueofelem4\of\pgfplotsE}%
					{\pgfplotsarrayvalueofelem5\of\pgfplotsE}%
				}%
				\let\pgfplotszlen=\pgfmathresult
				%
				% compute 'snap z' relative to
				% '\pgfplotszlen'
				\pgfplotscoordmath{default}{parsenumber}{\pgfplots@loc@TMPa}%
				\pgfplotscoordmath{default}{op}{multiply}{{\pgfmathresult}{\pgfplotszlen}}%
				\let\pgfplots@loc@TMPa=\pgfmathresult
				%
				\pgfplotscoordmath{default}{op}{abs}{{\pgfplots@zx}}%
				\pgfplotscoordmath{default}{if less than}{\pgfmathresult}{\pgfplots@loc@TMPa}{%
					\pgfplotscoordmath{default}{zero}%
				}{%
					\let\pgfmathresult=\pgfplots@zx
				}%
			\fi
			\pgfplotscoordmath{default}{tofixed}\pgfmathresult%
			\let\pgfplots@zx=\pgfmathresult
			%
			\edef\pgfmathresult{\pgfplotsarrayvalueofelem5\of\pgfplotsE}%
			\pgfplotscoordmath{default}{tofixed}{\pgfmathresult}%
			\let\pgfplots@zy=\pgfmathresult
			\if r\pgfkeysvalueof{/pgfplots/z dir/value}%
				% they will be reversed again during the final
				% processing:
				\edef\pgfplots@zx{-\pgfplots@zx}%
				\edef\pgfplots@zy{-\pgfplots@zy}%
			\fi
			%
			%
			\if1\b@pgfplots@compat@plot@graphics@threedim
				\pgfplotswarning{plot3 graphics compatibility mode}\pgfeov%
			\else
			\fi
			%
			\edef\pgfplotsretval{%
				x={(\pgfplots@xx,\pgfplots@xy)},%
				y={(\pgfplots@yx,\pgfplots@yy)},%
				z={(\pgfplots@zx,\pgfplots@zy)},%
				scale mode=scale uniformly,%
				\if1\b@pgfplots@compat@plot@graphics@threedim
					% this is the only strategy pre 1.6
					scale uniformly strategy=change vertical limits,%
				\fi
			}%
			%
			\if1\pgfplotsplothandlergraphicspointmapcomputerequiredview@debug
				\pgfplotsplothandlergraphicspointmapcomputerequiredview@debug@output
			\fi
			%
			\ifx\pgfplotsretval\pgfutil@empty
				\pgfplots@error{plot graphics failed to perform the 'auto adjust axis' feature \csname on@line\endcsname\space\space (compare 'plot graphics[debug]). The graphics might be scaled incorrectly. Perhaps the provided 'points' are not linearly independent?}%
			\else
				\begingroup
				\pgfkeysgetvalue{/pgfplots/plot graphics/src}\pgfplots@loc@TMPa
				\t@pgfplots@tokc=\expandafter{\pgfplots@loc@TMPa}%
				\immediate\write
					\if1\pgfplotsplothandlergraphicspointmapcomputerequiredview@debug 16\else -1\fi
					{PGFPlots plot graphics[auto adjust axis=true] {\the\t@pgfplots@tokc} \csname on@line\endcsname: determined options '\pgfplotsretval'. 
					\if1\pgfplotsplothandlergraphicspointmapcomputerequiredview@debug
						See \the\t@pgfplots@tokc.dat for debug output.
					\else
						Use 'plot graphics[debug]' or 'plot graphics[debug=visual]' to generate debug output files.
					\fi
					^^J}% 
				\endgroup
			\fi
			%
		\fi
	\fi
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%
\def\pgfplotsplothandlergraphics@debug@matrix@to@string{%
	\pgfplotsmatrixtotext\pgfplotsmatrix
	\let\pgfplotsmatrix@text=\pgfplotsretval
	\pgfplotsarraytotext\pgfplotsE
	\let\pgfplotsrhs@text=\pgfplotsretval
}%
\def\pgfplotsplothandlergraphicspointmapcomputerequiredview@debug@output{%
	\begingroup
	\immediate\openout\w@pgf@writea=\pgfkeysvalueof{/pgfplots/plot graphics/src}.dat
	\pgfplotsarrayselect0\of\pgfplotsE\to\pgfmathresult \pgfplotscoordmath{default}{tofixed}{\pgfmathresult}\let\pgfplots@loc@TMPa=\pgfmathresult
	\pgfplotsarrayselect1\of\pgfplotsE\to\pgfmathresult \pgfplotscoordmath{default}{tofixed}{\pgfmathresult}\let\pgfplots@loc@TMPb=\pgfmathresult
	\immediate\write\w@pgf@writea{img x unit=\pgfplots@loc@TMPa\space\pgfplots@loc@TMPb\if r\pgfkeysvalueof{/pgfplots/x dir/value}(reversed due to x dir=reverse)\fi,}%
	\pgfplotsarrayselect2\of\pgfplotsE\to\pgfmathresult \pgfplotscoordmath{default}{tofixed}{\pgfmathresult}\let\pgfplots@loc@TMPa=\pgfmathresult
	\pgfplotsarrayselect3\of\pgfplotsE\to\pgfmathresult \pgfplotscoordmath{default}{tofixed}{\pgfmathresult}\let\pgfplots@loc@TMPb=\pgfmathresult
	\immediate\write\w@pgf@writea{img y unit=\pgfplots@loc@TMPa\space\pgfplots@loc@TMPb\if r\pgfkeysvalueof{/pgfplots/y dir/value}(reversed due to y dir=reverse)\fi,}%
	\pgfplotsarrayselect4\of\pgfplotsE\to\pgfmathresult \pgfplotscoordmath{default}{tofixed}{\pgfmathresult}\let\pgfplots@loc@TMPa=\pgfmathresult
	\pgfplotsarrayselect5\of\pgfplotsE\to\pgfmathresult \pgfplotscoordmath{default}{tofixed}{\pgfmathresult}\let\pgfplots@loc@TMPb=\pgfmathresult
	\immediate\write\w@pgf@writea{img z unit=\pgfplots@loc@TMPa\space\pgfplots@loc@TMPb,}%
	\pgfplotsarrayselect6\of\pgfplotsE\to\pgfmathresult \pgfplotscoordmath{default}{tofixed}{\pgfmathresult}\let\pgfplots@loc@TMPa=\pgfmathresult
	\pgfplotsarrayselect7\of\pgfplotsE\to\pgfmathresult \pgfplotscoordmath{default}{tofixed}{\pgfmathresult}\let\pgfplots@loc@TMPb=\pgfmathresult
	\immediate\write\w@pgf@writea{img origin=\pgfplots@loc@TMPa\space\pgfplots@loc@TMPb\if r\pgfkeysvalueof{/pgfplots/z dir/value}(reversed due to z dir=reverse)\fi,}%
	\def\n{^^J}%
	\def\t{^^I}%
	\immediate\write\w@pgf@writea{canvasmapmatrix=[\pgfplotsmatrix@text];^^Jcanvasmaprhs = [\pgfplotsrhs@text];^^J}%
	%
	\immediate\write\w@pgf@writea{key configuration = \pgfplotsretval;^^J}%
	\immediate\write\w@pgf@writea{use debug=visual to see the mapped keys.^^J}%
	\immediate\closeout\w@pgf@writea
	\endgroup
}%

\def\pgfplots@plot@handler@graphics@process@pointmap{%
	\begingroup
	% determine natural size:
	\pgfplots@invoke@pgfkeyscode{/pgfplots/plot graphics/lowlevel get natural size/.@cmd}{}%
	\def\pgfplots@loc@TMPa##1##2{%
		\global\pgf@x=##1
		\global\pgf@y=##2
	}%
	\expandafter\pgfplots@loc@TMPa\pgfmathresult
	\edef\pgfplots@W{\pgf@sys@tonumber\pgf@x}% natural WIDTH
	\edef\pgfplots@H{\pgf@sys@tonumber\pgf@y}% natural HEIGHT
	%
	\def\pgfplots@extractimg##1##2{%
		\def\pgfplots@img@x{##1}%
		\def\pgfplots@img@y{##2}%
	}%
	\def\pgfplots@extractimgaspoint##1##2{%
		\pgfqpoint{##1pt}{##2pt}%
	}%
	\expandafter\pgfplots@extractimg\pgfplots@plot@handler@graphics@pointmap@A@img% anchor 1 in image
	\let\pgfplots@Ax=\pgfplots@img@x
	\let\pgfplots@Ay=\pgfplots@img@y
	%
	\pgfplots@plot@handler@graphics@pointmap@A@canvas% the canvas coordinate corresponding to 'A'
	\edef\pgfplots@ax{\pgf@sys@tonumber\pgf@x}% call it 'a'
	\edef\pgfplots@ay{\pgf@sys@tonumber\pgf@y}%
	%
	% compute the CANVAS diagonal between the two anchors points a,b,
	%  dd := b-a
	\pgfpointdiff
		\pgfplots@plot@handler@graphics@pointmap@A@canvas
		\pgfplots@plot@handler@graphics@pointmap@B@canvas
	\edef\pgfplots@ddx{\pgf@sys@tonumber\pgf@x}%
	\edef\pgfplots@ddy{\pgf@sys@tonumber\pgf@y}%
	%
	% compute the IMAGE diagonal between the two image anchor points A,B,
	%   DD := B - A
	\pgfpointdiff
		{\expandafter\pgfplots@extractimgaspoint\pgfplots@plot@handler@graphics@pointmap@A@img}
		{\expandafter\pgfplots@extractimgaspoint\pgfplots@plot@handler@graphics@pointmap@B@img}%
	\pgfplots@loop@CONTINUEtrue
	\ifdim\pgf@x=0pt \pgfplots@loop@CONTINUEfalse \fi
	\ifdim\pgf@y=0pt \pgfplots@loop@CONTINUEfalse \fi
	\ifpgfplots@loop@CONTINUE
	\else
		\pgfplots@error{Sorry, the first two points with '=>' in plot graphics[points={}] are expected to have different image Y coordinates. Please reorder the sequence.}%
	\fi
	\edef\pgfplots@DDx{\pgf@sys@tonumber\pgf@x}%
	\edef\pgfplots@DDy{\pgf@sys@tonumber\pgf@y}%
	%
	% What I need now is a shift and the CANVAS dimensions of the
	% image. Both can be computed using the relative sizes dd/DD.
	%
	% The shift is needed to compute the lower left corner of the
	% CANVAS image. thus, the lower left CANVAS image corresponds to
	% the (0,0) coordinate in the IMAGE.
	%
	% Remember that 'A' is the anchor 1 in IMAGE coordinates. It is a
	% vector from (0,0) --> (A_x,A_y) in IMAGE coordinates.
	%
	% Now, I want a vector (v_x,v_y)  such that q + v = a in CANVAS
	% coordinates. Here, 'q' is the lower left corner; it corresponds
	% to the (0,0) in IMAGE coordinates. Thus, we have
	% v = (a-q). Taking the relative sizes of dd and DD, we find
	%
	%   DD_x / A_x = dd_x / v_x
	%   DD_y / A_y = dd_y / v_y
	%
	% and finally q = a-v is the lower left CANVAS coordinate.
	\pgfmath@basic@divide@{\pgfplots@ddx}{\pgfplots@DDx}%
	\let\pgfplots@x@rel=\pgfmathresult
	%
	\pgfmath@basic@divide@{\pgfplots@ddy}{\pgfplots@DDy}%
	\let\pgfplots@y@rel=\pgfmathresult
	%
	\pgfmath@basic@multiply@{\pgfplots@Ax}{\pgfplots@x@rel}%
	\let\pgfplots@vx=\pgfmathresult
	%
	\pgfmath@basic@multiply@{\pgfplots@Ay}{\pgfplots@y@rel}%
	\let\pgfplots@vy=\pgfmathresult
	%
	%
	%
	%
	% now, the canvas width. It is even simpler because it holds
	%
	%  DD_x / dd_x = W / w
	%  DD_y / dd_y = H / h
	%
	% where (W,H) is the natural size (i.e. in IMAGE coordinates) of the picture and 
	% (w,h) is the size the picture will occupy in CANVAS coordinates.
	%  
	\pgfmath@basic@multiply@{\pgfplots@x@rel}{\pgfplots@W}%
	\let\pgfplots@w=\pgfmathresult
	%
	\pgfmath@basic@multiply@{\pgfplots@y@rel}{\pgfplots@H}%
	\let\pgfplots@h=\pgfmathresult
	%
	\edef\pgfplots@plot@handler@graphics@DRAW@{%
		\noexpand\pgfplots@invoke@pgfkeyscode{/pgfplots/plot graphics/lowlevel draw/.@cmd}{%
			{\pgfplots@w pt}% width
			{\pgfplots@h pt}% height
		}%
	}%
	\pgfpointadd
		{\pgfplots@plot@handler@graphics@pointmap@A@canvas}% the canvas coordinate corresponding to 'A'
		{\pgfqpointscale{-1}
			{\pgfqpoint{\pgfplots@vx pt}{\pgfplots@vy pt}}%
		}%
	\edef\pgfplots@plot@handler@graphics@pointmap@lowerleft@canvas{\pgf@x=\the\pgf@x\space\pgf@y=\the\pgf@y\space}%
%
	%
	%
	\begingroup
		\pgftransformshift{}% simply take \pgf@x and \pgf@y
		%
		\node[/pgfplots/plot graphics/node] {%
			\pgfplots@plot@handler@graphics@DRAW@
		};%
	\endgroup
	%
	%
	\pgfkeysgetvalue{/pgfplots/plot graphics/debug}\pgfplots@loc@TMPa
	\edef\pgfplots@loc@TMPb{visual}%
	\ifx\pgfplots@loc@TMPb\pgfplots@loc@TMPa
		% debug = visual: "sanitize" also triggers the visualization.
		\pgfplots@plot@handler@graphics@pointmap@sanitize@scaling{A}%
		\pgfplots@plot@handler@graphics@pointmap@sanitize@scaling{B}%
	\fi
	%
	%
	\ifx\pgfplots@plot@handler@graphics@pointmap@C@canvas\pgfutil@empty
		\ifpgfplots@threedim
			\pgfplotswarning{plot3 graphics too few inner anchors}\pgfeov%
		\fi
	\else
		\pgfplots@plot@handler@graphics@pointmap@sanitize@scaling{C}%
		\ifx\pgfplots@plot@handler@graphics@pointmap@D@canvas\pgfutil@empty
		\else
			\pgfplots@plot@handler@graphics@pointmap@sanitize@scaling{D}%
		\fi
	\fi
	\endgroup
}%

% Checks if the logical and canvas coordinates of the point identified
% by #1 are correct.
%
% #1: a character in {A,B,C...}.
%
\def\pgfplots@plot@handler@graphics@pointmap@sanitize@scaling#1{%
	\begingroup
	\expandafter\let\expandafter\pgfplots@point@img\csname pgfplots@plot@handler@graphics@pointmap@#1@img\endcsname
	\expandafter\let\expandafter\pgfplots@point@canvas\csname pgfplots@plot@handler@graphics@pointmap@#1@canvas\endcsname
	\expandafter\let\expandafter\pgfplots@point@logical\csname pgfplots@plot@handler@graphics@pointmap@#1@logical\endcsname
	\expandafter\pgfplots@extractimgaspoint\pgfplots@point@img% anchor 3 in image
	\edef\pgfplots@Cx{\pgf@sys@tonumber\pgf@x}%
	\edef\pgfplots@Cy{\pgf@sys@tonumber\pgf@y}%
	%
	\pgfmath@basic@multiply@{\pgfplots@Cx}{\pgfplots@x@rel}%
	\let\pgfplots@Cx=\pgfmathresult
	%
	\pgfmath@basic@multiply@{\pgfplots@Cy}{\pgfplots@y@rel}%
	\let\pgfplots@Cy=\pgfmathresult
	\pgfpointadd
		{\pgfplots@plot@handler@graphics@pointmap@lowerleft@canvas}%
		{\pgfpoint\pgfplots@Cx\pgfplots@Cy}%
	\edef\pgfplots@point@canvas@check{\pgf@x=\the\pgf@x\space\pgf@y=\the\pgf@y\space}%
	\pgfpointdiff
		{\pgfplots@point@canvas@check}%
		{\pgfplots@point@canvas}%
	\ifdim\pgf@x<0pt \pgf@x=-\pgf@x\fi
	\ifdim\pgf@y<0pt \pgf@y=-\pgf@y\fi
	\def\pgfplots@is@the@same@point{1}%
	\ifdim\pgf@x>\pgfkeysvalueof{/pgfplots/plot graphics/squeeze tol}
		\def\pgfplots@is@the@same@point{0}%
	\else
		\ifdim\pgf@y>\pgfkeysvalueof{/pgfplots/plot graphics/squeeze tol}
			\def\pgfplots@is@the@same@point{0}%
		\fi
	\fi
	\if0\pgfplots@is@the@same@point
		%
		\begingroup
		\pgfkeysgetvalue{/pgfplots/plot graphics/src}\pgfplots@loc@TMPa
		\t@pgfplots@tokc=\expandafter{\pgfplots@loc@TMPa}%
		\def\pgfplots@extractcoord##1##2##3{##1,##2,##3}%
		\pgfplots@error{sorry, I can't fix the scaling of 'plot graphics {\the\t@pgfplots@tokc}'.
			The points (\expandafter\pgfplots@extractcoord\pgfplots@plot@handler@graphics@pointmap@A@logical) and (\expandafter\pgfplots@extractcoord\pgfplots@plot@handler@graphics@pointmap@B@logical) are correct, but the point (\expandafter\pgfplots@extractcoord\pgfplots@point@logical) is wrong (its position vector has an error of (\the\pgf@x,\the\pgf@y) which is larger than 'squeeze tol=\pgfkeysvalueof{/pgfplots/plot graphics/squeeze tol}'). This is probably caused by improper relations between the axis' unit vectors because the view is incorrect.^^J
			- Is the 'view' argument correct (matlab: [h,v] = view)? ^^J
			- Does your image have a non-trivial 'plot box ratio' (matlab: ratio = pbaspect)?^^J
			Please refer to the pgfplots manual for details. If you continue now, I'll show the points in the image}%
		\endgroup
		%
		\pgfplots@plot@handler@graphics@pointmap@sanitize@scaling@draw
		%
	\fi
	\pgfkeysgetvalue{/pgfplots/plot graphics/debug}\pgfplots@loc@TMPa
	\edef\pgfplots@loc@TMPb{visual}%
	\ifx\pgfplots@loc@TMPb\pgfplots@loc@TMPa
		\pgfplots@plot@handler@graphics@pointmap@sanitize@scaling@draw
	\fi
	\endgroup
}

\def\pgfplots@plot@handler@graphics@pointmap@sanitize@scaling@draw{%
	\scope
	\pgfsetstrokecolor{black}%
	\pgfsetfillcolor{red}%
	\pgfpathcircle{\pgfplots@point@canvas@check}{2pt}%
	\pgfusepath{stroke,fill}%
	\pgfsetfillcolor{green}%
	\pgfpathcircle{\pgfplots@point@canvas}{2pt}%
	\pgfusepath{stroke,fill}%
	\draw[->,red] 
		\pgfextra{
			\pgfpathmoveto{\pgfplots@point@canvas@check}%
			\pgfpathlineto{\pgfplots@point@canvas}};
	\endscope
}%

\def\pgfplots@plot@handler@graphics@usebb{%
	\pgfpointdiff{\pgfplots@plot@handler@graphics@bb@first}{\pgfplots@plot@handler@graphics@bb@second}%
	\def\pgfplots@plot@handler@graphics@finish@ok{1}%
	\ifdim\pgf@x=0pt
		\def\pgfplots@plot@handler@graphics@finish@ok{0}%
	\else
		\ifdim\pgf@y=0pt
			\def\pgfplots@plot@handler@graphics@finish@ok{0}%
		\fi
	\fi
	\if0\pgfplots@plot@handler@graphics@finish@ok
		\pgfplots@error{Error using 'plot graphics': I got too few coordinates! I expected the lower left and upper right corners!}%
		\xdef\pgfplots@plot@handler@graphics@bb@first{\noexpand\pgfqpoint{0pt}{0pt}}%
		\xdef\pgfplots@plot@handler@graphics@bb@first{\noexpand\pgfqpoint{0pt}{0pt}}%
		
	\fi	
	\begingroup
	% determine the lower left / upper right corners.
	\pgfplots@plot@handler@graphics@bb@first
	\pgf@xa=\pgf@x
	\pgf@ya=\pgf@y
	\pgfplots@plot@handler@graphics@bb@second
	\pgf@xb=\pgf@x
	\pgf@yb=\pgf@y
	%
	% xc,yc = lower left corner
	% x,y = upper right
	\ifdim\pgf@xa<\pgf@xb
		\pgf@xc=\pgf@xa
		\pgf@x=\pgf@xb
	\else
		\pgf@xc=\pgf@xb
		\pgf@x=\pgf@xa
	\fi
	\ifdim\pgf@ya<\pgf@yb
		\pgf@yc=\pgf@ya
		\pgf@y=\pgf@yb
	\else
		\pgf@yc=\pgf@yb
		\pgf@y=\pgf@ya
	\fi
	\advance\pgf@x by-\pgf@xc
	\advance\pgf@y by-\pgf@yc
	\edef\pgfplots@plot@handler@graphics@DRAW@{%
		\noexpand\pgfplots@invoke@pgfkeyscode{/pgfplots/plot graphics/lowlevel draw/.@cmd}{%
			{\the\pgf@x}% width
			{\the\pgf@y}% height
		}%
	}%
	\pgf@x=\pgf@xc
	\pgf@y=\pgf@yc
	\pgftransformshift{}%
	\node[/pgfplots/plot graphics/node] {%
		\pgfplots@plot@handler@graphics@DRAW@
	};%
	\endgroup
}%
% initial value for /pgfplots/plots graphics/lowlevel draw:
\def\pgfplots@plot@handler@graphics@DRAW#1#2{%
	\pgfkeysgetvalue{/pgfplots/plot graphics/includegraphics}{\pgfplots@loc@TMPc}%
	\pgfkeysgetvalue{/pgfplots/plot graphics/src}{\pgfplots@loc@TMPd}%
	\ifx\pgfplots@loc@TMPd\pgfutil@empty
		\pgfplots@error{Error using 'plot graphics': I don't have a graphics file name! Please set the '/pgfplots/plot graphics/src' key to the image file name. Skipping this plot.}%
	\else
		\begingroup
		\t@pgfplots@toka=\expandafter{\pgfplots@loc@TMPc}%
		%
		\def\pgfplots@loc@TMPa{#1}%
		\def\pgfplots@loc@TMPb{#2}%
		%
		\edef\pgfplots@loc@TMPc{%
			\the\t@pgfplots@toka,%
			\ifx\pgfplots@loc@TMPa\pgfutil@empty\else width=#1,\fi
			\ifx\pgfplots@loc@TMPb\pgfutil@empty\else height=#2,\fi
		}%
		\pgfmath@smuggleone\pgfplots@loc@TMPc
		\endgroup
		%
		\def\pgfplots@loc@TMPa{\pgfkeysvalueof{/pgfplots/plot graphics/includegraphics cmd}}%
		\expandafter\pgfplots@loc@TMPa\expandafter[\pgfplots@loc@TMPc]{\pgfplots@loc@TMPd}%
	\fi
}%

\def\pgfplots@plot@handler@graphics@getnaturalsize{%
	\begingroup
	\setbox0=\hbox{%
		\pgfplots@invoke@pgfkeyscode{/pgfplots/plot graphics/lowlevel draw/.@cmd}{{}{}}%
	}%
	\pgf@x=\wd0
	\pgf@y=\ht0
	\ifdim\dp0>0pt
		\advance\pgf@y by\dp0
	\else
		\ifdim\dp0<0pt
			\advance\pgf@y by-\dp0
		\fi
	\fi
	\xdef\pgfplots@glob@TMPb{{\the\pgf@x}{\the\pgf@y}}%
	\endgroup
	\let\pgfmathresult=\pgfplots@glob@TMPb
}%

% legends for plot graphics should not use 'plot graphics' themselfes
% (for obvious reasons).
% This key handles that. Furthermore, it remembers the plot mark for
% the legend -- although no plot mark is allowed for plot graphics as
% such.
\pgfkeysdef{/pgfplots/plot graphics/@prepare legend}{%
	\pgfplots@gettikzinternal@keyval{mark}{tikz@plot@mark}{}%
	%
	\pgfplots@getcurrent@plothandler\pgfplots@basiclevel@plothandler
	\t@pgfplots@tokc=\expandafter{\pgfplots@basiclevel@plothandler}%
	%
	\edef\pgfplots@loc@TMPa{%
		\noexpand\pgfkeys{/pgfplots/every legend image post/.append code={%
				\noexpand\def\noexpand\tikz@plot@handler{\the\t@pgfplots@tokc}%
				\ifx\tikz@plot@mark\pgfutil@empty
				\else
					\noexpand\pgfkeysalso{/tikz/mark=\tikz@plot@mark}%
				\fi
			}%
		}%
	}%
	\pgfplots@loc@TMPa
}



% #1: a normalized coordinate stream.
%
% Output: a normalized coordinate stream in \pgfplotsglobalretval.
\def\pgfplots@apply@zbuffer#1{%
	\ifcase\pgfplotsplothandlermesh@zbuffer@choice\relax
		% none.
		\gdef\pgfplotsglobalretval{#1}%
	\or
		% reverse x seq: only for 'mesh'
		\if\pgfplots@meshmode n%
			\pgfplots@error{Sorry, `/pgfplots/z buffer=reverse x seq' can only be used for mesh/surf plots.}%
			\gdef\pgfplotsglobalretval{#1}%
		\else
			\pgfplotsautocompletemeshkeys
			\if\pgfplots@plot@mesh@ordering0%
				% ordering = rowwise -> scanline is cols!
				\pgfkeysgetvalue{/pgfplots/mesh/cols}\pgfplotsscanlinelength
				\pgfplots@apply@zbuffer@reversescanline{#1}%
			\else
				% ordering = colwise: scanline is rows!
				\pgfkeysgetvalue{/pgfplots/mesh/rows}\pgfplotsscanlinelength
				\pgfplots@apply@zbuffer@reversetransposed{#1}%
			\fi
		\fi
	\or
		% reverse y seq: only for 'mesh'
		\if\pgfplots@meshmode n%
			\pgfplots@error{Sorry, `/pgfplots/z buffer=reverse y seq' can only be used for mesh/surf plots.}%
			\gdef\pgfplotsglobalretval{#1}%
		\else
			\pgfplotsautocompletemeshkeys
			\if\pgfplots@plot@mesh@ordering0%
				% ordering = rowwise -> scanline is cols!
				\pgfkeysgetvalue{/pgfplots/mesh/cols}\pgfplotsscanlinelength
				\pgfplots@apply@zbuffer@reversetransposed{#1}%
			\else
				% ordering = colwise: scanline is rows!
				\pgfkeysgetvalue{/pgfplots/mesh/rows}\pgfplotsscanlinelength
				\pgfplots@apply@zbuffer@reversescanline{#1}%
			\fi
		\fi
	\or
		% reverse xy seq:
		\begingroup
		\def\pgfplots@coord@stream@start{%
			\pgfplotsprependlistXnewempty{reversed}%
		}%
		\def\pgfplots@coord@stream@coord{%
			\expandafter\pgfplotsprependlistXpushfront\expandafter{\pgfplots@coord@stream@foreach@NORMALIZED@curencoded@braced}\to{reversed}%
		}%
		\def\pgfplots@coord@stream@end{%
			\pgfplotsprependlistXlet\pgfplots@loc@TMPa={reversed}%
			\pgfplotsprependlistXnewempty{reversed}% clear it
			\global\let\pgfplotsglobalretval=\pgfplots@loc@TMPa
		}%
		\pgfplots@coord@stream@foreach@NORMALIZED{#1}%
		\endgroup
	\or
		% sort.
		\if\pgfplots@meshmode n%
			\begingroup
			\def\pgfplots@coord@stream@start{%
				\pgfplotsarraynewempty\pgfplots@zbuffer@local
				\pgfplotsarrayresize\pgfplots@zbuffer@local{\numcoords}%
				\c@pgfplots@scanlineindex=0
				\def\pgfplots@zbuffer@local@SETCUR####1{%
					\expandafter\pgfplotsarrayset\c@pgfplots@scanlineindex\of\pgfplots@zbuffer@local\to{####1}%
				}%
			}%
			\def\pgfplots@coord@stream@coord{%
				\expandafter\pgfplots@zbuffer@local@SETCUR\expandafter{\pgfplots@coord@stream@foreach@NORMALIZED@curencoded}%
				\advance\c@pgfplots@scanlineindex by1
			}%
			\def\pgfplots@coord@stream@end{%
				\ifnum\c@pgfplots@scanlineindex=\numcoords
				\else
					\pgfplotsarrayresize\pgfplots@zbuffer@local{\c@pgfplots@scanlineindex}%
				\fi
				\pgfkeyslet{/pgfplots/iflessthan/.@cmd}\pgfplots@apply@zbuffer@SORT@iflessthan
				\pgfkeysdef{/pgfplots/array/unscope pre}{%
					\pgfplotsapplistXnewempty{\pgfp@sortedlist}%
					\pgfplotsarrayforeachungrouped\pgfplots@zbuffer@local\as\curelem{%
						\expandafter\pgfplotsapplistXpushback\expandafter{\expandafter{\curelem}}\to{\pgfp@sortedlist}%
					}%
					\pgfplotsapplistXlet\pgfplots@loc@TMPa={\pgfp@sortedlist}%
					\global\let\pgfplotsglobalretval=\pgfplots@loc@TMPa
				}%
				\pgfkeysdef{/pgfplots/array/unscope post}{}%
				\pgfplotsarraysort\pgfplots@zbuffer@local
			}%
			\pgfplots@coord@stream@foreach@NORMALIZED{#1}%
			\endgroup
		\else
			% meshmode handles sort separately!
			\gdef\pgfplotsglobalretval{#1}%
		\fi
	\or
		% z buffer=auto
		%
		% I can decide for each axis if coordinate reversal is
		% necessary.
		% Idea: check if axis side planes are on foreground or not (a
		% very simple task)! I
		% only need to know whether [xy] coordinates are sorted
		% ascending or descending. This information is already ready.
		%
		\if1\pgfplotsplothandlermesh@matrixinput
			% mesh input=lattice
			\begingroup
			\if+\pgfkeysvalueof{/pgfplots/x coord sorting}%
				\def\pgfplots@minmaxvalue@x{0}%
			\else
				\def\pgfplots@minmaxvalue@x{0}%
			\fi
			\if+\pgfkeysvalueof{/pgfplots/y coord sorting}%
				\def\pgfplots@minmaxvalue@y{0}%
			\else
				\def\pgfplots@minmaxvalue@y{1}%
			\fi
			\pgfplotsifaxissurfaceisforeground{\pgfplots@minmaxvalue@x vv}{%
				\def\pgfplots@reverse@x{1}%
			}{%
				\def\pgfplots@reverse@x{0}%
			}%
			\pgfplotsifaxissurfaceisforeground{v\pgfplots@minmaxvalue@y v}{%
				\def\pgfplots@reverse@y{1}%
			}{%
				\def\pgfplots@reverse@y{0}%
			}%
			\if1\pgfplots@reverse@x
				\if1\pgfplots@reverse@y
					\pgfkeys{/pgfplots/z buffer=reverse xy seq}%
				\else
					\pgfkeys{/pgfplots/z buffer=reverse x seq}%
				\fi
			\else
				\if1\pgfplots@reverse@y
					\pgfkeys{/pgfplots/z buffer=reverse y seq}%
				\else
					\pgfkeys{/pgfplots/z buffer=none}%
				\fi
			\fi
%\message{z buffer=auto mode chose  z buffer= \ifcase\pgfplotsplothandlermesh@zbuffer@choice NONE \or reverse x seq \or reverse y seq \or reverse xy seq \or sort\or default \fi. mesh ordering = \ifcase\pgfplots@plot@mesh@ordering x varies/rowwise\or y varies/colwise\fi}%
		% 'z buffer' is no longer 'auto' now:
			\pgfplots@apply@zbuffer{#1}%
			\pgfmath@smuggleone\pgfplotsplothandlermesh@zbuffer@choice
			\endgroup
		\else
			% mesh input=patches
			\ifpgfplots@threedim
				\if\pgfplots@meshmode n%
				\else
					\pgfkeys{/pgfplots/z buffer=sort}%
				\fi
			\else
				\pgfkeys{/pgfplots/z buffer=none}%
			\fi
			\gdef\pgfplotsglobalretval{#1}%
		\fi
	\or
		% z buffer=default.
		\if\pgfplots@meshmode n%
			% mesh mode deactivated!
			\gdef\pgfplotsglobalretval{#1}%
		\else
			% mesh=true
			\pgfkeysalso{/pgfplots/z buffer=auto}%
			\pgfplots@apply@zbuffer{#1}%
		\fi
	\fi
}%

% Defines \pgfplotsglobalretval (globally) to be a partial reversion of the
% (normalized) 2d coordinate sequence '#1'.
%
% In other words, the normalized coordinate sequence '#1' is visited
% linearly and while we go, each scanline is reversed. The result is
% collected into \pgfplotsglobalretval.
%
% This implements the 'z buffer=reverse x seq' feature for
% ordering=y varies.
%
% PRECONDITION:
% 	\pgfplotsscanlinelength contains the scanline length
% POSTCONDITION:
% 	\pgfplotsglobalretval contains the partial reversion.
\def\pgfplots@apply@zbuffer@reversescanline#1{%
	\begingroup
	\def\pgfplots@coord@stream@start{%
		\pgfplotsprependlistXnewempty{reversedscanline}%
		\c@pgfplots@scanlineindex=0
		\pgfplotsapplistXnewempty{\resultlist}%
	}%
	\def\pgfplots@coord@stream@coord{%
		\expandafter\pgfplotsprependlistXpushfront\expandafter{\pgfplots@coord@stream@foreach@NORMALIZED@curencoded@braced}\to{reversedscanline}%
		\advance\c@pgfplots@scanlineindex by1
		\ifnum\c@pgfplots@scanlineindex=\pgfplotsscanlinelength\relax
			\pgfplotsprependlistXlet\pgfplots@loc@TMPa={reversedscanline}%
			\expandafter\pgfplotsapplistXpushback\expandafter{\pgfplots@loc@TMPa}\to\resultlist
			\pgfplotsprependlistXnewempty{reversedscanline}%
			\c@pgfplots@scanlineindex=0
		\fi
	}%
	\def\pgfplots@coord@stream@end{%
		\pgfplotsprependlistXlet\pgfplots@loc@TMPa={reversedscanline}%
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\pgfplots@zbuffer@error
		\fi
		\pgfplotsapplistXlet\pgfplots@loc@TMPa={\resultlist}%
		\global\let\pgfplotsglobalretval=\pgfplots@loc@TMPa
	}%
	\pgfplots@coord@stream@foreach@NORMALIZED{#1}%
%\message{I have performed partial reversion of '#1' and got     '\pgfplotsglobalretval'!}%
	\endgroup
}%

% A very similar method of \pgfplots@apply@zbuffer@reversescanline,
% but this one keeps everything inside of each scanline in the
% original ordering, and reverses the ordering in which whole
% scanlines occur.
\def\pgfplots@apply@zbuffer@reversetransposed#1{%
	\begingroup
	\def\pgfplots@coord@stream@start{%
		\pgfplotsapplistXnewempty{\scanline}%
		\c@pgfplots@scanlineindex=0
		\pgfplotsprependlistXnewempty{resultlist}%
	}%
	\def\pgfplots@coord@stream@coord{%
		\expandafter\pgfplotsapplistXpushback\expandafter{\pgfplots@coord@stream@foreach@NORMALIZED@curencoded@braced}\to{\scanline}%
		\advance\c@pgfplots@scanlineindex by1
		\ifnum\c@pgfplots@scanlineindex=\pgfplotsscanlinelength\relax
			\pgfplotsapplistXlet\pgfplots@loc@TMPa={\scanline}%
			\expandafter\pgfplotsprependlistXpushfront\expandafter{\pgfplots@loc@TMPa}\to{resultlist}
			\pgfplotsapplistXnewempty{\scanline}%
			\c@pgfplots@scanlineindex=0
		\fi
	}%
	\def\pgfplots@coord@stream@end{%
		\pgfplotsapplistXlet\pgfplots@loc@TMPa={\scanline}%
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\pgfplots@zbuffer@error
		\fi
		\pgfplotsprependlistXlet\pgfplots@loc@TMPa={resultlist}%
		\global\let\pgfplotsglobalretval=\pgfplots@loc@TMPa
	}%
	\pgfplots@coord@stream@foreach@NORMALIZED{#1}%
%\message{I have performed partial reversion of '#1' and got     '\pgfplotsglobalretval'!}%
	\endgroup
}%
\def\pgfplots@zbuffer@error{%
	\pgfplots@error{An internal error occured during z buffer reorderings: the rows/cols where not balanced! I have rows= \pgfkeysvalueof{/pgfplots/mesh/rows}, cols=\pgfkeysvalueof{/pgfplots/mesh/cols}. If this happens to be wrong, you might want to provide rows and cols manually.}%
}

% A special '<' operation which returns true if the point coordinate
% '#1' is BEHIND #2 with respect to the current 3D view.
\def\pgfplots@apply@zbuffer@SORT@iflessthan#1#2#3#4\pgfeov{%
	\pgfplotsaxisdeserializedatapointfrom{#1}%
	\pgfplotsmathvectorfromstring{\pgfplots@current@point@x,\pgfplots@current@point@y,\pgfplots@current@point@z}{default}%
	\pgfplotsmathvectorscalarproduct{\pgfplots@view@dir@threedim}{\pgfplotsretval}{default}%
	\let\pgfplots@apply@zbuffer@SORT@iflessthan@a=\pgfplotsretval
	%
	\pgfplotsaxisdeserializedatapointfrom{#2}%
	\pgfplotsmathvectorfromstring{\pgfplots@current@point@x,\pgfplots@current@point@y,\pgfplots@current@point@z}{default}%
	\pgfplotsmathvectorscalarproduct{\pgfplots@view@dir@threedim}{\pgfplotsretval}{default}%
	\let\pgfplots@apply@zbuffer@SORT@iflessthan@b=\pgfplotsretval
	%
	\pgfplotscoordmath{default}{if less than}{\pgfplots@apply@zbuffer@SORT@iflessthan@b}{\pgfplots@apply@zbuffer@SORT@iflessthan@a}{%
		#3\relax
	}{%
		#4\relax
	}%
}%


% Defines \pgfmathresult to be the view depth of a three component
% vector. The third component will be used if and only if the boolean
% \ifpgfplots@curplot@threedim is true.
% The return value will be assigned in floating point.
%
% The arguments need to be numbers (will be parsed with
% \pgfmathfloatparsenumber).
% @see \pgfplotsmathviewdepthxyz
% DEPRECATED use \pgfplotsmathvectorviewdepth instead!
\def\pgfplotsmathfloatviewdepthxyz#1#2#3{%
	\begingroup
	\pgfmathfloatparsenumber{#1}\let\pgfplots@loc@TMPa=\pgfmathresult
	\pgfmathfloatparsenumber{#2}\let\pgfplots@loc@TMPb=\pgfmathresult
	\pgfmathfloatparsenumber{#3}\let\pgfplots@loc@TMPc=\pgfmathresult
	\edef\pgfplots@loc@TMPa{{\pgfplots@loc@TMPa}{\pgfplots@loc@TMPb}{\pgfplots@loc@TMPc}}%
	\expandafter\pgfplotsmathfloatviewdepthxyz@\pgfplots@loc@TMPa
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%

% #1: a 3d vector of the form x,y,z  in 'default' coordmath format
% defines \pgfplotsretval to the view depth
% of the point
%
% Use \pgfplotsmathvectorfromstring{x,y,z}{default}  to transform a
% vector into the requested format.
%
% Use \pgfplotscoordmath{default}{tofixed}{\pgfplotsretval} to
% transform the result into fixed point representation.
\def\pgfplotsmathvectorviewdepth#1{%
	\pgfplotsmathvectorscalarproduct{#1}{\pgfplots@view@dir@threedim}{default}%
}%

\def\pgfplotsmathfloatviewdepthxyz@#1#2#3{%
	\pgfplots@error{Sorry, you can't use \string\pgfplotsmathfloatviewdepthxyz\space in this context.}%
}%
\def\pgfplotsmathfloatviewdepthxyz@infigure#1#2#3{%
	\pgfplotsmathvectorfromstring{\pgfplots@view@dir@threedim}{float}%
	\pgfplotsmathvectorscalarproduct{#1,#2,#3}{\pgfplotsretval}{float}% FIXME : \pgfplots@view@dir@threedim might have a different math format!
	\let\pgfmathresult=\pgfplotsretval
}%

% Similar to \pgfplotsmathfloatviewdepthxyz, but this always relies on
% fixed point arithmetics.
% DEPRECATED use \pgfplotsmathvectorviewdepth instead
\def\pgfplotsmathviewdepthxyz#1#2#3{\pgfplotsmathviewdepthxyz@{#1}{#2}{#3}}
\def\pgfplotsmathviewdepthxyz@#1#2#3{%
	\pgfplots@error{Sorry, you can't use \string\pgfplotsmathviewdepthxyz\space in this context.}%
}
\def\pgfplotsmathviewdepthxyz@infigure#1#2#3{%
	\pgfplotsmathvectorfromstring{\pgfplots@view@dir@threedim@unitlength}{pgfbasic}%
	\pgfplotsmathvectorscalarproduct{#1,#2,#3}{\pgfplotsretval}{pgfbasic}% FIXME : \pgfplots@view@dir@threedim might have a different math format!
	\let\pgfmathresult=\pgfplotsretval
}%


% Evaluate shell commands.
%
% #1 = filename prefix for .sh and .out files (optional,
%      default is \jobname)
% #2 = shell command text
%
% Description:
%
% This command will write the command text to a file called
% #1.sh. Then it calls sh (using the \write18 mechanism) to
% execute the file and redirect the output to a file called
% #1.out.
% In contrast to pgfplotgnuplot the result has to be read
% from #1.out later using \pgfplotxyfile. (This allows
% using the function from within the plot table functions
% as well.)
%
% Example:
%
% \pgfplothandlerlineto
% \pgfshell[\jobname]{cat table.dat}
% \pgfplotxyfile{\jobname.out}

\pgfutil@IfUndefined{w@pgf@writea}{%
	\csname newwrite\endcsname\pgf@shellwrite
}{%
	\let\pgf@shellwrite=\w@pgf@writea
}
\newif\ifpgf@resample@shell

\def\pgfshell{\pgfutil@ifnextchar[{\pgf@shell}{\pgf@shell[\jobname]}}%}
\def\pgf@shell[#1]#2{%
  \pgf@resample@shelltrue%
  % Check, whether it is up-to-date
  \openin\pgfutil@inputcheck=#1.sh
  \ifeof\pgfutil@inputcheck%
  \else%
    \read\pgfutil@inputcheck to\pgf@shell@line%
    \edef\pgf@plot@code{#2\space}%
    \ifx\pgf@plot@code\pgf@shell@line%
      \openin\pgfutil@inputcheck=#1.out
      \ifeof\pgfutil@inputcheck%
      \else%
        \pgf@resample@shellfalse
      \fi%
    \fi%
  \fi
  \ifpgf@resample@shell%
    \immediate\openout\pgf@shellwrite=#1.sh
    \immediate\write\pgf@shellwrite{#2}%
    \immediate\closeout\pgf@shellwrite%
    \immediate\write18{sh #1.sh > #1.out}
  \fi%
}

pgfplotscore.code.tex
%--------------------------------------------
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2007/2008 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------

\def\pgfplotsset#{\pgfqkeys{/pgfplots}}

% This is *identical* to \pgfutil@IfUndefined . I copied it here
% because pgf up to and including version 2.10 does not contain it.
\def\pgfplotsutil@IfUndefined#1{%
  \begingroup\expandafter\expandafter\expandafter\endgroup
  \expandafter\ifx\csname#1\endcsname\relax
    \expandafter\pgfutil@firstoftwo
  \else
    \expandafter\pgfutil@secondoftwo
  \fi
}
\pgfplotsutil@IfUndefined{pgfutil@IfUndefined}{\let\pgfutil@IfUndefined=\pgfplotsutil@IfUndefined}{}


\def\pgfplots@log#1#2{\immediate\write-1{Package pgfplots info: #2}}%
\def\pgfplots@error#1{\PackageError{pgfplots}{#1}{}}%
\def\pgfplotstable@error@pkg#1{\PackageError{pgfplotstable}{#1}{}}%
% DO NOT USE THIS METHOD DIRECTLY: use \pgfplotswarning{<warning name>}<args>\pgfeov
\pgfplotsutil@IfUndefined{PackageWarning}{%
	\def\pgfplots@warning#1{\pgfplots@message{! Package pgfplots Warning:
#1}}%
}{%
	\def\pgfplots@warning#1{\PackageWarning{pgfplots}{#1}{}}%
}%

\def\pgfplots@message#1{%
	\immediate\write16{#1}%
}%

\pgfutil@IfUndefined{pgfkeys}{%
	\pgfplots@error{It seems your version of PGF/Tikz is older than 2.00. Unfortunately, pgfplots requires at least version 2.00 ... you may need to update your TeX-Distribution or install PGF manually, sorry}%
}{\relax}

% Throws exception `#1' with arguments `#2'.
%
% #1 : the exception name
% #2: all what comes after the exception name is considered to be argument
%    (or arguments) for the exception '#1'.
%    the \pgfeov is IMPORTANT as it delimits the argument.
%
% Note that all standard pgfplots exceptions provide a feature to
% exchange the error message text: define \pgfplotsexceptionmsg
% set a replacement.
\def\pgfplotsthrow#1#2\pgfeov{%
	\def\pgfkeyscurrentkey{/pgfplots/exception/#1}%
	\pgfkeysvalueof{/pgfplots/exception/#1/.@cmd}#2\pgfeov
}%
\let\pgfplotsthrow@orig=\pgfplotsthrow

% Generates warning `#1' with argument(s) `#2'.
%
% It works in exactly the same way as \pgfplotsthrow.
\def\pgfplotswarning#1#2\pgfeov{%
	\def\pgfkeyscurrentkey{/pgfplots/warning/#1}%
	\pgfkeysvalueof{/pgfplots/warning/#1/.@cmd}#2\pgfeov
}%

\def\pgfplotsthrow@warning#1{%
	\pgfplots@warning{#1}%
	\immediate\write-1{ [warning \pgfkeyscurrentkey]}%
}%

\def\pgfplots@assert@not@zero#1#2{%
	\ifdim#1=0sp %
		\pgfplotsthrow{invalid argument}{\pgfplots@loc@TMPa}{#2}\pgfeov
	\fi
}%

% A primitive try #1 catch #2 end  block.
%
% It tries code #1. If any exception occurs within, it suppresses the
% exception and tries to continue. It then invokes #2 as soon as it
% can.
%
% You can use \pgfplotsrethrow in #2.
%
% ATTENTION: this is a simple attempt to simulate error control. Don't
% rely on it too heavily! In the moment, I am not even sure if it can
% be nested (perhaps you need to introduce extra scopes since
% \pgfplotstry doesn't).
\long\def\pgfplotstry#1\catch#2\endpgfplotstry{%
	\global\let\pgfplotstry@exception\pgfutil@empty
	\def\pgfplotsthrow##1##2\pgfeov{\gdef\pgfplotstry@exception{{##1}{##2}}}%
	#1\relax%
	\let\pgfplotsthrow=\pgfplotsthrow@orig
	\ifx\pgfplotstry@exception\pgfutil@empty
	\else
		#2%
	\fi
	\global\let\pgfplotstry@exception\pgfutil@empty
}%
\def\pgfplotsrethrow{\expandafter\pgfplotsthrow\pgfplotstry@exception\pgfeov}%

\pgfkeys{
	% #1: the argument which should have been assigned.
	% #2: an error message. 
	/pgfplots/exception/invalid argument/.code 2 args={%
		\ifx\pgfplotsexceptionmsg\relax
			\pgfplots@error{#2}%
		\else
			\pgfplots@error{\pgfplotsexceptionmsg}%
		\fi
		\let#1=\pgfutil@empty
	},%
	% #1 : the layer name
	% #2 : additional context information (message)
	/pgfplots/exception/inactive layer/.code 2 args={%
		\ifx\pgfplotsexceptionmsg\relax
			\pgfplots@error{Sorry, the layer '#1' has not been activated but it is referenced in #2. Perhaps you misspelled it? Each referenced layer must be activated (expect for layer 'discard').}%
		\else
			\pgfplots@error{\pgfplotsexceptionmsg}%
		\fi
	},%
	% #1: the argument which should have been assigned.
	% #2: an error message. 
	/pgfplots/exception/no such element/.code 2 args={%
		\ifx\pgfplotsexceptionmsg\relax
			\pgfplots@error{#2}%
		\else
			\pgfplots@error{\pgfplotsexceptionmsg}%
		\fi
		\let#1=\pgfutil@empty
	},%
	/pgfplots/exception/invalid color component/.code 2 args={%
		\ifx\pgfplotsexceptionmsg\relax
			\pgfplots@error{#2}%
		\else
			\pgfplots@error{\pgfplotsexceptionmsg}%
		\fi
		\let#1=\pgfutil@empty
	},%
	% #1: an error message
	/pgfplots/exception/unsupported operation/.code={%
		\ifx\pgfplotsexceptionmsg\relax
			\pgfplots@error{#1}%
		\else
			\pgfplots@error{\pgfplotsexceptionmsg}%
		\fi
	},%
	% #1: the argument which should have been assigned.
	% #2: the file name
	% #3: the error message
	/pgfplots/exception/no such table file/.code args={#1#2#3}{%
		\ifx\pgfplotsexceptionmsg\relax
			\pgfplots@error{#3}%
		\else
			\pgfplots@error{\pgfplotsexceptionmsg}%
		\fi
		\let#1=\relax
	},
	%
	%
	%
	%
	% Generated if you say 'ymin=0' in a log axis.
	% #1: the user argument ('ymin')
	% #2: the offending value.
	/pgfplots/warning/illegal user argument in log axis/.code args={#1#2}{%
		\pgfplotsthrow@warning{Ignoring illegal input argument #1=#2: cannot apply log.}%
	},
	/pgfplots/warning/plot without coordinates/.code={%
		\pgfplotsthrow@warning{the current plot has no coordinates (or all have been filtered away)}%
	},
	/pgfplots/warning/log basis required/.code 2 args={%
		\pgfplotsthrow@warning{Some input argument (#2) explicitly relies on the log basis of #1 (which is e). Please verify that this is intended and set 'log basis #1=10' otherwise. This warning will be shown only once per document.}%
	},
	/pgfplots/warning/no such legend to name/.code={%
		\pgfplotsthrow@warning{There is no `legend to name=#1', sorry. I am skipping it}%
	},
	/pgfplots/warning/no such colorbar to name/.code={%
		\pgfplotsthrow@warning{There is no `colorbar to name=#1', sorry. I am skipping it}%
	},
	/pgfplots/warning/no such addplot label/.code={%
		\pgfplotsthrow@warning{There is no \string\addplot\space label `#1', sorry. I am skipping it}%
	},
	/pgfplots/warning/enlargelimits respects figure size failed/.code={%
		\pgfplotsthrow@warning{enlargelimits respects figure size=true: could not respect the prescribed width/height (\pgfplotsretval). The size and/or aspect ratio of your image will be different than expected. You can try to modify BOTH width and height.}%
	},
	% #1: the axis
	/pgfplots/warning/empty range cleared axis/.code={%
		\pgfplotsthrow@warning{You have an axis with empty range (in direction #1). Replacing it with a default range and clearing all plots.}%
	},
	/pgfplots/warning/approx empty range enlarged/.code args={#1#2#3}{%
		\pgfplotsthrow@warning{Axis range for axis #1 is approximately empty; enlarging it (it is [#2:#3])}%
	},
	/pgfplots/warning/lossy colormap rgb conversion/.code 2 args={%
		\pgfplotsthrow@warning{I am about to convert colormap '#1' from #2\space to rgb (which might be lossy). Perhaps the choice 'colorbar sampled={surf,shader=interp}' yields better results since it supports #2.}%
	},
	/pgfplots/warning/colorbar uninitialised/.code={%
		\pgfplotsthrow@warning{Sorry, the colorbar is uninitialised - your axis has no color data. Consider using 'point meta=f(x)' or something like that. I am using a color range of [0,1] for the colorbar.}%
	},
	/pgfplots/warning/colorbar CMYK unsupported/.code={%
		\pgfplotsthrow@warning{colorbar remark: The colormap '#1' has a CMYK colorspace which is not (yet) supported by PGF. I switched colorbar styles automatically to the visually equivalent 'colorbar sampled={surf,shader=interp}' to generate a proper CMYK colorbar. This has less support in some previewers. Use \string\pgfplotscolorbarCMYKworkaroundfalse\space to disable this improvement. [This message won't be replicated for '#1']}%
	},
	/pgfplots/warning/ticklabel anchor undetermined/.code args={#1#2#3#4}{%
		\pgfplotsthrow@warning{the ticklabel anchor cannot be determined, the normal vector -(#2) and the unit #1 vector (#3) are almost parallel (abs(cos(angle)) = #4)!}%
	},
	/pgfplots/warning/point meta unbounded/.code 2 args={%
		\pgfplotsthrow@warning{The per point meta data `#1' (#2) (and probably others as well) is unbounded - using the minimum value instead.}%
	},
	/pgfplots/warning/gnuplot -V impossible/.code={%
		\pgfplotsthrow@warning{Sorry, I could not determine 'gnuplot -V' to check whether gnuplot and logscale writes results in log() or not. Please set `/pgfplots/gnuplot writes logscale=true|false' manually.}%
	},
	/pgfplots/warning/gnuplot -V format unknown/.code={%
		\pgfplotsthrow@warning{Sorry, I can't reliably check which version of gnuplot is available. I guess it is gnuplot < 4.4. Please set `/pgfplots/gnuplot writes logscale=true|false' manually if anything fails.}%
	},
	/pgfplots/warning/plot3 graphics compatibility mode/.code={%
		\pgfplotsthrow@warning{plot3 graphics is running in backwards compatibility mode. %
					Use \string\pgfplotsset{compat=1.6} or higher to benefit from upgraded scaling capabilites.}%
	},
	/pgfplots/warning/plot3 graphics too few inner anchors/.code={%
		\pgfplotsthrow@warning{plot graphics in 3D axis has just two inner anchors (those with '(x,y,z)=>(imgx,imgy)'). You should provide a third one such that I can check for correct scaling.}%
	},
	/pgfplots/warning/scatter classes no such class/.code={%
		\pgfplotsthrow@warning{scatter/classes: can't find class for '#1'!? Please make sure you have specified 'scatter src=explicit symbolic'. Ignoring class '#1' (this message will not come again).}%
	},
	/pgfplots/warning/interior colormap inefficient/.code={%
		\pgfplotsthrow@warning{the combination 'shader=interp,interior colormap name' is inefficient (it uses 'shader=faceted interp,faceted color=none') and may slow down the *display* of your document}%
	},
	/pgfplots/warning/matrix delinearize uses sqrt/.code args={#1#2#3#4}{%
		\pgfplotsthrow@warning{%
									mesh processing did not find '[mesh/rows=<N>]' or '[mesh/cols=<N>]'. 
									Assuming [mesh/rows=#1,mesh/cols=#2] 
									as sqrt(num points) = sqrt(#3) [ = #4].}%
	},
	/pgfplots/warning/matrix check/.code args={#1#2#3#4#5}{%
		#1{the arguments of [mesh/rows=#2,mesh/cols=#3] assume  #5\space points, but I got actually N = #4\space points! The data matrix appears to be incomplete or overcomplete!? [Use mesh/check=false to disable this message]}%
	},
	/pgfplots/warning/tick computation failed/.code 2 args={%
		\pgfplotsthrow@warning{Tick computation for direction #1 failed; there are always too few tick labels (try min ticks has already been advanced to #2)}%
	},
	/pgfplots/warning/scale uniformly unsupported/.code={%
		\pgfplotsthrow@warning{Sorry, 'scale uniformly' failed because its actual implementation works only if y_x = 0 and x_y = 0 (for 2d axes) or if z_x = 0 (for 3d axes). The result will not fill the prescribed dimensions. Falling back to 'scale uniformly strategy=units only. (use scale uniformly warning=false to disable this warning)}%
	},
	/pgfplots/warning/axis equal incompatible change/.code={%
		\pgfplotsthrow@warning{the content of your 3d axis has changed compared to previous versions of pgfplots. please review it. ^^J   %
		[continued]   explanation: you have a 3d axis with 'axis equal' and/or 'unit vector ratio' which has (probably) been optimized for an older version of pgfplots. any version older than 1.6 produced wrong output.^^J   %
	[continued]	  to remove this warning, write \string\pgfplotsset{compat=1.6} (or newer) in your preamble (may change all figures in your document) or by adding that to the affected axis.}%
	},
	/pgfplots/warning/unit vector ratio axis undetermined/.code={%
		\pgfplotsthrow@warning{The algorithm to implement 'unit vector ratio' failed! It could not determine the axis which shall be scaled and decided to use 'unit vector ratio axis=#1'.}%
	},
	/pgfplots/warning/linear system singular/.code={%
		\pgfplotsthrow@warning{Linear system is singular up to machine precision! Continuing with small threshold.}%
	},
	/pgfplots/warning/center lines upgrade required/.code={%
		\pgfplotsthrow@warning{Please use '\string\pgfplotsset{compat=1.8}' to enable correct label placement for 3d axes (at least compat/labels=1.8).}%
	},
	/pgfplots/warning/empty column name/.code 2 args={%
		\pgfplotsthrow@warning{Table '#1' has an empty column name; replacing it by '#2'}%
	},
}
\let\pgfplotsexceptionmsg=\relax

\def\pgfplots@EOI{\pgfplots@EOI}%

\newif\ifpgfplots@loc@tmp
\newtoks\t@pgfplots@toka
\newtoks\t@pgfplots@tokb
\newtoks\t@pgfplots@tokc
\newdimen\pgfplots@tmpa
\newcount\c@pgfplots@coordindex
\newcount\c@pgfplots@scanlineindex
\pgfutil@IfUndefined{r@pgf@reada}{%
	\csname newread\endcsname\r@pgfplots@reada
}{%
	\let\r@pgfplots@reada=\r@pgf@reada
}

% use these macros for GLOBAL temporary assignments.
% you can NEVER rely on their values unless you know exactly what you are doing.
\gdef\pgfplots@glob@TMPa{}%
\gdef\pgfplots@glob@TMPb{}%
\gdef\pgfplots@glob@TMPc{}%

% use these macros for LOCAL temporary assigments.
% you can NEVER rely on their values unless you know exactly what you are doing.
\def\pgfplots@loc@TMPa{}%
\def\pgfplots@loc@TMPb{}%
\def\pgfplots@loc@TMPc{}%


% Invokes code #2 if file '#1' exists and #3 if not.
\long\def\pgfplots@iffileexists#1#2#3{%
	\openin\r@pgfplots@reada=#1
	\ifeof\r@pgfplots@reada
		#3\relax
	\else
		\closein\r@pgfplots@reada
		#2\relax
	\fi
}
\let\pgfplotsiffileexists=\pgfplots@iffileexists

\pgfutil@ifundefined{pgfplots@texdist@protect}{%
	\def\pgfplots@texdist@protect{}%
}{}

\input pgfplotssysgeneric.code.tex
\endinput

pgfplotsdeque.code.tex
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% This is a helper package with an elementary double-ended-queue
% (deque) datastructure,
% featuring O(1) index access and O(N) creation, deletion, copy.
%
% The following macros are supplied:
%
% \pgfplotsdequenewempty
% \pgfplotsdequecopy
% \pgfplotsdequepushback
% \pgfplotsdequepopfront
% \pgfplotsdequecheckempty
% \pgfplotsdequeforeach
%
% Copyright 2007/2008 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% IMPLEMENTATION NOTES:
% I allocate an array which provides storage capacity and two pointers
% (indices) into that array.
%
% The deque is stored as
% - an array: \csname pgfpldq@<name>\endcsname
% - the pointers:
%   \csname pgfpldq@<name>@beg\endcsname
%   \csname pgfpldq@<name>@end\endcsname (one after the end)
%
% ATTENTION: <name> may NOT be a control sequence! 
%            this is in contrast to my other container structures.


% Allocates a new, empty deque #1.
%
% #1 the name of a deque (NO control sequence!)
% #2 is an integer denoting the maximum capacity. For now, this
% capacity is fixed afterwards and denotes the maximum number of
% entries.
\def\pgfplotsdequenewempty#1{%
	\pgfutil@ifnextchar\capacity{%
		\pgfplotsdequenewempty@{#1}%
	}{%
		\pgfplots@error{Expected \string\capacity\{the capacity\} after \string\pgfplotsdequenewempty...}%
		\pgfplotsdequenewempty@{#1}\capacity{100}%
	}%
}%
\def\pgfplotsdequenewempty@#1\capacity#2{%
	\pgfplotsarrayresize{pgfpldq@#1}{#2}%
	\pgfutil@namedef{pgfpldq@#1@beg}{0}%
	\pgfutil@namedef{pgfpldq@#1@end}{0}%
}%

\def\pgfplotsdequecopy#1\to#2{%
	\pgfutil@namelet{pgfpldq@#1@beg}{pgfpldq@#2@beg}%
	\pgfutil@namelet{pgfpldq@#1@end}{pgfpldq@#2@end}%
	\pgfplotsarraycopy{pgfpldq@#1}\to{pgfpldq@#2}%
}%

\def\pgfplotsdequepushback#1\to#2{%
	\pgfplotsarrayset{\csname pgfpldq@#2@end\endcsname}\of{pgfpldq@#2}\to{#1}%
	\c@pgfplotsarray@tmp=\csname pgfpldq@#2@end\endcsname
	\advance\c@pgfplotsarray@tmp by1
	\ifnum\c@pgfplotsarray@tmp=\pgfplotsarraysizeof{pgfpldq@#2}
		\c@pgfplotsarray@tmp=0
	\fi
	\expandafter\edef\csname pgfpldq@#2@end\endcsname{\the\c@pgfplotsarray@tmp}%
	\pgfplotsdequeifempty{#2}{\pgfplots@error{Error: \string\pgfplotsdeque\space capacity has been reached - it was too small. Sorry, I didn't write auto-enlargement...}}{}%
}%

\def\pgfplotsdequepopfront#1\to#2{%
	\pgfplotsarrayselect{\csname pgfpldq@#1@beg\endcsname}\of{pgfpldq@#1}\to{#2}%
	\c@pgfplotsarray@tmp=\csname pgfpldq@#1@beg\endcsname
	\advance\c@pgfplotsarray@tmp by1
	\ifnum\c@pgfplotsarray@tmp=\pgfplotsarraysizeof{pgfpldq@#1}
		\c@pgfplotsarray@tmp=0
	\fi
	\expandafter\edef\csname pgfpldq@#1@beg\endcsname{\the\c@pgfplotsarray@tmp}%
}%

% invokes #2 if deque '#1' is empty and '#3' if it is not empty.
\def\pgfplotsdequeifempty#1#2#3{%
	\ifnum\csname pgfpldq@#1@beg\endcsname=\csname pgfpldq@#1@end\endcsname\relax
		#2%
	\else
		#3%
	\fi
}%


\long\def\pgfplotsdequeforeach#1\as#2#3{%
	\c@pgfplotsarray@tmp=\csname pgfpldq@#1@beg\endcsname
	\long\def\pgfplotsdequeforeach@next{\pgfplotsdequeforeach@iter{#1}{#2}{#3}}%
	\pgfplotsdequeforeach@next
}%
\long\def\pgfplotsdequeforeach@iter#1#2#3{%
	\ifnum\c@pgfplotsarray@tmp=\csname pgfpldq@#1@end\endcsname
		\def\pgfplotsdequeforeach@next{}%
	\else
		\pgfplotsarrayselect\c@pgfplotsarray@tmp\of pgfpldq@#1\to#2%
		\edef\pgfplotsdequeforeach@{\the\c@pgfplotsarray@tmp}%
		#3\relax
		\c@pgfplotsarray@tmp=\pgfplotsdequeforeach@
		\advance\c@pgfplotsarray@tmp by1
		\ifnum\c@pgfplotsarray@tmp=\pgfplotsarraysizeof{pgfpldq@#1}
			\c@pgfplotsarray@tmp=0
		\fi
	\fi
	\pgfplotsdequeforeach@next
}%

pgfplots.errorbars.code.tex
%--------------------------------------------
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2007-2013 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------


% the \addplot commands assign
%   \pgfplots@current@point@error@x@plus
%   \pgfplots@current@point@error@x@minus
%   \pgfplots@current@point@error@y@plus
%   \pgfplots@current@point@error@y@minus
%   \pgfplots@current@point@error@z@plus
%   \pgfplots@current@point@error@z@minus
%
% the error bar processing takes these values as input, adds them to
% the current coordinates where applicable and according the the error
% bar configuration and overwrites these macros.
%   
% Then, these values are registered as "visualization depends on",
% i.e. they will be available for every visualization phase.
%
% The visualization phase, in turn, expects these values. More
% precisely, a separate visualization phase called
% \pgfplotsaxis@visphase@name@errorbars is started. This installs the
% plot handler \pgfplots@errorbars@plot@handler and does the same job
% as it would for normal plot handlers.
%
\def\pgfplots@errorbars@survey@begin{%
	%
	\pgfplots@errorbars@prepare@value@serialization
	%
	% Now, prepare the coordinate processing for errorbars:
	\pgfplots@PREPARE@errorbar@processing@in@dir x%
	\pgfplots@PREPARE@errorbar@processing@in@dir y%
	\ifpgfplots@curplot@threedim
		\pgfplots@PREPARE@errorbar@processing@in@dir z%
	\else
		\let\pgfplots@PREPARE@errorbar@process@z=\relax
	\fi
}

\def\pgfplots@errorbars@survey@end{%
	\pgfplots@streamerrorbarend
}%

\def\pgfplots@errorbars@survey@point{%
	% This thing gets the 'current@point@...' context,
	% that means 
	% \pgfplots@current@point@[xy]
	% \pgfplots@current@point@[xy]@error
	% \pgfplots@current@point@[xy]@unfiltered
	\pgfplots@PREPARE@errorbar@process@x%
	\pgfplots@PREPARE@errorbar@process@y%
	\pgfplots@PREPARE@errorbar@process@z%
}

\def\pgfplots@errorbars@visphase@begin{%
	\pgfplots@errorbars@prepare@value@serialization
}

\def\pgfplots@errorbars@visphase@end{%
}%

\def\pgfplots@errorbars@visphase@point{%
}%

\def\pgfplots@errorbars@prepare@value@serialization{%
	\if0\pgfplots@errorbars@xdirection
	\else
		\pgfplotsset{%
			visualization depends on=value \pgfplots@current@point@error@x@plus\as\pgfplots@current@point@error@x@plus,
			visualization depends on=value \pgfplots@current@point@error@x@minus\as\pgfplots@current@point@error@x@minus,
		}%
	\fi
	\if0\pgfplots@errorbars@ydirection
	\else
		\pgfplotsset{%
			visualization depends on=value \pgfplots@current@point@error@y@plus\as\pgfplots@current@point@error@y@plus,
			visualization depends on=value \pgfplots@current@point@error@y@minus\as\pgfplots@current@point@error@y@minus,
		}%
	\fi
	\ifpgfplots@curplot@threedim
		\if0\pgfplots@errorbars@zdirection
		\else
			\pgfplotsset{%
				visualization depends on=value \pgfplots@current@point@error@z@plus\as\pgfplots@current@point@error@z@plus,
				visualization depends on=value \pgfplots@current@point@error@z@minus\as\pgfplots@current@point@error@z@minus,
			}%
		\fi
	\fi
}%

% Prepares a macro \pgfplots@PREPARE@process@errorbar@for@dir##1
% which can then be used to process error bars. The macro will be
% \relax if error bars are disabled for #1.
%
% #1: either x, y or z.
%
% POSTCONDITION:
%   the macro \pgfplots@PREPARE@errorbar@process@#1 will be defined.
%   It is supposed to be used inside of the pgfplots streaming methods
%   and depends on the arguments
% 		\pgfplots@current@point@[xyz]
%		\pgfplots@current@point@[xyz]@unfiltered
%		\pgfplots@current@point@[xyz]@error
%	The '@unfilterered' arguments are needed for log plots. I do not
%	want to compute exp(current@point@[xyz]) again.
\def\pgfplots@PREPARE@errorbar@processing@in@dir#1{%
	\pgfplots@PREPARE@errorbar@processing@in@dir@reset#1%
	%
	\if0\csname pgfplots@errorbars@#1direction\endcsname
		% no error bars. Ok. Do nothing here.
		\expandafter\let\csname pgfplots@PREPARE@errorbar@process@#1\endcsname=\relax
	\else
		%
		% The routine which is invoked for every reported input
		% coordinate is \pgfplots@process@errorbar@for.
		%
		% This here prepares its helper macros for direction '#1':
		%
		% More precisely, it prepared 
		%
		% ##1 is either '+' or '-':
		% \pgfplots@PREPARE@errorbar@process@x@##1
		% \pgfplots@PREPARE@errorbar@process@y@##1
		% \pgfplots@PREPARE@errorbar@process@z@##1
		%
		\pgfplots@if{pgfplots@#1islinear}{%
			\ifcase\csname pgfplots@errorbars@#1mode\endcsname\relax
				% fixed absolute error.
				\pgfplotscoordmath{#1}{parsenumber}{\csname pgfplots@errorbars@#1fixed\endcsname}%
				\expandafter\let\csname pgfplots@error@coord@#1\endcsname=\pgfmathresult
				\expandafter\def\csname pgfplots@PREPARE@errorbar@process@#1@\endcsname##1{%
					\if +##1%
						\def\pgfplots@loc@TMPb{add}%
					\else
						\def\pgfplots@loc@TMPb{subtract}%
					\fi
					\pgfplotscoordmath{#1}{op}{\pgfplots@loc@TMPb}{%
						{\csname pgfplots@current@point@#1\endcsname}%
						{\csname pgfplots@error@coord@#1\endcsname}%
					}%
					\let\pgfplots@error@coord=\pgfmathresult
					\pgfplots@PREPARE@errorbar@stream@it@#1##1%
				}%
			\or% fixed relative error:
				\pgfplotscoordmath{#1}{parsenumber}{\csname pgfplots@errorbars@#1rel\endcsname}%
				\let\pgfplots@loc@TMPb=\pgfmathresult
				%
				% +1:
				\pgfplotscoordmath{#1}{parsenumber}{1}%
				\let\pgfplots@loc@TMPa=\pgfmathresult
				%
				% Prepare '1 + err':
				\pgfplotscoordmath{#1}{op}{add}{%
					{\pgfplots@loc@TMPa}%
					{\pgfplots@loc@TMPb}%
				}%
				\expandafter\let\csname pgfplots@error@coord@#1@+\endcsname=\pgfmathresult
				%
				% Prepare '1 - err':
				\pgfplotscoordmath{#1}{op}{subtract}{%
					{\pgfplots@loc@TMPa}%
					{\pgfplots@loc@TMPb}%
				}%
				\expandafter\let\csname pgfplots@error@coord@#1@-\endcsname=\pgfmathresult
				%
				\expandafter\def\csname pgfplots@PREPARE@errorbar@process@#1@\endcsname##1{%
					\pgfplotscoordmath{#1}{op}{multiply}{%
						{\csname pgfplots@current@point@#1\endcsname}
						{\csname pgfplots@error@coord@#1@##1\endcsname}%
					}%
					\let\pgfplots@error@coord=\pgfmathresult
					\pgfplots@PREPARE@errorbar@stream@it@#1##1%
				}%
			\or% explicit absolute:
				\expandafter\def\csname pgfplots@PREPARE@errorbar@process@#1@\endcsname##1{%
					\edef\pgfplots@error@coord{\csname pgfplots@current@point@error@#1@\pgfplots@errorbars@plusminus##1\endcsname}%
					\ifx\pgfplots@error@coord\pgfutil@empty
						\pgfplots@PREPARE@errorbar@stream@it@empty#1##1%
					\else
						\pgfplotscoordmath{#1}{parsenumber}{\pgfplots@error@coord}%
						\pgfplotscoordmath{#1}{if is bounded}{\pgfmathresult}{%
							\let\pgfplots@error@coord=\pgfmathresult
							% remember result here - will be used in case
							% of '+' AND '-' error bars:
							%\expandafter\let\csname pgfplots@current@point@error@#1@\pgfplots@errorbars@plusminus##1\endcsname=\pgfmathresult
							\if +##1%
								\def\pgfplots@loc@TMPb{add}%
							\else
								\def\pgfplots@loc@TMPb{subtract}%
							\fi
							\pgfplotscoordmath{#1}{op}{\pgfplots@loc@TMPb}{%
								{\csname pgfplots@current@point@#1\endcsname}%
								{\pgfplots@error@coord}%
							}%
							\let\pgfplots@error@coord=\pgfmathresult
							\pgfplots@PREPARE@errorbar@stream@it@#1##1%
						}{%
							% input is unbounded. Skip it.
							\pgfplots@PREPARE@errorbar@stream@it@empty#1##1%
						}%
					\fi
				}%
			\or% explicit relative:
				\expandafter\def\csname pgfplots@PREPARE@errorbar@process@#1@\endcsname##1{%
					\edef\pgfplots@error@coord{\csname pgfplots@current@point@error@#1@\pgfplots@errorbars@plusminus##1\endcsname}%
					\ifx\pgfplots@error@coord\pgfutil@empty
						\pgfplots@PREPARE@errorbar@stream@it@empty#1##1%
					\else
						\pgfplotscoordmath{#1}{parsenumber}{\pgfplots@error@coord}%
						\pgfplotscoordmath{#1}{if is bounded}{\pgfmathresult}{%
							\let\pgfplots@error@coord=\pgfmathresult
							% compute ' 1 + value' or '1-value':
							\pgfplotscoordmath{#1}{one}%
							\if +##1%
								\def\pgfplots@loc@TMPb{add}%
							\else
								\def\pgfplots@loc@TMPb{subtract}%
							\fi
							\pgfplotscoordmath{#1}{op}{\pgfplots@loc@TMPb}{%
								{\pgfmathresult}%
								{\pgfplots@error@coord}%
							}%
							\let\pgfplots@error@coord=\pgfmathresult
							\pgfplotscoordmath{#1}{op}{multiply}{%
								{\csname pgfplots@current@point@#1\endcsname}
								{\pgfplots@error@coord}%
							}%
							\let\pgfplots@error@coord=\pgfmathresult
							\pgfplots@PREPARE@errorbar@stream@it@#1##1%
						}{%
							% input is unbounded. Skip it.
							\pgfplots@PREPARE@errorbar@stream@it@empty#1##1%
						}%
					\fi
				}%
			\fi
		}{%
			% LOGARITHMIC scaling. All errors are interpreted as 
			%   log(x +- e_x)
			% or
			%   log( x*(1+-e_x) )
			%
			% That means any input argument is
			% given in log base e and in fixed point.
			% Furthermore, we expect the '@unfiltered' keys to be
			% present (I don't want to apply 'exp' again!).
			%
			\ifcase\csname pgfplots@errorbars@#1mode\endcsname
				% fixed absolute, log( x +- e_x )
				%
				\pgfplotscoordmath{default}{parsenumber}{\csname pgfplots@errorbars@#1fixed\endcsname}%
				\expandafter\let\csname pgfplots@error@coord@#1\endcsname=\pgfmathresult
				\expandafter\def\csname pgfplots@PREPARE@errorbar@process@#1@\endcsname##1{%
					\pgfplotscoordmath{default}{parsenumber}{\csname pgfplots@current@point@#1@unfiltered\endcsname}%
					\let\pgfplots@loc@TMPa=\pgfmathresult
					\if +##1%
						\def\pgfplots@loc@op{add}%
					\else
						\def\pgfplots@loc@op{subtract}%
					\fi
					\pgfplotscoordmath{default}{op}{\pgfplots@loc@op}{%
						{\pgfplots@loc@TMPa}%
						{\csname pgfplots@error@coord@#1\endcsname}%
					}%
					\pgfplotscoordmath{default}{tostring}{\pgfmathresult}%
					\pgfplotscoordmath{#1}{log}{\pgfmathresult}%
					\let\pgfplots@error@coord=\pgfmathresult
					\pgfplots@PREPARE@errorbar@stream@it@#1##1%
				}%
			\or% fixed relative, log( x ( 1+-e_x ) ) = log(x) + log(1+-e_x)
				\pgfplotscoordmath{default}{parsenumber}{\csname pgfplots@errorbars@#1rel\endcsname}%
				\let\pgfplots@loc@TMPb=\pgfmathresult
				%
				% +1:
				\pgfplotscoordmath{default}{one}%
				\let\pgfplots@loc@TMPa=\pgfmathresult
				%
				% Prepare '1 + err':
				\pgfplotscoordmath{default}{op}{add}{{\pgfplots@loc@TMPa}{\pgfplots@loc@TMPb}}%
				\pgfplotscoordmath{default}{tostring}{\pgfmathresult}%
				\pgfplotscoordmath{#1}{log}{\pgfmathresult}%
				\pgfplotscoordmath{#1}{if is bounded}{\pgfmathresult}{%
				}{%
					% 1 + err <= 0  and log(1+err) is undefined:
					\pgfplotscoordmath{default}{tostring}{\pgfplots@loc@TMPb}%
					\pgfplots@error{Sorry, log(1 + \pgfmathresult) is undefined. Please provide a different argument for '/pgfplots/error bar/#1 fixed relative'.}%
					\let\pgfmathresult=\pgfutil@empty
				}%
				\expandafter\let\csname pgfplots@error@coord@#1@+\endcsname=\pgfmathresult
				%
				% Prepare '1 - err':
				\pgfplotscoordmath{default}{op}{subtract}{{\pgfplots@loc@TMPa}{\pgfplots@loc@TMPb}}%
				\pgfplotscoordmath{default}{tostring}{\pgfmathresult}%
				\pgfplotscoordmath{#1}{log}{\pgfmathresult}%
				\pgfplotscoordmath{#1}{if is bounded}{\pgfmathresult}{%
				}{%
					% 1 - err <= 0  and log(1+err) is undefined:
					\pgfplotscoordmath{default}{tostring}{\pgfplots@loc@TMPb}%
					\pgfplots@error{Sorry, log(1 - \pgfmathresult) (\pgfplots@loc@TMPa - \pgfplots@loc@TMPb) is undefined. Please provide a different argument for '/pgfplots/error bar/#1 fixed relative'.}%
					\let\pgfmathresult=\pgfutil@empty
				}%
				\expandafter\let\csname pgfplots@error@coord@#1@-\endcsname=\pgfmathresult
				%
				\expandafter\def\csname pgfplots@PREPARE@errorbar@process@#1@\endcsname##1{%
					\expandafter\ifx\csname pgfplots@current@point@#1@##1\endcsname\pgfutil@empty
						\pgfplots@PREPARE@errorbar@stream@it@empty#1##1%
					\else
						\pgfmath@basic@add@
							{\csname pgfplots@current@point@#1\endcsname}
							{\csname pgfplots@error@coord@#1@##1\endcsname}%
						\let\pgfplots@error@coord=\pgfmathresult
						\pgfplots@PREPARE@errorbar@stream@it@#1##1%
					\fi
				}%
			\or% explicit absolute
				% log( x +- e_x )
				\expandafter\def\csname pgfplots@PREPARE@errorbar@process@#1@\endcsname##1{%
					\edef\pgfplots@error@coord{\csname pgfplots@current@point@error@#1@\pgfplots@errorbars@plusminus##1\endcsname}%
					\ifx\pgfplots@error@coord\pgfutil@empty
						\pgfplots@PREPARE@errorbar@stream@it@empty#1##1%
					\else
						\pgfplotscoordmath{default}{parsenumber}{\pgfplots@error@coord}%
						\pgfplotscoordmath{default}{if is bounded}{\pgfmathresult}{%
							\let\pgfplots@error@coord=\pgfmathresult
							% remember result here - will be used in case
							% of '+' AND '-' error bars:
							%\expandafter\let\csname pgfplots@current@point@error@#1@\pgfplots@errorbars@plusminus##1\endcsname=\pgfmathresult
							\pgfplotscoordmath{default}{parsenumber}{\csname pgfplots@current@point@#1@unfiltered\endcsname}%
							\let\pgfplots@loc@TMPa=\pgfmathresult
							\if +##1%
								\def\pgfplots@loc@op{add}%
							\else
								\def\pgfplots@loc@op{subtract}%
							\fi
							\pgfplotscoordmath{default}{op}{\pgfplots@loc@op}{%
								{\pgfplots@loc@TMPa}%
								{\pgfplots@error@coord}%
							}%
							\pgfplotscoordmath{default}{tostring}{\pgfmathresult}%
							\pgfplotscoordmath{#1}{log}{\pgfmathresult}%
							\let\pgfplots@error@coord=\pgfmathresult
							\pgfplots@PREPARE@errorbar@stream@it@#1##1%
						}{%
							% input is unbounded. Skip it.
							\pgfplots@PREPARE@errorbar@stream@it@empty#1##1%
						}%
					\fi
				}%
				%
			\or% explicit relative:
				% log( x ( 1+-e_x ) ) = log(x) + log(1+-e_x)
				\expandafter\def\csname pgfplots@PREPARE@errorbar@process@#1@\endcsname##1{%
					\edef\pgfplots@error@coord{\csname pgfplots@current@point@error@#1@\pgfplots@errorbars@plusminus##1\endcsname}%
					\ifx\pgfplots@error@coord\pgfutil@empty
						\pgfplots@PREPARE@errorbar@stream@it@empty#1##1%
					\else
						\pgfplotscoordmath{default}{parsenumber}{\pgfplots@error@coord}%
						\pgfplotscoordmath{default}{if is bounded}{\pgfmathresult}{%
							\let\pgfplots@error@coord=\pgfmathresult
							% remember result here - will be used in case
							% of '+' AND '-' error bars:
							%\expandafter\let\csname pgfplots@current@point@error@#1@\pgfplots@errorbars@plusminus##1\endcsname=\pgfmathresult
							%
							\pgfplotscoordmath{default}{one}%
							\let\pgfplots@loc@TMPa=\pgfmathresult
							\if +##1%
								\def\pgfplots@loc@op{add}%
							\else
								\def\pgfplots@loc@op{subtract}%
							\fi
							\pgfplotscoordmath{default}{op}{\pgfplots@loc@op}{%
								{\pgfplots@loc@TMPa}%
								{\pgfplots@error@coord}%
							}%
							\pgfplotscoordmath{default}{tostring}{\pgfmathresult}%
							\pgfplotscoordmath{#1}{log}{\pgfmathresult}%
							\let\pgfplots@error@coord=\pgfmathresult
							\pgfplotscoordmath{#1}{if is bounded}{\pgfmathresult}{%
								\pgfplotscoordmath{#1}{op}{add}{%
									{\csname pgfplots@current@point@#1\endcsname}
									{\pgfplots@error@coord}%
								}%
								\let\pgfplots@error@coord=\pgfmathresult
								\pgfplots@PREPARE@errorbar@stream@it@#1##1%
							}{%
								% -> log( <= 0 ) -> do nothing.
								\pgfplots@PREPARE@errorbar@stream@it@empty#1##1%
							}%
						}{%
							% input is unbounded - do nothing.
							\pgfplots@PREPARE@errorbar@stream@it@empty#1##1%
						}%
					\fi
				}%
				%
			\fi
		}%
		\ifcase\csname pgfplots@errorbars@#1direction\endcsname
			% none
		\or
			% plus
			\expandafter\edef\csname pgfplots@PREPARE@errorbar@process@#1\endcsname{%
				\expandafter\noexpand\csname pgfplots@PREPARE@errorbar@process@#1@\endcsname+%
			}%
		\or
			% minus
			\expandafter\edef\csname pgfplots@PREPARE@errorbar@process@#1\endcsname{%
				\expandafter\noexpand\csname pgfplots@PREPARE@errorbar@process@#1@\endcsname-%
			}%
		\or
			% both
			\expandafter\edef\csname pgfplots@PREPARE@errorbar@process@#1\endcsname{%
				\expandafter\noexpand\csname pgfplots@PREPARE@errorbar@process@#1@\endcsname+%
				\expandafter\noexpand\csname pgfplots@PREPARE@errorbar@process@#1@\endcsname-%
			}%
		\fi
	\fi
}

\def\pgfplots@PREPARE@errorbar@processing@in@dir@reset#1{%
	\expandafter\let\csname pgfplots@current@point@error@#1@plus\endcsname=\pgfutil@empty
	\expandafter\let\csname pgfplots@current@point@error@#1@minus\endcsname=\pgfutil@empty
}%

% #1: one of x,y, or z
% #2: either '+' or '-', denotes the direction of the error
% bar
%
% PRECONDITION: \pgfplots@error@coord contains the value which is to
% be stored as \pgfplots@current@point@error@#1@plus or
% \pgfplots@current@point@error@#1@minus
%
% POSTCONDITION: limits updated and
% \pgfplots@current@point@error@#1@plus or
% \pgfplots@current@point@error@#1@minus
% is defined.
\def\pgfplots@PREPARE@errorbar@stream@it@#1#2{%
	\ifx\pgfplots@error@coord\pgfutil@empty
	\else
		\expandafter\let\expandafter\pgfplots@current@point@@old\csname pgfplots@current@point@#1\endcsname
		\expandafter\let\csname pgfplots@current@point@#1\endcsname=\pgfplots@error@coord
		\pgfplotsaxisupdatelimitsforcoordinate\pgfplots@current@point@x\pgfplots@current@point@y\pgfplots@current@point@z
		\expandafter\let\csname pgfplots@current@point@#1\endcsname=\pgfplots@current@point@@old
	\fi
	%
	% ... and remember what we need! This value will be stored as
	% "visualization depends on"
	\expandafter\let\csname pgfplots@current@point@error@#1@\pgfplots@errorbars@plusminus#2\endcsname=\pgfplots@error@coord
}%

\def\pgfplots@PREPARE@errorbar@stream@it@empty#1#2{%
	% ... and remember what we need! This value will be stored as
	% "visualization depends on"
	\expandafter\let\csname pgfplots@current@point@error@#1@\pgfplots@errorbars@plusminus#2\endcsname=\pgfutil@empty
}

\def\pgfplots@errorbars@plusminus#1{%
	\if#1+%
		plus%
	\else
		minus%
	\fi
}%

% A dummy plot handler which is used in a special visualization phase
% for error bars.
\def\pgfplots@errorbars@plot@handler{%
	\gdef\pgf@plotstreamstart{%
		\pgfplots@streamerrorbar@directdraw
		\global\let\pgf@plotstreampoint=\pgfplots@errorbars@plot@handler@point
		\global\let\pgf@plotstreamspecial=\relax
		\global\let\pgf@plotstreamend=\pgfplots@streamerrorbarend
		\pgfplots@streamerrorbarstart
	}%
}%

\def\pgfplots@errorbars@plot@handler@point#1{%
	\pgf@process{#1}%
	\edef\pgfplots@errorbars@src{(\the\pgf@x,\the\pgf@y)}%
	%
	% we want to allow scatter plots to vary depending on 'point
	% meta'. This here does not hurt:
	\pgfplotsaxisvisphasetransformpointmetaifany
	%
	\pgfplots@errorbars@plot@handler@point@dir x%
	\pgfplots@errorbars@plot@handler@point@dir y%
	\ifpgfplots@curplot@threedim
		\pgfplots@errorbars@plot@handler@point@dir z%
	\fi
}

% #1: one of x,y, or z
% #2: the error bar value in dir #1
% output: \pgfplots@errorbars@trg in the form (<x>,<y>,<z>)
\def\pgfplots@errorbars@to@pt#1#2{%
	\begingroup
	\expandafter\let\csname pgfplots@current@point@#1\endcsname=#2%
	\ifpgfplots@curplot@threedim
		\edef\pgfplotsretval{(\pgfplots@current@point@x,\pgfplots@current@point@y,\pgfplots@current@point@z)}%
	\else
		\edef\pgfplotsretval{(\pgfplots@current@point@x,\pgfplots@current@point@y)}%
	\fi
	\global\let\pgfplots@errorbars@trg=\pgfplotsretval
	\endgroup
}%

% #1: a <\macro> containing the value 
% #2: either x,y, or z
\def\pgfplots@errorbars@plot@handler@point@dir@@#1#2{%
	\ifx#1\pgfutil@empty
	\else
		\pgfplotsaxisvisphasetransformcoordinateentry{#2}{#1}%
		\pgfplots@errorbars@to@pt{#2}{\pgfmathresult}%
		\pgfplots@streamerrorbarcoords{\pgfplots@errorbars@src}{\pgfplots@errorbars@trg}%
	\fi
}%

\def\pgfplots@errorbars@plot@handler@point@dir#1{%
	\ifcase\csname pgfplots@errorbars@#1direction\endcsname
		% none
	\or
		% plus
		\expandafter\pgfplots@errorbars@plot@handler@point@dir@@\csname pgfplots@current@point@error@#1@plus\endcsname#1%
	\or
		% minus
		\expandafter\pgfplots@errorbars@plot@handler@point@dir@@\csname pgfplots@current@point@error@#1@minus\endcsname#1%
	\or
		% both
		\expandafter\pgfplots@errorbars@plot@handler@point@dir@@\csname pgfplots@current@point@error@#1@plus\endcsname#1%
		\expandafter\pgfplots@errorbars@plot@handler@point@dir@@\csname pgfplots@current@point@error@#1@minus\endcsname#1%
	\fi
}%

\def\pgfplots@streamerrorbarstart{%
}%
\def\pgfplots@streamerrorbarend{%
}%
\def\pgfplots@streamerrorbarcoords#1#2{%
}%

\def\pgfplots@streamerrorbar@directdraw{%
	\def\pgfplots@streamerrorbarstart{}%
	\def\pgfplots@streamerrorbarend{}%
	\def\pgfplots@streamerrorbarcoords##1##2{%
		\pgfplots@errorbar@draw{##1}{##2}%
	}%
}
	
% This thing here shall draw all error bar commands listed in '#2'.
%
% It will be invoked when any plotting commands take effect (that
% means all limits are computed; the axis has been drawn,
% transformations are set up...)
\def\pgfplots@errorbars@finishwithstyleoptions[#1]#2{%
	\scope[/pgfplots/.cd,#1,/pgfplots/every error bar]% it uses the /pgfplots/.unknown handler
	#2%
	\endscope
}

\def\pgfplots@errorbar@draw#1#2{%
	\begingroup
	\pgfplots@restorepgfpoint
	\pgfkeysvalueof{/pgfplots/error bars/draw error bar/.@cmd}{#1}{#2}\pgfeov%
	\endgroup
}%

\def\pgfplotsaxis@visphase@name@errorbars{errorbars}

\expandafter\def\csname pgfplots@visphase@\pgfplotsaxis@visphase@name@errorbars\endcsname{%
	\pgfplots@errorbars@finishwithstyleoptions[]{%
		\let\tikz@plot@handler=\pgfplots@errorbars@plot@handler
		\expandafter\pgfplots@coord@stream@finalize@storedcoords@START\pgfplots@stored@current@data\pgfplots@EOI
	}%
}%

\endinput

pgfplotslibrary.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.
% Comment: This file has been modified to utilize libraries in the pgfplots package.
% Edited by Nick Papior Andersen



% Loading further libraries

% Include a library file.
%
% #1 = List of names of library file.
%  
% Description:
%
% This command includes a list of pgfplots library files. For each file X in the
% list, the file tikzlibrarypgfplots.X.code.tex is included, provided this has
% not been done earlier. 
%
% For the convenience of Context users, both round and square brackets
% are possible for the argument.
%
% Example:
%
% \usepgfplotslibrary{units}
% \usepgfplotslibrary[units,dateplot]

\def\usepgfplotslibrary{\pgfutil@ifnextchar[{\use@pgfplotslibrary}{\use@@pgfplotslibrary}}%}
\def\use@pgfplotslibrary[#1]{\use@@pgfplotslibrary{#1}}
\def\use@@pgfplotslibrary#1{%
  \edef\pgf@list{#1}%
  \pgfutil@for\pgf@temp:=\pgf@list\do{%
	\expandafter\pgfkeys@spdef\expandafter\pgf@temp\expandafter{\pgf@temp}%
	\ifx\pgf@temp\pgfutil@empty
	\else
		\expandafter\ifx\csname pgfp@library@\pgf@temp @loaded\endcsname\relax%
		  \expandafter\global\expandafter\let\csname pgfp@library@\pgf@temp @loaded\endcsname=\pgfutil@empty%
		  \expandafter\edef\csname tikz@library@#1@atcode\endcsname{\the\catcode`\@}
		  \expandafter\edef\csname tikz@library@#1@barcode\endcsname{\the\catcode`\|}
		  \catcode`\@=11
		  \catcode`\|=12
		  \pgfplots@iffileexists{tikzlibrarypgfplots.\pgf@temp.code.tex}{%
		  \input tikzlibrarypgfplots.\pgf@temp.code.tex}{%
		  \input pgflibrarypgfplots.\pgf@temp.code.tex}%
		  \catcode`\@=\csname tikz@library@#1@atcode\endcsname
		  \catcode`\|=\csname tikz@library@#1@barcode\endcsname
		\fi%
	\fi
  }%
}


% Default loaded libraries:
% Currently none

pgfplotsliststructure.code.tex
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% This is a helper package with an elementary list datastructure.
%
% Its implementation is based on Knuth's list macros in "The TeXbook".
%
% It features a convenient set of list macros, but it is not fast.
% In fact, every elementary operation requires time O(N), so working 
% with this list easily leads to O(N^2) runtime.
%
% The following macros are supplied:
%
% \pgfplotslistnewempty
% \pgfplotslistnew
% \pgfplotslistcopy
% \pgfplotslistpopfront
% \pgfplotslistfront
% \pgfplotslistpushback
% \pgfplotslistpushfront
% \pgfplotslistsize
% \pgfplotslistselect
% \pgfplotslistset
% \pgfplotslistcheckempty
% \pgfplotslistforeach
%
% @see \pgfplotsapplist a "real" list with O(1) pushback, but limited application.
% @see \pgfplotsapplistX a preasymptotical fast list to accumulate elements.
% @see \pgfplotsapplistXX an optimized version of \pgfplotsapplistX.
%
% Copyright 2007/2008 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\newif\ifpgfplotslistempty

% Low-level IMPLEMENTATION NOTE 
% the list is stored in the form 
% '\pgfpl@@{<first>}\pgfpl@@{<second>}\pgfpl@@{<third>}....\pgfpl@@{<last>}'

\newif\ifpgfplots@loop@CONTINUE
\newif\ifpgfplotslist@is@backslash@terminated

% Creates a new, empty list.
\long\def\pgfplotslistnewempty#1{\let#1=\pgfutil@empty}

% Creates a new list with an abirtrary number of elements.
% Arguments:
% #1: the list's name (a macro name)
% #2: the elements in the form 
%     first\\second\\third\\ ...\\
%     like in tabular with one column.
%     You can also use comma-separated lists
%     first,second,third
%
% Example:
% 1.
%  \pgfplotslistnew\foolist{First Element\\Second Element\\Third Element\\}
%   WARNING: do NOT forget the final '\\'!
%
% 2.
% \pgfplotslistnew\foolist{First Element,Second Element,Third Element}
%
% Use braces '{}' to use '\\' or ',' as arguments.
%
\long\def\pgfplotslistnew#1#2{%
	\pgfplotslist@check@backslash@list #2\\\pgfplotslist@EOI
	\ifpgfplotslist@is@backslash@terminated
		\pgfplotslistnew@backslash@{#1}{#2}%
	\else
		\pgfplots@foreach@to@list{#2}\to#1%
	\fi
}
% Is this here *ever* used!? I guess not.
\long\def\pgfplotslistnew@backslash#1#2{%
	\pgfplotslistnewempty{#1}%
	\pgfplotslist@check@backslash@list #2\\\pgfplotslist@EOI
	\ifpgfplotslist@is@backslash@terminated
		\long\def\pgfplotslistnew@impl@rest{#2\pgfplotslist@EOI\\}%
		\def\pgfplotslistnew@backslash@loop{\pgfplotslistnew@impl{#1}}%
	\else
		\def\pgfplotslistnew@backslash@loop{\pgfplotslistnew@impl@comma{#1}}%
		\long\def\pgfplotslistnew@impl@rest{#2\pgfplotslist@EOI,}%
	\fi
	\expandafter\pgfplotslistnew@backslash@loop\pgfplotslistnew@impl@rest
}%
\long\def\pgfplotslistnew@backslash@#1#2{%
	\pgfplotslistnewempty{#1}%
	\def\pgfplotslistnew@backslash@loop{\pgfplotslistnew@impl{#1}}%
	\pgfplotslistnew@backslash@loop#2\pgfplotslist@EOI\\%
}%

% helper macro for \pgfplotslistnew
\long\def\pgfplotslistnew@impl#1#2\\{%
	\def\pgfplotslist@loc@TMPa{#2}%
	\ifx\pgfplotslist@loc@TMPa\pgfplotslist@EOI
	\else
		\pgfplotslistpushback{#2}\to#1\relax%
		\expandafter\pgfplotslistnew@backslash@loop
	\fi
}
\long\def\pgfplotslistnew@impl@comma#1#2,{%
	\def\pgfplotslist@loc@TMPa{#2}%
	\ifx\pgfplotslist@loc@TMPa\pgfplotslist@EOI
	\else
		\pgfplotslistpushback{#2}\to#1\relax%
		\expandafter\pgfplotslistnew@backslash@loop
	\fi
}
\def\pgfplotslist@EOI{\pgfplotslist@EOI}
\def\pgfplotslist@backslashsep{\\}

\long\def\pgfplotslist@check@backslash@list#1\\#2\pgfplotslist@EOI{%
	\def\pgfplotslist@loc@TMPx{#2}%
	\ifx\pgfplotslist@loc@TMPx\pgfutil@empty
		\pgfplotslist@is@backslash@terminatedfalse
		\let\pgfplotslist@check@backslash@list@next=\relax
	\else
		\def\pgfplotslist@loc@TMPy{ }%
		\ifx\pgfplotslist@loc@TMPx\pgfplotslist@loc@TMPy
			\pgfplotslist@is@backslash@terminatedfalse
			\let\pgfplotslist@check@backslash@list@next=\relax
		\else
			\ifx\pgfplotslist@loc@TMPx\pgfplotslist@backslashsep
				% ok. The list is something like 'a\\b\\' so the
				% complete input is
				% 'a\\b\\ \\ \EOI'
				% we have iterated long enough to find only the '\\'
				% right before the \EOI. It is thus backslash
				% terminated.
				\pgfplotslist@is@backslash@terminatedtrue
				\let\pgfplotslist@check@backslash@list@next=\relax
			\else
				% Iterate. We want to check the last list element.
				\long\def\pgfplotslist@check@backslash@list@next{\pgfplotslist@check@backslash@list#2\pgfplotslist@EOI}%
			\fi
		\fi
	\fi
	\pgfplotslist@check@backslash@list@next
}%

% Copies list #1 to list #2.
\def\pgfplotslistcopy#1\to#2{\let#2=#1}




% #1: the item to prepend
% #2: the list as macro name
% Example:
% \pgfplotslistpushfront Next first Element\to\foolist
\long\def\pgfplotslistpushfront#1\to#2{%
	\t@pgfplots@toka={\pgfpl@@{#1}}%
	\t@pgfplots@tokb=\expandafter{#2}%
  	\edef#2{\the\t@pgfplots@toka\the\t@pgfplots@tokb}%
}
\long\def\pgfplotslistpushfrontglobal#1\to#2{%
	\t@pgfplots@toka={\pgfpl@@{#1}}%
	\t@pgfplots@tokb=\expandafter{#2}%
  	\xdef#2{\the\t@pgfplots@toka\the\t@pgfplots@tokb}%
}

% Assembles a low-level list item representation into the token
% register #2.
\long\def\pgfplotslist@assembleentry#1\into#2{%
	#2={\pgfpl@@{#1}}%
}

% #1: the item to append
% #2: the list as macro name
% Example:
% \pgfplotslistpushback Next last element\to\foolist
\long\def\pgfplotslistpushback#1\to#2{%
	\t@pgfplots@toka={\pgfpl@@{#1}}%
	\ifx#2\pgfutil@empty
		\t@pgfplots@tokb={}%
	\else
		\t@pgfplots@tokb=\expandafter{#2}%
	\fi
 	\edef#2{\the\t@pgfplots@tokb\the\t@pgfplots@toka}%
}
% Adds '#1' to the GLOBAL list '#2'.
\long\def\pgfplotslistpushbackglobal#1\to#2{%
	\t@pgfplots@toka={\pgfpl@@{#1}}%
	\ifx#2\pgfutil@empty
		\t@pgfplots@tokb={}%
	\else
		\t@pgfplots@tokb=\expandafter{#2}%
	\fi
 	\xdef#2{\the\t@pgfplots@tokb\the\t@pgfplots@toka}%
}

% Concatenates two lists #2 and #3 into #1
% Example:
% \pgfplotslistconcat\result=\foolist&\bar
\long\def\pgfplotslistconcat#1=#2&#3{%
	\t@pgfplots@toka=\expandafter{#2}%
	\t@pgfplots@tokb=\expandafter{#3}%
	\edef#1{\the\t@pgfplots@toka\the\t@pgfplots@tokb}%
}

% implements #2 := pop_front(#1)
% Example:
% \pgfplotslistpopfront\foolist\to\poppedfirstelem
\long\def\pgfplotslistpopfront#1\to#2{%
	\pgfplotslistcheckempty#1\relax
	\ifpgfplotslistempty
		\pgfplotsthrow{no such element}{#1}{\string\pgfplotslistpopfront\ from \string#1\ although list is EMPTY}\pgfeov%
	\else
		\expandafter\pgfplotslistpopfront@impl#1\pgfplotslistpopfront@macronames#1#2%
	\fi
}
\long\def\pgfplotslistfront#1\to#2{%
	\pgfplotslistcheckempty#1\relax
	\ifpgfplotslistempty
		\pgfplotsthrow{no such element}{#2}{\string\pgfplotslistfront\ from \string#1\ although list is EMPTY}\pgfeov%
	\else
		\expandafter\pgfplotslistfront@impl#1\pgfplotslistpopfront@macronames#2%
	\fi
}

% implementation helper for listpopfront
\long\def\pgfplotslistpopfront@impl\pgfpl@@#1#2\pgfplotslistpopfront@macronames#3#4{%
	\def#4{#1}%
	\def#3{#2}%
}
\long\def\pgfplotslistfront@impl\pgfpl@@#1#2\pgfplotslistpopfront@macronames#3{%
	\def#3{#1}%
}

% Counts the number of elements in list #1, storing it into the count
% register #2.
% Example:
% \pgfplotslistsize\foo\to{\count0}%
% \the\count0
\long\def\pgfplotslistsize#1\to#2{%
	#2=0%
	\long\def\pgfpl@@##1{\advance#2 by 1 }%
	#1%
}

% Returns the #1th element of list #2 into macro #3
% Arguments:
% #1: a count 0,...,N-1 where N is the list size.
%     You may specify a number of a count.
% #2: a list
% #3: a macro name
% Example:
%   Element 0:
%   \pgfplotslistselect0\of\foo\to\elem
%   \elem
%   Element \count1:
%   \pgfplotslistselect\count1\of\foo\to\elem
\long\def\pgfplotslistselect#1\of#2\to#3{%
	\global\def\pgfplotslistselect@tmp{\pgfplotsthrow{no such element}{#3}{The requested list entry with index #1 of \string#2 is too large; this list has not enough elements.}\pgfeov}%
	\pgfplotslistselect@{#1}\of{#2}\to{#3}%
}
\long\def\pgfplotslistselect@#1\of#2\to#3{%
	\begingroup
	\count0=#1\relax
 	\long\def\pgfpl@@##1{%
		\advance\count0 by-1\relax
		\ifnum\count0=-1\relax
			\global\def\pgfplotslistselect@tmp{\def#3{##1}}%
		\fi%
	}%
	#2%
	\endgroup
	\pgfplotslistselect@tmp
}

% Selects a list entry. If it does not exist, '#' will be empty.
\long\def\pgfplotslistselectorempty#1\of#2\to#3{%
	\global\def\pgfplotslistselect@tmp{\def#3{}}%
	\pgfplotslistselect@{#1}\of{#2}\to{#3}%
}

% Changes the element at index '#1' of list '#2' to the content '#3'.
%
% This operation has quadratic (!) time in the worst case.
\long\def\pgfplotslistset#1\of#2\to#3{%
	\ifcase#1\relax
		% change first:
		\def\pgfplotslistset@\pgfpl@@##1##2\relax{\def#2{\pgfpl@@{#3}##2}}%
		\expandafter\pgfplotslistset@#2\relax
	\or
		% change second:
		\def\pgfplotslistset@\pgfpl@@##1\pgfpl@@##2##3\relax{\def#2{\pgfpl@@{##1}\pgfpl@@{#3}##2}}%
		\expandafter\pgfplotslistset@#2\relax
	\or
		\def\pgfplotslistset@\pgfpl@@##1\pgfpl@@##2\pgfpl@@##3##4\relax{\def#2{\pgfpl@@{##1}\pgfpl@@{##2}\pgfpl@@{#3}##3}}%
		\expandafter\pgfplotslistset@#2\relax
	\or
		\def\pgfplotslistset@\pgfpl@@##1\pgfpl@@##2\pgfpl@@##3\pgfpl@@##4##5\relax{\def#2{\pgfpl@@{##1}\pgfpl@@{##2}\pgfpl@@{##3}\pgfpl@@{#3}##4}}%
		\expandafter\pgfplotslistset@#2\relax
	\else
		\begingroup
		\global\pgfplotslistnewempty\pgfplotslistnewempty\pgfplotslist@glob@TMPa
		\let\pgfpl@@=\pgfutil@empty % make sure it is not \relax.
		\count0=#1\relax
		\count1=0
		\def\pgfplotslistset@newelem{#3}%
		\expandafter\pgfplotslistset@loop#2\relax
		\ifnum\count1 =\count0
		\else
			\pgfplotsthrow{no such element}{\pgfplots@loc@TMPa}{\string\pgfplotslistset{\the\count0} failed because there are only \the\count1\space elements in the list. Use pushback to resize it.}\pgfeov%
			\global\let\pgfplotslist@glob@TMPa=\pgfplots@loc@TMPa
		\fi
		\endgroup
		\let#3=\pgfplotslist@glob@TMPa
		\global\let\pgfplotslist@glob@TMPa=\relax
	\fi
}%

\def\pgfplotslistset@loop{%
	\pgfutil@ifnextchar\relax{%
		\pgfplotslistset@loop@break
	}{%
		\pgfplotslistset@loop@next
	}%
}
\def\pgfplotslistset@loop@break#1\relax{%
	% re-append remaining elements:
	\expandafter\gdef\expandafter\pgfplotslist@glob@TMPa\expandafter{\pgfplotslist@glob@TMPa#1}
}%
\def\pgfplotslistset@loop@next\pgfpl@@#1{%
	\ifnum\count1 =\count0
		% Ah - we found the element to replace!
		\expandafter\pgfplotslistpushbackglobal\expandafter{\pgfplotslistset@newelem}\to\pgfplotslist@glob@TMPa
		\expandafter\pgfplotslistset@loop@break
	\else
		\pgfplotslistpushbackglobal{#1}\to\pgfplotslist@glob@TMPa
		\advance\count1 by1
		\expandafter\pgfplotslistset@loop
	\fi
}%

% Sets the boolean \ifpgfplotslistempty depending on whether list #1 is empty
% or not.
% Example:
%
% \pgfplotslistcheckempty\foolist
% \ifpgfplotslistempty
%    List foolist is empty!
% \else
%    List is not empty.
% \fi
\def\pgfplotslistcheckempty#1{%
	\ifx#1\pgfutil@empty
		\pgfplotslistemptytrue
	\else
		\ifx#1\relax
			\pgfplots@warning{WARNING: possible logic error in script code: the command \string\pgfplotslistcheckempty{\string#1} encountered an undefined argument.}%
			\pgfplotslistemptytrue
		\else
			\pgfplotslistemptyfalse
		\fi
	\fi
}


% Iterates through each list element, names it #2 and calls code #3.
% Example:
% \pgfplotslistnew\foolist{Eins\\Zwei\\Drei\\}%
% \pgfplotslistforeach\foolist\as\foo{Element \foo\par}%
% results in
%  Element Eins
%  Element Zwei
%  Element Drei
% Each single element will be grouped with TeX groups.
\long\def\pgfplotslistforeach#1\as#2#3{%
	\begingroup
	\long\def\pgfpl@@##1{%
		\t@pgfplots@tokc={##1}% this allows '#' inside of '##1'
		\edef#2{\the\t@pgfplots@tokc}%
		\begingroup #3\endgroup}%
	#1\relax
	\endgroup
}

% The same but without groups around #3.
%
% The list can be nested.
\long\def\pgfplotslistforeachungrouped#1\as#2#3{%
	\t@pgfplots@tokb={{#2}{#3}}%
	\t@pgfplots@tokc=\expandafter{#1}%
	\edef\pgfplotslist@loc@TMPa{%
		\noexpand\pgfplotslistforeachungrouped@
		\the\t@pgfplots@tokb%
		\the\t@pgfplots@tokc
		\noexpand\pgfpl@@\noexpand\pgfplotslistforeachungrouped@EOI
	}%
	\pgfplotslist@loc@TMPa
}%

% Technical helper method which performs the loop.
% ASSUMPTION:
% \pgfplotslistforeachungrouped@
% 	{<macro name>}
% 	{<code to execute>}
% 	\pgfpl@@{<list elem>}\pgfpl@@{<list elem>}\pgfpl@@{<list elem>}\pgfpl@@\pgfplotslistforeachungrouped@EOI
%
% -> iterate through argument until \pgfplotslistforeachungrouped@EOI
%  comes.
\long\def\pgfplotslistforeachungrouped@#1#2\pgfpl@@#3{%
	\t@pgfplots@tokc={#3}% this allows '#' inside of '#3'
	\edef\pgfplotslist@loc@TMPa{\the\t@pgfplots@tokc}%
	\ifx\pgfplotslist@loc@TMPa\pgfplotslistforeachungrouped@EOI
		% ok, terminate loop.
		\let\pgfplotslistforeachungrouped@next=\relax
	\else
		% perform loop iteration ... 
		\let#1=\pgfplotslist@loc@TMPa
		#2\relax
		% and continue iterating.
		\def\pgfplotslistforeachungrouped@next{\pgfplotslistforeachungrouped@{#1}{#2}}%
	\fi
	\pgfplotslistforeachungrouped@next
}%
\def\pgfplotslistforeachungrouped@EOI{\pgfplotslistforeachungrouped@EOI}% equals only itself in \ifx


pgfplotsliststructureext.code.tex
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% This is a helper package with an elementary list datastructure.
% In contrast to \pgfplotslist, this one features fast append and fast
% copy-to-macro.
%
% The 'pgfplotsapplist' is a list which has ONLY the features
%
%  \pgfplotsapplistnewempty 
%  \pgfplotsapplistpushback O(1)
%  \pgfplotsapplistedefcontenttomacro (N)
%  \pgfplotsapplistxdefcontenttomacro (N)
%
% It has been designed to accumulate macro content in O(N) (in
% contrast to TeX's macro append routines which lead to O(N^2)
% runtime).
%
% Furthermore, there is the 
%
%  \pgfplotsapplistXnewempty 
%  \pgfplotsapplistXpushback
%  \pgfplotsapplistXedefcontenttomacro (N)
%  \pgfplotsapplistXxdefcontenttomacro (N)
%  \pgfplotsapplistXlet (N)
%
% structure which features **preasymptotical** constant runtime for
% pushback. That means, as long as N < 80000, the runtime is linear.
% It is only slightly slower than \pgfplotsapplist, and that only due
% to its generality. It could easily be adopted to be FASTER than
% \pgfplotsapplist.
%
% Credits for \pgfplotsapplist go to Till Tantau: he developped it for
% the PGF kernel.
%
%
% Copyright 2007/2008 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%




%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the applist defines one macro for each element, like
% 
% \def\element<i>{<content>\element<i+1>}
% \def\element<i+1>{<content>\element<i+2>}
% \def\element<i+2>{}
%
% The '<i>' value belongs to the private interface and is part of the
% macro name.
%
% It features:
% - real O(1) pushback
% - O(N) edef to macro
% - O(N) execute
% - it requires O(N) different macros.
% - it ***can't*** be copied outside of the current TeX group!
%
% I have never used it (besides early tests)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


% Time: O(1), number of macros: 3
\def\pgfplotsapplistnewempty#1{%
	\expandafter\def\csname\string#1@endno\endcsname{0}%
	\edef#1{\expandafter\noexpand\csname\string#1@0\endcsname}%
	\expandafter\def\csname\string#1@0\endcsname{}%
}%

% Time: O(1), number of macros per list: about N
% #1: the item to append
% #2: the list as macro name
\long\def\pgfplotsapplistpushback#1\to#2{%
	\expandafter\let\expandafter\pgfplots@loc@TMPa\csname\string#2@endno\endcsname
	\begingroup
	\c@pgf@counta=\pgfplots@loc@TMPa\relax
	\advance\c@pgf@counta by1
	\xdef\pgfplots@glob@TMPa{\the\c@pgf@counta}%
	\endgroup
	\expandafter\let\csname\string#2@endno\endcsname=\pgfplots@glob@TMPa%
	\t@pgfplots@toka={#1}%
	\t@pgfplots@tokb=\expandafter{\csname\string#2@\pgfplots@glob@TMPa\endcsname}%
	\expandafter\edef\csname\string#2@\pgfplots@loc@TMPa\endcsname{\the\t@pgfplots@toka\the\t@pgfplots@tokb}%
	\expandafter\let\the\t@pgfplots@tokb=\pgfutil@empty
}%
	
% time O(N)
% Expands the complete content of list #1 as-is into the macro #2.
\def\pgfplotsapplistedefcontenttomacro#1\to#2{\edef#2{#1}}
\def\pgfplotsapplistxdefcontenttomacro#1\to#2{\xdef#2{#1}}

% Foreach list element, the stored value will simply be processed by
% TeX. Characters will be printed and commands will be executed.
% time O(N)
\def\pgfplotsapplistexecute#1{#1}%




%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
%
% This list here is a general re-implementation of the list used in
% the PGF system layer.
% It employs two collect-buffers to reduce the runtime.
%
% - It has preasymptotical runtime O(N), but is O(N^2) asymptotically.
% - It requires only 5 macros per list.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Usage: 
% \pgfplotsapplistXnewempty\macro
% \pgfplotsapplistXnewempty[to global]\macro
%
% The 'to global' flag will configure the list such that all
% assignments to \macro are global. The list accumulation is
% LOCAL, however: 'to global' is to be used inside of a local
% group such that the final result, when all buffers are flushed,
% is assigned globally.
%
% ATTENTION: maybe that [to global] thing is useless.
% Consider using the \pgfplotsapplistXglobal list (see below)
\def\pgfplotsapplistXnewempty{%
	\pgfutil@ifnextchar[{%
		\pgfplotsapplistXnewempty@opt
	}{%
		\pgfplotsapplistXnewempty@opt[]%
	}%
}

\def\pgfplotsapplistXnewempty@opt@TOGLOBAL{to global}

\def\pgfplotsapplistXnewempty@opt[#1]#2{%
	\def\pgfplots@loc@TMPa{#1}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\expandafter\let\csname\string#2@let\endcsname=\let%
		\expandafter\let\csname\string#2@edef\endcsname=\edef
	\else
		\ifx\pgfplots@loc@TMPa\pgfplotsapplistXnewempty@opt@TOGLOBAL
			\expandafter\def\csname\string#2@let\endcsname{\global\let}%
			\expandafter\let\csname\string#2@edef\endcsname=\xdef
		\else
			\pgfplots@error{Sorry, the argument '#1' to \string\pgfplotsapplistXnewempty\ is unknown. Accepted is 'to global' or empty.}%
		\fi
	\fi
	\pgfplotsapplistXnewempty@{#2}%
}%

\def\pgfplotsapplistXnewempty@#1{%
	\csname\string#1@let\endcsname#1=\pgfutil@empty
	\expandafter\let\csname\string#1@smallbuf\endcsname=\pgfutil@empty
	\expandafter\let\csname\string#1@bigbuf\endcsname=\pgfutil@empty
	\expandafter\def\csname\string#1@smallbuf@c\endcsname{0}%
	\expandafter\def\csname\string#1@bigbuf@c\endcsname{0}%
}%

% #1: the item to append
% #2: the list as macro name
\long\def\pgfplotsapplistXpushback#1\to#2{%
	\begingroup
		\c@pgf@counta=\csname\string#2@smallbuf@c\endcsname\relax
		\advance\c@pgf@counta by1
		\xdef\pgfplots@glob@TMPa{\the\c@pgf@counta}%
	\endgroup
	\expandafter\let\csname\string#2@smallbuf@c\endcsname=\pgfplots@glob@TMPa
	\ifnum\csname\string#2@smallbuf@c\endcsname<40
		\t@pgfplots@toka=\expandafter\expandafter\expandafter{\csname\string#2@smallbuf\endcsname#1}%
		\expandafter\edef\csname\string#2@smallbuf\endcsname{\the\t@pgfplots@toka}%
	\else
		\pgfplotsapplistXpushback@smallbufoverfl{#1}{#2}%
	\fi
}%
\long\def\pgfplotsapplistXpushback@smallbufoverfl#1#2{%
	\begingroup
		\c@pgf@counta=\csname\string#2@bigbuf@c\endcsname\relax
		\advance\c@pgf@counta by1
		\xdef\pgfplots@glob@TMPa{\the\c@pgf@counta}%
	\endgroup
	\expandafter\let\csname\string#2@bigbuf@c\endcsname=\pgfplots@glob@TMPa
	%
	\ifnum\csname\string#2@bigbuf@c\endcsname<30
		\t@pgfplots@toka=\expandafter\expandafter\expandafter{\csname\string#2@bigbuf\endcsname}%
		\t@pgfplots@tokb=\expandafter\expandafter\expandafter{\csname\string#2@smallbuf\endcsname#1}%
		\expandafter\edef\csname\string#2@bigbuf\endcsname{\the\t@pgfplots@toka\the\t@pgfplots@tokb}%
		\expandafter\let\csname\string#2@smallbuf\endcsname=\pgfutil@empty
		\expandafter\def\csname\string#2@smallbuf@c\endcsname{0}%
	\else%
		\t@pgfplots@toka=\expandafter{#2}%
		\t@pgfplots@tokb=\expandafter\expandafter\expandafter{\csname\string#2@bigbuf\endcsname}%
		\t@pgfplots@tokc=\expandafter\expandafter\expandafter{\csname\string#2@smallbuf\endcsname#1}%
		\csname\string#2@edef\endcsname#2{\the\t@pgfplots@toka\the\t@pgfplots@tokb\the\t@pgfplots@tokc}%
		\expandafter\let\csname\string#2@smallbuf\endcsname=\pgfutil@empty
		\expandafter\def\csname\string#2@smallbuf@c\endcsname{0}%
		\expandafter\let\csname\string#2@bigbuf\endcsname=\pgfutil@empty
		\expandafter\def\csname\string#2@bigbuf@c\endcsname{0}%
	\fi%
}%
\def\pgfplotsapplistXflushbuffers#1{%
	\t@pgfplots@toka=\expandafter{#1}%
	\t@pgfplots@tokb=\expandafter\expandafter\expandafter{\csname\string#1@bigbuf\endcsname}%
	\t@pgfplots@tokc=\expandafter\expandafter\expandafter{\csname\string#1@smallbuf\endcsname}%
	\csname\string#1@edef\endcsname#1{\the\t@pgfplots@toka\the\t@pgfplots@tokb\the\t@pgfplots@tokc}%
	\expandafter\let\csname\string#1@smallbuf\endcsname=\pgfutil@empty
	\expandafter\def\csname\string#1@smallbuf@c\endcsname{0}%
	\expandafter\let\csname\string#1@bigbuf\endcsname=\pgfutil@empty
	\expandafter\def\csname\string#1@bigbuf@c\endcsname{0}%
}%

	
% Expands the complete content of list #1 as-is into the macro #2.
\def\pgfplotsapplistXedefcontenttomacro#1\to#2{%
	\pgfplotsapplistXflushbuffers#1%
	\edef#2{#1}}
\def\pgfplotsapplistXxdefcontenttomacro#1\to#2{%
	\pgfplotsapplistXflushbuffers#1%
	\xdef#2{#1}}
\def\pgfplotsapplistXlet#1=#2{%
	\pgfplotsapplistXflushbuffers#2%
	\let#1=#2}

% Foreach list element, the stored value will simply be processed by
% TeX. Characters will be printed and commands will be executed.
\def\pgfplotsapplistXexecute#1{%
	\pgfplotsapplistXflushbuffers#1%
	#1}%


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 
% A variant of applist which has the same runtime requirements, but
% does PUSH FRONT only.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


% Usage: 
% \pgfplotsprependlistXnewempty{liste}
\def\pgfplotsprependlistXnewempty#1{%
	\expandafter\let\csname pgfpPRP@#1\endcsname=\pgfutil@empty
	\expandafter\let\csname pgfpPRP@#1@smallbuf\endcsname=\pgfutil@empty
	\expandafter\let\csname pgfpPRP@#1@bigbuf\endcsname=\pgfutil@empty
	\expandafter\def\csname pgfpPRP@#1@smallbuf@c\endcsname{0}%
	\expandafter\def\csname pgfpPRP@#1@bigbuf@c\endcsname{0}%
}%

% #1: the item to append
% #2: the list as macro name
\long\def\pgfplotsprependlistXpushfront#1\to#2{%
	\begingroup
		\c@pgf@counta=\csname pgfpPRP@#2@smallbuf@c\endcsname\relax
		\advance\c@pgf@counta by1
		\xdef\pgfplots@glob@TMPa{\the\c@pgf@counta}%
	\endgroup
	\expandafter\let\csname pgfpPRP@#2@smallbuf@c\endcsname=\pgfplots@glob@TMPa
	\ifnum\csname pgfpPRP@#2@smallbuf@c\endcsname<40
		\t@pgfplots@toka=\expandafter\expandafter\expandafter{\csname pgfpPRP@#2@smallbuf\endcsname}%
		\t@pgfplots@tokb={#1}%
		\expandafter\edef\csname pgfpPRP@#2@smallbuf\endcsname{\the\t@pgfplots@tokb\the\t@pgfplots@toka}%
	\else
		\pgfplotsprependlistXpushfront@smallbufoverfl{#1}{#2}%
	\fi
}%
\long\def\pgfplotsprependlistXpushfront@smallbufoverfl#1#2{%
	\begingroup
		\c@pgf@counta=\csname pgfpPRP@#2@bigbuf@c\endcsname\relax
		\advance\c@pgf@counta by1
		\xdef\pgfplots@glob@TMPa{\the\c@pgf@counta}%
	\endgroup
	\expandafter\let\csname pgfpPRP@#2@bigbuf@c\endcsname=\pgfplots@glob@TMPa
	%
	\ifnum\csname pgfpPRP@#2@bigbuf@c\endcsname<30
		\t@pgfplots@toka=\expandafter\expandafter\expandafter{\csname pgfpPRP@#2@bigbuf\endcsname}%
		\t@pgfplots@tokb=\expandafter\expandafter\expandafter{\csname pgfpPRP@#2@smallbuf\endcsname}%
		\t@pgfplots@tokc={#1}%
		\expandafter\edef\csname pgfpPRP@#2@bigbuf\endcsname{\the\t@pgfplots@tokc\the\t@pgfplots@tokb\the\t@pgfplots@toka}%
		\expandafter\let\csname pgfpPRP@#2@smallbuf\endcsname=\pgfutil@empty
		\expandafter\def\csname pgfpPRP@#2@smallbuf@c\endcsname{0}%
	\else%
		\pgfplotsprependlistXflushbuffers{#2}%
		\t@pgfplots@toka=\expandafter\expandafter\expandafter{\csname pgfpPRP@#2\endcsname}%
		\t@pgfplots@tokb={#1}%
		\expandafter\edef\csname pgfpPRP@#2\endcsname{\the\t@pgfplots@tokb\the\t@pgfplots@toka}%
	\fi%
}%
\def\pgfplotsprependlistXflushbuffers#1{%
	\t@pgfplots@toka=\expandafter\expandafter\expandafter{\csname pgfpPRP@#1\endcsname}%
	\t@pgfplots@tokb=\expandafter\expandafter\expandafter{\csname pgfpPRP@#1@bigbuf\endcsname}%
	\t@pgfplots@tokc=\expandafter\expandafter\expandafter{\csname pgfpPRP@#1@smallbuf\endcsname}%
	\expandafter\edef\csname pgfpPRP@#1\endcsname{\the\t@pgfplots@tokc\the\t@pgfplots@tokb\the\t@pgfplots@toka}%
	\expandafter\let\csname pgfpPRP@#1@smallbuf\endcsname=\pgfutil@empty
	\expandafter\def\csname pgfpPRP@#1@smallbuf@c\endcsname{0}%
	\expandafter\let\csname pgfpPRP@#1@bigbuf\endcsname=\pgfutil@empty
	\expandafter\def\csname pgfpPRP@#1@bigbuf@c\endcsname{0}%
}%

\def\pgfplotsprependlistXlet#1=#2{%
	\pgfplotsprependlistXflushbuffers{#2}%
	\expandafter\let\expandafter#1\csname pgfpPRP@#2\endcsname}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
% 
% This list \pgfplotsapplistXX here is essentially the SAME as \pgfplotslistX.
%
% But there can only be one such list at a time, so it is faster than
% \pgfplotslistX.
%
% This here is probably the fastest list.
%
% It is nothing else but a copy of Till Tantau's pgf kernel list.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5



% WARNING: call \pgfplotsapplistclear if there is another list active.
\def\pgfplotsapplistXXnewempty{%
	\pgfutil@ifundefined{pgfplotsapplistXX}{}{%
		\ifx\pgfplotsapplistXX\pgfutil@empty
		\else
			\pgfplots@error{\string\pgfplotsapplistXXnewempty: there is already another list which is *not* empty. It currently contains '\meaning\pgfplotsapplistXX'. Please call '\string\pgfplotsapplistXXclear' before using a new list to ensure clean separations.}%
		\fi
	}%
	\let\pgfplotsapplistXX=\pgfutil@empty
	\let\pgfplotsapplistXX@smallbuf=\pgfutil@empty
	\let\pgfplotsapplistXX@bigbuf=\pgfutil@empty
	\def\pgfplotsapplistXX@smallbuf@c{0}%
	\def\pgfplotsapplistXX@bigbuf@c{0}%
}%


\def\pgfplotsapplistXXclear{%
	\pgfutil@ifundefined{pgfplotsapplistXX}{}{%
		\let\pgfplotsapplistXX=\pgfutil@empty
		\let\pgfplotsapplistXX@smallbuf=\pgfutil@empty
		\let\pgfplotsapplistXX@bigbuf=\pgfutil@empty
		\def\pgfplotsapplistXX@smallbuf@c{0}%
		\def\pgfplotsapplistXX@bigbuf@c{0}%
	}%
}%

% #1: the item to append
% #2: the list as macro name
\long\def\pgfplotsapplistXXpushback#1{%
	\begingroup
		\c@pgf@counta=\pgfplotsapplistXX@smallbuf@c\relax
		\advance\c@pgf@counta by1
		\xdef\pgfplots@glob@TMPa{\the\c@pgf@counta}%
	\endgroup
	\let\pgfplotsapplistXX@smallbuf@c=\pgfplots@glob@TMPa
	\ifnum\pgfplotsapplistXX@smallbuf@c<40
		\t@pgfplots@toka=\expandafter{\pgfplotsapplistXX@smallbuf#1}%
		\edef\pgfplotsapplistXX@smallbuf{\the\t@pgfplots@toka}%
	\else
		\pgfplotsapplistXXpushback@smallbufoverfl{#1}%
	\fi
}%
\long\def\pgfplotsapplistXXpushback@smallbufoverfl#1{%
	\begingroup
		\c@pgf@counta=\pgfplotsapplistXX@bigbuf@c\relax
		\advance\c@pgf@counta by1
		\xdef\pgfplots@glob@TMPa{\the\c@pgf@counta}%
	\endgroup
	\let\pgfplotsapplistXX@bigbuf@c=\pgfplots@glob@TMPa
	%
	\ifnum\pgfplotsapplistXX@bigbuf@c<30
		\t@pgfplots@toka=\expandafter{\pgfplotsapplistXX@bigbuf}%
		\t@pgfplots@tokb=\expandafter{\pgfplotsapplistXX@smallbuf#1}%
		\edef\pgfplotsapplistXX@bigbuf{\the\t@pgfplots@toka\the\t@pgfplots@tokb}%
		\let\pgfplotsapplistXX@smallbuf=\pgfutil@empty
		\def\pgfplotsapplistXX@smallbuf@c{0}%
	\else%
		\t@pgfplots@toka=\expandafter{\pgfplotsapplistXX}%
		\t@pgfplots@tokb=\expandafter{\pgfplotsapplistXX@bigbuf}%
		\t@pgfplots@tokc=\expandafter{\pgfplotsapplistXX@smallbuf#1}%
		\edef\pgfplotsapplistXX{\the\t@pgfplots@toka\the\t@pgfplots@tokb\the\t@pgfplots@tokc}%
		\let\pgfplotsapplistXX@smallbuf=\pgfutil@empty
		\def\pgfplotsapplistXX@smallbuf@c{0}%
		\let\pgfplotsapplistXX@bigbuf=\pgfutil@empty
		\def\pgfplotsapplistXX@bigbuf@c{0}%
	\fi%
}%
\def\pgfplotsapplistXXflushbuffers{%
	\t@pgfplots@toka=\expandafter{\pgfplotsapplistXX}%
	\t@pgfplots@tokb=\expandafter{\pgfplotsapplistXX@bigbuf}%
	\t@pgfplots@tokc=\expandafter{\pgfplotsapplistXX@smallbuf}%
	\edef\pgfplotsapplistXX{\the\t@pgfplots@toka\the\t@pgfplots@tokb\the\t@pgfplots@tokc}%
	\let\pgfplotsapplistXX@smallbuf=\pgfutil@empty
	\def\pgfplotsapplistXX@smallbuf@c{0}%
	\let\pgfplotsapplistXX@bigbuf=\pgfutil@empty
	\def\pgfplotsapplistXX@bigbuf@c{0}%
}%

	
% Expands the complete content of list #1 as-is into the macro #2.
\def\pgfplotsapplistXXedefcontenttomacro#1{%
	\pgfplotsapplistXXflushbuffers
	\edef#1{\pgfplotsapplistXX}}
\def\pgfplotsapplistXXxdefcontenttomacro#1{%
	\pgfplotsapplistXXflushbuffers%
	\xdef#1{\pgfplotsapplistXX}}
\def\pgfplotsapplistXXlet#1{%
	\pgfplotsapplistXXflushbuffers%
	\let#1=\pgfplotsapplistXX}

% Foreach list element, the stored value will simply be processed by
% TeX. Characters will be printed and commands will be executed.
\def\pgfplotsapplistXXexecute#1{%
	\pgfplotsapplistXXflushbuffers
	#1}%


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
% 
% \pgfplotslistXXglobal  assigns to a global list.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
\def\pgfplotsapplistXXglobalnewempty{%
	\pgfutil@ifundefined{pgfplotsapplistXXglobal}{}{%
		\ifx\pgfplotsapplistXXglobal\pgfutil@empty
		\else
			\pgfplots@error{\string\pgfplotsapplistXXglobalnewempty: there is already another list which is *not* empty. It currently contains '\meaning\pgfplotsapplistXXglobal'. Please call '\string\pgfplotsapplistXXglobalclear' before using a new list to ensure clean separations.}%
		\fi
	}%
	\global\let\pgfplotsapplistXXglobal=\pgfutil@empty
	\global\let\pgfplotsapplistXXglobal@smallbuf=\pgfutil@empty
	\global\let\pgfplotsapplistXXglobal@bigbuf=\pgfutil@empty
	\gdef\pgfplotsapplistXXglobal@smallbuf@c{0}%
	\gdef\pgfplotsapplistXXglobal@bigbuf@c{0}%
}%


\def\pgfplotsapplistXXglobalclear{%
	\pgfutil@ifundefined{pgfplotsapplistXXglobal}{}{%
		\global\let\pgfplotsapplistXXglobal=\pgfutil@empty
		\global\let\pgfplotsapplistXXglobal@smallbuf=\pgfutil@empty
		\global\let\pgfplotsapplistXXglobal@bigbuf=\pgfutil@empty
		\gdef\pgfplotsapplistXXglobal@smallbuf@c{0}%
		\gdef\pgfplotsapplistXXglobal@bigbuf@c{0}%
	}%
}%

% #1: the item to append
% #2: the list as macro name
\long\def\pgfplotsapplistXXglobalpushback#1{%
	\begingroup
		\c@pgf@counta=\pgfplotsapplistXXglobal@smallbuf@c\relax
		\advance\c@pgf@counta by1
		\xdef\pgfplots@glob@TMPa{\the\c@pgf@counta}%
	\endgroup
	\global\let\pgfplotsapplistXXglobal@smallbuf@c=\pgfplots@glob@TMPa
	\ifnum\pgfplotsapplistXXglobal@smallbuf@c<40
		\t@pgfplots@toka=\expandafter{\pgfplotsapplistXXglobal@smallbuf#1}%
		\xdef\pgfplotsapplistXXglobal@smallbuf{\the\t@pgfplots@toka}%
	\else
		\pgfplotsapplistXXglobalpushback@smallbufoverfl{#1}%
	\fi
}%
\long\def\pgfplotsapplistXXglobalpushback@smallbufoverfl#1{%
	\begingroup
		\c@pgf@counta=\pgfplotsapplistXXglobal@bigbuf@c\relax
		\advance\c@pgf@counta by1
		\xdef\pgfplots@glob@TMPa{\the\c@pgf@counta}%
	\endgroup
	\global\let\pgfplotsapplistXXglobal@bigbuf@c=\pgfplots@glob@TMPa
	%
	\ifnum\pgfplotsapplistXXglobal@bigbuf@c<30
		\t@pgfplots@toka=\expandafter{\pgfplotsapplistXXglobal@bigbuf}%
		\t@pgfplots@tokb=\expandafter{\pgfplotsapplistXXglobal@smallbuf#1}%
		\xdef\pgfplotsapplistXXglobal@bigbuf{\the\t@pgfplots@toka\the\t@pgfplots@tokb}%
		\global\let\pgfplotsapplistXXglobal@smallbuf=\pgfutil@empty
		\gdef\pgfplotsapplistXXglobal@smallbuf@c{0}%
	\else%
		\t@pgfplots@toka=\expandafter{\pgfplotsapplistXXglobal}%
		\t@pgfplots@tokb=\expandafter{\pgfplotsapplistXXglobal@bigbuf}%
		\t@pgfplots@tokc=\expandafter{\pgfplotsapplistXXglobal@smallbuf#1}%
		\xdef\pgfplotsapplistXXglobal{\the\t@pgfplots@toka\the\t@pgfplots@tokb\the\t@pgfplots@tokc}%
		\global\let\pgfplotsapplistXXglobal@smallbuf=\pgfutil@empty
		\gdef\pgfplotsapplistXXglobal@smallbuf@c{0}%
		\global\let\pgfplotsapplistXXglobal@bigbuf=\pgfutil@empty
		\gdef\pgfplotsapplistXXglobal@bigbuf@c{0}%
	\fi%
}%
\def\pgfplotsapplistXXglobalflushbuffers{%
	\t@pgfplots@toka=\expandafter{\pgfplotsapplistXXglobal}%
	\t@pgfplots@tokb=\expandafter{\pgfplotsapplistXXglobal@bigbuf}%
	\t@pgfplots@tokc=\expandafter{\pgfplotsapplistXXglobal@smallbuf}%
	\xdef\pgfplotsapplistXXglobal{\the\t@pgfplots@toka\the\t@pgfplots@tokb\the\t@pgfplots@tokc}%
	\global\let\pgfplotsapplistXXglobal@smallbuf=\pgfutil@empty
	\gdef\pgfplotsapplistXXglobal@smallbuf@c{0}%
	\global\let\pgfplotsapplistXXglobal@bigbuf=\pgfutil@empty
	\gdef\pgfplotsapplistXXglobal@bigbuf@c{0}%
}%

	
% Expands the complete content of list #1 as-is into the macro #2.
%
% this assigns locally into #1.
\def\pgfplotsapplistXXglobaledefcontenttomacro#1{%
	\pgfplotsapplistXXglobalflushbuffers
	\edef#1{\pgfplotsapplistXXglobal}}
% this assigns locally into #1.
\def\pgfplotsapplistXXglobalxdefcontenttomacro#1{%
	\pgfplotsapplistXXglobalflushbuffers%
	\xdef#1{\pgfplotsapplistXXglobal}}
% this assigns locally into #1.
\def\pgfplotsapplistXXgloballet#1{%
	\pgfplotsapplistXXglobalflushbuffers%
	\let#1=\pgfplotsapplistXXglobal}

% Foreach list element, the stored value will simply be processed by
% TeX. Characters will be printed and commands will be executed.
% this assigns locally into #1.
\def\pgfplotsapplistXXglobalexecute#1{%
	\pgfplotsapplistXXglobalflushbuffers
	#1}%


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  \pgfplotsapplistXglobalnewempty --> same as \pgfplotsapplistX, but
%  it always assigns everything *globally*.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\def\pgfplotsgloballet{\global\let}%

% Usage: 
% \pgfplotsapplistXglobalnewempty\macro
% \pgfplotsapplistXglobalnewempty[to global]\macro
%
% The 'to global' flag will configure the list such that all
% assignments to \macro are global. The list accumulation is
% LOCAL, however: 'to global' is to be used inside of a local
% group such that the final result, when all buffers are flushed,
% is assigned globally.
\def\pgfplotsapplistXglobalnewempty#1{%
	\pgfplotsgloballet#1=\pgfutil@empty
	\expandafter\pgfplotsgloballet\csname\string#1@smallbuf\endcsname=\pgfutil@empty
	\expandafter\pgfplotsgloballet\csname\string#1@bigbuf\endcsname=\pgfutil@empty
	\expandafter\gdef\csname\string#1@smallbuf@c\endcsname{0}%
	\expandafter\gdef\csname\string#1@bigbuf@c\endcsname{0}%
}%

% #1: the item to append
% #2: the list as macro name
\long\def\pgfplotsapplistXglobalpushback#1\to#2{%
	\begingroup
		\c@pgf@counta=\csname\string#2@smallbuf@c\endcsname\relax
		\advance\c@pgf@counta by1
		\expandafter\xdef\csname\string#2@smallbuf@c\endcsname{\the\c@pgf@counta}%
	\endgroup
	\ifnum\csname\string#2@smallbuf@c\endcsname<40
		\t@pgfplots@toka=\expandafter\expandafter\expandafter{\csname\string#2@smallbuf\endcsname#1}%
		\expandafter\xdef\csname\string#2@smallbuf\endcsname{\the\t@pgfplots@toka}%
	\else
		\pgfplotsapplistXglobalpushback@smallbufoverfl{#1}{#2}%
	\fi
}%
\long\def\pgfplotsapplistXglobalpushback@smallbufoverfl#1#2{%
	\begingroup
		\c@pgf@counta=\csname\string#2@bigbuf@c\endcsname\relax
		\advance\c@pgf@counta by1
		\expandafter\xdef\csname\string#2@bigbuf@c\endcsname{\the\c@pgf@counta}%
	\endgroup
	%
	\ifnum\csname\string#2@bigbuf@c\endcsname<30
		\t@pgfplots@toka=\expandafter\expandafter\expandafter{\csname\string#2@bigbuf\endcsname}%
		\t@pgfplots@tokb=\expandafter\expandafter\expandafter{\csname\string#2@smallbuf\endcsname#1}%
		\expandafter\xdef\csname\string#2@bigbuf\endcsname{\the\t@pgfplots@toka\the\t@pgfplots@tokb}%
		\expandafter\pgfplotsgloballet\csname\string#2@smallbuf\endcsname=\pgfutil@empty
		\expandafter\gdef\csname\string#2@smallbuf@c\endcsname{0}%
	\else%
		\t@pgfplots@toka=\expandafter{#2}%
		\t@pgfplots@tokb=\expandafter\expandafter\expandafter{\csname\string#2@bigbuf\endcsname}%
		\t@pgfplots@tokc=\expandafter\expandafter\expandafter{\csname\string#2@smallbuf\endcsname#1}%
		\xdef#2{\the\t@pgfplots@toka\the\t@pgfplots@tokb\the\t@pgfplots@tokc}%
		\expandafter\pgfplotsgloballet\csname\string#2@smallbuf\endcsname=\pgfutil@empty
		\expandafter\gdef\csname\string#2@smallbuf@c\endcsname{0}%
		\expandafter\pgfplotsgloballet\csname\string#2@bigbuf\endcsname=\pgfutil@empty
		\expandafter\gdef\csname\string#2@bigbuf@c\endcsname{0}%
	\fi%
}%
\def\pgfplotsapplistXglobalflushbuffers#1{%
	\t@pgfplots@toka=\expandafter{#1}%
	\t@pgfplots@tokb=\expandafter\expandafter\expandafter{\csname\string#1@bigbuf\endcsname}%
	\t@pgfplots@tokc=\expandafter\expandafter\expandafter{\csname\string#1@smallbuf\endcsname}%
	\xdef#1{\the\t@pgfplots@toka\the\t@pgfplots@tokb\the\t@pgfplots@tokc}%
	\expandafter\pgfplotsgloballet\csname\string#1@smallbuf\endcsname=\pgfutil@empty
	\expandafter\gdef\csname\string#1@smallbuf@c\endcsname{0}%
	\expandafter\pgfplotsgloballet\csname\string#1@bigbuf\endcsname=\pgfutil@empty
	\expandafter\gdef\csname\string#1@bigbuf@c\endcsname{0}%
}%

	
\def\pgfplotsapplistXgloballet#1=#2{%
	\pgfplotsapplistXglobalflushbuffers#2%
	\let#1=#2}

pgfplots.markers.code.tex
%--------------------------------------------
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2007-2013 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------
	
\def\pgfplots@markers@visphase@name@none{none}%
\def\pgfplots@markers@visphase@name@afterpath@clipped{afterpath@clipped}%
\def\pgfplots@markers@visphase@name@afterpath@unclipped{afterpath@unclipped}%
\def\pgfplots@markers@visphase@name@endaxis@unclipped{endaxis@unclipped}%

% defines \pgfplotsretval to contain the visualization phase used by
% the current plot.
\def\pgfplots@markers@survey@set@visphasename{%
	\begingroup
	%
	% this validates+normalizes \tikz@plot@mark:
	\pgfplots@markers@check@for@default@plot@mark
	\ifx\tikz@plot@mark\pgfutil@empty
		\ifpgfplots@scatterplotenabled
			\def\b@pgfplots@has@plot@mark{1}%
		\else
			\def\b@pgfplots@has@plot@mark{0}%
		\fi
	\else
		\def\b@pgfplots@has@plot@mark{1}%
	\fi
	%
	% this sets \ifpgfplots@clip@marker@paths:
	\pgfplots@markers@prepare@layered@graphics@marks
	%
	\if0\b@pgfplots@has@plot@mark
		% no markers. Ok, we do not need a visualization phase for
		% markers.
		\let\pgfplotsretval=\pgfplots@markers@visphase@name@none
	\else
		\ifpgfplots@clip@marker@paths
			\let\pgfplotsretval=\pgfplots@markers@visphase@name@afterpath@clipped
		\else
			\if2\pgfplots@clipmode
				% clip mode=individual:
				\let\pgfplotsretval=\pgfplots@markers@visphase@name@afterpath@unclipped
			\else
				% clip mode=global
				\let\pgfplotsretval=\pgfplots@markers@visphase@name@endaxis@unclipped
			\fi
		\fi
	\fi
	%
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%

\def\pgfplots@markers@visphase@after@axis@prepare{%
	\global\pgfplotslistnewempty\pgfplots@stored@markerlist
}

% Draw any markers for which drawing has been postponed.
%
% The motivation here is that markers should be drawn on top of
% their plots, and AFTER the clip path.
%
\def\pgfplots@markers@visphase@after@axis{%
	\begingroup
	\pgfplotslistforeach\pgfplots@stored@plotlist\as\pgfplots@loc@TMPa{%
		\expandafter\pgfplots@stored@plotlist@EXTRACTENTRY\pgfplots@loc@TMPa
%\message{^^JProcessing stored plot with precommand '\meaning\pgfplots@stored@current@precmd';^^J  pgfplots@plotcmd '\meaning\pgfplots@stored@current@cmd'^^J postcommand '\meaning\pgfplots@stored@current@postcmd'^^J}%
%\message{DATA: '\meaning\pgfplots@stored@current@data';^^J}%
		% The precmd sets all required variables needed to
		% finalize a plot.
		% @see the stream preparation routines.
		\pgfplots@stored@current@precmd
		\ifx\pgfplots@markers@visphase@name\pgfplots@markers@visphase@name@endaxis@unclipped
			\ifx\pgfplots@stored@current@cmd\pgfutil@empty
				% Ah: some \pgfplotsextra command like \draw,\path,
				% \node or even \scope or \endscope.
				% Has been done earlier.
			\else
				\begingroup
				% reconfigure...
				\pgfkeyssetvalue{/pgfplots/on layer}{\pgfkeysvalueof{/pgfplots/mark layer}}%
				%
				% choose the one that is necessary for us here:
				\let\pgfplots@markers@visphase@name=\pgfplots@markers@visphase@name@afterpath@unclipped
				%
				% provide an empty list of phase names here in order
				% to turn off standard visualization phases: they
				% have been applied already.
				\pgfplots@stored@plotlist@visualize@selected@phases{}%
				\endgroup
			\fi
			\pgfplots@stored@current@postcmd
		\fi
	}%
	\endgroup
}

\def\pgfplots@execute@at@begin@plot@visualization@internal{%
	\global\let\pgfplots@stored@markerlist@last=\relax
}%

\def\pgfplots@markers@install@plotmark@handler{%
	% note: I can't check on tikz@transform because it can be '\relax'.
	\pgfplots@gettikzinternal@keyval{mark indices}{tikz@mark@list}{}%
	\pgfplots@gettikzinternal@keyval{mark}{tikz@plot@mark}{}%
	%
	%
	% do not reset \tikz@options: draw color may be acquired
	% from 'current plot style'
	%\let\tikz@options=\pgfutil@empty%
	\let\tikz@transform=\pgfutil@empty%
	\tikzset{every plot/.try,every mark}%
	%
	% This sets colors:
	\tikz@options
	%
	% This sets the \iftikz@mode@draw etc:
	%\tikz@mode
	% FIXME: using 'color=blue' will NOT activate filltrue!
	% So: if 'tikz@mode' *contains* 'fillfalse', I know what to do... 
	% but all other cases are not clear
	%--------------------------------------------------
	% \iftikz@mode@draw
	% \else
	% 	% Override the marker codes: force 'draw=none'
	% 	% even if the markers likes to be stroked:
	% 	\let\pgfusepathqfillstroke=\pgfusepathqfill
	% \fi
	% \iftikz@mode@fill
	% \else
	% 	% Override the marker codes: force 'fill=none'
	% 	% even if the markers likes to be filled:
	% 	\let\pgfusepathqfillstroke=\pgfusepathqstroke
	% \fi
	%-------------------------------------------------- 
	%
	% this here is the MAIN marker code.
	% It may be modified if scatter plot is enabled, see below.
	\def\pgfplots@loc@TMPa{%
		% the transformation has been reset before processing plot
		% marks.
		% Consequently, it applies only transformation options in "every mark".
		\tikz@transform
		\pgfuseplotmark{\tikz@plot@mark}%
	}%
	\ifpgfplots@scatterplotenabled
		% Scatter plots work like this:
		%
		% <compute per-point meta info>
		% /pgfplots/scatter/@pre marker code
		% <marker code, lowlevel>
		% /pgfplots/scatter/@post marker code
		%
		% -> that's all. The Rest is configurable with style which
		%  (re)define '@pre marker code' and '@post marker code' (see
		%  the docs for details).
		%
		% Prepare arguments for '@pre/@post' macros:
		\t@pgfplots@toka={%
			\begingroup
			% prepare programmatic access to '/data point/x' etc:
   			\pgfplotspointgetcoordinates
			\pgfplotsaxisvisphasetransformpointmeta
			\pgfkeysvalueof{/pgfplots/scatter/@pre marker code/.@cmd}\pgfeov
		}%
		\t@pgfplots@tokb=\expandafter{\pgfplots@loc@TMPa}%
		\t@pgfplots@tokc={%
			\pgfkeysvalueof{/pgfplots/scatter/@post marker code/.@cmd}\pgfeov
			\endgroup
		}%
		\edef\pgfplots@loc@TMPa{%
			\the\t@pgfplots@toka
			\the\t@pgfplots@tokb
			\the\t@pgfplots@tokc
		}%
		\if r\pgfplots@scatter@position
			% scatter/position=relative
			%
			% tikz transforms the coordinate system such that "(0,0)"
			% is the point where the mark should be placed.
		\else
			% scatter/position=absolute
			%
			% ah - we do not want tikz's transformation.
			%
			% Disable it by means of \aftergroup hackery:
			\t@pgfplots@tokc=\expandafter{\pgfplots@loc@TMPa}%
			\xdef\pgfplots@scatter@plot@mark{%
				\noexpand\begingroup
				\the\t@pgfplots@tokc
				\noexpand\endgroup
			}%
			\def\pgfplots@loc@TMPa{\aftergroup\pgfplots@scatter@plot@mark}%
		\fi
	\fi
	\def\pgfplots@loc@TMPb##1{%
		\ifx\tikz@mark@list\pgfutil@empty%
			\pgfplothandlermark{##1}%
		\else
			\pgfplothandlermarklisted{##1}{\tikz@mark@list}%
		\fi
	}%
	\t@pgfplots@tokc=\expandafter\expandafter\expandafter{\expandafter\pgfplots@loc@TMPb\expandafter{\pgfplots@loc@TMPa}}%
	\edef\pgfplots@basiclevel@plothandler{\the\t@pgfplots@tokc}%
	\expandafter\def\expandafter\pgfplots@basiclevel@plothandler\expandafter{%
		\pgfplots@basiclevel@plothandler
		\global\let\pgfplots@markers@plotstreamstart=\pgf@plotstreamstart
		\def\pgf@plotstreamstart{%
			\pgfplots@markers@plotstreamstart
			\global\let\pgfplots@markers@mark@handler@@=\pgf@plotstreampoint
			\global\let\pgf@plotstreampoint=\pgfplots@markers@mark@handler
		}%
	}%
	\let\tikz@plot@handler=\pgfplots@basiclevel@plothandler
	%
	\pgfplots@basiclevel@plothandler
	%
}%

\def\pgfplots@markers@mark@handler#1{%
	\ifpgfplots@clip
		% check for clip marker paths:
		\pgfplotsaxisifcontainspoint{\pgfplots@markers@mark@handler@@{#1}}{}%
	\else
		\pgfplots@markers@mark@handler@@{#1}
	\fi
}%


\def\pgfplots@markers@check@for@default@plot@mark{%
	% make sure there is a mark set!
	\pgfplots@gettikzinternal@keyval{mark}{tikz@plot@mark}{}%
	\def\pgfplots@loc@TMPa{none}%
	\ifx\tikz@plot@mark\pgfplots@loc@TMPa
		% this here happens only in older versions of pgf.
		\let\tikz@plot@mark\pgfutil@empty
	\fi
	\ifx\tikz@plot@mark\pgfutil@empty
		\pgfplots@getcurrent@plothandler\pgfplots@basiclevel@plothandler
		\ifx\pgfplots@basiclevel@plothandler\pgfplothandlerdiscard
			% oh, the "only marks" plot handler-- and no plot mark!?
			% what's that!?
			\ifpgfplots@scatterplotenabled
				% scatter handles this in /pgfplots/scatter/true
				% automatically.
			\else
				% that appears to be nonsense...
				\def\tikz@plot@mark{*}%
			\fi
		\fi
	\fi
}%


% Used inside of /pgfplots/scatter/classes :
\def\pgfplots@scatter@classes@pre@marker@code{%
	\pgfutil@ifundefined{pgfp@scatter@class@\pgfplotspointmeta}{%
		\let\pgfplots@loc@TMPa=\pgfplotspointmeta
		%
		% ups - no styles available? Maybe something went
		% wrong with the 'scatter src' key. Check whether it
		% was accidentally a numerical style:
		\if1\csname pgfpmeta@\pgfplotspointmetainputhandler @issymbolic\endcsname
		\else
			% ok, be fault tolerant and round to an integer:
			\pgfplotscoordmath{meta}{tofixed}{\pgfplotspointmeta}%
			\begingroup
			\pgfkeys{/pgf/number format/precision=0}%
			\expandafter\pgfmathroundto\expandafter{\pgfmathresult}%
			\pgfmath@smuggleone\pgfmathresult
			\endgroup
			\let\pgfplotspointmeta=\pgfmathresult
		\fi
		% now, check again:
		\pgfutil@ifundefined{pgfp@scatter@class@\pgfplotspointmeta}{%
			% still not possible? Then, try truncating the
			% number to an integer.
			\expandafter\pgfutil@in@\expandafter.\expandafter{\pgfplotspointmeta}%
			\ifpgfutil@in@
				\def\pgfplots@loc@TMPb##1.##2\relax{\def\pgfplotspointmeta{##1}}%
				\expandafter\pgfplots@loc@TMPb\pgfplots@loc@TMPa\relax
			\fi
			% now, check again:
			\pgfutil@ifundefined{pgfp@scatter@class@\pgfplotspointmeta}{%
				\pgfutil@ifundefined{pgfp@scatter@WARNING@\pgfplotspointmeta}{%
					\pgfplotswarning{scatter classes no such class}\pgfplotspointmeta\pgfeov%
					\expandafter\gdef\csname pgfp@scatter@WARNING@\pgfplotspointmeta\endcsname{ALREADY CHECKED}%
				}{}%
				\def\pgfplots@loc@TMPa{}%
			}{%
				\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfp@scatter@class@\pgfplotspointmeta\endcsname
			}%
		}{%
			\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfp@scatter@class@\pgfplotspointmeta\endcsname
		}%
	}{%
		\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfp@scatter@class@\pgfplotspointmeta\endcsname
	}%
	\expandafter\scope\expandafter[\pgfplots@loc@TMPa]%
}%

% validates 'mark layer' such that it can be queried afterwards.
\def\pgfplots@markers@prepare@layered@graphics@marks{%
	\ifpgfplots@layered@graphics
		\pgfkeysgetvalue{/pgfplots/mark layer}\pgfplots@loc@TMPa
		\edef\pgfplots@loc@TMPa{\pgfplots@loc@TMPa}%
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
			\def\pgfplots@loc@TMPa{auto}%
		\fi
		\def\pgfplots@loc@TMPb{auto}%
		\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
			% COMBINATION: 'activate layers,mark layer=auto' --> keep
			% backwards compatibility with 'clip marker paths'
			% -> nothing to do.
			\pgfkeyslet{/pgfplots/mark layer}\pgfutil@empty%
		\else
			% mark layer=like plot
			\def\pgfplots@loc@TMPb{like plot}%
			\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
				% draw markers together with their plot (no matter
				% on which layer):
				\pgfplots@clip@marker@pathstrue
				\pgfkeyslet{/pgfplots/mark layer}\pgfutil@empty%
			\else
				\edef\pgfplots@loc@TMPb{\pgfkeysvalueof{/pgfplots/on layer}}%
				\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
					% nothing to do; they are on the same layer
					% anyway: (this is the same as 'like plot'
					\pgfplots@clip@marker@pathstrue
					\pgfkeyslet{/pgfplots/mark layer}\pgfutil@empty%
				\else
					% OK, marks will be plotted on their own layer.
				\fi
			\fi
		\fi
	\else
		% reset its value:
		\pgfkeyslet{/pgfplots/mark layer}\pgfutil@empty%
	\fi
}%


pgfplotsmatrix.code.tex
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% This is a helper package with an elementary (full) matrix datastructure,
% featuring O(1) index access and O(N) creation, deletion, copy.
%
% The following macros are supplied:
%
% \pgfplotsmatrixnewempty
% \pgfplotsmatrixresize
% \pgfplotsmatrixsize
% \pgfplotsmatrixselect
% \pgfplotsmatrixset
% \pgfplotsmatrixletentry
% \pgfplotsmatrixforeach
% \pgfplotsmatrixLUdecomp
% \pgfplotsmatrixLUsolve
%
%
% Copyright 2007/2008 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Creates a new, empty matrix.
\def\pgfplotsmatrixnewempty#1{%
	\pgfplotsarray@@def{#1@rows}{0}%
	\pgfplotsarray@@def{#1@cols}{1}%
}

% resizes (truncates) matrix #1 to #2 rows and #3 cols.
%
% the elements won't be initialised. Use 'set' for each element.
\def\pgfplotsmatrixresize#1#2#3{%
	\pgfplotsarray@@edef{#1@rows}{#2}%
	\pgfplotsarray@@edef{#1@cols}{#3}%
}

% Invokes code '#2' if the matrix named '#1' exists and '#3' if it does
% not exist.
\def\pgfplotsmatrixifdefined#1#2#3{%
	\pgfutil@ifundefined{#1@rows}{#3}{#2}%
}%



% Counts the number of rows/cols in matrix #1, storing it into the count
% registers #2, #3.
% Example:
% \pgfplotsmatrixsize\foo\to{\count0}{\count1}%
% \the\count0, \the\count1
\long\def\pgfplotsmatrixsize#1\to#2#3{%
	#2=\csname\string#1@rows\endcsname\relax
	#3=\csname\string#1@cols\endcsname\relax
}

\long\def\pgfplotsmatrixsizetomacro#1\to#2#3{%
	\expandafter\let\expandafter#2\csname\string#1@rows\endcsname
	\expandafter\let\expandafter#3\csname\string#1@cols\endcsname
}


% Returns the (#1,#2) element of matrix #3 into macro #4
% Arguments:
% #1: a row index 0,...,N-1 where N is rowcount.
%     #1 must expand to an integer.
% #2: a col index 0,...,N-1 where N is colcount.
%     #2 must expand to an integer.
% #3: a matrix
% #4: a macro name
% Example:
%   Element 0:
%   \pgfplotsmatrixselect0,1\of\foo\to\elem
%   \elem
%   Element \count1:
%   \pgfplotsmatrixselect\count1,2\of\foo\to\elem
\def\pgfplotsmatrixselect#1,#2\of#3\to#4{%
	\expandafter\let\expandafter#4\csname\string#3@#1,#2\endcsname%
	\ifx#4\relax
		\pgfplotsthrow{no such element}{#1,#2}{No such element: \string\pgfplotsmatrixselect#1,#2\string\of{\string#3}}\pgfeov%
	\fi
}

% Expands to the value (#1,#2) of matrix #3.
% #1: a row index (not a register)
% #2: a col index 
% #3: a matrix
\def\pgfplotsmatrixvalueofelem#1,#2\of#3{\csname\string#3@#1,#2\endcsname}%

% Sets element '#1,#2' of matrix '#3' to '#4'.
\def\pgfplotsmatrixset#1,#2\of#3\to#4{%
	\pgfutil@namedef{\string#3@#1,#2}{#4}%
}
\long\def\pgfplotsmatrixletentry#1,#2\of#3=#4{%
	\expandafter\let\csname\string#3@#1,#2\endcsname=#4\relax
}

% During the loop, \pgfplotsmatrixforeachrowindex expands to the
% current row index and \pgfplotsmatrixforeachcolindex to the actual
% col index. It invokes \pgfplotsmatrixforeachrowend after each
% complete row.
%
% This macro uses
% \c@pgf@counta,\c@pgf@countb,\c@pgf@countc,\c@pgf@countd
\long\def\pgfplotsmatrixforeach#1\as#2#3{%
	\pgfplotsmatrixsize#1\to\c@pgf@countc\c@pgf@countd
	\long\def\pgfplotsmatrixforeach@{#3}%
	\def\pgfplotsmatrixforeach@assign##1{\def#2{##1}}%
	\def\pgfplotsmat@select##1,##2\to{\pgfplotsmatrixselect##1,##2\of#1\to}%
	\def\pgfplotsmatrixforeachrowindex{\the\c@pgf@counta}%
	\def\pgfplotsmatrixforeachcolindex{\the\c@pgf@countb}%
	\c@pgf@counta=0
	\pgfplotsmatrixforeach@loop
	\let\pgfplotsmatrixforeachcolindex\relax
	\let\pgfplotsmatrixforeachrowindex\relax%
}%
\let\pgfplotsmatrixforeachrowend=\relax
\def\pgfplotsmatrixforeach@loop{%
	\ifnum\c@pgf@counta<\c@pgf@countc
		\c@pgf@countb=0
		\pgfplotsmatrixforeach@loop@
		%
		\pgfplotsmatrixforeachrowend
		%
		\advance\c@pgf@counta by1
		\expandafter\pgfplotsmatrixforeach@loop
	\fi
}%
\def\pgfplotsmatrixforeach@loop@{%
	\ifnum\c@pgf@countb<\c@pgf@countd
		\pgfplotsmat@select\the\c@pgf@counta,\the\c@pgf@countb\to\pgfplotsmat@Aij
		\expandafter\pgfplotsmatrixforeach@assign\expandafter{\pgfplotsmat@Aij}%
		\pgfplotsmatrixforeach@
		%
		\advance\c@pgf@countb by1
		\expandafter\pgfplotsmatrixforeach@loop@
	\fi
}%

% Defines \pgfplotsretval to be a text-representation of the matrix.
% It will contain '\n' as newline macro and \t to separate cells.
%
\def\pgfplotsmatrixtotext#1{%
	\begingroup
	\pgfplotsapplistXnewempty\pgfplotsretval@
	\def\pgfplotsmatrixforeachrowend{%
		\pgfplotsapplistXpushback\n\to\pgfplotsretval@
	}%
	\pgfplotsmatrixforeach#1\as\entry{%
		\pgfmathfloatparsenumber\entry
		\pgfmathfloattosci\pgfmathresult
		\edef\entry{\pgfmathresult\noexpand\t}%
		\expandafter\pgfplotsapplistXpushback\entry\to\pgfplotsretval@
	}%
	\pgfplotsapplistXlet\pgfplotsretval=\pgfplotsretval@
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}

% Takes a matrix #1 and replaces it by its LU decomposition.
% The LU decomposition uses implicit pivoting; the pivoting
% information is stored in a permutation array #2 and a sign macro #3.
%
% It is to be used together with \pgfplotsmatrixsolveLEQS.
%
% #1: the input matrix (square size)
% #2: a macro name; will be used to store the permutation array for
% the pivoting.
% #3: a macro name, will contain the sign of the permutation (either
% +1 or -1).
%
% The algorithm has been converted from Numerical Recipes in C (I did
% not copy the comments, though). You find the complete reference in
% Chapter 2 of Numerical Recipes.
%
% If the matrix is singular, an exception will be raised.
% If the matrix is singular up to working precision,
% \pgfplotsmatrixLUdecompwarnsingular will be invoked and the
% algorithm continues with a small threshold.
%
% All arithmetics is computed with \pgfplotscoordmath{default} (which
% is float in the initial configuration). Use
% \pgfplotssetcoordmathfor{default}{pgfbasic} to switch it to standard
% pgf arithmetics.
%
% ATTENTION. This routine re-uses the four counters
% \c@pgf@counta,...\c@pgf@countd.
% Furthermore, it does not free any memory.
% Make sure you use it inside of local scopes.
\def\pgfplotsmatrixLUdecomp#1\perm#2\sign#3{%
	\let\pgfplotsmat@i=\c@pgf@counta
	\let\pgfplotsmat@imax=\c@pgf@countb
	\let\pgfplotsmat@j=\c@pgf@countc
	\let\pgfplotsmat@k=\c@pgf@countd
	\countdef\pgfplotsmat@n=0
	\let\pgfplotsmat@big=\pgfutil@empty
	\let\pgfplotsmat@dum=\pgfutil@empty
	\let\pgfplotsmat@sum=\pgfutil@empty
	\let\pgfplotsmat@temp=\pgfutil@empty
	\pgfplotsmatrixsize#1\to\pgfplotsmat@n\c@pgf@countd
	\ifnum\c@pgf@countd=\pgfplotsmat@n
	\else
		\pgfplots@error{Sorry, \string\pgfplotsmatrixLUdecomp\space expected an n x n matrix, but got \the\pgfplotsmat@n\space x \the\c@pgf@countd.}%
	\fi
	\pgfplotsarraynewempty\pgfplotsmat@vv
	\pgfplotsarrayresize\pgfplotsmat@vv\pgfplotsmat@n
	\pgfplotsarrayresize#2\pgfplotsmat@n
	\def\pgfplotsmat@parity{1}%
	\def\pgfplotsmat@select##1,##2\to{\pgfplotsmatrixselect##1,##2\of#1\to}%
	\def\pgfplotsmat@letentry##1,##2={\pgfplotsmatrixletentry##1,##2\of#1=}%
	\def\pgfplotsmat@letpermentry##1={\pgfplotsarrayletentry##1\of#2=}%
	%
	\pgfplotsmat@i=0
	\pgfplotsmatrixLUdecomp@scalingloop
	%
	\ifnum\pgfplotsmat@n>0 % this is used for error recovery.
		%
		\pgfplotsmat@j=0
		\pgfplotsmatrixLUdecomp@mainloop@j
		%
		\let#3=\pgfplotsmat@parity
	\fi
}%
\def\pgfplotsmatrixLUdecomp@scalingloop{%
	\ifnum\pgfplotsmat@i<\pgfplotsmat@n
		\pgfplotscoordmath{default}{zero}%
		\let\pgfplotsmat@big=\pgfmathresult
		%
		\pgfplotsmat@j=0
		\pgfplotsmatrixLUdecomp@scalingloop@
		%
		\pgfplotscoordmath{default}{if is}{\pgfplotsmat@big}{0}{%
			\pgfplotsthrow{invalid argument}{\pgfplots@loc@TMPa}{Singular matrix in \string\pgfplotsmatrixLUdecomp}\pgfeov%
			\pgfplotsmat@n=-1
		}{%
			\pgfplotscoordmath{default}{op}{reciprocal}{{\pgfplotsmat@big}}%
			\pgfplotsarrayletentry\pgfplotsmat@i\of\pgfplotsmat@vv=\pgfmathresult
		}%
		%
		\advance\pgfplotsmat@i by1
		\expandafter\pgfplotsmatrixLUdecomp@scalingloop
	\fi
}%
\def\pgfplotsmatrixLUdecomp@scalingloop@{%
	\ifnum\pgfplotsmat@j<\pgfplotsmat@n
		%
		\pgfplotsmat@select\the\pgfplotsmat@i,\the\pgfplotsmat@j\to\pgfplotsmat@Aij
		\pgfplotscoordmath{default}{parsenumber}{\pgfplotsmat@Aij}%
		\let\pgfplotsmat@Aij=\pgfmathresult
		\pgfplotsmat@letentry\the\pgfplotsmat@i,\the\pgfplotsmat@j=\pgfplotsmat@Aij
		%
		\pgfplotscoordmath{default}{op}{abs}{{\pgfplotsmat@Aij}}%
		\let\pgfplotsmat@temp=\pgfmathresult
		\pgfplotscoordmath{default}{max}{\pgfplotsmat@temp}{\pgfplotsmat@big}%
		\let\pgfplotsmat@big=\pgfmathresult
		%
		\advance\pgfplotsmat@j by1
		\expandafter\pgfplotsmatrixLUdecomp@scalingloop@
	\fi
}%

\def\pgfplotsmatrixLUdecomp@mainloop@j{%
	\ifnum\pgfplotsmat@j<\pgfplotsmat@n
		%
		\pgfplotsmat@i=0
		\pgfplotsmatrixLUdecomp@mainloop@j@i
		%
		\pgfplotscoordmath{default}{zero}%
		\let\pgfplotsmat@big=\pgfmathresult
		%
		\pgfplotsmat@i=\pgfplotsmat@j
		\pgfplotsmatrixLUdecomp@mainloop@j@i@second
		%
		\ifnum\pgfplotsmat@j=\pgfplotsmat@imax
		\else
			% interchange rows...
			\pgfplotsmat@k=0
			\pgfplotsmatrixLUdecomp@mainloop@j@k
			%
			\c@pgfplotsarray@tmp=-\pgfplotsmat@parity\relax%
			\edef\pgfplotsmat@parity{\the\c@pgfplotsarray@tmp}%
			%
			% FIXME : this here is DIFFERENT. Seems there is something
			% missing in Numerical Recipes book
			\pgfplotsarrayselect\pgfplotsmat@j\of\pgfplotsmat@vv\to\pgfplotsmat@dum
			%\pgfplotsarrayselect\pgfplotsmat@imax\of\pgfplotsmat@vv\to\pgfplotsmat@temp
			%\pgfplotsarrayletentry\pgfplotsmat@j\of\pgfplotsmat@vv=\pgfplotsmat@temp
			\pgfplotsarrayletentry\pgfplotsmat@imax\of\pgfplotsmat@vv=\pgfplotsmat@dum
		\fi
		%
		\edef\pgfplotsmat@dum{\the\pgfplotsmat@imax}%
		\pgfplotsmat@letpermentry\pgfplotsmat@j=\pgfplotsmat@dum
		%
		\pgfplotsmat@select\the\pgfplotsmat@j,\the\pgfplotsmat@j\to\pgfplotsmat@Ajj
		\pgfplotscoordmath{default}{if is}{\pgfplotsmat@Ajj}{0}{%
			\pgfplotscoordmath{default}{parsenumber}{1e-15}%
			\pgfplotsmatrixLUdecompwarnsingular
			\pgfplotsmat@letentry\the\pgfplotsmat@j,\the\pgfplotsmat@j=\pgfmathresult
		}{%
		}%
		%
		%
		\advance\pgfplotsmat@j by1
		\ifnum\pgfplotsmat@j=\pgfplotsmat@n
			\advance\pgfplotsmat@j by-1
		\else
			\advance\pgfplotsmat@j by-1
			\pgfplotsmat@select\the\pgfplotsmat@j,\the\pgfplotsmat@j\to\pgfplotsmat@Ajj
			\pgfplotscoordmath{default}{op}{reciprocal}{{\pgfplotsmat@Ajj}}%
			\let\pgfplotsmat@dum=\pgfmathresult
			\pgfplotsmat@i=\pgfplotsmat@j
			\advance\pgfplotsmat@i by1
			\pgfplotsmatrixLUdecomp@mainloop@j@i@final
		\fi
		\advance\pgfplotsmat@j by1
		\expandafter\pgfplotsmatrixLUdecomp@mainloop@j
	\fi
}%
\def\pgfplotsmatrixLUdecompwarnsingular{%
	\pgfplotswarning{linear system singular}\pgfeov%
}%
\def\pgfplotsmatrixLUdecomp@mainloop@j@i{%
	\ifnum\pgfplotsmat@i<\pgfplotsmat@j
		%
		\pgfplotsmat@select\the\pgfplotsmat@i,\the\pgfplotsmat@j\to\pgfplotsmat@sum
		\pgfplotsmat@k=0
		\pgfplotsmatrixLUdecomp@mainloop@j@i@k
		\pgfplotsmat@letentry\the\pgfplotsmat@i,\the\pgfplotsmat@j=\pgfplotsmat@sum
		%
		\advance\pgfplotsmat@i by1
		\expandafter\pgfplotsmatrixLUdecomp@mainloop@j@i
	\fi
}%
\def\pgfplotsmatrixLUdecomp@mainloop@j@i@k{%
	\ifnum\pgfplotsmat@k<\pgfplotsmat@i
		%
		\pgfplotsmat@select\the\pgfplotsmat@i,\the\pgfplotsmat@k\to\pgfplotsmat@Aik
		\pgfplotsmat@select\the\pgfplotsmat@k,\the\pgfplotsmat@j\to\pgfplotsmat@Akj
		\pgfplotscoordmath{default}{op}{multiply}{{\pgfplotsmat@Aik}{\pgfplotsmat@Akj}}%
		\pgfplotscoordmath{default}{op}{subtract}{{\pgfplotsmat@sum}{\pgfmathresult}}%
		\let\pgfplotsmat@sum=\pgfmathresult
		%
		\advance\pgfplotsmat@k by1
		\expandafter\pgfplotsmatrixLUdecomp@mainloop@j@i@k
	\fi
}
\def\pgfplotsmatrixLUdecomp@mainloop@j@i@second{%
	\ifnum\pgfplotsmat@i<\pgfplotsmat@n
		%
		\pgfplotsmat@select\the\pgfplotsmat@i,\the\pgfplotsmat@j\to\pgfplotsmat@sum
		%
		\pgfplotsmat@k=0
		\pgfplotsmatrixLUdecomp@mainloop@j@i@second@k
		\pgfplotsmat@letentry\the\pgfplotsmat@i,\the\pgfplotsmat@j=\pgfplotsmat@sum
		%
		\pgfplotscoordmath{default}{op}{abs}{{\pgfplotsmat@sum}}%
		\pgfplotscoordmath{default}{op}{multiply}{{\pgfmathresult}{\pgfplotsarrayvalueofelem\the\pgfplotsmat@i\of\pgfplotsmat@vv}}%
		\let\pgfplotsmat@dum=\pgfmathresult
		\pgfplotscoordmath{default}{if less than}{\pgfplotsmat@dum}{\pgfplotsmat@big}{%
		}{%
			\let\pgfplotsmat@big=\pgfplotsmat@dum
			\pgfplotsmat@imax=\pgfplotsmat@i
		}%
		%
		\advance\pgfplotsmat@i by1
		\expandafter\pgfplotsmatrixLUdecomp@mainloop@j@i@second
	\fi
}%
\def\pgfplotsmatrixLUdecomp@mainloop@j@i@second@k{%
	\ifnum\pgfplotsmat@k<\pgfplotsmat@j
		%
		\pgfplotsmat@select\the\pgfplotsmat@i,\the\pgfplotsmat@k\to\pgfplotsmat@Aik
		\pgfplotsmat@select\the\pgfplotsmat@k,\the\pgfplotsmat@j\to\pgfplotsmat@Akj
		\pgfplotscoordmath{default}{op}{multiply}{{\pgfplotsmat@Aik}{\pgfplotsmat@Akj}}%
		\pgfplotscoordmath{default}{op}{subtract}{{\pgfplotsmat@sum}{\pgfmathresult}}%
		\let\pgfplotsmat@sum=\pgfmathresult
		%
		\advance\pgfplotsmat@k by1
		\expandafter\pgfplotsmatrixLUdecomp@mainloop@j@i@second@k
	\fi
}%

\def\pgfplotsmatrixLUdecomp@mainloop@j@k{%
	\ifnum\pgfplotsmat@k<\pgfplotsmat@n
		%
		\pgfplotsmat@select\the\pgfplotsmat@imax,\the\pgfplotsmat@k\to\pgfplotsmat@dum
		\pgfplotsmat@select\the\pgfplotsmat@j,\the\pgfplotsmat@k\to\pgfplotsmat@Ajk
		\pgfplotsmat@letentry\the\pgfplotsmat@imax,\the\pgfplotsmat@k=\pgfplotsmat@Ajk
		\pgfplotsmat@letentry\the\pgfplotsmat@j,\the\pgfplotsmat@k=\pgfplotsmat@dum
		%
		\advance\pgfplotsmat@k by1
		\expandafter\pgfplotsmatrixLUdecomp@mainloop@j@k
	\fi
}
\def\pgfplotsmatrixLUdecomp@mainloop@j@i@final{%
	\ifnum\pgfplotsmat@i<\pgfplotsmat@n
		%
		\pgfplotsmat@select\the\pgfplotsmat@i,\the\pgfplotsmat@j\to\pgfplotsmat@Aij
		\pgfplotscoordmath{default}{op}{multiply}{{\pgfplotsmat@Aij}{\pgfplotsmat@dum}}%
		\pgfplotsmat@letentry\the\pgfplotsmat@i,\the\pgfplotsmat@j=\pgfmathresult
		%
		\advance\pgfplotsmat@i by1
		\expandafter\pgfplotsmatrixLUdecomp@mainloop@j@i@final
	\fi
}



% Solves the set of n linear equations Ax = b where A = LU is given in
% (#1,#2) and b = #3.
%
% #1: is a result of \pgfplotsmatrixLUdecomp
% #2: is the permutation vector returned by \pgfplotsmatrixLUdecomp
% #3: the right hand side. On output, it will be *overwritten* with
% the solution.
%
% The algorithm has been converted from Numerical Recipes in C (I did
% not copy the comments, though). You find the complete reference in
% Chapter 2 of Numerical Recipes.
\def\pgfplotsmatrixLUbacksubst#1\perm#2\inout#3{%
	\let\pgfplotsmat@i=\c@pgf@counta
	\let\pgfplotsmat@ii=\c@pgf@countb
	\let\pgfplotsmat@j=\c@pgf@countc
	\let\pgfplotsmat@n=\c@pgf@countd
	\let\pgfplotsmat@sum=\pgfutil@empty
	\pgfplotsmatrixsize#1\to\pgfplotsmat@n\c@pgf@counta
	\pgfplotsarraysize#3\to\c@pgf@counta
	\ifnum\c@pgf@counta=\pgfplotsmat@n
		\def\pgfplotsmat@select##1,##2\to{\pgfplotsmatrixselect##1,##2\of#1\to}%
		\def\pgfplotsmat@selectperm##1\to{\pgfplotsarrayselect##1\of#2\to}%
		\def\pgfplotsmat@selectb##1\to{\pgfplotsarrayselect##1\of#3\to}%
		\def\pgfplotsmat@letresult##1={\pgfplotsarrayletentry##1\of#3=}%
		%
		\pgfplotsmat@ii=-1
		\pgfplotsmat@i=0
		\pgfplotsmatrixLUbacksubst@loop@i
		%
		\pgfplotsmat@i=\pgfplotsmat@n
		\advance\pgfplotsmat@i by-1
		\pgfplotsmatrixLUbacksubst@loop@i@backw
	\else
		\pgfplots@error{Sorry, \string\pgfplotsmatrixLUbacksubst\space expected a vector of length \the\pgfplotsmat@n\space, not \the\c@pgf@counta}%
	\fi
}%
\def\pgfplotsmatrixLUbacksubst@loop@i{%
	\ifnum\pgfplotsmat@i<\pgfplotsmat@n
		%
		\pgfplotsmat@selectperm\pgfplotsmat@i\to\pgfplotsmat@ip
		\pgfplotsmat@selectb\pgfplotsmat@ip\to\pgfplotsmat@sum
		\pgfplotsmat@selectb\pgfplotsmat@i\to\pgfplotsmat@temp
		%
		\pgfplotscoordmath{default}{parsenumber}{\pgfplotsmat@sum}%
		\let\pgfplotsmat@sum=\pgfmathresult
		\pgfplotscoordmath{default}{parsenumber}{\pgfplotsmat@temp}%
		\let\pgfplotsmat@temp=\pgfmathresult
		%
		\pgfplotsmat@letresult\pgfplotsmat@ip=\pgfplotsmat@temp
		%
		\ifnum\pgfplotsmat@ii<0
			\pgfplotscoordmath{default}{if is}{\pgfplotsmat@sum}{0}{%
			}{%
				\pgfplotsmat@ii=\pgfplotsmat@i
			}%
		\else
			\pgfplotsmat@j=\pgfplotsmat@ii
			\pgfplotsmatrixLUbacksubst@loop@i@j
		\fi
		\pgfplotsmat@letresult\pgfplotsmat@i=\pgfplotsmat@sum
		%
		\advance\pgfplotsmat@i by1
		\expandafter\pgfplotsmatrixLUbacksubst@loop@i
	\fi
}%
\def\pgfplotsmatrixLUbacksubst@loop@i@j{%
	\ifnum\pgfplotsmat@j<\pgfplotsmat@i
		%
		\pgfplotsmat@select\the\pgfplotsmat@i,\the\pgfplotsmat@j\to\pgfplotsmat@Aij
		\pgfplotsmat@selectb\pgfplotsmat@j\to\pgfplotsmat@temp
		\pgfplotscoordmath{default}{op}{multiply}{{\pgfplotsmat@temp}{\pgfplotsmat@Aij}}%
		\pgfplotscoordmath{default}{op}{subtract}{{\pgfplotsmat@sum}{\pgfmathresult}}%
		\let\pgfplotsmat@sum=\pgfmathresult
		%
		\advance\pgfplotsmat@j by1
		\expandafter\pgfplotsmatrixLUbacksubst@loop@i@j
	\fi
}%

\def\pgfplotsmatrixLUbacksubst@loop@i@backw{%
	\ifnum\pgfplotsmat@i<0
	\else
		%
		\pgfplotsmat@selectb\pgfplotsmat@i\to\pgfplotsmat@sum
		\pgfplotsmat@j=\pgfplotsmat@i
		\advance\pgfplotsmat@j by1
		\pgfplotsmatrixLUbacksubst@loop@i@backw@j
		%
		\pgfplotsmat@select\the\pgfplotsmat@i,\the\pgfplotsmat@i\to\pgfplotsmat@Aii
		\pgfplotscoordmath{default}{op}{divide}{{\pgfplotsmat@sum}{\pgfplotsmat@Aii}}%
		\pgfplotsmat@letresult\pgfplotsmat@i=\pgfmathresult
		%
		\advance\pgfplotsmat@i by-1
		\expandafter\pgfplotsmatrixLUbacksubst@loop@i@backw
	\fi
}%
\def\pgfplotsmatrixLUbacksubst@loop@i@backw@j{%
	\ifnum\pgfplotsmat@j<\pgfplotsmat@n
		%
		\pgfplotsmat@select\the\pgfplotsmat@i,\the\pgfplotsmat@j\to\pgfplotsmat@Aij
		\pgfplotsmat@selectb\pgfplotsmat@j\to\pgfplotsmat@temp
		\pgfplotscoordmath{default}{op}{multiply}{{\pgfplotsmat@temp}{\pgfplotsmat@Aij}}%
		\pgfplotscoordmath{default}{op}{subtract}{{\pgfplotsmat@sum}{\pgfmathresult}}%
		\let\pgfplotsmat@sum=\pgfmathresult
		%
		\advance\pgfplotsmat@j by1
		\expandafter\pgfplotsmatrixLUbacksubst@loop@i@backw@j
	\fi
}%

% Solves the linear equation system Ax = b.
% #1: the matrix A
% #2: the right-hand-side b. On output, #2 will contain the solution
% and A will be overwritten.
%
% ATTENTION. This routine re-uses the four counters
% \c@pgf@counta,...\c@pgf@countd.
% Furthermore, it does not free any memory.
% Make sure you use it inside of local scopes.
\def\pgfplotsmatrixsolveLEQS#1=#2{%
	\pgfplotsmatrixLUdecomp#1\perm\pgfplotsmatrix@perm\sign\pgfplotsmatrix@sign
	\pgfplotsmatrixLUbacksubst#1\perm\pgfplotsmatrix@perm\inout#2%
}%

pgfplotsmeshplothandler.code.tex
%--------------------------------------------
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2007-2010 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------

% The low-level tikz plot handler for 3D mesh and surface plots.
%
% It expects 
% a) a coordinate stream which is a linearized matrix, iterated either
% rowwise or column wise,
% b) the current set of options in /pgfplots/mesh/.
%
%
% ATTENTION:
% 	this handler is NOT as general as the others. In particular, it
% 	can't be interrupted by TeX groups: every single statement,
% 	starting with streamstart and ending with stream end, must be in
% 	the same scope!
%
% 	As a consequence, you can't use this handler inside of (all) TikZ
% 	input streams. Try it out. It will work in pgfplots, however.
%
% Furthermore, it relies on a couple of pgfplots macros. This may
% change in future versions.
% It relies on:
% 	- \ifpgfplots@curplot@threedim
% 	- \pgfplots@current@point@meta
% 		-> it also invokes \pgfplots@perpointmeta@preparetrafo and its
% 		@APPLY counterpart which checks for
% 	- \pgfplots@metamax
% 		If you use it outside of pgfplots, use
% 		\global\let\pgfplots@metamax=\pgfutil@empty
% 		This is can be used without an initialised
% 		pgfplots axes - as long as \pgfplots@current@point@meta is in
% 		the range [0,1000].
% 	- for the case 'shader=interp', a bounding box must be established
% 	before the plot is finished. This must be done using 
%	\def\pgfplotspointbbupperright{\pgfqpointxyz{2}{2}{0.9}}
%	\def\pgfplotspointbblowerleft {\pgfqpointxyz{0}{0}{0.1}}
%	or something like that.
%
% Besides these internals, it also relies on all public /pgfplots
% configuration keys related to mesh/surface plots.
%
% Please note that the 'z buffer' feature will not work without
% pgfplots (especially the z buffer=sort feature).
%
% Here is an example which compiles without a pgfplots axes:
% ----------------------------------------------------------
% \begin{tikzpicture}
% 	\scope[
% 		/pgfplots/.cd,
% 		surf,
% 		shader=faceted,
% 		mesh/rows=4,
% 		mesh/cols=4,
% 		mesh/num points=,
% 		/tikz/x={(0.44237cm,-0.07439cm)}, 
% 		/tikz/y={(0.30942cm,0.23932cm)},
% 		/tikz/z={(0.0cm,1.5cm)},
% 	]
% \makeatletter
% 
% 	\global\let\pgfplots@metamax=\pgfutil@empty
% 	\pgfplots@curplot@threedimtrue
% 
% 	\pgfplotsplothandlermesh
% 	\pgfplotstreamstart
% 
% 	\def\rangea{0.21}%
% 	\def\rangeb{0.9}%
% 
% 	\pgfmathparse{1000/(\rangeb-\rangea)}
% 	\let\factor=\pgfmathresult
% 
% 	\def\simplecoordinate(#1,#2,#3){%
% 		\pgfmathparse{\factor*(#3 - \rangea)}%
% 		\let\pgfplots@current@point@meta=\pgfmathresult
% 		\pgfplotstreampoint{\pgfqpointxyz{#1}{#2}{#3}}%
% 	}%
% 	% for the case 'shaer=interp':
%	\def\pgfplotspointbbupperright{\pgfqpointxyz{2}{2}{0.9}}
%	\def\pgfplotspointbblowerleft {\pgfqpointxyz{0}{0}{0.1}}
% 
% \simplecoordinate(0,3,0.7)
% \simplecoordinate(1,3,0.5)
% \simplecoordinate(2,3,0.58)
% \simplecoordinate(3,3,0.9)
% 
% \simplecoordinate(0,2,0.68)
% \simplecoordinate(1,2,0.22)
% \simplecoordinate(2,2,0.25)
% \simplecoordinate(3,2,0.4)
% 
% \simplecoordinate(0,1,0.6)
% \simplecoordinate(1,1,0.3)
% \simplecoordinate(2,1,0.21)
% \simplecoordinate(3,1,0.3)
% 
% \simplecoordinate(0,0,0.8)
% \simplecoordinate(1,0,0.56)
% \simplecoordinate(2,0,0.5)
% \simplecoordinate(3,0,0.75)
% 
% 
% 	\pgfplotstreamend
% 	\pgfusepath{stroke}
% 
% 	\endscope
% \end{tikzpicture}
% ----------------------------------------------------------
%  END OF EXAMPLE
%  -> see also the legend image for mesh plots.
%
\def\pgfplotsplothandlermesh{%
	\pgfkeysgetvalue{/pgfplots/patch type}\pgfplotsplothandlermesh@patchclass
	\ifx\pgfplotsplothandlermesh@patchclass\pgfplotsplothandlermesh@patchclass@defaulttext
		\let\pgfplotsplothandlermesh@patchclass=\pgfutil@empty
	\fi
	% FIXME : detect 1d mode here!
	\ifx\pgfplotsplothandlermesh@patchclass\pgfutil@empty
		% assign default patch class.
		\if1\pgfplotsplothandlermesh@matrixinput
			\def\pgfplotsplothandlermesh@patchclass{rectangle}%
		\else
			\def\pgfplotsplothandlermesh@patchclass{triangle}%
		\fi
		\pgfkeyslet{/pgfplots/patch type}\pgfplotsplothandlermesh@patchclass
	\fi
	%
	\if0\pgfplotsplothandlermesh@matrixinput
		% mesh input=patches: simply skip empty input lines:
		\pgfkeyssetvalue{/pgfplots/empty line}{none}%
	\fi
	%
	\let\pgfplotsplothandlersurveystart=\pgfplotsplothandlersurveystart@mesh
	\let\pgfplotsplothandlersurveyend=\pgfplotsplothandlersurveyend@mesh
	\let\pgfplotsplothandlersurveyaftersetpointmeta=\pgfplotsplothandlersurveyaftersetpointmeta@mesh@cdatanormalize
	%
	\pgfkeysgetvalue{/pgfplots/patch table/value}\pgfplotsplothandlermesh@patchtable
	\ifx\pgfplotsplothandlermesh@patchtable\pgfutil@empty
	\else
		\def\pgfplotsplothandlermesh@matrixinput{0}% implies 'patch input=patches'
		\let\pgfplotsplothandlersurveystart=\pgfplotsplothandlersurveystart@mesh@patchtable
		\let\pgfplotsplothandlersurveypoint=\pgfplotsplothandlersurveypoint@mesh@patchtable
		\let\pgfplotsplothandlersurveyend=\pgfplotsplothandlersurveyend@mesh@patchtable
	\fi
	\if0\pgfplotsplothandlermesh@colorinput
		% mesh/color input=colormap
	\else
		% mesh/color input=explicit
		\if0\csname pgfpmeta@\pgfplotspointmetainputhandler @issymbolic\endcsname
			\pgfplotsthrow{invalid argument}{\pgfplots@loc@TMPa}{Sorry, color input!=colormap requires 'point meta=symbolic' or 'explicit symbolic'. Please adjust the format of your input point meta data}\pgfeov%
		\fi
	\fi
	%
	\def\pgf@plotstreamstart{%
%		\scope
		%
		% this shouldn't be necessary, but it doesn't hurt either.
		\pgfplots@perpointmeta@preparetrafo
		%
		\def\pgfplotsplothandlermesh@ONEDIMMODE{0}%
		\pgfplotsplothandlermesh@init@meshkeys
		%
		%
		\let\pgfplotsplothandlermesh@patchclass@input=\pgfplotsplothandlermesh@patchclass
		\let\pgfplotsplothandlermesh@patchclass@output=\pgfplotsplothandlermesh@patchclass@input
		\if0\pgfplotsplothandlermesh@triangulate
		\else
			\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@input}{triangulate class}%
			\let\pgfplotsplothandlermesh@patchclass@output=\pgfplotsretval
		\fi
		%
		\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@input}{init}%
		\ifx\pgfplotsplothandlermesh@patchclass@input\pgfplotsplothandlermesh@patchclass@output
		\else
			\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@output}{init}%
		\fi
		%
		% assign boolean:
		\let\b@pgfplotsplothandlermesh@matrixoutput=\pgfplotsplothandlermesh@matrixinput
		\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@output}{allow matrix}%
		\if0\pgfplotsretval
			\def\b@pgfplotsplothandlermesh@matrixoutput{0}%
		\fi
		\ifnum\pgfkeysvalueof{/pgfplots/patch refines}>0
			\def\b@pgfplotsplothandlermesh@matrixoutput{0}%
		\fi
		\if1\pgfplotsaxisplothasjumps
			\def\b@pgfplotsplothandlermesh@matrixoutput{0}%
		\fi
		\if\pgfplotsplothandlermesh@zbuffer@choice4% 'z buffer=sort':
			\def\b@pgfplotsplothandlermesh@matrixoutput{0}%
		\fi
		%
		\if2\pgfplotsplothandlermesh@shader
			% shader=interp
			%
			\pgfkeysgetvalue{/pgfplots/mesh/interior colormap name}\pgfplots@loc@TMPc
			\ifx\pgfplots@loc@TMPc\pgfutil@empty
			\else
				\pgfplotswarning{interior colormap inefficient}\pgfeov%
				\pgfplotsset{shader=faceted interp,faceted color=none}%
			\fi
		\fi
		\if2\pgfplotsplothandlermesh@shader
			% shader=interp
			\if0\pgfplotsplothandlermesh@triangulate
			 	% patch to triangles=false
			\else
				% no matrix output possible:
				\def\b@pgfplotsplothandlermesh@matrixoutput{0}%
			\fi
		\else
			% 'shader!=interp'
			\def\b@pgfplotsplothandlermesh@matrixoutput{0}%
		\fi
		\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@output}{get pdf shading type}%
		\if5\pgfplotsretval
		\else
			\def\b@pgfplotsplothandlermesh@matrixoutput{0}%
		\fi
		%
		% special handling: check if Type=5 shadings need to be
		% converted to Type=4
		\if0\b@pgfplotsplothandlermesh@matrixoutput
			% no matrix output possible
			\if5\pgfplotsretval
				% pdf shading type=5 (matrix output)
				\if2\pgfplotsplothandlermesh@shader
					% shader=interp
					%
					% FIXME : I am unsure if this here is still
					% necessary as of 3fc734d7ac3020600c06258b1bc80b22da53edf3
					% -> perhaps the check can be skipped entirely.
					%
					% oh. shading type=5 is *essentially* the same as
					% matrix output, but matrix output is forbidden. 
					% In that case, triangulate the matrix and shade the
					% triangles:
					\def\pgfplotsplothandlermesh@triangulate{1}%
					\def\pgfplotsplothandlermesh@patchclass@output{triangle}%
					% Note shader=faceted interp  can be written as
					% matrix -- it shades individual elements anyway;
					% and one single patch can be written as matrix.
				\fi
			\fi
		\fi
		%
		\pgfplotsplothandlermesh@init@DECODE
		\pgfplotsplothandlermesh@init@REFINE
		%
		\pgfutil@IfUndefined{pgfplots@drawmodes}{%
			\let\pgfplots@drawmodes=\tikz@mode
			\let\pgfplots@drawoptions=\tikz@options
		}{}%
		%
		%
		% Prepare color data source:
		\ifx\pgfplotspointmetainputhandler\pgfutil@empty%
			% oh. There is no color data!? 
			\pgfplotsplothandlermesh@init@path@without@point@meta
			%
		\else
			\pgfplotsplothandlermesh@init@cdata
			\pgfplotsplothandlermesh@init@shader
			\pgfplotsplothandlermesh@init@flat@color
		\fi
		% PREPARE THE STREAM PROCESSING:
		% handling of jumps.
		\pgfplotsplothandlermesh@init@jumphandling
		%
		\ifpgfplotsplothandlermesh@shownormals
			\let\pgfplotsplothandlermesh@show@normals@if@configured=\pgfplotsplothandlermesh@show@normals
			% actually store 3d coordinates:
			\let\pgfplotsplothandlermesh@serialize@logical@coords=\pgfplotsplothandlermesh@serialize@logical@coords@doit
		\fi
		%
		% z buffering:
		\pgfplotsplothandlermesh@init@zbuffer
		%
		\pgfplotsplothandlermesh@init@mesh@stream
		%
		\c@pgfplots@scanlineindex=0
	}%
	%
	\let\pgfplotsplothandlerifcurrentpointcanbefirstlast=\pgfplotsplothandlerifcurrentpointcanbefirstlast@mesh
}%

\def\pgfplotsplothandlerifcurrentpointcanbefirstlast@mesh#1#2{%
	\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@output}{if current point can be first last}{#1}{#2}%
}%

% Assigns default values to 'rows' and 'cols' in case
% their values are empty.
%
% PRECONDITION:
% 	The values of
% - '/pgfplots/mesh/rows' 
% - '/pgfplots/mesh/cols'
% - '/pgfplots/mesh/num points'
% - \pgfplotsscanlinelength
% - '/pgfplots/mesh/ordering'
%   are assigned properly.
%
% POSTCONDITION:
% 	'rows' and 'cols' now incorporates \pgfplotsscanlinelength if
% 	their values had been empty. However, there may still be empty
% 	values.
%
% @see \pgfplotsautocompletemeshkeys
\def\pgfplotspreparemeshkeydefaults{%
	\pgfplots@autocomplete@meshkeys0%
}%

% Completes and sanitizes 'mesh/rows' and 'mesh/cols' such that they
% have useful integer values afterwards.
%
% This method works similarly to \pgfplotspreparemeshkeydefaults.
% However, it really completes values and issues error messages if
% that proves to be impossible.
%
% PRECONDITION:
% 	The values of
% - '/pgfplots/mesh/rows' 
% - '/pgfplots/mesh/cols'
% - '/pgfplots/mesh/num points'
% - '/pgfplots/mesh/ordering'
%   are assigned properly.
%   If 
% - \pgfplotsscanlinelength
%   exists and is positive, it may also be used.
%
% POSTCONDITION:
% 	'rows' and 'cols' have useful integer values.
\def\pgfplotsautocompletemeshkeys{%
	\pgfplots@autocomplete@meshkeys1%
}%
\def\pgfplots@autocomplete@meshkeys#1{%
	% For #1 = 0, the values are only partially completed (which is
	% also compatible with patch plots)
	\pgfkeysgetvalue{/pgfplots/mesh/rows}\pgfplotsplothandlermesh@rows
	\pgfkeysgetvalue{/pgfplots/mesh/cols}\pgfplotsplothandlermesh@cols
	\pgfkeysgetvalue{/pgfplots/mesh/num points}\pgfplotsplothandlermesh@numpoints
	\edef\pgfplotsplothandlermesh@numpoints{\pgfplotsplothandlermesh@numpoints}%
	\edef\pgfplotsplothandlermesh@cols{\pgfplotsplothandlermesh@cols}%
	\edef\pgfplotsplothandlermesh@rows{\pgfplotsplothandlermesh@rows}%
	%
	\def\pgfplots@loc@TMPa{0}%
	\ifpgfplots@curplot@threedim
		\def\pgfplots@loc@TMPa{1}%
	\else
		\if s\pgfplots@meshmode
			% we have a 'surf' plot. That doesn't make sense unless
			% one has a matrix, even for a two--dimensional plot. Try it.
			\def\pgfplots@loc@TMPa{1}%
		\fi
	\fi
	\if1\pgfplots@loc@TMPa
		\ifx\pgfplotsplothandlermesh@rows\pgfutil@empty
			\ifx\pgfplotsplothandlermesh@cols\pgfutil@empty
				\pgfutil@ifundefined{pgfplotsscanlinelength}{\def\pgfplotsscanlinelength{-1}}{}%
				\ifpgfplots@scanline@verbose
					\ifnum\pgfplotsscanlinelength>0
						% we have scanlinelength set! Use it:
						\message{PGFPlots: Scanline length is \pgfplotsscanlinelength.}%
					\else
						\ifnum\pgfplotsscanlinelength=-2
							\message{PGFPlots: Scanline length could not be determined since multiple, different scan line lengths have been found.}%
						\else
							\message{PGFPlots: No end-of-scanline marker found in input stream.}%
						\fi
					\fi
				\fi
				\ifnum\pgfplotsscanlinelength>0
					% we have scanlinelength set! Use it:
					\if\pgfplots@plot@mesh@ordering0%
						% ordering = x varies= rowwise -> scanline is cols!
						\edef\pgfplotsplothandlermesh@cols{\pgfplotsscanlinelength}%
					\else
						% ordering = y varies = colwise: scanline is rows!
						\edef\pgfplotsplothandlermesh@rows{\pgfplotsscanlinelength}%
					\fi
				\else
					\if1#1%
						% try to get reasonable values:
						\ifx\pgfplotsplothandlermesh@numpoints\pgfutil@empty
							\pgfplots@error{Sorry, a mesh needs either '[mesh/rows=<N>]' or '[mesh/cols=<N>]' set - or at least '[mesh/num points=<N>]'. But it did not find any of them...}%
							\def\pgfplotsplothandlermesh@cols{5}%
							\def\pgfplotsplothandlermesh@rows{5}%
						\else
							% We don't have rows/cols. Well, try using
							% sqrt(num points) for both of them!
							\ifnum\pgfplotsplothandlermesh@numpoints<16380
								\pgfmath@basic@sqrt@{\pgfplotsplothandlermesh@numpoints}%
							\else
								\pgfmathfloatparsenumber{\pgfplotsplothandlermesh@numpoints}%
								\pgfmathfloatsqrt@{\pgfmathresult}%
								\pgfmathfloattofixed{\pgfmathresult}%
							\fi
							\begingroup
							% Try whether this rows*rows yields numpoints:
							\afterassignment\pgfplots@gobble@until@relax
							\c@pgf@counta=\pgfmathresult\relax
							\c@pgf@countb=\c@pgf@counta
							\multiply\c@pgf@counta by\c@pgf@counta
							\def\pgfplotsretval{1}%
							\ifnum\c@pgf@counta=\pgfplotsplothandlermesh@numpoints\relax
								% ok, rows*rows = numpoints.
								\edef\pgfplotsplothandlermesh@rows{\the\c@pgf@countb}%
							\else
								% oh. Did not work. Check for rounding errors:
								\c@pgf@counta=\c@pgf@countb
								\advance\c@pgf@counta by1
								\c@pgf@countb=\c@pgf@counta
								\multiply\c@pgf@counta by\c@pgf@counta
								\ifnum\c@pgf@counta=\pgfplotsplothandlermesh@numpoints
									% ok, (rows+1)*(rows+1) = numpoints.
									\edef\pgfplotsplothandlermesh@rows{\the\c@pgf@countb}%
								\else
									% no... did not work. num points doesn't
									% appear to be a squared number.
									\def\pgfplotsretval{0}%
									\edef\pgfplotsplothandlermesh@rows{5}%
								\fi
							\fi
							\if\pgfplotsretval1
								\pgfplotswarning{matrix delinearize uses sqrt}{\pgfplotsplothandlermesh@rows}{\pgfplotsplothandlermesh@cols}{\pgfplotsplothandlermesh@numpoints}{\pgfmathresult}\pgfeov%
							\else
								\pgfplots@error{Sorry, 'plot mesh' needs either '[mesh/rows=<N>]' or '[mesh/cols=<N>]' set,
									but it did not find any of them. 
									I also tried rows = sqrt(num points) = sqrt(\pgfplotsplothandlermesh@numpoints) = \pgfmathresult\space without success.}%
							\fi
							\pgfmath@smuggleone\pgfplotsplothandlermesh@rows
							\endgroup
							\let\pgfplotsplothandlermesh@cols=\pgfplotsplothandlermesh@rows
						\fi
					\else
						% #1=0 -> leave them empty.
					\fi
				\fi
			\fi
		\fi
		\if1#1%
			\ifx\pgfplotsplothandlermesh@rows\pgfutil@empty
				\ifx\pgfplotsplothandlermesh@cols\pgfutil@empty
				\else
					% Compute 'rows' out of 'num points' and 'cols':
					\ifx\pgfplotsplothandlermesh@numpoints\pgfutil@empty
						\pgfplots@error{Sorry, matrix input needs a valid '[mesh/num points=<N>]' variable if only one of '[mesh/rows=<N>]' or '[mesh/cols=<N>]' is given.}%
						\def\pgfplotsplothandlermesh@numpoints{100}%
					\fi
					\begingroup
					\c@pgf@counta=\pgfplotsplothandlermesh@numpoints\relax
					\divide\c@pgf@counta by\pgfplotsplothandlermesh@cols\relax
					\xdef\pgfplots@glob@TMPa{\the\c@pgf@counta}%
					\endgroup
					\let\pgfplotsplothandlermesh@rows=\pgfplots@glob@TMPa
				\fi
			\else
				\ifx\pgfplotsplothandlermesh@cols\pgfutil@empty
					% Compute 'cols' out of 'num points' and 'rows':
					\ifx\pgfplotsplothandlermesh@numpoints\pgfutil@empty
						\pgfplots@error{Sorry, matrix input needs a valid '[mesh/num points=<N>]' variable if only one of '[mesh/cols=<N>]' or '[mesh/rows=<N>]' is given.}%
						\def\pgfplotsplothandlermesh@numpoints{100}%
					\fi
					\begingroup
					\c@pgf@counta=\pgfplotsplothandlermesh@numpoints\relax
					\divide\c@pgf@counta by\pgfplotsplothandlermesh@rows\relax
					\xdef\pgfplots@glob@TMPa{\the\c@pgf@counta}%
					\endgroup
					\let\pgfplotsplothandlermesh@cols=\pgfplots@glob@TMPa
				\fi
			\fi
			\ifx\pgfplotsplothandlermesh@numpoints\pgfutil@empty
				\c@pgfplots@scanlineindex=\pgfplotsplothandlermesh@rows\relax
				\multiply\c@pgfplots@scanlineindex by \pgfplotsplothandlermesh@cols\relax
				\edef\pgfplotsplothandlermesh@numpoints{\the\c@pgfplots@scanlineindex}%
			\fi
			%
			\c@pgfplots@scanlineindex=\pgfplotsplothandlermesh@rows\relax
			\multiply\c@pgfplots@scanlineindex by\pgfplotsplothandlermesh@cols\relax
			\ifnum\c@pgfplots@scanlineindex=\pgfplotsplothandlermesh@numpoints\relax
			\else
				\ifcase\pgfplots@mesh@checkmode\relax
					% mesh/check=false
					\def\pgfplots@loc@TMPa##1{}%
				\or
					% mesh/check=warning
					\def\pgfplots@loc@TMPa##1{\pgfplotsthrow@warning{##1}}%
				\or
					% mesh/check=error
					\def\pgfplots@loc@TMPa##1{\pgfplots@error{##1}}%
				\fi
				\pgfplotswarning{matrix check}{\pgfplots@loc@TMPa}{\pgfplotsplothandlermesh@rows}{\pgfplotsplothandlermesh@cols}{\pgfplotsplothandlermesh@numpoints}{\the\c@pgfplots@scanlineindex}\pgfeov%
			\fi
		\fi
	\else
		% 2d visualization has no mesh:
		\edef\pgfplotsplothandlermesh@rows{\pgfplotsplothandlermesh@numpoints}%
		\def\pgfplotsplothandlermesh@cols{1}%
	\fi
	%
	\def\pgfplots@loc@TMPa{\pgfkeyssetvalue{/pgfplots/mesh/rows}}%
	\expandafter\pgfplots@loc@TMPa\expandafter{\pgfplotsplothandlermesh@rows}%
	\def\pgfplots@loc@TMPa{\pgfkeyssetvalue{/pgfplots/mesh/cols}}%
	\expandafter\pgfplots@loc@TMPa\expandafter{\pgfplotsplothandlermesh@cols}%
}%

%% 
%% Helper structs for patch plots (surfaces)

% #1: the canvas x coordinate
% #2: the canvas y coordinate
% #3: the point meta data (cdata)
% #4: the vertex'es depth (if required)
% #5: the 3d coordinates of the vertex (will only be stored if it is deemed necessary)
\def\pgfplotspatchvertex#1#2#3#4:#5\endvertex{%
	\def\pgfplotspatchvertexstruct{{#1}{#2}{#3}#4:#5}%
	\def\pgfplotspatchvertexx{#1}%
	\def\pgfplotspatchvertexy{#2}%
	\def\pgfplotspatchvertexmeta{#3}%
	\def\pgfplotspatchvertexdepth{#4}%
	\def\pgfplotspatchvertexcoords{#5}%
}%
\def\pgfplotspointpatchvertex#1#2#3#4:#5\endvertex{%
	\global\pgf@x=#1
	\global\pgf@y=#2
}%

% Allows to combined different vertices in the form
% \pgfplotspatchvertexaccumstart
% \expandafter\pgfplotspatchvertexadd\vertexA\times{0.25}%
% \expandafter\pgfplotspatchvertexadd\vertexB\times{0.5}%
% \expandafter\pgfplotspatchvertexadd\vertexC\times{0.75}%
% \pgfplotspatchvertexfinish\finalvertex
% --> now, \finalvertex contains the result vertex, 0.25*A + 0.5*B + 0.75*C .
%
% THERE MUST NOT BE MATH INBETWEEN.
% More precisely, this overwrites the macros
% \pgf@x,\pgf@y, \pgf@xa,\pgf@ya, \pgf@yb, \pgfmathresult and \pgfplotspatchvertexdepth
\def\pgfplotspatchvertexaccumstart{%
	\pgf@xa=0pt
	\pgf@ya=0pt
	\pgf@yb=0pt
	\if0\pgfplotsplothandlermesh@colorinput
		% mesh/color input=colormap
		\pgfplotscoordmath{meta}{zero}%
	\else
		% mesh/color input=explicit
		\begingroup
		\pgfplotscolorzero{\pgfplotsplothandlermesh@explicit@color@num@comps}%
		\let\pgfmathresult=\pgfplotsretval
		\pgfmath@smuggleone\pgfmathresult
		\endgroup
	\fi
}%

% #1: the patch's x coordinate
% #2: the patch's y coordinate
% #3: the patch's point meta value
% #4: depth (if required)
% #5: 3d coordinate of the vertex
\def\pgfplotspatchvertexadd#1#2#3#4:#5\times#6{%
	\global\pgf@x=#1 %
	\global\pgf@y=#2 %
	\advance\pgf@xa by#6\pgf@x
	\advance\pgf@ya by#6\pgf@y
	\let\pgfmathresult@=\pgfmathresult
	\if0\pgfplotsplothandlermesh@colorinput
		% mesh/color input=colormap
		\pgfplotscoordmath{meta}{parsenumber}{#6}%
		\pgfplotscoordmath{meta}{op}{multiply}{{#3}{\pgfmathresult}}%
		\pgfplotscoordmath{meta}{op}{add}{{\pgfmathresult@}{\pgfmathresult}}%
	\else
		% mesh/color input=explicit
		\begingroup
		\pgfplotscoloraddweighted{\pgfplotsplothandlermesh@explicit@color@num@comps}
			{\pgfmathresult@}{#6}{#3}%
		\let\pgfmathresult=\pgfplotsretval
		\pgfmath@smuggleone\pgfmathresult
		\endgroup
	\fi
	\def\pgfplotspatchvertexdepth{#4}%
	\ifx\pgfplotspatchvertexdepth\pgfutil@empty
	\else
		\global\pgf@y=#4pt %
		\advance\pgf@yb by#6\pgf@y
	\fi
}%
\def\pgfplotspatchvertexfinish#1{%
	\edef#1{%
		{\the\pgf@xa}%
		{\the\pgf@ya}%
		{\pgfmathresult}%
		\ifx\pgfplotspatchvertexdepth\pgfutil@empty\else\pgf@sys@tonumber\pgf@yb\fi%
		:%
	}%
}
% Same as \pgfplotspatchvertexadd, but it only adds the X and Y
% coordinates (ignoring the rest).
\def\pgfplotspatchvertexaddXY#1#2#3#4:#5\times#6{%
	\global\pgf@x=#1
	\global\pgf@y=#2
	\advance\pgf@xa by#6\pgf@x
	\advance\pgf@ya by#6\pgf@y
}%
% Same as \pgfplotspatchvertexfinish, but it only saves X and Y.
\def\pgfplotspatchvertexfinishXY#1{%
	\edef#1{{\the\pgf@xa}{\the\pgf@ya}{}:}%
}

% #1 class name
% #2 method
% <any method arguments follow>
\def\pgfplotspatchclass#1#2{%
	\pgfutil@ifundefined{pgfpptch@#1@#2}{%
		\pgfplotspatchclasserror{#1}{#2}%
	}{%
		\edef\pgfplotspatchclassname{#1}%
		\csname pgfpptch@#1@#2\endcsname
	}%
}%
\def\pgfplotspatchclasserror#1#2{%
	\pgfutil@ifundefined{pgfpptch@#1@}{%
		\pgfplots@error{Sorry, the 'patch type=#1' is not defined. Maybe you misspelled it? Or perhaps you need to load \string\usepgfplotslibrary{patchplots}?}%
	}{%
		\pgfplots@error{Sorry, the patch class '#1' has no method '#2' (or it is not yet implemented)}%
	}%
}%

% #1: will be expanded with \edef
\def\pgfplotsplothandlermesh@setnextvertex#1{%
	\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{set next vertex}{#1}%
}%

% Declares a new patch class named #1.
% 
% #1: a string name.
% #2: methods defining the class, provided as key values. See the
% predefined classes to adjust your own ones. Documentation about the
% available methods and their arguments can be found below in this
% file.
%
% @see \usepgfplotslibrary{patchplots}
\def\pgfplotsdeclarepatchclass#1#2{%
	\edef\pgfplotsdeclarepatchclass@{@#1@}%
	\pgfutil@ifundefined{pgfpptch@#1@}{%
		% Ok. This is the FIRST declaration of this patch class.
		% Define some default algorithms.
		%
		\expandafter\def\csname pgfpptch@#1@\endcsname{#1}%
		\pgfqkeys{/pgfplots/@declare patch}{%
			init=,
			allow matrix=\def\pgfplotsretval{0},
			init pdf shading=,
			stream to shader={%
%\message{\pgfplotspatchclassname: stream to shader: Starting  ^^J}%
				\pgfplotspatchclass{\pgfplotspatchclassname}{foreach vertex}{%
%\message{vertex (\pgfplotspatchvertexx,\pgfplotspatchvertexy[\pgfplotspatchvertexmeta]. ^^J}%
					\let\pgfplots@current@point@meta=\pgfplotspatchvertexmeta
					\pgfplotsaxisvisphasetransformpointmeta
					\pgfplotslibrarysurfstreamcoord{%
						\global\pgf@x=\pgfplotspatchvertexx\space
						\global\pgf@y=\pgfplotspatchvertexy\space
					}{\pgfplotspointmetatransformed}%
				}%
			},%
			fill path={%
				\def\b@pgfplotsmeshplothandler@fillpath@default@isfirst{1}%
				\pgfplotspatchclass{\pgfplotspatchclassname}{foreach vertex}{%
%\message{vertex (\pgfplotspatchvertexx,\pgfplotspatchvertexy[\pgfplotspatchvertexmeta]. ^^J}%
					\if1\b@pgfplotsmeshplothandler@fillpath@default@isfirst
						\expandafter\pgfpathmoveto
					\else
						\expandafter\pgfpathlineto
					\fi
					{\global\pgf@x=\pgfplotspatchvertexx\space\global\pgf@y=\pgfplotspatchvertexy\space}%
					\def\b@pgfplotsmeshplothandler@fillpath@default@isfirst{0}%
				}%
				\pgfpathclose
			},
			get num cdata vertices=\pgfplotspatchclass{\pgfplotspatchclassname}{get num vertices},
			get dimension=\def\pgfplotsretval{2},
			supports global path=\def\pgfplotsretval{0},
			set edge visible=\expandafter\edef\csname pgfppatchedge@##1\endcsname{##2},
			uses view depth=\def\pgfplotsretval{0},
			if current point can be first last=##1,
			serialize except vertices=\let\pgfplotsretval\pgfutil@empty,
			deserialize except vertices=##1,
			serialize={%
				% the default serialization is not necessarily the fastest
				% possible. But it should work.
				\pgfplotspatchclass{\pgfplotspatchclassname}{serialize except vertices}%
				\t@pgfplots@toka=\expandafter{\pgfplotsretval
					\let\pgfplotspatchready@defaultserialize=\pgfplotspatchready
					\let\pgfplotspatchready=\relax
				}%
				\edef\pgfplotsretval{%
					\noexpand\pgfplotspatchclass{\pgfplotspatchclassname}{new}%
					\the\t@pgfplots@toka
				}%
				\pgfplotspatchclass{\pgfplotspatchclassname}{foreach vertex}{%
					\t@pgfplots@toka=\expandafter{\pgfplotsretval}%
					\edef\pgfplotsretval{\the\t@pgfplots@toka
						\noexpand\pgfplotspatchclass{\pgfplotspatchclassname}{set next vertex}{\pgfplotspatchvertexstruct}%
					}%
				}%
				\expandafter\def\expandafter\pgfplotsretval\expandafter{\pgfplotsretval
					\let\pgfplotspatchready=\pgfplotspatchready@defaultserialize
				}%
			},
			deserialize=##1,
			triangulate class=\def\pgfplotsretval{triangle},
			triangulate={%
				\pgfplots@error{triangulate: not yet implemented for \pgfplotspatchclassname}%
			},%
			refine={%
				\let\pgfplotsrefinedpatchready=\pgfplotspatchready
				\pgfplotspatchclass@recursiverefine{##1}%
			},%
			recursive refine@={%
				\pgfplots@error{refine: not yet implemented for \pgfplotspatchclassname}%
			},%
			compute normal={%
				\pgfplotsplothandlermesh@compute@normal@default
			},%
			sample in unit cube={%
				\pgfplots@error{sample in unit cube: not implemented for \pgfplotspatchclassname}%
			},
		}%
	}{}%
	%
	%
	\pgfqkeys{/pgfplots/@declare patch}{#2}%
	%
	%
	\pgfutil@ifundefined{pgfpptch\pgfplotsdeclarepatchclass@ foreach cdata vertex}{%
		\pgfutil@namelet
			{pgfpptch\pgfplotsdeclarepatchclass@ foreach cdata vertex}
			{pgfpptch\pgfplotsdeclarepatchclass@ foreach vertex}%
	}{%
	}%
	\pgfutil@ifundefined{pgfpptch\pgfplotsdeclarepatchclass@ stroke path}{%
		\pgfutil@namelet
			{pgfpptch\pgfplotsdeclarepatchclass@ stroke path}
			{pgfpptch\pgfplotsdeclarepatchclass@ fill path}%
	}{%
	}%
}%
\pgfqkeys{/pgfplots/@declare patch}{%
	% may do any more or less global preparations. It is some sort (!)
	% of constructor.
	init/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ init\endcsname{#1}},%
	allow matrix/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ allow matrix\endcsname{#1}},%
	%
	% FIXME : this is NOT properly used in higher order patches!?
	% Uses view depth defines \pgfplotsretval to '1' if and only if it
	% does ALWAYS needs the view depth. Note that 'z buffer=sort' will
	% automatically provide the view depth. Use this key if view depth
	% is necessary even for 'z buffer!=sort'.
	uses view depth/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ uses view depth\endcsname{#1}},%
	%
	% creates a new patch. The vertices need to be added by 'set next
	% vertex'
	new/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ new\endcsname{#1}},%
	%
	% sets the next vertex value of the patch.
	%
	% if the patch has all expected vertices, \pgfplotspatchready is
	% invoked and the next call to 'set next vertex' will start a new
	% patch.
	%
	% #1: encodes the current vertex such that
	%   \pgfplotspatchvertex#1\endvertex
	% is accepted.
	set next vertex/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ set next vertex\endcsname##1{#1}},%
	%
	%
	% Creates a new patch by means of sampling. The sampling is
	% applied in the unit cube [0,1]x[0,1] (unit interval if this is an 1d patch
	% type).
	%
	% 'sample in unit cube={<code to invoke for each sampled point>}'
	% 
	% It will invoke <code to invoke for each sampled point> once for
	% every sampled vertex. The complete unit cube will be covered.
	% Depending on the patch type, either one or more patches are
	% required to fill the unit cube. As soon as one patch is ready,
	% \pgfplotspatchready will be invoked.
	%
	%
	% PRECONDITION: 
	%  -\pgfplotspatchready is defined. 
	%
	% Arguments:
	%  #1: code which will be invoked whenever a new coordinate is
	%  ready. Inside of #1, the macros \pgfplotspatchclassx and
	%  \pgfplotspatchclassy result in the x and y coordinate (inside
	%  of the unit cube), in fixed point representation.
	%
	% Example:
	%   \def\pgfplotspatchready{}
	%   \pgfplotspatchclass{biquadratic}{sample in unit cube}{%
	%       point ready at (\pgfplotspatchclassx, \pgfplotspatchclassy)
	%   }
	sample in unit cube/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ sample in unit cube\endcsname##1{#1}},%
	%
	% declares whether a single edge is visible or not.
	% #1: an integer denoting the edge, either 0,1,2,...,N-1 where N = num verts
	% #2: 0 if the edge is not to be stroked and 1 if it is stroked.
	%
	% This command doesn't need to be called; but if it is, it needs
	% to be called for every edge.
	%
	% ATTENTION: this is *only* used by 'stroke path'. You will never
	% need 'stroke path' unless some edges are invisible. If all edges
	% are visible, 'stroke path' and 'fill path' are the same.
	%
	% This is currently *only* used for triangle triangulations!
	set edge visible/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ set edge visible\endcsname##1##2{#1}},%
	%
	% Defines \pgfplotsretval to be a serialized representation of
	% this patch.
	serialize/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ serialize\endcsname{#1}},%
	% Defines \pgfplotsretval to be a serialized representation of
	% this patches extra data fields, excluding vertices.
	% This is often a NO-OP (unless 'set edge visible' has been used)
	serialize except vertices/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ serialize except vertices\endcsname{#1}},%
	%
	% Restores a serialized representation from #1.
	deserialize/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ deserialize\endcsname##1{#1}},%
	% Restores a serialized representation from #1. Only vertices are
	% not stored here.
	deserialize except vertices/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ deserialize except vertices\endcsname##1{#1}},%
	%
	% issues \pgfplotspatchvertex{...}\endvertex for the first vertex.
	first vertex/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ first vertex\endcsname{#1}},%
	%
	% invokes 
	% 	\pgfplotspatchvertex...\endvertex
	% 	#1
	% for the every vertex.
	foreach vertex/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ foreach vertex\endcsname##1{#1}},%
	%
	% invokes 
	% 	\pgfplotspatchvertex...\endvertex
	% 	#1
	% for every colored vertex.
	% See 'get num cdata vertices'
	foreach cdata vertex/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ foreach cdata vertex\endcsname##1{#1}},%
	%
	% generates a pgf path which is readily usable for filling.
	fill path/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ fill path\endcsname{#1}},%
	%
	% Similar to 'fill path', this here paints the edges. It is only
	% useful if 'set edge visible' is in use. In all other cases, it
	% is the same as 'fill path'
	%
	% This is currently *only* used for triangle triangulations!
	stroke path/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ stroke path\endcsname{#1}},%
	%
	init pdf shading/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ init pdf shading\endcsname{#1}},%
	stream to shader/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ stream to shader\endcsname{#1}},%
	%
	% defines \pgfplotsretval to contain the number of vertices.
	get num vertices/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ get num vertices\endcsname{#1}},%
	%
	% defines \pgfplotsretval to contain the number of vertices which have color data
	% attached. This is usually the same as 'get num vertices' (but
	% see coons patches).
	get num cdata vertices/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ get num cdata vertices\endcsname{#1}},%
	%
	% defines \pgfplotsretval to contain the dimension of this patch
	% (either 1 for lines or 2 for patches).
	get dimension/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ get dimension\endcsname{#1}},%
	%
	% defines \pgfplotsretval to be 1 if and only if the patch class
	% supports global paths.
	% A global path is one which is drawn as one huge, uninterrupted
	% PGF path (except for jumps perhaps). Its area can be filled,
	% i.e. it behaves exactly like the 'sharp' plot handler. This is
	% used implicitly if 'point meta=none' (if there is point meta
	% data, we always want individual path segments and \pgfusepath
	% them after each segment).
	supports global path/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ supports global path\endcsname{#1}},%
	%
	% Approximates the given patch by at least one triangle.
	% For every finished triangle, \pgfplotspatchready will be invoked
	% and \pgfplotsplothandlermesh@patchclass will be set to triangle.
	% More precisely, it is expected to be set to the return value of
	% 'triangulate class'.
	triangulate/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ triangulate\endcsname{#1}},%
	% Defines \pgfplotsretval to be the classname returned by
	% 'triangulate'. This is usually 'triangle'
	triangulate class/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ triangulate class\endcsname{#1}},%
	%
	% Refines the given patch #1 times.
	% For every finished patch, \pgfplotspatchready will be invoked.
	refine/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ refine\endcsname##1{#1}},%
	%
	% shared helper method which can be invoked recursively by refine.
	% the default implementation of 'refine' will invoke this one.
	%
	% #1: a serialized representation of the given patch. Use it to
	% restore the current patch in intermediate steps. Note that you
	% may not use \begingroup/\endgroup in this method; otherwise the
	% 'z buffer' algorithm will need to be done with \global (and I
	% don't want that. You probably neither).
	%
	% The refinement loop as such will be controlled by the default
	% implementation of 'refine'. This macro is ONLY to be called by the
	% default implementation of 'refine'! Overwriting it should
	% automatically yield refinement facilities.
	%
	% the macro \pgfplotspatchready should be called for each refined
	% element (happens automatically if you use 'set next vertex').
	%
	% POSTCONDITION:
	% 	the element has been refined once.
	recursive refine@/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ recursive refine@\endcsname##1{#1}},%
	%
	get pdf shading type/.style={get pdf shading type*={\def\pgfplotsretval{#1}}},
	get pdf shading type*/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ get pdf shading type\endcsname{#1}},%
	%
	% A method which defines \pgfplotsretval to be the normal of the current segment.
	% The values will be given in a format understood by
	% \pgfplotsmathvectortostring{\pgfplotsretval}{default}
	% 
	% This method REQUIRES that 3d coordinates are stored (see \pgfplotsplothandlermesh@serialize@logical@coords).
	compute normal/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ compute normal\endcsname{#1}},%
	%
	% executes '##1' if the current point can be the first or last
	% point of the patch. Executes ##2 if that is not the case.
	if current point can be first last/.code=
		{\expandafter\def\csname pgfpptch\pgfplotsdeclarepatchclass@ if current point can be first last\endcsname##1##2{#1}},%
}

% This implements 'compute normal' :
\def\pgfplotsplothandlermesh@compute@normal@default{%
	\begingroup
	\c@pgf@countd=0
	\pgfplotspatchclass{\pgfplotspatchclassname}{foreach vertex}{%
		\ifx\pgfplotspatchvertexcoords\pgfutil@empty
			\pgfplotsplothandlermesh@compute@normal@error
		\fi
		\pgfplotsmathvectorfromstring{\pgfplotspatchvertexcoords}{default}%
		\expandafter\let\csname point\the\c@pgf@countd\endcsname=\pgfplotsretval
		\let\pointlast=\pgfplotsretval
		\advance\c@pgf@countd by1 %
	}%
	\pgfplotsmathvectorsubtract{\csname point1\endcsname}{\csname point0\endcsname}{default}%
	\let\diffA=\pgfplotsretval
	% Hm. usually, I would use \point2 here... but it turned out that
	% the result looks ugly for rectangular patches -- so I used the
	% last point instead (which is, at least, consistent with the
	% patch boundaries)
	\pgfplotsmathvectorsubtract{\csname pointlast\endcsname}{\csname point0\endcsname}{default}%
	\let\diffB=\pgfplotsretval
	\pgfplotsmathvectorcrossprod{\diffA}{\diffB}{default}%
	\let\crossAB=\pgfplotsretval
	% this here is an experiment to use the MEAN of two normal
	% vectors for rectangular patches... but it did not work as good
	% as expected:
	% \pgfplotspatchclass{\pgfplotspatchclassname}{get num vertices}%
	% \ifnum\pgfplotsretval=4
	% 	\pgfplotsmathvectorsubtract{\csname point3\endcsname}{\csname point0\endcsname}{default}%
	% 	\let\diffC=\pgfplotsretval
	% 	\pgfplotsmathvectorcrossprod{\diffB}{\diffC}{default}%
	% 	\let\crossBC=\pgfplotsretval
	% 	\pgfplotsmathvectoradd{\crossAB}{\crossBC}{default}%
	% 	\pgfplotscoordmath{default}{parsenumber}{0.5}%
	% 	\pgfplotsmathvectorscale{\pgfplotsretval}{\pgfmathresult}{default}%
	% 	\let\normal=\pgfplotsretval
	% \else
		\let\normal=\crossAB
	%\fi
	%
	% specific choices of z buffering change the sequence of points.
	% If the number of reversals is off, we need to switch the
	% normal's sign:
	\def\pgfplots@switch@normal@dir{0}%
	\if1\pgfplotsplothandlermesh@zbuffer@choice
		% z buffer=reverse x seq
		\def\pgfplots@switch@normal@dir{1}%
	\else
		\if2\pgfplotsplothandlermesh@zbuffer@choice
			% z buffer=reverse y seq
			\def\pgfplots@switch@normal@dir{1}%
		\fi
	\fi
	\if1\pgfplots@switch@normal@dir
		\pgfplotscoordmath{default}{parsenumber}{-1}%
		\pgfplotsmathvectorscale{\normal}{\pgfmathresult}{default}%
	\fi
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%
\def\pgfplotsplothandlermesh@compute@normal@error{%
	\pgfplots@error{Cannot compute normal vectors: due to some reason, only canvas coordinates of the involved patch are available in this context, but the original input coordinates are required. This indicates an incompatible combination of variables (sorry). Please report this as a bug}%
}%

\def\pgfplotspatchclass@recursiverefine#1{%
	\c@pgf@counta=#1
	\ifnum\c@pgf@counta=1
		\let\pgfplotspatchready=\pgfplotsrefinedpatchready
	\else
		\advance\c@pgf@counta by-1
		\edef\pgfplotspatchready{\noexpand\pgfplotspatchclass@recursiverefine{\the\c@pgf@counta}}%
	\fi
	%
	\pgfplotspatchclass{\pgfplotspatchclassname}{serialize}%
	\t@pgfplots@toka=\expandafter{\pgfplotsretval}%
	\t@pgfplots@tokc=\expandafter{\pgfplotspatchready}%
	\edef\pgfplots@loc@TMPa{%
		\noexpand\pgfplotspatchclass{\pgfplotspatchclassname}{deserialize}{\the\t@pgfplots@toka}%
		\noexpand\def\noexpand\pgfplotspatchready{\the\t@pgfplots@tokc}%
		\noexpand\def\noexpand\pgfplotspatchclassname{\pgfplotspatchclassname}% % FIXME: is that correct?
	}%
	\expandafter\pgfplotspatchclass@recursiverefine@\expandafter{\pgfplots@loc@TMPa}%
}%
\def\pgfplotspatchclass@recursiverefine@{%
	\pgfplotspatchclass{\pgfplotspatchclassname}{recursive refine@}%
}%


% sequence macros preferred over integer indices.
% using characters avoids the extensive use of \csname ...\endcsname
% and \expandafter which would be necessary for integer indices.
\def\pgfpptchindexnext@A{B}% 0->1
\def\pgfpptchindexnext@B{C}% 1->2
\def\pgfpptchindexnext@C{D}% 2->3
\def\pgfpptchindexnext@D{E}% 3->4
\def\pgfpptchindexnext@E{F}% 4->5
\def\pgfpptchindexnext@F{G}% 5->6
\def\pgfpptchindexnext@G{H}% 6->7
\def\pgfpptchindexnext@H{I}% 7->8
\def\pgfpptchindexnext@I{J}% 8->9
\def\pgfpptchindexnext@J{K}% 9->10
\def\pgfpptchindexnext@K{L}% 10->11
\def\pgfpptchindexnext@L{M}% 11->12
\def\pgfpptchindexnext@M{N}% 12->13
\def\pgfpptchindexnext@N{O}% 13->14
\def\pgfpptchindexnext@O{P}% 14->15
\def\pgfpptchindexnext@P{Q}% 15->16
\def\pgfpptchindexnext@Q{R}% 16->17

\pgfplotsdeclarepatchclass{line}{%
	allow matrix=\def\pgfplotsretval{0},
	new=\def\pgfplotspatchclass@line@no{0},
	set next vertex={%
		\if0\pgfplotspatchclass@line@no\relax
			\edef\pgfplotspatchclass@line@A{#1}%
			\def\pgfplotspatchclass@line@no{1}%
		\else
			\edef\pgfplotspatchclass@line@B{#1}%
			\def\pgfplotspatchclass@line@no{0}%
			\pgfplotspatchready%
		\fi
	},
	sample in unit cube={%
		\def\pgfplotspatchclassx{0}%
		\def\pgfplotspatchclassy{0}%
		#1%
		\def\pgfplotspatchclassx{1}%
		\def\pgfplotspatchclassy{0}%
		#1%
		\pgfplotspatchready
	},%
	get dimension=\def\pgfplotsretval{1},
	supports global path=\def\pgfplotsretval{1},
	first vertex=\expandafter\pgfplotspatchvertex\pgfplotspatchclass@line@A\endvertex,
	foreach vertex={%
		\expandafter\pgfplotspatchvertex\pgfplotspatchclass@line@A\endvertex #1%
		\expandafter\pgfplotspatchvertex\pgfplotspatchclass@line@B\endvertex #1%
	},
	fill path={%
		\pgfplotsplothandlermesh@pathmoveto{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@line@A\endvertex}%
		\pgfpathlineto{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@line@B\endvertex}%
		\pgfplotsplothandlermesh@setlastpoint{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@line@B\endvertex}%
	},
	serialize except vertices=\let\pgfplotsretval\pgfutil@empty,%
	deserialize except vertices=,
	get num vertices=\def\pgfplotsretval{2},
	get pdf shading type=0,
}%

\def\pgfplotsplothandlermesh@last@x{-16000pt}
\def\pgfplotsplothandlermesh@last@y{-16000pt}

\def\pgfplotsplothandlermesh@pathmoveto#1{%
	\pgf@process{#1}%
	\pgfpathmoveto{}%
}
\def\pgfplotsplothandlermesh@setlastpoint#1{%
}

% Applies a moveto to #1 - but only if #1 is NOT the last used path
% segment.
\def\pgfplotsplothandlermesh@pathmoveto@globalpath#1{%
	\pgf@process{#1}%
	\pgfplots@loc@tmptrue
	\ifdim\pgf@x=\pgfplotsplothandlermesh@last@x\relax
		\ifdim\pgf@y=\pgfplotsplothandlermesh@last@y\relax
			\pgfplots@loc@tmpfalse
		\fi
	\fi
	\ifpgfplots@loc@tmp
		\pgfpathmoveto{}%
	\fi
}%

\def\pgfplotsplothandlermesh@setlastpoint@globalpath#1{%
	\pgf@process{#1}%
	\xdef\pgfplotsplothandlermesh@last@x{\the\pgf@x}%
	\xdef\pgfplotsplothandlermesh@last@y{\the\pgf@y}%
}%

\pgfplotsdeclarepatchclass{triangle}{%
	allow matrix=\def\pgfplotsretval{0},
	new=\def\pgfplotspatchclass@tri@no{0}\let\pgfplotspatchclass@trie@AB\relax,
	set next vertex={%
		\ifcase\pgfplotspatchclass@tri@no\relax
			\edef\pgfplotspatchclass@tri@A{#1}%
			\def\pgfplotspatchclass@tri@no{1}%
		\or
			\edef\pgfplotspatchclass@tri@B{#1}%
			\def\pgfplotspatchclass@tri@no{2}%
		\or
			\edef\pgfplotspatchclass@tri@C{#1}%
			\def\pgfplotspatchclass@tri@no{0}%
			\pgfplotspatchready%
		\fi
	},
	sample in unit cube={%
		\def\pgfplotspatchclassx{0}%
		\def\pgfplotspatchclassy{0}%
		#1%
		\def\pgfplotspatchclassx{1}%
		\def\pgfplotspatchclassy{0}%
		#1%
		\def\pgfplotspatchclassx{0}%
		\def\pgfplotspatchclassy{1}%
		#1%
		\pgfplotspatchready
		%
		%
		\def\pgfplotspatchclassx{0}%
		\def\pgfplotspatchclassy{1}%
		#1%
		\def\pgfplotspatchclassx{1}%
		\def\pgfplotspatchclassy{0}%
		#1%
		\def\pgfplotspatchclassx{1}%
		\def\pgfplotspatchclassy{1}%
		#1%
		\pgfplotspatchready
	},%
	first vertex=\expandafter\pgfplotspatchvertex\pgfplotspatchclass@tri@A\endvertex,
	foreach vertex={%
		\expandafter\pgfplotspatchvertex\pgfplotspatchclass@tri@A\endvertex #1%
		\expandafter\pgfplotspatchvertex\pgfplotspatchclass@tri@B\endvertex #1%
		\expandafter\pgfplotspatchvertex\pgfplotspatchclass@tri@C\endvertex #1%
	},
	fill path={%
		\pgfpathmoveto{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@tri@A\endvertex}%
		\pgfpathlineto{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@tri@B\endvertex}%
		\pgfpathlineto{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@tri@C\endvertex}%
		\pgfpathclose
	},
	stroke path={%
		\ifx\pgfplotspatchclass@trie@AB\relax
			\pgfpathmoveto{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@tri@A\endvertex}%
			\pgfpathlineto{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@tri@B\endvertex}%
			\pgfpathlineto{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@tri@C\endvertex}%
			\pgfpathclose
		\else
			\if1\pgfplotspatchclass@trie@AB
				\pgfpathmoveto{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@tri@A\endvertex}%
				\pgfpathlineto{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@tri@B\endvertex}%
			\fi
			\if1\pgfplotspatchclass@trie@BC
				\pgfpathmoveto{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@tri@B\endvertex}%
				\pgfpathlineto{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@tri@C\endvertex}%
			\fi
			\if1\pgfplotspatchclass@trie@CA
				\pgfpathmoveto{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@tri@C\endvertex}%
				\pgfpathlineto{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@tri@A\endvertex}%
			\fi
		\fi
	},
	triangulate=\pgfplotspatchready,
	set edge visible={%
		\ifcase#1
			\edef\pgfplotspatchclass@trie@AB{#2}%
		\or
			\edef\pgfplotspatchclass@trie@BC{#2}%
		\or
			\edef\pgfplotspatchclass@trie@CA{#2}%
		\fi
	},
	serialize except vertices={%
		\ifx\pgfplotspatchclass@trie@AB\relax
			\let\pgfplotsretval\pgfutil@empty%
		\else
			\edef\pgfplotsretval{%
				\noexpand\def\noexpand\pgfplotspatchclass@trie@AB{\pgfplotspatchclass@trie@AB}%
				\noexpand\def\noexpand\pgfplotspatchclass@trie@BC{\pgfplotspatchclass@trie@BC}%
				\noexpand\def\noexpand\pgfplotspatchclass@trie@CA{\pgfplotspatchclass@trie@CA}%
			}%
		\fi
	},%
	recursive refine@={%
		%
		\pgfplotspatchclass{\pgfplotspatchclassname}{new}%
		%
		% Perform longest edge bisection.
		\pgfpointdiff
			{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@tri@A\endvertex}%
			{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@tri@B\endvertex}%
		\edef\pgfplots@loc@TMPa{{\pgf@sys@tonumber\pgf@x}{\pgf@sys@tonumber\pgf@y}}%
		\expandafter\pgfmath@basic@veclen@\pgfplots@loc@TMPa
		\pgf@xa=\pgfmathresult pt
		\pgf@yc=\pgf@xa % "max so far"
		\def\pgfplotspatch@tri@longestedgestart{A}%
		%
		\pgfpointdiff
			{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@tri@B\endvertex}%
			{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@tri@C\endvertex}%
		\edef\pgfplots@loc@TMPa{{\pgf@sys@tonumber\pgf@x}{\pgf@sys@tonumber\pgf@y}}%
		\expandafter\pgfmath@basic@veclen@\pgfplots@loc@TMPa
		\pgf@xa=\pgfmathresult pt
		\ifdim\pgf@xa>\pgf@yc
			\pgf@yc=\pgf@xa
			\def\pgfplotspatch@tri@longestedgestart{B}%
		\fi
		%
		\pgfpointdiff
			{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@tri@C\endvertex}%
			{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@tri@A\endvertex}%
		\edef\pgfplots@loc@TMPa{{\pgf@sys@tonumber\pgf@x}{\pgf@sys@tonumber\pgf@y}}%
		\expandafter\pgfmath@basic@veclen@\pgfplots@loc@TMPa
		\pgf@xa=\pgfmathresult pt
		\ifdim\pgf@xa>\pgf@yc
			\def\pgfplotspatch@tri@longestedgestart{C}%
		\fi
		% The ordering is not arbitrary
		% (unless z buffer=sort is in effect). Let's assume that the
		% AB edge is BACKGROUND and the CD edge is FOREGROUND. Then
		% this sequence here should have approximately the same depth
		% ordering:
		%
		\pgfplotspatchvertexaccumstart
		\if A\pgfplotspatch@tri@longestedgestart
			\expandafter\pgfplotspatchvertexadd\pgfplotspatchclass@tri@A\times{0.5}%
			\expandafter\pgfplotspatchvertexadd\pgfplotspatchclass@tri@B\times{0.5}%
				\def\pgfplots@loc@TMPa{ACM,BCM}%
		\else
			\if B\pgfplotspatch@tri@longestedgestart
				\expandafter\pgfplotspatchvertexadd\pgfplotspatchclass@tri@B\times{0.5}%
				\expandafter\pgfplotspatchvertexadd\pgfplotspatchclass@tri@C\times{0.5}%
				\def\pgfplots@loc@TMPa{ABM,ACM}%
			\else
				\expandafter\pgfplotspatchvertexadd\pgfplotspatchclass@tri@C\times{0.5}%
				\expandafter\pgfplotspatchvertexadd\pgfplotspatchclass@tri@A\times{0.5}%
				\def\pgfplots@loc@TMPa{ABM,BCM}%
			\fi
		\fi
		\pgfplotspatchvertexfinish\pgfplotspatchclass@tri@M
		\edef\pgfplots@loc@TMPa{\pgfplots@loc@TMPa;\pgfplotspatchclass@tri@M}%
		%
		% invoke helper method such that I don't need to restore or
		% recompute \pgfplotspatchclass@tri@M during recursion.
		\expandafter\pgfplotspatchclass@tri@recursiverefine@@\pgfplots@loc@TMPa\relax{#1}%
	},
	deserialize except vertices=%
		\let\pgfplotspatchclass@trie@AB\relax
		#1,
	get pdf shading type=4,
	get num vertices=\def\pgfplotsretval{3},
}%
\def\pgfplotspatchclass@tri@recursiverefine@@#1#2M,#3#4M;#5\relax#6{%
	\expandafter\let\expandafter\pgfplotspatchclass@tri@A@\csname pgfplotspatchclass@tri@#1\endcsname
	\expandafter\let\expandafter\pgfplotspatchclass@tri@B@\csname pgfplotspatchclass@tri@#2\endcsname
	\expandafter\pgfplotsplothandlermesh@setnextvertex\expandafter{\pgfplotspatchclass@tri@A@}%
	\expandafter\pgfplotsplothandlermesh@setnextvertex\expandafter{\pgfplotspatchclass@tri@B@}%
	\pgfplotsplothandlermesh@setnextvertex{#5}%
	#6%
	%
	\expandafter\let\expandafter\pgfplotspatchclass@tri@A@\csname pgfplotspatchclass@tri@#3\endcsname
	\expandafter\let\expandafter\pgfplotspatchclass@tri@B@\csname pgfplotspatchclass@tri@#4\endcsname
	\expandafter\pgfplotsplothandlermesh@setnextvertex\expandafter{\pgfplotspatchclass@tri@A@}%
	\expandafter\pgfplotsplothandlermesh@setnextvertex\expandafter{\pgfplotspatchclass@tri@B@}%
	\pgfplotsplothandlermesh@setnextvertex{#5}%
	#6%
}%


% A rectangle specified in the sequence
% D <-- C
% |     ^
% v     |
% A --> B 
%       
\pgfplotsdeclarepatchclass{rectangle}{%
	allow matrix=\def\pgfplotsretval{1},
	new=\def\pgfplotspatchclass@rect@no{0},
	set next vertex={%
		\ifcase\pgfplotspatchclass@rect@no\relax
			\edef\pgfplotspatchclass@rect@A{#1}%
			\def\pgfplotspatchclass@rect@no{1}%
		\or
			\edef\pgfplotspatchclass@rect@B{#1}%
			\def\pgfplotspatchclass@rect@no{2}%
		\or
			\edef\pgfplotspatchclass@rect@C{#1}%
			\def\pgfplotspatchclass@rect@no{3}%
		\or
			\edef\pgfplotspatchclass@rect@D{#1}%
			\def\pgfplotspatchclass@rect@no{0}%
			\pgfplotspatchready%
		\fi
	},
	sample in unit cube={%
		\def\pgfplotspatchclassx{0}%
		\def\pgfplotspatchclassy{0}%
		#1%
		\def\pgfplotspatchclassx{1}%
		\def\pgfplotspatchclassy{0}%
		#1%
		\def\pgfplotspatchclassx{1}%
		\def\pgfplotspatchclassy{1}%
		#1%
		\def\pgfplotspatchclassx{0}%
		\def\pgfplotspatchclassy{1}%
		#1%
		\pgfplotspatchready
	},%
	first vertex=\expandafter\pgfplotspatchvertex\pgfplotspatchclass@rect@A\endvertex,
	foreach vertex={%
		\expandafter\pgfplotspatchvertex\pgfplotspatchclass@rect@A\endvertex #1%
		\expandafter\pgfplotspatchvertex\pgfplotspatchclass@rect@B\endvertex #1%
		\expandafter\pgfplotspatchvertex\pgfplotspatchclass@rect@C\endvertex #1%
		\expandafter\pgfplotspatchvertex\pgfplotspatchclass@rect@D\endvertex #1%
	},
	stream to shader={%
		% a 'foreach vertex' with slightly different sequence:
		\def\pgfplots@foreachvertex@@{%
			\let\pgfplots@current@point@meta=\pgfplotspatchvertexmeta
			\pgfplotsaxisvisphasetransformpointmeta
			\pgfplotslibrarysurfstreamcoord{%
				\global\pgf@x=\pgfplotspatchvertexx\space
				\global\pgf@y=\pgfplotspatchvertexy\space
			}{\pgfplotspointmetatransformed}%
		}%
		\if1\b@pgfplotsplothandlermesh@matrixoutput
			\expandafter\pgfplotspatchvertex\pgfplotspatchclass@rect@A\endvertex\pgfplots@foreachvertex@@%
			\expandafter\pgfplotspatchvertex\pgfplotspatchclass@rect@B\endvertex\pgfplots@foreachvertex@@%
			\expandafter\pgfplotspatchvertex\pgfplotspatchclass@rect@D\endvertex\pgfplots@foreachvertex@@% EXCHANGED SEQUENCE
			\expandafter\pgfplotspatchvertex\pgfplotspatchclass@rect@C\endvertex\pgfplots@foreachvertex@@%
		\else
			\expandafter\pgfplotspatchvertex\pgfplotspatchclass@rect@A\endvertex\pgfplots@foreachvertex@@%
			\expandafter\pgfplotspatchvertex\pgfplotspatchclass@rect@B\endvertex\pgfplots@foreachvertex@@%
			\expandafter\pgfplotspatchvertex\pgfplotspatchclass@rect@D\endvertex\pgfplots@foreachvertex@@%
			\expandafter\pgfplotspatchvertex\pgfplotspatchclass@rect@B\endvertex\pgfplots@foreachvertex@@%
			\expandafter\pgfplotspatchvertex\pgfplotspatchclass@rect@C\endvertex\pgfplots@foreachvertex@@%
			\expandafter\pgfplotspatchvertex\pgfplotspatchclass@rect@D\endvertex\pgfplots@foreachvertex@@%
		\fi
	},%
	fill path={%
		\pgfpathmoveto{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@rect@A\endvertex}%
		\pgfpathlineto{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@rect@B\endvertex}%
		\pgfpathlineto{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@rect@C\endvertex}%
		\pgfpathlineto{\expandafter\pgfplotspointpatchvertex\pgfplotspatchclass@rect@D\endvertex}%
		\pgfpathclose
	},
	init pdf shading={%
		\if0\b@pgfplotsplothandlermesh@matrixoutput
			\ifnum\pgfkeysvalueof{/pgfplots/surf shading/cols}=2
			\else
				\pgfplots@error{Sorry, (patch type=rectangle) and (rectangular patch shadings with more than one rectangle) is not supported (got \pgfkeysvalueof{/pgfplots/surf shading/cols} x * input points).
					It is supported if z buffer!=sort. Consider using 'patch to triangles=true' to combine it with z buffer=sort}%
			\fi
		\fi
	},
	recursive refine@={%
		\pgfplots@error{Please use \string\usepgfplotslibrary{patchplots} in order to use 'refine,patch type=\pgfplotspatchclassname'}%
	},
	triangulate={%
		\let\pgfplotsplothandlermesh@patchclass@=\pgfplotsplothandlermesh@patchclass
		\def\pgfplotsplothandlermesh@patchclass{triangle}%
		\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{new}%
		\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{set edge visible}01%
		\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{set edge visible}10%
		\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{set edge visible}21%
		\expandafter\pgfplotsplothandlermesh@setnextvertex\expandafter{\pgfplotspatchclass@rect@A}%
		\expandafter\pgfplotsplothandlermesh@setnextvertex\expandafter{\pgfplotspatchclass@rect@B}%
		\expandafter\pgfplotsplothandlermesh@setnextvertex\expandafter{\pgfplotspatchclass@rect@D}%
		%
		\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{set edge visible}01%
		\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{set edge visible}11%
		\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{set edge visible}20%
		\expandafter\pgfplotsplothandlermesh@setnextvertex\expandafter{\pgfplotspatchclass@rect@B}%
		\expandafter\pgfplotsplothandlermesh@setnextvertex\expandafter{\pgfplotspatchclass@rect@C}%
		\expandafter\pgfplotsplothandlermesh@setnextvertex\expandafter{\pgfplotspatchclass@rect@D}%
		\let\pgfplotsplothandlermesh@patchclass=\pgfplotsplothandlermesh@patchclass@
	},%
	serialize except vertices=\let\pgfplotsretval\pgfutil@empty,%
	deserialize except vertices=,
	get pdf shading type=5,
	get num vertices=\def\pgfplotsretval{4},
}%

\def\pgfplots@rect@next@A{B}
\def\pgfplots@rect@next@B{C}
\def\pgfplots@rect@next@C{D}
\def\pgfplots@rect@next@D{A}

\def\pgfplots@rect@rnext@A{D}
\def\pgfplots@rect@rnext@B{A}
\def\pgfplots@rect@rnext@C{B}
\def\pgfplots@rect@rnext@D{C}

% Ideas: make sure that the foreground edge is the 'v=1'
% edge of the coons patch, i.e. that it is drawn on top of
% the rest.
%
% Furthermore, for fixed v, the 'u=1' point should belong
% to the foreground (as it is drawn on top of u=0).
%
% In other words, if the coons patch looks like 
%
% BB-------CC   <--v=1
%  |        |
%  |        |
%  |        |
% AA-------DD   <--v=0
%  |        |
%  u=0      u=1
%
% where the AA,BB,CC,DD are the corners of the coons
% patch, The FOREGROUND POINT of our visualization here should be CC, 
% the second most foreground point BB (assuming that
% foreground point and second most foreground point are
% adjacent).
%
% Thus, if 'CC' is behind of 'BB' in the A,B,C,D ordering:
%    start the coons patch with AA := BB-1 in forward
%    direction.
% else
%    start the coons patch with AA := BB+1 in reverse
%    direction.
%
% #1: the vertex prefix for the rectangular shape.
% Thus, \csname #1A\endcsname is the first vertex, \csname #1B\endcsname the second
% and #1C, #1D the third and fourth.
%
% [output] #2: A macro name which will be filled with the FIRST point
% to stream to the shader. It will be defined to be either A,B,C or D.
% [output] #3: A macro name which indicates whether the stream shall
% be forward or backward. It will be defined to be either empty or 'r'. If
% it is empty, the coons patch shall be in the sequence
% #2,next(#2),next(next(#2),....
% If it is 'r', the coons patch shall be in the sequence
% #2,prev(#2),prev(prev(#2),...
%
% Note that this method works also for biquadratic patches since these
% patches also have #1A, #1B, #1C and #1D as their corners.
% 
\def\pgfplotspatchclass@rect@to@coonspatch@findshadingsequence@for@depth#1#2#3{%
	\def#2{A}%
	\def#3{}%
	%
	\expandafter\expandafter\expandafter\pgfplotspatchvertex\csname #1A\endcsname\endvertex
	\ifx\pgfplotspatchvertexdepth\pgfutil@empty
	\else
		% aaah -- we have z buffer information. Then we will use it!
		\edef\PA{\pgfplotspatchvertexdepth pt A}%
		\expandafter\expandafter\expandafter\pgfplotspatchvertex\csname #1B\endcsname\endvertex
		\edef\PB{\pgfplotspatchvertexdepth pt B}%
		\expandafter\expandafter\expandafter\pgfplotspatchvertex\csname #1C\endcsname\endvertex
		\edef\PC{\pgfplotspatchvertexdepth pt C}%
		\expandafter\expandafter\expandafter\pgfplotspatchvertex\csname #1D\endcsname\endvertex
		\edef\PD{\pgfplotspatchvertexdepth pt D}%
		\pgfplotsutilsortfour\PA\PB\PC\PD
		\def\toCHAR##1pt ##2{##2}% get original index
		%
		%
		\edef\PA{\expandafter\toCHAR\PA}%%
		\edef#2{\expandafter\toCHAR\PB}%%
		\edef\Pnext{\csname pgfplots@rect@next@#2\endcsname}% this here uses only A,B,C and D (also for biquadratic patches!)
		\if\Pnext\PA
			% ok, next(BB) = CC.
			% that means we have to advance forward.
			\def#3{}%
			\edef#2{\csname pgfplots@rect@rnext@#2\endcsname}%
		\else
			\edef#2{\csname pgfplots@rect@next@#2\endcsname}%
			\def#3{r}%
		\fi
%\message{^^JDEPTH SEQUENCE for rectangle: \PA, \PB, \PC, \PD^^J}%
%\message{COONS PATH ORDERING: starts with #2, direction: \ifx#3\pgfutil@empty forward\else backward\fi^^J}%
	\fi
}%

\def\pgfplotspatchclass@rect@to@coonspatch@findshadingsequence@for@depth@no@op#1#2#3{%
	\def#2{A}%
	\def#3{}%
}

\def\pgfplotsplothandlermesh@patchclass@defaulttext{default}%

% This is a VERY special case. The idea is to switch to
% "normal" path mode:
% \pgfpathmoveto \pgfpathlineto \pgfpathlineto
% \pgfpathlineto \pgfusepath.
%
% Note that the mesh handler's default is to issue
% \pgfusepath after *each* elementary patch.
%
% This special use-case might not cover all aspects of the
% mesh/surf/patch plot handler.
\def\pgfplotsplothandlermesh@init@path@without@point@meta{%
	%
	\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@output}{supports global path}%
	\ifnum\pgfplotsretval=1 %
		\def\pgfplotsplothandlermesh@definecolor{%
			% no-op
		}%
		% FIXME : this does not handle separate edges, i.e.
		% \pgfplotsplothandlermesh@VISUALIZE@std@separate@fillstroke
		\def\pgfplotsplothandlermesh@VISUALIZE{\pgfplotsplothandlermesh@VISUALIZE@globalpath@fill@andor@stroke}%
		\let\pgfplotsplothandlermesh@pathmoveto=\pgfplotsplothandlermesh@pathmoveto@globalpath
		\let\pgfplotsplothandlermesh@setlastpoint=\pgfplotsplothandlermesh@setlastpoint@globalpath
		% 
		% This activates tikz colors:
		%\tikz@options
		\pgfplots@drawoptions
		% Acquire the values for \tikz@mode@* [used for faceted]
		\pgfplots@drawmodes
	\else
		\pgfplots@error{Please provide 'point meta' for your plot. Omitting point meta is only supported for 1d patch types.}%
	\fi
}

% implements 'show normals'. Keep in mind that this is more-or-less a
% debugging helper, not productive code.
\def\pgfplotsplothandlermesh@show@normals{%
	\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{compute normal}%
	\let\pgfplots@normal@vector=\pgfplotsretval
%\pgfplotsmathvectortostring\pgfplots@normal@vector{default}%
%\message{got normal \pgfplotsretval^^J}%
	\pgfplotsmathvectorlength{\pgfplots@normal@vector}{default}%
	\pgfplotscoordmath{default}{parsenumber}{\pgfkeysvalueof{/pgfplots/mesh/show normals length factor}}% FIXME
	\pgfplotscoordmath{default}{op}{divide}{{\pgfmathresult}{\pgfplotsretval}}%
	\pgfplotsmathvectorscale{\pgfplots@normal@vector}{\pgfmathresult}{default}%
	%\pgfplotsmathvectoradd{\pgfplotspatchvertexcoords}{\pgfplotsretval}{default}%
	\let\pgfplots@normal@vector=\pgfplotsretval
	%
	\draw[/pgfplots/every patch normal]
		\pgfextra{%
			\pgfpathmoveto
			{%
				\pgf@process{%
					\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{get num vertices}%
					\pgfmath@basic@reciprocal@{\pgfplotsretval}%
					\let\scale=\pgfmathresult
					\pgfplotspatchvertexaccumstart
					\pgfplotspatchclass{\pgfplotspatchclassname}{foreach vertex}{%
						\expandafter\pgfplotspatchvertexadd\pgfplotspatchvertexstruct\times{\scale}%
					}%
					\pgfplotspatchvertexfinishXY{\pgfplots@loc@TMPa}%
					\expandafter\pgfplotspointpatchvertex\pgfplots@loc@TMPa\endvertex%
				}%
			}%
			\edef\pgfplots@loc@TMPa{\pgf@x=\the\pgf@x\space\pgf@y=\the\pgf@y\space}%
			%
			\pgfpathlineto{%
				\pgfpointadd
					{\pgfplots@loc@TMPa}
					{\pgfplotspointfromcsvvector\pgfplots@normal@vector{default}}%
			}%
		}%
	;
}%

% Defines \pgfplotsretval to be either empty or the current point's
% depth according to z buffer information.
\def\pgfplotsplothandlermesh@compute@vertex@depth{\let\pgfplotsretval\pgfutil@empty}%

% If \pgfplotsplothandlermesh@compute@vertex@depth is set to this
% particular implementation, the \pgfplotspatchvertexdepth macro will
% contain the view depth.
%
\def\pgfplotsplothandlermesh@compute@vertex@depth@doit{%
	\ifx\pgfplots@current@point@x\pgfutil@empty
		\let\pgfplotsretval\pgfutil@empty
	\else
		\pgfplotsmathvectorfromstring{\pgfplots@current@point@x,\pgfplots@current@point@y,\pgfplots@current@point@z}{default}%
		\pgfplotsmathvectorviewdepth{\pgfplotsretval}%
		\pgfplotscoordmath{default}{tofixed}{\pgfplotsretval}%
		\edef\pgfplotsretval{\pgfmathresult}%
	\fi
}%

% A command which defines \pgfplotsretval to be either empty or to
% the (x,y,z) 3d coordinates of the data point. Usually, the data
% scaling transformation will already be applied to these points.
%
% Note that this is unnecessary for most applications of mesh plots.
%
% The resulting value will be available as \pgfplotspatchvertexcoords
\def\pgfplotsplothandlermesh@serialize@logical@coords{%
	% empty by default
	\let\pgfplotsretval=\pgfutil@empty
}%
\def\pgfplotsplothandlermesh@serialize@logical@coords@doit{%
	\ifx\pgfplots@current@point@x\pgfutil@empty
		\let\pgfplotsretval=\pgfutil@empty
	\else
		% note that these points are the result of the data scaling
		% trafo. That is OK because the view normal is also in the
		% same coordinate space.
		\pgfplotsmathvectorfromstring{\pgfplots@current@point@x,\pgfplots@current@point@y,\pgfplots@current@point@z}{default}%
	\fi
}

% the inverse for \pgfplotsplothandlermesh@serialize@logical@coords: it defines \pgfplots@current@point@[xyz].
% You should only call it if you know that there IS something to deserialize.
\def\pgfplotsplothandlermesh@deserialize@logical@coords#1{%
	\expandafter\pgfplotsplothandlermesh@deserialize@logical@coords@#1\relax
}%
\def\pgfplotsplothandlermesh@deserialize@logical@coords@#1,#2,#3\relax{%
	\def\pgfplots@current@point@x{#1}%
	\def\pgfplots@current@point@y{#2}%
	\def\pgfplots@current@point@z{#3}%
}%

% The patch visualization works like a PIPELINE:
%
% DECODE -> CHECK JUMP -> REFINE -> FINISH
%
% where FINISH is usually nothing but VISUALIZE; but it can also mean
% to collect patches, sort them according to view depth and visualize
% the result.
%
% Each single PIPE element can be exchanged by a separate "subclass".
% For example, DECODE can either DECODE from a matrix (a lattice) or a
% sequence of patch coords.
%
\def\pgfplotsplothandlermesh@stream#1{%
	\pgfplotsplothandlermesh@PIPE@DECODE{#1}%
}%

% accumulates a patch vertex-by-vertex.
% #1 the next vertex of a patch (#1 defines canvas coordinates \pgf@x
% and \pgf@y).
%
% @PRECONDITION \pgfplots@current@point@[xyz] and \pgfplots@current@point@meta
% need to be defined.
\def\pgfplotsplothandlermesh@PIPE@DECODE#1{%
	\let\pgfplotsplothandlermesh@patchclass\pgfplotsplothandlermesh@patchclass@input
	\pgfplotsplothandlermesh@compute@vertex@depth% <-- this modifies \pgfplotsretval
	\let\pgfplots@view@depth=\pgfplotsretval
	\pgf@process{#1}%
	% calls \pgfplotspatchready when ready
	\pgfplotsplothandlermesh@serialize@logical@coords
	\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{set next vertex}{{\the\pgf@x}{\the\pgf@y}{\pgfplots@current@point@meta}\pgfplots@view@depth:\pgfplotsretval}%%
}%
\def\pgfplotspatchready{%
	\pgfplotsplothandlermesh@PIPE@CHECKJUMP
}%
\let\pgfplotspatchready@orig=\pgfplotspatchready
\def\pgfplotsplothandlermesh@PIPE@CHECKJUMP{%
	\pgfplots@loc@tmptrue
	\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{foreach vertex}{%
		\pgfplotsplothandlermesh@check@unbounded%
	}%
	\ifpgfplots@loc@tmp
		\expandafter\pgfplotsplothandlermesh@PIPE@REFINE
	\fi
}%
\def\pgfplotsplothandlermesh@PIPE@REFINE@no@op{%
	\pgfplotsplothandlermesh@PIPE@FINISH
}%
\let\pgfplotsplothandlermesh@PIPE@REFINE=\pgfplotsplothandlermesh@PIPE@REFINE@no@op

% invoked when a patch is completely processed.
% This might be replaced by the z buffering algorithm
\def\pgfplotsplothandlermesh@PIPE@FINISH{%
	\pgfplotsplothandlermesh@PIPE@interior@exterior@styles
}%

\def\pgfplotsplothandlermesh@PIPE@interior@exterior@styles{%
	\pgfplotsplothandlermesh@interior@exterior@hook
	\pgfplotsplothandlermesh@VISUALIZE
}%

% Standard implementation for VISUALIZE
\def\pgfplotsplothandlermesh@VISUALIZE@std@fill@andor@stroke{%
	\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{fill path}%
	\pgfplotsplothandlermesh@definecolor
	\pgfplotsplothandlermesh@usepath
	\pgfplotsplothandlermesh@show@normals@if@configured
}%

% a special VISUALIZE implementation which allows to draw a CONTINUOS
% global path, i.e. one which is not "\pgfusepath"ed after each patch
% segment. This is only used if 'point meta=none'
\def\pgfplotsplothandlermesh@VISUALIZE@globalpath@fill@andor@stroke{%
	\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{fill path}%
}%

\def\pgfplotsplothandlermesh@VISUALIZE@std{\pgfplotsplothandlermesh@VISUALIZE@std@fill@andor@stroke}

\def\pgfplotsplothandlermesh@VISUALIZE{\pgfplotsplothandlermesh@VISUALIZE@std}

\let\pgfplotsplothandlermesh@show@normals@if@configured\relax


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\def\pgfplotsplothandlermesh@init@DECODE{%
	\if1\pgfplotsplothandlermesh@matrixinput
		% mesh input=lattice
		% Init memory:
		%
		% And now finally: initialise the conversion from 
		%  LINEARIZED COORD STREAM -> DATA MATRIX:
		\if\pgfplots@plot@mesh@ordering0%
			% x varies (=rowwise):
			\let\pgfplotsplothandlermesh@scanlinelength=\pgfplotsplothandlermesh@cols
		\else
			% y varies (=colwise):
			\let\pgfplotsplothandlermesh@scanlinelength=\pgfplotsplothandlermesh@rows
		\fi
		%
		\if1\pgfplotsplothandlermesh@ONEDIMMODE
%\message{initialised DECODE for 1d mode.^^J}%
			\let\pgfplotsplothandlermesh@PIPE@DECODE=\pgfplotsplothandlermesh@PIPE@DECODE@matrix@ONEDIMMODE
		\else
			\if0\b@pgfplotsplothandlermesh@matrixoutput
				% in fact, this does only remember the maximum capacity;
				% it doesn't fill the memory.
				\c@pgfplots@scanlineindex=\pgfplotsplothandlermesh@scanlinelength\relax
				\advance\c@pgfplots@scanlineindex by1
				\pgfplotsdequenewempty{lastscanline}\capacity{\the\c@pgfplots@scanlineindex}%
				\let\pgfplotsplothandlermesh@PIPE@DECODE=\pgfplotsplothandlermesh@PIPE@DECODE@matrix@fillscanline
%\message{initialised DECODE for patch output (from matrix).^^J}%
			\else
				% SPECIAL HANDLING!
				\let\pgfplotsplothandlermesh@PIPE@DECODE=\pgfplotsplothandlermesh@PIPE@DECODE@to@shader
%\message{initialised DECODE for direct matrix output (from matrix).^^J}%
			\fi
		\fi
	\else
%\message{initialised DECODE for patch output (from patch).^^J}%
	\fi
}%


\def\pgfplotsplothandlermesh@PIPE@REFINE@triangulate{%
	\let\pgfplotspatchready\pgfplotsplothandlermesh@PIPE@FINISH
	\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{triangulate}%
	\let\pgfplotspatchready\pgfplotspatchready@orig
}%
\def\pgfplotsplothandlermesh@PIPE@REFINE@recursively{%
	\let\pgfplotspatchready\pgfplotsplothandlermesh@PIPE@FINISH
	\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{refine}{\pgfplotsplothandlermesh@refinecount}%
	\let\pgfplotspatchready\pgfplotspatchready@orig
}%
\def\pgfplotsplothandlermesh@PIPE@REFINE@triangulate@recursively{%
	\let\pgfplotspatchready=\pgfplotsplothandlermesh@PIPE@REFINE@triangulate@recursively@patchready
	\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{refine}{\pgfplotsplothandlermesh@refinecount}%
	\let\pgfplotspatchready\pgfplotspatchready@orig
}%
\def\pgfplotsplothandlermesh@PIPE@REFINE@triangulate@recursively@patchready{%
	\let\pgfplotspatchready\pgfplotsplothandlermesh@PIPE@FINISH
	\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{triangulate}%
	\let\pgfplotspatchready\pgfplotsplothandlermesh@PIPE@REFINE@triangulate@recursively@patchready
}%
\def\pgfplotsplothandlermesh@init@REFINE{%
	\pgfkeysgetvalue{/pgfplots/patch refines}\pgfplotsplothandlermesh@refinecount
	\if0\pgfplotsplothandlermesh@triangulate
		\ifnum\pgfplotsplothandlermesh@refinecount>0
%\message{initiased REFINE to REFINE.}%
			\let\pgfplotsplothandlermesh@PIPE@REFINE=\pgfplotsplothandlermesh@PIPE@REFINE@recursively
		\else
%\message{initiased REFINE to NOP.}%
			\let\pgfplotsplothandlermesh@PIPE@REFINE=\pgfplotsplothandlermesh@PIPE@REFINE@no@op
		\fi
	\else
%\message{initiased REFINE to triangulate.}%
		\ifnum\pgfplotsplothandlermesh@refinecount>0
			\let\pgfplotsplothandlermesh@PIPE@REFINE=\pgfplotsplothandlermesh@PIPE@REFINE@triangulate@recursively
		\else
			\let\pgfplotsplothandlermesh@PIPE@REFINE=\pgfplotsplothandlermesh@PIPE@REFINE@triangulate
		\fi
	\fi
}%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MESH SURVEY
\def\pgfplotsplothandlersurveystart@mesh{%
	\pgfplotsplothandlersurveystart@default
	\if0\pgfplotsplothandlermesh@colorinput
		% mesh/color input=colormap
	\else
		% mesh/color input=explicit
		\if1\pgfplotsplothandlermesh@colorinput@mathparse
			\pgfkeysdef{/pgfplots/color sequence/every input component}{%
				\expandafter\pgfmathparse\expandafter{\pgfmathresult}%
				\ifpgfplots@usefpu
					\pgfmathfloattofixed\pgfmathresult
				\fi
			}%
		\else
			\pgfkeysdef{/pgfplots/color sequence/every input component}{}%
		\fi
		\pgfplotscolornormalizesequence[
			colorspace=\pgfkeysvalueof{/pgfplots/mesh/colorspace explicit color output},
			default input colorspace=\pgfkeysvalueof{/pgfplots/mesh/colorspace explicit color input},
			context message={point meta '\pgfplots@current@point@meta' of coord no \the\c@pgfplots@coordindex\space (\pgfplots@current@point@x,\pgfplots@current@point@y\ifpgfplots@curplot@threedim,\pgfplots@current@point@z\fi)},
		]%
	\fi
}%
\def\pgfplotsplothandlersurveyend@mesh{%
	\pgfplotsplothandlersurveyend@default
	\if0\pgfplotsplothandlermesh@colorinput
		% mesh/color input=colormap
	\else
		% mesh/color input=explicit
		\endpgfplotscolornormalizesequence
	\fi
}

\def\pgfplotsplothandlersurveyaftersetpointmeta@mesh@cdatanormalize{%	
	\pgfplotsplothandlersurveyaftersetpointmeta@default
	\if0\pgfplotsplothandlermesh@colorinput
		% mesh/color input=colormap
	\else
		% mesh/color input=explicit
		\pgfplotscolornormalizesequencenext{\pgfplots@current@point@meta}%
		\let\pgfplots@current@point@meta=\pgfplotsretval
	\fi
}%

\newif\ifpgfplotsplothandlermesh@patchtable@hascdata
\newif\ifpgfplotsplothandlermesh@patchtable@cdata@individual
\def\pgfplotsplothandlersurveystart@mesh@patchtable{%
	\pgfplotsplothandlersurveystart@mesh
	\pgfplotsarraynewempty\pgfplots@verts
}%
\def\pgfplotsplothandlersurveypoint@mesh@patchtable{%
	\pgfplotscoordmath{x}{parsenumber}{\pgfplots@current@point@x}%
	\let\pgfplots@current@point@x=\pgfmathresult
	%
	\pgfplotscoordmath{y}{parsenumber}{\pgfplots@current@point@y}%
	\let\pgfplots@current@point@y=\pgfmathresult
	%
	\ifpgfplots@curplot@threedim
		\pgfplotscoordmath{z}{parsenumber}{\pgfplots@current@point@z}%
		\let\pgfplots@current@point@z=\pgfmathresult
	\fi
	%
	\ifpgfplotsplothandlermesh@patchtable@hascdata
		% will be handled later, using data from within 'patch table':
		\let\pgfplots@current@point@meta=\pgfutil@empty
	\else
		\pgfplotsaxissurveysetpointmeta
	\fi
	%
	\def\pgfplots@loc@TMPa{1}%
	\ifx\pgfplots@current@point@x\pgfutil@empty
		\def\pgfplots@loc@TMPa{0}%
	\else
		\ifx\pgfplots@current@point@y\pgfutil@empty
			\def\pgfplots@loc@TMPa{0}%
		\else
			\ifx\pgfplots@current@point@z\pgfutil@empty
				\ifpgfplots@curplot@threedim
					\def\pgfplots@loc@TMPa{0}%
				\fi
			\fi
		\fi
	\fi
	\if1\pgfplots@loc@TMPa
		\edef\pgfplots@loc@TMPa{\pgfplots@current@point@x,\pgfplots@current@point@y,\pgfplots@current@point@z;\pgfplots@current@point@meta;}%
		\expandafter\pgfplotsarraypushback\pgfplots@loc@TMPa\to\pgfplots@verts
	\fi
}%
\def\pgfplotsplothandlersurveyend@mesh@patchtable{%
	\pgfplotsplothandlersurveyend@mesh
	\let\pgfplotsplothandlersurveystart=\pgfplotsplothandlersurveystart@default
	\let\pgfplotsplothandlersurveyend=\pgfplotsplothandlersurveyend@default
	\let\pgfplotsplothandlersurveypoint=\pgfplotsplothandlersurveypoint@default@noreset@of@pointmeta
	\pgfplotsplothandlersurveystart
	\expandafter\pgfplotstable@isloadedtable\expandafter{\pgfplotsplothandlermesh@patchtable}{%
		\pgfplots@error{Sorry, 'patch table={<loaded table>}' has not been implemented; it would probably be too slow :-(. Please provide a file name or inline table data}%
	}{%
		\expandafter\pgfplotstableread\expandafter*\expandafter{\pgfplotsplothandlermesh@patchtable} to listener\pgfplotsplothandlermesh@patchtable@rowlistener
	}%
	\pgfplotsplothandlersurveyend
}%

\def\pgfplotsplothandlermesh@patchtable@init{%
	\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{get num vertices}%
	\let\pgfplotsplothandlermesh@patchtable@numverts=\pgfplotsretval
	%
	\ifpgfplotsplothandlermesh@patchtable@hascdata
		\ifpgfplotsplothandlermesh@patchtable@cdata@individual
		\else
			\ifnum\pgfplotsplothandlermesh@patchtable@numverts<\pgfplotstablecols\relax
				% prepare a pointer to data column: use the column
				% after the last vertex index.
				% this thing constitutes the "default" cdata source for
				% 'point meta=explicit'.
				\pgfplotstablereadgetptrtocolindex
					{\pgfplotsplothandlermesh@patchtable@numverts}
					{\pgfplots@table@PTR@CDATA}%
			\else
				\let\pgfplots@table@PTR@CDATA=\relax
			\fi
		\fi
	\else
		\pgfplotsplothandlermesh@patchtable@cdata@individualfalse
	\fi
	%
	\c@pgf@countb=0
	\pgfutil@loop
	\ifnum\c@pgf@countb<\pgfplotsplothandlermesh@patchtable@numverts\relax
		\edef\pgfplots@loc@TMPa{%
			\noexpand\pgfplotstablereadgetptrtocolindex{\the\c@pgf@countb}{\expandafter\noexpand\csname pgfplots@table@PTR@\the\c@pgf@countb\endcsname}%
		}%
		\pgfplots@loc@TMPa
		\advance\c@pgf@countb by1
	\pgfutil@repeat
	\let\pgfplotsplothandlermesh@patchtable@init=\relax
}%
\def\pgfplotsplothandlermesh@patchtable@rowlistener@exceptionmsg{%
	patch table \pgfplotsplothandlermesh@patchtable\space line \pgfplotstablelineno: could not read column no \the\c@pgf@countb: expected '\pgfplots@current@vertexindex' to be a valid index into the vertex arrays (the \pgfplotsarraysizeof\pgfplots@verts\space input coordinates)%
}%
\def\pgfplotsplothandlermesh@patchtable@rowlistener{%
	\pgfplotsplothandlermesh@patchtable@init%
	%
	\ifpgfplotsplothandlermesh@patchtable@hascdata
		\ifpgfplotsplothandlermesh@patchtable@cdata@individual
		\else
			\ifx\pgfplots@table@PTR@CDATA\relax
				\let\pgfplots@current@point@meta=\pgfutil@empty
			\else
				\pgfplotstablereadevalptr\pgfplots@table@PTR@CDATA\pgfplots@current@point@meta
			\fi
		\fi
	\fi
	%
	\c@pgf@countb=0
	\pgfutil@loop
	\ifnum\c@pgf@countb<\pgfplotsplothandlermesh@patchtable@numverts\relax
		\expandafter\pgfplotstablereadevalptr\csname pgfplots@table@PTR@\the\c@pgf@countb\endcsname\pgfplots@current@vertexindex%
		%
		\ifx\pgfplots@current@vertexindex\pgfutil@empty
		\else
			\pgfmathfloatparsenumber{\pgfplots@current@vertexindex}%
			\pgfmathfloattoint\pgfmathresult
			\let\pgfplots@current@vertexindex=\pgfmathresult
			%
			\let\pgfplotsexceptionmsg=\pgfplotsplothandlermesh@patchtable@rowlistener@exceptionmsg
			\pgfplotsarrayselect\pgfplots@current@vertexindex\of\pgfplots@verts\to\pgfplots@stored@pt
			\let\pgfplotsexceptionmsg=\relax
			%
			\ifpgfplotsplothandlermesh@patchtable@cdata@individual
				\c@pgf@countc=\c@pgf@countb\relax
				\advance\c@pgf@countc by\pgfplotsplothandlermesh@patchtable@numverts\relax
				\expandafter\getthisrowno\expandafter{\the\c@pgf@countc}\pgfplots@current@point@meta
			\fi
			%
			\expandafter\pgfplotsplothandlermesh@patchtable@stream\pgfplots@stored@pt
		\fi
		\advance\c@pgf@countb by1
	\pgfutil@repeat
}
\def\pgfplotsplothandlermesh@patchtable@stream#1,#2,#3;#4;{%
	\def\pgfplots@current@point@x{#1}%
	\def\pgfplots@current@point@y{#2}%
	\def\pgfplots@current@point@z{#3}%
	\ifpgfplotsplothandlermesh@patchtable@hascdata
		\def\pgfplots@set@perpointmeta@done{0}%
		\pgfplotsaxissurveysetpointmeta
	\else
		\def\pgfplots@current@point@meta{#4}%
	\fi
	\pgfplotsplothandlersurveypoint
}%
% MESH SURVEY
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\def\pgfplotsplothandlermesh@init@meshkeys{%
	\if1\pgfplotsplothandlermesh@matrixinput
		% mesh input=lattice
		\pgfplotsautocompletemeshkeys%
		\pgfkeysgetvalue{/pgfplots/mesh/rows}\pgfplotsplothandlermesh@rows
		\pgfkeysgetvalue{/pgfplots/mesh/cols}\pgfplotsplothandlermesh@cols
		\pgfkeysgetvalue{/pgfplots/mesh/num points}\pgfplotsplothandlermesh@numpoints
		%
		% the \pgfplotsplothandlermesh@ONEDIMMODE macro is ONLY
		% interesting for matrix input.
		\ifnum\pgfplotsplothandlermesh@cols>1
		\else
			\def\pgfplotsplothandlermesh@ONEDIMMODE{1}%
		\fi
		\ifnum\pgfplotsplothandlermesh@rows>1
		\else
			\def\pgfplotsplothandlermesh@ONEDIMMODE{1}%
		\fi
		\if1\pgfplotsplothandlermesh@ONEDIMMODE
			\def\pgfplotsplothandlermesh@patchclass{line}%
			\pgfkeyslet{/pgfplots/patch type}\pgfplotsplothandlermesh@patchclass
		\fi
	\else
		% mesh input=patches
		\pgfkeys{/pgfplots/mesh/ordering/x varies}% disable any special handling.
	\fi
	%
	\pgfplotspatchclass{\pgfkeysvalueof{/pgfplots/patch type}}{get dimension}%
	\ifnum\pgfplotsretval=1 %
		\def\pgfplots@meshmode{m}% mesh.
	\fi
	%
}%

\let\pgfplotsplothandlermesh@interior@exterior@hook=\relax
\def\pgfplotsplothandlermesh@interior@exterior@hook@active@zerothresh{%
	\begingroup
	\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{compute normal}%
% \let\pgfplots@normal=\pgfplotsretval
% \pgfplotsmathvectorlength{\pgfplotsretval}{default}%
% \pgfplotscoordmath{default}{op}{reciprocal}{{\pgfplotsretval}}%
% \pgfplotsmathvectorscale{\pgfplots@normal}{\pgfmathresult}{default}%
	%
	\pgfplotsmathvectorscalarproduct{\pgfplots@view@dir@threedim}{\pgfplotsretval}{default}%
	\pgfplotscoordmath{default}{if is}{\pgfplotsretval}{-}{%
		% <0:
		\global\let\pgfplots@glob@TMPc\pgfplotsplothandlermesh@is@interior
	}{%
		% >=0:
		\global\let\pgfplots@glob@TMPc\pgfplotsplothandlermesh@is@exterior
	}%
	\endgroup
	\pgfplots@glob@TMPc
}%

\def\pgfplotsplothandlermesh@interior@exterior@hook@active{%
	\begingroup
	\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{compute normal}%
	\let\pgfplots@normal=\pgfplotsretval
	\pgfplotsmathvectorlength{\pgfplotsretval}{default}%
	\let\pgfplots@normal@len=\pgfplotsretval
	%
	\pgfplotsmathvectorscalarproduct{\pgfplots@view@dir@threedim}{\pgfplots@normal}{default}%
	\let\pgfplots@dot=\pgfplotsretval
	\pgfplotscoordmath{default}{op}{multiply}{{\pgfplots@view@dir@threedim@len}{\pgfplots@normal@len}}%
	\pgfplotscoordmath{default}{op}{divide}{{\pgfplots@dot}{\pgfmathresult}}%

	\pgfplotscoordmath{default}{if less than}{\pgfmathresult}{\pgfplotsplothandlermesh@interior@thresh}{%
		% <0:
		\global\let\pgfplots@glob@TMPc\pgfplotsplothandlermesh@is@interior
	}{%
		% >=0:
		\global\let\pgfplots@glob@TMPc\pgfplotsplothandlermesh@is@exterior
	}%
	\endgroup
	\pgfplots@glob@TMPc
}%


% only used if
% \pgfplotsplothandlermesh@interior@exterior@hook@active is
% active
\def\pgfplotsplothandlermesh@is@interior{%
%\def\pgfplotsplothandlermesh@usepath{\pgfusepath{discard}}%
	\pgfkeyslet{/pgfplots/colormap name}\pgfplotsplothandlermesh@colormapname@interior
	\pgfkeyslet{/pgfplots/surf shading/colormap}\pgfplotsplothandlermesh@shader@colormap@interior
}%
\def\pgfplotsplothandlermesh@is@exterior{%
%\let\pgfplotsplothandlermesh@usepath=\pgfusepathqfillstroke
	\pgfkeyslet{/pgfplots/colormap name}\pgfplotsplothandlermesh@colormapname
	\pgfkeyslet{/pgfplots/surf shading/colormap}\pgfplotsplothandlermesh@shader@colormap
}%

\def\pgfplotsplothandlermesh@init@cdata{%
	% Ok, we have color data.
	%
	\pgfkeysgetvalue{/pgfplots/mesh/colorspace explicit color output}\pgfplots@loc@TMPa
	\pgfplotscolorspacegetcomponents{\pgfplots@loc@TMPa}%
	\let\pgfplotsplothandlermesh@explicit@color@num@comps=\pgfplotsretval
	%
	\pgfkeysgetvalue{/pgfplots/colormap name}\pgfplotsplothandlermesh@colormapname
	%
	\pgfkeysgetvalue{/pgfplots/mesh/interior colormap name}\pgfplotsplothandlermesh@colormapname@interior
	\ifx\pgfplotsplothandlermesh@colormapname@interior\pgfutil@empty
	\else
		\pgfkeysgetvalue{/pgfplots/mesh/interior colormap thresh}\pgfplotsplothandlermesh@interior@thresh
		\pgfplotscoordmath{default}{parsenumber}{\pgfplotsplothandlermesh@interior@thresh}%
		\let\pgfplotsplothandlermesh@interior@thresh=\pgfmathresult
		\pgfplotscoordmath{default}{if is}{\pgfplotsplothandlermesh@interior@thresh}{0}{%
			\let\pgfplotsplothandlermesh@interior@exterior@hook=\pgfplotsplothandlermesh@interior@exterior@hook@active@zerothresh
		}{%
			\pgfplotsmathvectorlength{\pgfplots@view@dir@threedim}{default}% should be 1, but never mind
			\let\pgfplots@view@dir@threedim@len=\pgfplotsretval
			\let\pgfplotsplothandlermesh@interior@exterior@hook=\pgfplotsplothandlermesh@interior@exterior@hook@active
		}%
		% actually store 3d coordinates:
		\let\pgfplotsplothandlermesh@serialize@logical@coords=\pgfplotsplothandlermesh@serialize@logical@coords@doit
	\fi
	%
	% Prepare:
	\def\pgfplotsplothandlermesh@definecolor{%
		\pgfplotsplothandlermesh@get@flat@color
		\pgfplotsplothandlermesh@definemappedcolor{\pgfplotsretval}%
		\pgfplots@drawoptions
	}%
	%
	% Acquire the values for \tikz@mode@* [used for faceted]
	\pgfplots@drawmodes
}

\def\pgfplotsplothandlermesh@definemappedcolor#1{%
	\if0\pgfplotsplothandlermesh@colorinput
		% mesh/color input=colormap
		\pgfplotscolormapdefinemappedcolor{#1}%
	\else
		% mesh/color input=explicit
		%
		% we assume that the color *is* already normalized, 
		% i.e. it is {<comma-separate-components>} and to be
		% interpreted in the correct color space.
		\edef\pgfplots@loc@TMPb{%
			\noexpand\pgfutil@definecolor{mapped color}
				{\pgfkeysvalueof{/pgfplots/mesh/colorspace explicit color output}}
				{#1}%
		}%
		\pgfplots@loc@TMPb
	\fi
}%

\let\pgfsetstrokecolor@orig=\pgfsetstrokecolor
\def\pgfplotsplothandlermesh@VISUALIZE@std@separate@fillstroke@setstrokecolor#1{%
	\pgfsetstrokecolor@orig{.}%
}%
\def\pgfplotsplothandlermesh@VISUALIZE@std@separate@fillstroke{%
	\pgfplotsplothandlermesh@get@flat@color
	\pgfplotsplothandlermesh@definemappedcolor{\pgfplotsretval}%
	%
	\ifx\pgfplotsplothandlermesh@usepathfill\relax
	\else
		\let\pgfsetstrokecolor=\pgfplotsplothandlermesh@VISUALIZE@std@separate@fillstroke@setstrokecolor
		\pgfplots@drawoptions
		\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{fill path}%
		\pgfplotsplothandlermesh@usepathfill
	\fi
	\ifx\pgfplotsplothandlermesh@usepathstroke\relax
	\else
		\let\pgfsetstrokecolor=\pgfsetstrokecolor@orig
		\pgfplots@drawoptions
		\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{stroke path}%
		\pgfplotsplothandlermesh@usepathstroke
	\fi
}%

% This is one of two places where shadings are served with
% coordinates; the other one uses matrix output (which does not work
% with 'stream to shader')
\def\pgfplotsplothandlermesh@VISUALIZE@interp{%
	\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{stream to shader}%
	\ifpgf@relevantforpicturesize
		\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{foreach vertex}{%
			\global\pgf@x=\pgfplotspatchvertexx\space
			\global\pgf@y=\pgfplotspatchvertexy\space
			% compute the bounding box using the vertices:
			\pgfpointtransformed{}%
			\pgf@protocolsizes{\pgf@x}{\pgf@y}%
		}%
	\fi
}%

\def\pgfplotsplothandlermesh@VISUALIZE@faceted@interp{%
	\pgfplotslibrarysurfstreamstart
	\pgfplotsplothandlermesh@VISUALIZE@interp
	\pgfplotslibrarysurfstreamend
	\pgfplotslibrarysurfdrawinpicture
	%
	\pgfplotsplothandlermesh@VISUALIZE@std
}%

\def\pgfplotsplothandlermesh@PIPE@CHECKJUMP@disable{%
	\def\pgfplotsplothandlermesh@PIPE@CHECKJUMP{\pgfplotsplothandlermesh@PIPE@REFINE}%
}%

\def\pgfplotsplothandlermesh@init@shader{%
	% 
	% Now, process the 'shader'  key here:
	\if\pgfplots@meshmode m% mesh
		% this is processed by the 'shader=flat' code below.
		\def\pgfplotsplothandlermesh@shader{0}% 'flat'
	\fi
	\ifnum\pgfplotsplothandlermesh@shader>1% 'shader=interp' and 'shader=faceted interp'
		\pgflibrarysurfshadingifactive
			{}%
			{%
				\pgfutil@ifundefined{pgfplotsplothandlermesh@shader@warning}{%
					\pgfplots@error{Sorry, surface shading (shader=interp) is NOT available for the selected driver `\pgfsysdriver'. I will use 'shader=flat' if you continue now}%
					\gdef\pgfplotsplothandlermesh@shader@warning{x}%
				}{}%
				\def\pgfplotsplothandlermesh@shader{0}%
			}%
	\fi
	%
	%
	\ifnum\pgfplotsplothandlermesh@shader>1
		% 'shader=2': 'interp':
		% very simple: defer work to surf library. Only
		% provide the mapped colordata.
		%
		% 'shader=3': 'faceted interp':
		% a mix of 'faceted' and 'interp'. (might be inefficient in
		% terms of pdf memory and rendering times)
		%
		% This won't be used for mesh plots, neither in one
		% nor in two dimensions.
		\pgfkeyssetvalue{/pgfplots/surf shading/anchor}{\pgfpointorigin}%
		%
 		% do NOT update the picture's BB using the streamed low-level coordinates 
		% (which are bezier control points in most cases). 
		% We do that on our own using the input vertices.
		\pgfkeys{/pgfplots/surf shading/update BB=false}%
		\if1\b@pgfplotsplothandlermesh@matrixoutput
			% this *implies* a compatible patch class, see the
			% definition of \b@pgfplotsplothandlermesh@matrixoutput
			\def\pgfplotsretval{5}%
		\else
			\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@output}{get pdf shading type}%
			\if5\pgfplotsretval
				% we have no matrix output->
				% downgrade lattice triangular grid to individual
				% triangles:
				\def\pgfplotsretval{4}%
			\fi
		\fi
		\pgfkeyslet{/pgfplots/surf shading/shading type}\pgfplotsretval%
		%
		\pgfplotsplothandlermesh@set@shader@colormap
		\pgfkeysgetvalue{/pgfplots/mesh/interior colormap name}\pgfplots@loc@TMPa
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\let\pgfplotsplothandlermesh@shader@colormap=\pgfplotsretval
			\begingroup
			\pgfkeyslet{/pgfplots/colormap name}\pgfplots@loc@TMPa
			\pgfplotsplothandlermesh@set@shader@colormap
			\pgfmath@smuggleone\pgfplotsretval
			\endgroup
			\let\pgfplotsplothandlermesh@shader@colormap@interior=\pgfplotsretval
		\fi
		%
		\if0\pgfplotsplothandlermesh@colorinput
			% mesh/color input=colormap
			\pgfkeysgetvalue{/pgfplots/colormap name}\pgfplots@loc@TMPa
			\pgfplotscolormapgetcolorspace\pgfplots@loc@TMPa
			\pgfkeyslet{/pgfplots/surf shading/colorspace}\pgfplotsretval
		\else
			% mesh/color input=explicit
			\pgfkeysgetvalue{/pgfplots/mesh/colorspace explicit color output}\pgfplots@loc@TMPa
			\edef\pgfplots@loc@TMPa{\pgfplots@loc@TMPa}%
			\pgfkeyslet{/pgfplots/surf shading/colorspace}\pgfplots@loc@TMPa
		\fi
		\if2\pgfplotsplothandlermesh@shader
			% shader=interp
			\let\pgfplotsplothandlermesh@definecolor=\relax
			\let\pgfplotsplothandlermesh@VISUALIZE=\pgfplotsplothandlermesh@VISUALIZE@interp%
			\pgfkeyslet{/pgfplots/surf shading/cols}\pgfplotsplothandlermesh@scanlinelength
			%\if1\b@pgfplotsplothandlermesh@matrixoutput
			\iffalse% FIXME : is this special handling necessary!?
				\if\pgfplots@plot@mesh@ordering0%
					% ordering=x varies:
					% nothing special to do
				\else
					% FIXME 
					% [this happens only for mesh input=lattice]
					% colwise:
					%
					% The low level shader NEEDS rowwise ordering. So, we need to transpose the data matrix.
					% As usual in TeX, we should save macros as much as possible. I guess we NEED at least one macro for each matrix row.
					% Idea:
					% while we iterate colwise through the input data, accumulate row vectors.
					% Then, process the row vectors.
					% Since vectors are expensive (in terms of number of macros), we use fast "append" lists instead of vectors.
					\let\pgfplotsplothandlermesh@shader@interp=\pgfplotsplothandlermesh@shader@interp@incremental@transpose
					%
					% init all required row vectors:
					\c@pgfplots@scanlineindex=0
					\pgfutil@loop
					\ifnum\c@pgfplots@scanlineindex<\pgfplotsplothandlermesh@rows\relax
						\expandafter\pgfplotsapplistXnewempty\csname pgfp@transprow@\the\c@pgfplots@scanlineindex\endcsname%
						\advance\c@pgfplots@scanlineindex by1
					\pgfutil@repeat
					%\pgfkeyslet{/pgfplots/surf shading/cols}\pgfplotsplothandlermesh@rows
					%\pgfplots@error{Sorry, the 'shader=interp' does not yet support 'mesh/ordering=colwise'... You can continue now, but the plot will be transposed.}%
				\fi
			\fi
			\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@output}{init pdf shading}%
			\pgfplotslibrarysurfstreamstart
		\else
			% shader='faceted interp'
			\def\pgfplotsplothandlermesh@VISUALIZE{\pgfplotsplothandlermesh@VISUALIZE@faceted@interp}%
			\pgfkeyssetvalue{/pgfplots/surf shading/cols}{2}%
			\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@output}{init pdf shading}%
		\fi
	\else
		\def\pgfplotsplothandlermesh@VISUALIZE{\pgfplotsplothandlermesh@VISUALIZE@std}%
	\fi
	%
	%%
	\ifpgfplotsplothandlermesh@internaldepth
	\else
		% disable internal sorting.
		\let\pgfplotspatchclass@rect@to@coonspatch@findshadingsequence@for@depth=\pgfplotspatchclass@rect@to@coonspatch@findshadingsequence@for@depth@no@op%
		\let\pgfplotspatchclass@tri@to@coonspatch@findshadingsequence@for@depth=\pgfplotspatchclass@tri@to@coonspatch@findshadingsequence@for@depth@no@op
	\fi
}%

\def\pgfplotsplothandlermesh@init@flat@color{%
	\ifcase\pgfplotsplothandlermesh@shader
		% 0 == 'flat'
		\def\pgfplotsplothandlermesh@needs@flat@color{1}%
	\or
		% 1 == 'faceted'
		\def\pgfplotsplothandlermesh@needs@flat@color{1}%
	\or
		% 2 == 'interp'
		\def\pgfplotsplothandlermesh@needs@flat@color{0}%
	\or
		% 3 == 'faceted interp'
		\def\pgfplotsplothandlermesh@needs@flat@color{1}%
	\fi
	\if1\pgfplotsplothandlermesh@needs@flat@color
		\pgfplotsplothandlermesh@init@flat@color@getter
		%
		\pgfplotsplothandlermesh@init@flat@color@usepath
		%
		%
		\pgfplotsplothandlermesh@init@flat@color@visualize@pipe@step
	\fi
}%

\def\pgfplotsplothandlermesh@init@flat@color@visualize@pipe@step{%
	\ifx\pgfplotsplothandlermesh@PIPE@REFINE\pgfplotsplothandlermesh@PIPE@REFINE@no@op
		\let\pgfplotsplothandlermesh@VISUALIZE@std=\pgfplotsplothandlermesh@VISUALIZE@std@fill@andor@stroke
	\else
		\ifpgfplotsplothandlermesh@hide@refined@edges
			% this is (at most) partially implemented.
			\let\pgfplotsplothandlermesh@VISUALIZE@std=\pgfplotsplothandlermesh@VISUALIZE@std@separate@fillstroke
		\else
			\let\pgfplotsplothandlermesh@VISUALIZE@std=\pgfplotsplothandlermesh@VISUALIZE@std@fill@andor@stroke
		\fi
		%
		% FIXME : that doesn't work.
		% filling *always* seems to need a stroke operation,
		% otherwise there will be translucent edges.
		% I need to adjust the stroke color :-(
		%
		% FIXME : even that doesn't work correctly. The problem
		% is: drawing adjacent patches on top of each other
		% OVERDRAWS edges: once with the correct stroke color;
		% once with the fill color.
		%
		\ifx\pgfplotsplothandlermesh@usepath\pgfusepathqstroke
			\let\pgfplotsplothandlermesh@usepathfill=\relax
			\let\pgfplotsplothandlermesh@usepathstroke=\pgfusepathqstroke
		\else
			\ifx\pgfplotsplothandlermesh@usepath\pgfusepathqfillstroke
				\let\pgfplotsplothandlermesh@usepathfill=\pgfusepathqfillstroke
				\let\pgfplotsplothandlermesh@usepathstroke=\pgfusepathqstroke
			\else
				\let\pgfplotsplothandlermesh@usepathfill=\relax
				\let\pgfplotsplothandlermesh@usepathstroke=\relax
			\fi
		\fi
	\fi
}%

\def\pgfplotsplothandlermesh@init@flat@color@usepath{%
	\if\pgfplots@meshmode m%
		% 'mesh' plot: stroke only and use the 'flat' code
		% here just to define the color for each mesh
		% segment.
		\let\pgfplotsplothandlermesh@usepath=\pgfusepathqstroke
	\else
		% 'surf' plot: 
		\let\pgfplotsplothandlermesh@usepath=\pgfusepathqfillstroke
		\if\pgfplotsplothandlermesh@shader3% faceted interp
			% it has an extra fill command (shading)
			\let\pgfplotsplothandlermesh@usepath=\pgfusepathqstroke
		\fi
		%
		% the distinction between 'faceted' and 'flat' is
		% technical: it is just the default draw color.
		%
		% 'flat,draw=black' is the same as 'faceted'.
		\pgfkeysgetvalue{/pgfplots/faceted color}\pgfplots@loc@TMPb
		\def\pgfplots@loc@TMPc{none}%
		\ifx\pgfplots@loc@TMPb\pgfplots@loc@TMPc
			\pgfkeyslet{/pgfplots/faceted color}\pgfutil@empty
			\def\pgfplots@loc@TMPb{}%
		\fi
		%
		\def\pgfplots@loc@TMPa{0}%
		\if\pgfplotsplothandlermesh@shader1% faceted
			\def\pgfplots@loc@TMPa{1}%
			\ifx\pgfplots@loc@TMPb\pgfutil@empty
				% oh. no faceted color. Then: fill only, use
				% whatever color is available.
				\def\pgfplots@loc@TMPa{0}%
				%\let\pgfplotsplothandlermesh@usepath=\pgfusepathqfill
			\fi
		\fi
		\if\pgfplotsplothandlermesh@shader3% faceted interp
			\def\pgfplots@loc@TMPa{1}%
			\ifx\pgfplots@loc@TMPb\pgfutil@empty
				% oh. no faceted color. Then: no-op!
				% This is the same as interp with more overhead
				% (but allows z buffering).
				\def\pgfplots@loc@TMPa{0}%
				\def\pgfplotsplothandlermesh@usepath{\pgfusepath{discard}}%
			\fi
		\fi
		\if1\pgfplots@loc@TMPa
			% make sure there is a the correct color.
			\expandafter\def\expandafter\pgfplots@drawoptions\expandafter{%
				\pgfplots@drawoptions
				\pgfsetstrokecolor{\pgfkeysvalueof{/pgfplots/faceted color}}%
			}%
		\fi
		%
	\fi
}

\def\pgfplotsplothandlermesh@init@flat@color@getter{%
	\if\pgfplotsplothandlermesh@flatmode c% 'flat corner':
		%
		% use colordata of ONE corner point. That's easy, not
		% much to do.
		\def\pgfplotsplothandlermesh@get@flat@color{%
			\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@output}{first vertex}%
			\let\pgfplots@current@point@meta=\pgfplotspatchvertexmeta
			\pgfplotsaxisvisphasetransformpointmeta
			\let\pgfplotsretval=\pgfplotspointmetatransformed%
		}%
	\else
		% 'flat mean':
		%
		% use colordata as mean of all corners for shading.
		\if0\pgfplotsplothandlermesh@colorinput
			% mesh/color input=colormap
			\def\pgfplotsplothandlermesh@get@flat@color{%
				\global\pgfplots@tmpa=0pt
				\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@output}{foreach cdata vertex}{%
					\let\pgfplots@current@point@meta=\pgfplotspatchvertexmeta
					\pgfplotsaxisvisphasetransformpointmeta
					\global\advance\pgfplots@tmpa by\pgfplotspointmetatransformed pt
				}%
				\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@output}{get num cdata vertices}%
				\global\divide\pgfplots@tmpa by\pgfplotsretval\relax
				\edef\pgfplotsretval{\pgf@sys@tonumber\pgfplots@tmpa}%
				\global\pgfplots@tmpa=0pt
			}%
		\else
			% mesh/color input=explicit
			\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@output}{get num cdata vertices}%
			\pgf@xa=1pt %
			\divide\pgf@xa by\pgfplotsretval\relax
			\edef\pgfplotsplothandlermesh@get@flat@color@@{\pgf@sys@tonumber\pgf@xa}%
			%
			\def\pgfplotsplothandlermesh@get@flat@color{%
				\pgfplotscolorzero{\pgfplotsplothandlermesh@explicit@color@num@comps}%
				\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@output}{foreach cdata vertex}{%
					\pgfplotscoloraddweighted
						{\pgfplotsplothandlermesh@explicit@color@num@comps}%
						{\pgfplotsretval}
						{\pgfplotsplothandlermesh@get@flat@color@@}%
						{\pgfplotspatchvertexmeta}%
				}%
				\let\pgfplots@current@point@meta=\pgfplotspatchvertexmeta
				\pgfplotsaxisvisphasetransformpointmeta
			}%
		\fi
	\fi
}%

\def\pgfplotsplothandlermesh@init@jumphandling{%
	% For matrix input, a "jump" should result in something
	% visible although it must not destroy the matrix structure.
	%
	% try this here:
	\def\pgfplotsplothandlervisualizejump{%
		\pgfplotstreampoint{\global\pgf@x=-16000.0pt \global\pgf@y=-16000.0pt }%
	}%
	%
	\if0\pgfplotsaxisplothasjumps
		\pgfplotsplothandlermesh@PIPE@CHECKJUMP@disable
	\fi
}%


\def\pgfplotsplothandlermesh@init@zbuffer{%
	\ifpgfplots@curplot@threedim
		\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@output}{uses view depth}%
		\if1\pgfplotsretval
			\let\pgfplotsplothandlermesh@compute@vertex@depth=\pgfplotsplothandlermesh@compute@vertex@depth@doit%
		\fi
		%
		\if\pgfplotsplothandlermesh@zbuffer@choice4%
			% z buffer=sort:
			% create a z buffer:
			% the z buffer contains elements {<view depth>}{{<pt1>}{<pt2>}{<pt3>}{<pt4>}}
			\pgfplotsarraynewempty\pgfplots@zbuffer@local
			%
			\let\pgfplotsplothandlermesh@compute@vertex@depth=\pgfplotsplothandlermesh@compute@vertex@depth@doit%
			%
			% the "element depth" is defined to be the MEAN of all
			% vertex depths. 
			% And since the mean is 1/n * sum_{i=1}^n V_i, we can
			% directly omit the 1/n --- it is the same for every
			% vertex anyway, and we only want to compare the depth
			% values.
			\let\pgfplotsplothandlermesh@accum@element@depth=\pgfmath@basic@add@
			%
			% and collect each point into the z buffer
			% (instead of drawing it):
			\def\pgfplotsplothandlermesh@PIPE@FINISH{%
				%
				% compute DEPTH(lattice element):= min{DEPTH(A),DEPTH(B),DEPTH(C),DEPTH(D)}
				\def\pgfmathresult{0}%
				\def\pgfplotsplothandlermesh@zbuffer@tmp{}%
				\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@output}{foreach vertex}{%
					\pgfplotsplothandlermesh@accum@element@depth\pgfplotspatchvertexdepth\pgfmathresult
					\t@pgfplots@toka=\expandafter{\pgfplotsplothandlermesh@zbuffer@tmp}%
					\t@pgfplots@tokb=\expandafter{\pgfplotspatchvertexstruct}%
					\edef\pgfplotsplothandlermesh@zbuffer@tmp{%
						\the\t@pgfplots@toka
						{\the\t@pgfplots@tokb}%
					}%
				}%
				\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@output}{serialize except vertices}%
				\t@pgfplots@toka=\expandafter{\pgfplotsretval}%
				\t@pgfplots@tokb=\expandafter{\pgfplotsplothandlermesh@zbuffer@tmp}%
				\edef\pgfplotsplothandlermesh@zbuffer@tmp{%
					{\the\t@pgfplots@toka}% first argument is meta data, then follow the vertices
					\the\t@pgfplots@tokb%
				}%
				%
				% assemble array element:
				\t@pgfplots@toka=\expandafter{\pgfplotsplothandlermesh@zbuffer@tmp}%
				\edef\pgfplots@loc@TMPa{%
					{\pgfmathresult}%
					{%
						\the\t@pgfplots@toka
					}%
				}%
				\expandafter\pgfplotsarraypushback\pgfplots@loc@TMPa\to\pgfplots@zbuffer@local
			}%
		\fi
	\fi
}%
\def\pgfplotsplothandlermesh@init@mesh@stream{%
	\global\let\pgf@plotstreamspecial=\pgfutil@gobble%
	\global\let\pgf@plotstreamend=\pgfplotsplothandlermesh@finish%
	\global\let\pgf@plotstreampoint=\pgfplotsplothandlermesh@stream
	\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass}{new}%
}

\def\pgfplotsplothandlermesh@set@shader@colormap{%
	\if0\pgfplotsplothandlermesh@colorinput
		% mesh/color input=colormap
		\pgfkeysgetvalue{/pgfplots/colormap name}\pgfplots@loc@TMPa
		\expandafter\pgfplotscolormaptopdffunction\expandafter{\pgfplots@loc@TMPa}%
		\pgfkeyslet{/pgfplots/surf shading/colormap}\pgfplotsretval
	\else
		% mesh/color input=explicit
		%
		% tell it to expect explicit colors:
		\pgfkeyslet{/pgfplots/surf shading/colormap}\pgfutil@empty
	\fi
}%

{
\dimen0=-16000.0pt
\xdef\pgfplotsplothandlermesh@check@unbounded@text{\the\dimen0}%
}

\def\pgfplotsplothandlermesh@check@unbounded{%
	\ifx\pgfplotspatchvertexx\pgfplotsplothandlermesh@check@unbounded@text
		\pgfplots@loc@tmpfalse
	\fi
}%

\long\def\pgfplotsplothandlermesh@defaultlegend@img#1{%
	\scope[%
		#1,
		/pgfplots/mesh/rows=3,
		/pgfplots/mesh/cols=3,
		/pgfplots/mesh/num points=,
		/pgfplots/mesh input=lattice,
		/pgfplots/patch type=rectangle,
		/tikz/x={(0.44237cm,-0.07439cm)}, 
		/tikz/y={(0.30942cm,0.23932cm)},
		/tikz/z={(0.0cm,1.5cm)},
		scale=0.4,
		yshift=-0.7cm,
		/pgfplots/point meta=explicit,
	]
	\let\pgfplots@metamax=\pgfutil@empty
	\pgfplots@curplot@threedimtrue

	\pgfplotsplothandlermesh
	\pgfplotstreamstart

	\def\rangea{0.21}%
	\def\rangeb{0.7}%

	\pgfmathparse{1000/(\rangeb-\rangea)}
	\let\factor=\pgfmathresult

	\def\simplecoordinate(##1,##2,##3){%
		\pgfmathparse{\factor*(##3 - \rangea)}%
		\pgfmathfloatparsenumber\pgfmathresult
		\let\pgfplots@current@point@meta=\pgfmathresult
		\pgfplotstreampoint{\pgfqpointxyz{##1}{##2}{##3}}%
	}%
	% for the case 'shader=interp':
	%\def\pgfplotspointbbupperright{\pgfqpointxyz{2}{2}{0.9}}
	%\def\pgfplotspointbblowerleft {\pgfqpointxyz{0}{0}{0.1}}

	\simplecoordinate(0,2,0.7)
	\simplecoordinate(1,2,0.5)
	\simplecoordinate(2,2,0.43)

	\simplecoordinate(0,1,0.68)
	\simplecoordinate(1,1,0.4)
	\simplecoordinate(2,1,0.25)

	\simplecoordinate(0,0,0.6)
	\simplecoordinate(1,0,0.35)
	\simplecoordinate(2,0,0.21)

	\pgfplotstreamend
	\pgfusepath{stroke}
	\endscope
}%

\def\pgfplotsplothandlermesh@finish{%
	\if\pgfplotsplothandlermesh@zbuffer@choice4%
		% z buffer=sort:
		% process the z buffer:
		\pgfkeyslet{/pgfplots/iflessthan/.@cmd}\pgfplotsplothandlermesh@zbuffer@sort@iflessthen
		\pgfkeysdef{/pgfplots/array/unscope pre}{%
			\let\pgfplotsplothandlermesh@patchclass=\pgfplotsplothandlermesh@patchclass@output
			\def\pgfplotspatchready{\pgfplotsplothandlermesh@PIPE@interior@exterior@styles}%
			\pgfplotsarrayforeachungrouped\pgfplots@zbuffer@local\as\curelem{%
				\expandafter\pgfplotsplothandlermesh@draw@zbufferelement\curelem%
			}%
		}%
		\pgfkeysdef{/pgfplots/array/unscope post}{}%
		\pgfplotsarraysort\pgfplots@zbuffer@local
	\fi
	%
	\if2\pgfplotsplothandlermesh@shader
		% shader=interp:
		% FIXME : broken!
		%\ifx\pgfplotsplothandlermesh@shader@interp\pgfplotsplothandlermesh@shader@interp@incremental@transpose%
			% This is the case for 'mesh/ordering=colwise'. We need to finish the transpose procedure:
		%	\pgfplotsplothandlermesh@shader@interp@transpose@finish
		%\fi
		\pgfplotslibrarysurfstreamend
		\pgfplotslibrarysurfdrawinpicture
	\fi
}%


% This is one of two places where the shader is served with
% coordinates: it handles the special matrix-form shading which is
% incompatible with the patch-wise sequence of coordinates
\def\pgfplotsplothandlermesh@PIPE@DECODE@to@shader#1{%
	\pgfplotsaxisvisphasetransformpointmeta
	\ifpgf@relevantforpicturesize
		\pgfpointtransformed{#1}%
		\pgf@protocolsizes{\pgf@x}{\pgf@y}%
	\fi
	\pgfplotslibrarysurfstreamcoord
		{#1}%
		{\pgfplotspointmetatransformed}%
}%

\def\pgfplotsplothandlermesh@PIPE@DECODE@matrix@ONEDIMMODE#1{%
	\let\pgfplotsplothandlermesh@patchclass\pgfplotsplothandlermesh@patchclass@input
	\pgfplotsplothandlermesh@compute@vertex@depth% <-- this modifies \pgfplotsretval
	\let\pgfplots@view@depth=\pgfplotsretval
	\pgf@process{#1}%
	\pgfplotsplothandlermesh@serialize@logical@coords
	\edef\pgfplotsplothandlermesh@i{{\the\pgf@x}{\the\pgf@y}{\pgfplots@current@point@meta}\pgfplots@view@depth:\pgfplotsretval}%
	\ifnum\c@pgfplots@scanlineindex>0
		\expandafter\pgfplotsplothandlermesh@setnextvertex\expandafter{\pgfplotsplothandlermesh@im}%
		\expandafter\pgfplotsplothandlermesh@setnextvertex\expandafter{\pgfplotsplothandlermesh@i}%
	\else
		\advance\c@pgfplots@scanlineindex by1
	\fi
	\let\pgfplotsplothandlermesh@im=\pgfplotsplothandlermesh@i
}%

% the pgf@plotstreampoint routine for the first scan line:
\def\pgfplotsplothandlermesh@PIPE@DECODE@matrix@fillscanline#1{%
	\pgfplotsplothandlermesh@compute@vertex@depth% <-- this modifies \pgfplotsretval
	\let\pgfplots@view@depth=\pgfplotsretval
	\pgf@process{#1}%
	\pgfplotsplothandlermesh@serialize@logical@coords
	\edef\pgfplots@loc@TMPa{{\the\pgf@x}{\the\pgf@y}{\pgfplots@current@point@meta}\pgfplots@view@depth:\pgfplotsretval}%
	\expandafter\pgfplotsdequepushback\pgfplots@loc@TMPa\to{lastscanline}%
	\advance\c@pgfplots@scanlineindex by1
	\ifnum\c@pgfplots@scanlineindex=\pgfplotsplothandlermesh@scanlinelength\relax
		% second line!
		\let\pgfplotsplothandlermesh@PIPE@DECODE=\pgfplotsplothandlermesh@PIPE@DECODE@matrix%%
		\c@pgfplots@scanlineindex=0
	\fi
}%
% This is the pgf@plotstreampoint for all scan lines starting with the
% second.
%
% We perform
% // i == y
% // j == x
% for i = 1  to rows (note the 1! 0 would be the first row)
% 	for j = 0 to cols
% 		get (i-1, j) from front of deque // remember: i: rows, j : cols. We iterate rowwise.
% 		push (i,j) to back of deque
% 		if j > 0
% 			draw 
% 				(i-1,j-1) [from last iteration]  -- (i-1,j  ) [from deque]
% 			--  (  i,j  ) [from last iteration]  -- (i  ,j-1) [from #1]
% 			-- cycle
% 		endif
% 		let (i-1,j-1) := (i-1,j) // for next iteration
% 		let (  i,j-1) := (  i,j) // for next iteration
% 	end
% end
%
% This is a SWEEP through the data matrix.
\def\pgfplotsplothandlermesh@PIPE@DECODE@matrix#1{%
	% NOTATION: 
	% 	'im == (i-1)'
	% 	'jm == (j-1)'
	\pgfplotsplothandlermesh@compute@vertex@depth% <-- this modifies \pgfplotsretval
	\let\pgfplots@view@depth=\pgfplotsretval
	\pgf@process{#1}%
	\pgfplotsplothandlermesh@serialize@logical@coords
	\edef\pgfplotsplothandlermesh@i@j{{\the\pgf@x}{\the\pgf@y}{\pgfplots@current@point@meta}\pgfplots@view@depth:\pgfplotsretval}% FIXME relies on pgfplots macros
%\message{##\the\c@pgfplots@scanlineindex: prepare rectangle with corner \meaning\pgfplotsplothandlermesh@i@j.}%
	\pgfplotsdequepopfront{lastscanline}\to\pgfplotsplothandlermesh@im@j
	\expandafter\pgfplotsdequepushback\pgfplotsplothandlermesh@i@j\to{lastscanline}%
	\ifnum\c@pgfplots@scanlineindex>0
		\let\pgfplotsplothandlermesh@patchclass\pgfplotsplothandlermesh@patchclass@input
		\expandafter\pgfplotsplothandlermesh@setnextvertex\expandafter{\pgfplotsplothandlermesh@im@jm}%
		\expandafter\pgfplotsplothandlermesh@setnextvertex\expandafter{\pgfplotsplothandlermesh@im@j}%
		\expandafter\pgfplotsplothandlermesh@setnextvertex\expandafter{\pgfplotsplothandlermesh@i@j}%
		\expandafter\pgfplotsplothandlermesh@setnextvertex\expandafter{\pgfplotsplothandlermesh@i@jm}%
	\fi
	\let\pgfplotsplothandlermesh@im@jm=\pgfplotsplothandlermesh@im@j
	\let\pgfplotsplothandlermesh@i@jm=\pgfplotsplothandlermesh@i@j
	\advance\c@pgfplots@scanlineindex by1
	\ifnum\c@pgfplots@scanlineindex=\pgfplotsplothandlermesh@scanlinelength\relax
		\c@pgfplots@scanlineindex=0
	\fi
}%
\def\pgfplotsplothandlermesh@shader@interp@incremental@transpose#1{%
	\pgfplotsaxisvisphasetransformpointmeta
	\pgf@process{#1}%
	\edef\pgfplotsplothandlermesh@i{\noexpand\pgfplotsplothandlermesh@shader@interp@next{\the\pgf@x}{\the\pgf@y}{\pgfplotspointmetatransformed}}%
	%
	% Store the postprocessed point into the appropriate row vector:
	\def\pgfplots@loc@TMPa{\expandafter\pgfplotsapplistXpushback\expandafter{\pgfplotsplothandlermesh@i}\to}
	\expandafter\pgfplots@loc@TMPa\csname pgfp@transprow@\the\c@pgfplots@scanlineindex\endcsname%
	%
	\advance\c@pgfplots@scanlineindex by1
	\ifnum\c@pgfplots@scanlineindex=\pgfplotsplothandlermesh@scanlinelength\relax
		\c@pgfplots@scanlineindex=0
	\fi
}%
\def\pgfplotsplothandlermesh@shader@interp@transpose@finish{%
	% Now, "execute" each row vector:
	\def\pgfplotsplothandlermesh@shader@interp@next##1##2##3{%
		\pgfplotslibrarysurfstreamcoord{\global\pgf@x=##1 \global\pgf@y=##2 }{##3}%
	}%
	\c@pgfplots@scanlineindex=0
	\pgfutil@loop
	\ifnum\c@pgfplots@scanlineindex<\pgfplotsplothandlermesh@rows\relax
		\expandafter\pgfplotsapplistXlet\expandafter\pgfplots@loc@TMPd\expandafter=\csname pgfp@transprow@\the\c@pgfplots@scanlineindex\endcsname%
		\expandafter\pgfplotsapplistXnewempty\csname pgfp@transprow@\the\c@pgfplots@scanlineindex\endcsname% clear
		% execute the row:
		\pgfplots@loc@TMPd
		\advance\c@pgfplots@scanlineindex by1
	\pgfutil@repeat
	\let\pgfplots@loc@TMPd=\relax
}%

\def\pgfplotsplothandlermesh@draw@zbufferelement#1#2{%
	\pgfplotsplothandlermesh@draw@zbufferelement@#2\pgfplots@EOI
}
\def\pgfplotsplothandlermesh@draw@zbufferelement@#1{%
	\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@output}{deserialize except vertices}{#1}%
	\pgfplotsplothandlermesh@draw@zbufferelement@@
}
\def\pgfplotsplothandlermesh@draw@zbufferelement@@#1{%
	\def\pgfplots@loc@TMPa{#1}%
	\ifx\pgfplots@loc@TMPa\pgfplots@EOI
	\else
		\pgfplotspatchclass{\pgfplotsplothandlermesh@patchclass@output}{set next vertex}{#1}%
		\expandafter\pgfplotsplothandlermesh@draw@zbufferelement@@
	\fi
}%


\def\pgfplotsplothandlermesh@zbuffer@sort@iflessthen#1#2#3#4\pgfeov{%
	\edef\pgfplots@loc@TMPa{#1}%
	\expandafter\pgfplotsplothandlermesh@zbuffer@sort@iflessthen@\pgfplots@loc@TMPa\relax
	\let\pgfplotsplothandlermesh@zbuffer@sort@iflessthen@a=\pgfmathresult
	\edef\pgfplots@loc@TMPb{#2}%
	\expandafter\pgfplotsplothandlermesh@zbuffer@sort@iflessthen@\pgfplots@loc@TMPb\relax
	\let\pgfplotsplothandlermesh@zbuffer@sort@iflessthen@b=\pgfmathresult
	\ifdim\pgfplotsplothandlermesh@zbuffer@sort@iflessthen@b pt<\pgfplotsplothandlermesh@zbuffer@sort@iflessthen@a pt%
		#3\relax
	\else
		#4\relax
	\fi
}%
\def\pgfplotsplothandlermesh@zbuffer@sort@iflessthen@#1#2{%
	\def\pgfmathresult{#1}%
}%
\def\pgfplotsplothandlermesh@unpack@zbuffer@pointdepth#1{%
	\expandafter\pgfplotsplothandlermesh@unpack@zbuffer@pointdepth@#1%
}%
\def\pgfplotsplothandlermesh@unpack@zbuffer@pointdepth@#1#2#3#4{%
	\def\pgfplotsretval{#4}%
}%

pgfplotsoldpgfsupp_loader.code.tex

%\input pgfplotsoldpgfsupp_pgfmathparse.opt.code.tex
%\beginpgfmathparsecheckfornumber

\pgfutil@ifundefined{pgfmathlessthan@}{%
	\let\pgfmathlessthan@=\pgfmathless@
	\let\pgfmathgreaterthan@=\pgfmathgreater@
}{}%


\def\pgfplotsusecompatibilityfile#1{%
	\pgfutil@IfUndefined{pgfplotsusecompatibilityfile@loaded@#1}{%
		\expandafter\gdef\csname pgfplotsusecompatibilityfile@loaded@#1\endcsname{1}%
		\input pgfplotsoldpgfsupp_#1
	}{%
		% already loaded.
	}%
}%

\def\pgfmathfloatrounddisplaystyle@shared@impl@WRONG#1#2{%
	{\toks0={#1}%
	\toks1=\expandafter{\pgfmathfloatrounddisplaystyle@e@mark #2}%
	\xdef\pgfmathfloat@glob@TMP{\the\toks0 \the\toks1 }%
	}%
	\let\pgfmathresult=\pgfmathfloat@glob@TMP
}%

% check whether we need to load supplementary code.
% The development of pgfplots and pgf is intermingled, so pgfplots
% always uses up-to-date pgf CVS versions - the relevant complements between
% PGF 2.10 and PGF CVS are loaded here:
%
% #1: for backwards compatibility
% #2: for normal processing.
\def\pgfplots@ifneedspgfcompabitibilitycode@has@pgf@one@zero@zero#1#2{%
	%\pgfkeysifdefined{/pgf/number format/sci precision/.@cmd}{#2}{#1}%
	\pgfutil@ifundefined{pgfmathprintnumber@RELATIVE@choice@roundtofixed}{#1}{#2}%
}%

\let\pgfplots@ifneedspgfcompabitibilitycode=\pgfplots@ifneedspgfcompabitibilitycode@has@pgf@one@zero@zero

\pgfplots@ifneedspgfcompabitibilitycode
	{%
		\immediate\write16{Package pgfplots: loading complementary code for your PGF version...}
		\input pgfplotsoldpgfsupp_misc.code.tex
		\let\pgfkeysloaded=\undefined
		\input pgfplotsoldpgfsupp_pgfkeys.code.tex
		\input pgfplotsoldpgfsupp_pgfmathfloat.code.tex
		\input pgfplotsoldpgfsupp_pgflibraryplothandlers.code.tex
		\input pgfplotsoldpgfsupp_pgflibraryfpu.code.tex
		\input pgfplotsoldpgfsupp_pgfcorescopes.code.tex
		\input pgfplotsoldpgfsupp_pgfcorelayers.code.tex
	}%
	{%
		\pgfplots@iffileexists{pgflibraryfpu.code.tex}{%
			\usepgflibrary{fpu}%
		}{%
			\immediate\write16{Package pgfplots: loading FPU library which doesn't appear to exist in your PGF version...}
			\input pgfplotsoldpgfsupp_pgflibraryfpu.code.tex
		}%
	}%

\pgfutil@ifundefined{pgfmathdeclarepseudoconstant}{
	\immediate\write16{Package pgfplots: loading complementary arithmetics for your pgf version...}
	\input pgfplotsoldpgfsupp_pgflibraryfpu.code.tex
}
{}%

\pgfutil@IfUndefined{pgfmathdeclarefunction}{
	\pgfplots@warning{Parts of pgfplots require PGF 2.10; you have PGF 2.00 . Consider upgrading if you experience problems.}%
}{%
}%

\pgfutil@IfUndefined{pgfapplistnewempty}{%
	\immediate\write16{Package pgfplots: loading complementary utilities for your pgf version...}
	\csname newtoks\endcsname\t@pgf@toka
	\csname newtoks\endcsname\t@pgf@tokb
	\csname newtoks\endcsname\t@pgf@tokc
	\gdef\pgfutil@advancestringcounter{\pgfplotsutil@advancestringcounter}%
	\input pgfplotsoldpgfsupp_pgfutil-common-lists.tex
}{}%

\pgfutil@IfUndefined{pgfmathiftrigonometricusesdeg}{%
	\pgfutil@ifundefined{pgfmathdeclarefunction}{%
		% PGF 2.00 !? Well, trig format won't work here.
	}{%
		\input pgfplotsoldpgfsupp_trig_format.code.tex
	}%
}{}%


\endinput

pgfplotsoldpgfsupp_pgflibraryintersections.code.tex
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% This file is a copy of some part of PGF/Tikz.
%%% It has been copied here to provide :
%%%  - compatibility with older PGF versions
%%%  - availability of PGF contributions by Christian Feuersaenger
%%%    which are necessary or helpful for pgfplots.
%%%
%%% For reasons of simplicity, I have copied the whole file, including own contributions AND
%%% PGF parts. The copyrights are as they appear in PGF.
%%%
%%% Note that pgfplots has compatible licenses.
%%% 
%%% This copy has been modified in the following ways:
%%%  - nested \input commands have been updated
%%%  
%
% Support for the contents of this file will NOT be done by the PGF/TikZ team. 
% Please contact the author and/or maintainer of pgfplots (Christian Feuersaenger) if you need assistance in conjunction
% with the deployment of this patch or partial content of PGF. Note that the author and/or maintainer of pgfplots has no obligation to fix anything:
% This file comes without any warranty as the rest of pgfplots; there is no obligation for help.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Date of this copy: Fr 14. Feb 21:37:39 CET 2014 %%%



% Copyright 2008 by Mark Wibrow
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Free Documentation License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

% Note: at the time of this writing, the library has quadratic runtime.
%   Experimentally, it performed well while computing ~12 intersections of two
%   plots, each with 600 samples. It failed when the number of samples exceeded 700.

\usepgflibrary{fpu}

\newcount\pgf@intersect@solutions

\newif\ifpgf@intersect@sort
\newif\ifpgf@intersect@sort@by@second@path

\def\pgfintersectionsortbyfirstpath{%
	\pgf@intersect@sorttrue%
	\pgf@intersect@sort@by@second@pathfalse%
}

\def\pgfintersectionsortbysecondpath{%
	\pgf@intersect@sorttrue%
	\pgf@intersect@sort@by@second@pathtrue%
}

% #1: the index. It starts at 1 and ends with \pgfintersectionsolutions (inclusive).
% Invalid values will implicitly result in the origin.
\def\pgfpointintersectionsolution#1{%
	\ifnum#1<1\relax%
		\pgfpoint@intersect@solution@orgin%
	\else%
		\ifnum#1>\pgfintersectionsolutions\relax%
			\pgfpoint@intersect@solution@orgin%
		\else%
			\csname pgfpoint@intersect@solution@#1\endcsname%
		\fi%
	\fi%
}

% Gets the segment indices of solution #1.
%
% #1: the solution index (i.e. the same argument as in \pgfpointintersectionsolution)
% #2: [output] a macro name which will contain the segment index of the first path which contains the solution
% #3: [output] a macro name which will contain the segment index of the second path which contains the solution
%
% Example: \pgfintersectiongetsolutionsegmentindices{0}{\first}{\second}
%
% -> \first may be 0 if point #0 is in the 0'th segment
% -> \second may be 42 if point #0 is in the 42'th segment 
%
% The "segment index" is actually close to the "time" of the solution.
% If a solution is at "time" 42.2, it will have segment index 42.
\def\pgfintersectiongetsolutionsegmentindices#1#2#3{%
	\ifnum#1<1\relax%
		\let#2=\pgfutil@empty
		\let#3=\pgfutil@empty
	\else%
		\ifnum#1>\pgfintersectionsolutions\relax%
			\let#2=\pgfutil@empty
			\let#3=\pgfutil@empty
		\else%
			\def\pgf@temp##1##2##3##4{%
				\edef#2{##1}%
				\edef#3{##2}%
			}%
			\expandafter\let\expandafter\pgf@tempb\csname pgf@intersect@solution@props@#1\endcsname
			\expandafter\pgf@temp\pgf@tempb
		\fi%
	\fi%
}%

% Gets the time indices of solution #1.
%
% #1: the solution index (i.e. the same argument as in \pgfpointintersectionsolution)
% #2: [output] a macro name which will contain the time of the first path which contains the solution
%   It will never be empty.
% #3: [output] a macro name which will contain the time of the second path which contains the solution
%   It will never be empty.
%
% Example: \pgfintersectiongetsolutiontimes{0}{\first}{\second}
%
% -> \first may be 0.5 if point #0 is in just in the middle of the path
% -> \second may be 42.8 if point #0 is in the 42'th segment (compare
%  \pgfintersectiongetsolutionsegmentindices) and is at 80% of the
%  42'th segment
%
% Note that the precise time inside of a segment may be unavailable
% (currently, it is only computed for curveto paths and not
% necessarily for lineto). If the precise time is unavailable, this
% call will return the value of
% \pgfintersectiongetsolutionsegmentindices (which is a
% "coarse-grained" time).
\def\pgfintersectiongetsolutiontimes#1#2#3{%
	\ifnum#1<1\relax%
		\let#2=\pgfutil@empty
		\let#3=\pgfutil@empty
	\else%
		\ifnum#1>\pgfintersectionsolutions\relax%
			\let#2=\pgfutil@empty
			\let#3=\pgfutil@empty
		\else%
			\def\pgf@temp##1##2##3##4{%
				\edef#2{##3}%
				\edef#3{##4}%
				% 
				% check for fallback to segment indices:
				\ifx#2\pgfutil@empty \edef#2{##1}\fi
				\ifx#3\pgfutil@empty \edef#3{##2}\fi
			}%
			\expandafter\let\expandafter\pgf@tempb\csname pgf@intersect@solution@props@#1\endcsname
			\expandafter\pgf@temp\pgf@tempb
		\fi%
	\fi%
}%

\def\pgfpoint@intersect@solution@orgin{%
	\begingroup%
		\pgftransforminvert%
		\pgfpointorigin%
		\pgf@pos@transform{\pgf@x}{\pgf@y}%
		\global\pgf@x=\pgf@x%
		\global\pgf@y=\pgf@y%
	\endgroup%
}

% #1 code which assigns the first path using \pgfsetpath.
% #2 code which assigns the second path using \pgfsetpath.
%
% On output, the points, their properties, and the number of points are set.
% Use \pgfintersectionsolutions which expands to the number of intersections
\long\def\pgfintersectionofpaths#1#2{%
	\begingroup%
		\pgfinterruptpath%
		#1% 
		\pgfgetpath\pgf@intersect@path@a%
		\global\let\pgf@intersect@path@temp=\pgf@intersect@path@a%
		\endpgfinterruptpath%
	\endgroup%
	\let\pgf@intersect@path@a=\pgf@intersect@path@temp%
	%
	\begingroup%
		\pgfinterruptpath%
		#2% 
		\pgfgetpath\pgf@intersect@path@b%
		\global\let\pgf@intersect@path@temp=\pgf@intersect@path@b%
		\endpgfinterruptpath%
	\endgroup%
	\let\pgf@intersect@path@b=\pgf@intersect@path@temp%
	%
	\pgf@intersect@solutions=0\relax%
	\pgf@intersect@path@reset@a
	%
	\ifpgf@intersect@sort@by@second@path%
		\let\pgf@intersect@temp=\pgf@intersect@path@a%
		\let\pgf@intersect@path@a=\pgf@intersect@path@b%
		\let\pgf@intersect@path@b=\pgf@intersect@temp%
	\fi%
	%
	\pgfprocessround\pgf@intersect@path@a\pgf@intersect@path@a%
	\pgfprocessround\pgf@intersect@path@b\pgf@intersect@path@b%
	%
	\let\pgf@intersect@token@after=\pgf@intersect@path@process@a%
	\expandafter\pgf@intersectionofpaths\pgf@intersect@path@a\pgf@stop%
	\edef\pgfintersectionsolutions{\the\pgf@intersect@solutions}%
	\pgfmathloop%
		\ifnum\pgfmathcounter>\pgfintersectionsolutions\relax%
		\else%
			\pgfutil@namelet{pgfpoint@intersect@solution@\pgfmathcounter}%
				{pgfpoint@g@intersect@solution@\pgfmathcounter}%
			\edef\pgf@marshal{\noexpand\pgf@intersection@set@properties{\csname pgfpoint@g@intersect@solution@\pgfmathcounter @props\endcsname}}%
			\pgf@marshal
			\ifpgf@intersect@sort%
				\pgfutil@namelet{pgf@intersect@solution@\pgfmathcounter @time@a}%
					{pgf@g@intersect@solution@\pgfmathcounter @time@a}%
			\fi%
	\repeatpgfmathloop%
	\ifpgf@intersect@sort%
		\pgfintersectionsolutionsortbytime%
	\fi%
}

\def\pgf@intersection@set@properties#1{%
	\pgfutil@namedef{pgf@intersect@solution@props@\pgfmathcounter}{#1}%
}%

% #1 a global name prefix to store properties.
\def\pgf@intersection@store@properties#1{%
	% we store the time offsets as well and make them available programmatically:
	% note that \pgf@intersect@time@a and \pgf@intersect@time@b may be empty.
	%
	% However, \pgf@intersect@time@offset and
	% \pgf@intersect@time@offset@b are *always* valid. In fact,they
	% resemble a part of the time: it holds 
	%   0 <= \pgf@intersect@time@a < 1
	% and \pgf@intersect@time@offset > 0. 
	%
	% If we have an intersection in segment 42 of path A,
	% \pgf@intersect@time@offset will be 42. The time inside of that
	% segment is given as number in the interval [0,1]. If it is 0.3,
	% the total time will be 42.3 and that number will be stored as
	% \pgf@intersect@time@a.
	%
	\expandafter\xdef\csname #1@props\endcsname{{\pgf@intersect@time@offset}{\pgf@intersect@time@offset@b}{\pgf@intersect@time@a}{\pgf@intersect@time@b}}%
}

\def\pgf@intersectionofpaths#1{%
	\ifx#1\pgf@stop%
		\let\pgf@intersect@next=\relax%
	\else%
		\ifx#1\pgfsyssoftpath@movetotoken%
			\let\pgf@intersect@next=\pgf@intersect@token@moveto%
		\else%
			\ifx#1\pgfsyssoftpath@linetotoken%
				\let\pgf@intersect@next=\pgf@intersect@token@lineto%
			\else%
				\ifx#1\pgfsyssoftpath@closepathtoken%
					\let\pgf@intersect@next=\pgf@intersect@token@lineto%
				\else%
					\ifx#1\pgfsyssoftpath@curvetosupportatoken%
						\let\pgf@intersect@next=\pgf@intersect@token@curveto%
					\else%
						\ifx#1\pgfsyssoftpath@rectcornertoken%
							\let\pgf@intersect@next=\pgf@intersect@token@rect%
						\fi%
					\fi%
				\fi%
			\fi%
		\fi%
	\fi%
	\pgf@intersect@next}

\def\pgf@intersect@token@moveto#1#2{%
	\def\pgfpoint@intersect@start{\pgfqpoint{#1}{#2}}%
	\pgf@intersectionofpaths%
}

\def\pgf@intersect@token@lineto#1#2{%
	\def\pgfpoint@intersect@end{\pgfqpoint{#1}{#2}}%
	\def\pgf@intersect@type{line}%
	\pgf@intersect@token@after%
}
\def\pgf@intersect@token@curveto#1#2\pgfsyssoftpath@curvetosupportbtoken#3#4\pgfsyssoftpath@curvetotoken#5#6{%
	\def\pgfpoint@intersect@firstsupport{\pgfqpoint{#1}{#2}}%
	\def\pgfpoint@intersect@secondsupport{\pgfqpoint{#3}{#4}}%
	\def\pgfpoint@intersect@end{\pgfqpoint{#5}{#6}}%
	\def\pgf@intersect@type{curve}%
	\pgf@intersect@token@after%
}

\def\pgf@intersect@token@rect#1#2\pgfsyssoftpath@rectsizetoken#3#4{%
	\pgf@xa=#1\relax%
	\advance\pgf@xa by#3\relax%
	\pgf@ya=#2\relax%
	\advance\pgf@ya by#4\relax%
	\edef\pgf@marshal{%
		\noexpand\pgfsyssoftpath@movetotoken{#1}{#2}%
		\noexpand\pgfsyssoftpath@linetotoken{#1}{\the\pgf@ya}%
		\noexpand\pgfsyssoftpath@linetotoken{\the\pgf@xa}{\the\pgf@ya}%
		\noexpand\pgfsyssoftpath@linetotoken{\the\pgf@xa}{#2}%
		\noexpand\pgfsyssoftpath@closepathtoken{#1}{#2}%
	}%
	\expandafter\pgf@intersectionofpaths\pgf@marshal%
}

\def\pgf@intersect@path@process@a{%
	\pgf@intersect@path@getpoints@a%
	\let\pgf@intersect@token@after=\pgf@intersect@path@process@b%
	\pgf@intersect@path@reset@b
	\expandafter\pgf@intersectionofpaths\pgf@intersect@path@b\pgf@stop%
	\let\pgfpoint@intersect@start=\pgfpoint@intersect@end@a%
	\let\pgf@intersect@token@after=\pgf@intersect@path@process@a%
	\c@pgf@counta=\pgf@intersect@time@offset\relax%
	\advance\c@pgf@counta by1\relax%
	\edef\pgf@intersect@time@offset{\the\c@pgf@counta}%
	\pgf@intersectionofpaths%
}

\def\pgf@intersect@path@reset@a{%
	\def\pgf@intersect@time@offset{0}%
	\def\pgf@intersect@time@a{}%
}%

\def\pgf@intersect@path@reset@b{%
	\def\pgf@intersect@time@offset@b{0}%
	\def\pgf@intersect@time@b{}%
}%

\def\pgf@intersect@path@getpoints@a{%
	\let\pgfpoint@intersect@start@a=\pgfpoint@intersect@start%
	\let\pgfpoint@intersect@end@a=\pgfpoint@intersect@end%
	\let\pgfpoint@intersect@firstsupport@a=\pgfpoint@intersect@firstsupport%
	\let\pgfpoint@intersect@secondsupport@a=\pgfpoint@intersect@secondsupport%
	\let\pgf@intersect@type@a=\pgf@intersect@type%
}

\def\pgf@intersect@path@process@b{%
	\pgf@intersect@path@getpoints@b%
	\csname pgf@intersect@\pgf@intersect@type@a @and@\pgf@intersect@type@b\endcsname%
	\let\pgfpoint@intersect@start=\pgfpoint@intersect@end@b%
	\c@pgf@counta=\pgf@intersect@time@offset@b\relax%
	\advance\c@pgf@counta by1\relax%
	\edef\pgf@intersect@time@offset@b{\the\c@pgf@counta}%
	\pgf@intersectionofpaths}

\def\pgf@intersect@path@getpoints@b{%
	\let\pgfpoint@intersect@start@b=\pgfpoint@intersect@start%
	\let\pgfpoint@intersect@end@b=\pgfpoint@intersect@end%
	\let\pgfpoint@intersect@firstsupport@b=\pgfpoint@intersect@firstsupport%
	\let\pgfpoint@intersect@secondsupport@b=\pgfpoint@intersect@secondsupport%
	\let\pgf@intersect@type@b=\pgf@intersect@type%
}

\def\pgf@intersect@line@and@line{%
	\pgf@intersectionoflines{\pgfpoint@intersect@start@a}{\pgfpoint@intersect@end@a}%
		{\pgfpoint@intersect@start@b}{\pgfpoint@intersect@end@b}%
}%

\def\pgf@intersect@line@and@curve{%
	\pgf@intersectionoflineandcurve%
		{\pgf@process{\pgfpoint@intersect@start@a}}{\pgf@process{\pgfpoint@intersect@end@a}}%
		{\pgf@process{\pgfpoint@intersect@start@b}}{\pgf@process{\pgfpoint@intersect@firstsupport@b}}%
		{\pgf@process{\pgfpoint@intersect@secondsupport@b}}{\pgf@process{\pgfpoint@intersect@end@b}}%
}

\def\pgf@intersect@curve@and@line{%
	\pgf@intersectionofcurveandline%
		{\pgf@process{\pgfpoint@intersect@start@a}}{\pgf@process{\pgfpoint@intersect@firstsupport@a}}%
		{\pgf@process{\pgfpoint@intersect@secondsupport@a}}{\pgf@process{\pgfpoint@intersect@end@a}}%
		{\pgf@process{\pgfpoint@intersect@start@b}}{\pgf@process{\pgfpoint@intersect@end@b}}%
}

\def\pgf@intersect@curve@and@curve{%
	\pgf@intersectionofcurves%
		{\pgf@process{\pgfpoint@intersect@start@a}}{\pgf@process{\pgfpoint@intersect@firstsupport@a}}%
		{\pgf@process{\pgfpoint@intersect@secondsupport@a}}{\pgf@process{\pgfpoint@intersect@end@a}}%
		{\pgf@process{\pgfpoint@intersect@start@b}}{\pgf@process{\pgfpoint@intersect@firstsupport@b}}%
		{\pgf@process{\pgfpoint@intersect@secondsupport@b}}{\pgf@process{\pgfpoint@intersect@end@b}}%
}


\def\pgfintersectionoflines#1#2#3#4{%
	\pgf@intersect@solutions=0\relax%
	\pgf@intersectionoflines{#1}{#2}{#3}{#4}%
}

\def\pgf@intersectionoflines#1#2#3#4{%
	\pgf@iflinesintersect{#1}{#2}{#3}{#4}%
	{%
		\pgfextract@process\pgf@intersect@solution@candidate{%
			\pgfpointintersectionoflines{\pgfpoint@intersect@start@a}{\pgfpoint@intersect@end@a}%
				{\pgfpoint@intersect@start@b}{\pgfpoint@intersect@end@b}%
		}%
		\pgf@ifsolution@duplicate{\pgf@intersect@solution@candidate}{%
			% ah - we a duplicate. Apparently, we have a hit on an
			% endpoint.
		}{%
			\global\advance\pgf@intersect@solutions by1\relax%
			\expandafter\global\expandafter\let\csname pgfpoint@g@intersect@solution@\the\pgf@intersect@solutions\endcsname=\pgf@intersect@solution@candidate
			\ifpgf@intersect@sort%
				\pgf@xc=\pgf@x%
				\pgf@yc=\pgf@y%
				\pgf@process{\pgfpointdiff{\pgfpoint@intersect@start@a}{\pgfpoint@intersect@end@a}}%
				\edef\pgf@marshal{%
					\noexpand\pgfmathveclen@{\pgfmath@tonumber{\pgf@xa}}{\pgfmath@tonumber{\pgf@ya}}%
				}%
				\pgf@marshal%
				\let\pgf@intersect@length@a=\pgfmathresult%
				\pgf@process{\pgfpointdiff{\pgfpoint@intersect@start@a}{\pgfqpoint{\pgf@xc}{\pgf@yc}}}%
				\edef\pgf@marshal{%
					\noexpand\pgfmathveclen@{\pgfmath@tonumber{\pgf@x}}{\pgfmath@tonumber{\pgf@y}}%
				}%
				\pgf@marshal%
				\pgfmathdivide@{\pgfmathresult}{\pgf@intersect@length@a}%
				\pgf@x=\pgfmathresult pt\relax%
				\advance\pgf@x by\pgf@intersect@time@offset pt\relax%		
				\edef\pgf@intersect@time@a{\pgfmath@tonumber{\pgf@x}}%
				\expandafter\global\expandafter\let\csname pgf@g@intersect@solution@\the\pgf@intersect@solutions @time@a\endcsname=
					\pgf@intersect@time@a
			\else
				\let\pgf@intersect@time@a=\pgfutil@empty
			\fi%
			\let\pgf@intersect@time@b=\pgfutil@empty
			\pgf@intersection@store@properties{pgfpoint@g@intersect@solution@\the\pgf@intersect@solutions}%
		}%
		%
	}{}%		
}

% Test if two lines L1 and L2 intersect.
%
% #1 - first point P1 on L1.
% #2 - second point P2 on L1.
% #3 - first point P3 on L2.
% #2 - second point P4 on L2.
% #5 - code executed if intersection occurs.
% #6 - code executed if intersection does no occur.
%
% Let L1 be represented by P1+(P2-P1)s where 0<=s<=1
% Let L2 be represented by P3+(P4-P3)t where 0<=t<=1
%
% Then L1 and L2 intersect at
%
% s = |x2-x1  x3-x1| / |x4-x3  x2-x1|
%     |y2-y1  y3-y1|   |y4-y3  y2-y1|
%
% t = |x4-x3  x3-x1| / |x4-x3  x2-x1|
%     |y4-y3  y3-y1|   |y4-y3  y2-y1|
% 
% with 0<=s,t<=1
%		
% s and t do not need to be calculated:
%
% Let s = A / C and t = B / C
% 
% Then 0<=s<=1 if !(C=0) && ((A=0) || ((A>0) && !(C<A)) || ((A<0) && !(C>A)))
%      0<=t<=1 if !(C=0) && ((B=0) || ((B>0) && !(C<B)) || ((B<0) && !(C>B)))
% 
\newif\ifpgf@s
\newif\ifpgf@t
\def\pgfiflinesintersect#1#2#3#4{%
	\begingroup%
		\pgf@iflinesintersect{\pgf@process{#1}}{\pgf@process{#2}}{\pgf@process{#3}}{\pgf@process{#4}}%
			{\aftergroup\pgfutil@firstoftwo}{\aftergroup\pgfutil@secondoftwo}%
	\endgroup%
}

\def\pgf@iflinesintersect#1#2#3#4{%
	#4\relax%
	\pgf@xc=\pgf@x%
	\pgf@yc=\pgf@y%
	#3\relax%
	\advance\pgf@xc by-\pgf@x%
	\advance\pgf@yc by-\pgf@y%
	\pgf@xb=\pgf@x%
	\pgf@yb=\pgf@y%
	#2\relax%
	\pgf@xa=\pgf@x%
	\pgf@ya=\pgf@y%
	#1\relax%
	\advance\pgf@xa by-\pgf@x%
	\advance\pgf@ya by-\pgf@y%
	\advance\pgf@xb by-\pgf@x%
	\advance\pgf@yb by-\pgf@y%
	%
	% xc = x4-x3; yc=y4-y3;
	% xb = x3-x1; yb=y3-y1;
	% xa = x2-x1; ya=y2-y1;
	%
	%
	% Normalise a little. 16384 may not be a robust choice.
	%
	\c@pgf@counta=\pgf@xa\divide\c@pgf@counta by16384\relax% 
	\c@pgf@countb=\pgf@xb\divide\c@pgf@countb by16384\relax%
	\c@pgf@countc=\pgf@ya\divide\c@pgf@countc by16384\relax%
	\c@pgf@countd=\pgf@yb\divide\c@pgf@countd by16384\relax%
	\multiply\c@pgf@counta by\c@pgf@countd%
	\multiply\c@pgf@countc by\c@pgf@countb%
	\advance\c@pgf@counta by-\c@pgf@countc%
	\pgfutil@tempcnta=\c@pgf@counta%
	%
	\c@pgf@counta=\pgf@xc\divide\c@pgf@counta by16384\relax%
	\c@pgf@countc=\pgf@yc\divide\c@pgf@countc by16384\relax%
	\multiply\c@pgf@countd by\c@pgf@counta%
	\multiply\c@pgf@countb by\c@pgf@countc%
	\advance\c@pgf@countd by-\c@pgf@countb%
	\pgfutil@tempcntb=\c@pgf@countd%
	%
	\c@pgf@countb=\pgf@xa\divide\c@pgf@countb by16384\relax%
	\c@pgf@countd=\pgf@ya\divide\c@pgf@countd by16384\relax%
	\multiply\c@pgf@counta by\c@pgf@countd%
	\multiply\c@pgf@countc by\c@pgf@countb%
	\advance\c@pgf@counta by-\c@pgf@countc%
	%
	\pgf@sfalse%
	\pgf@tfalse%
	\ifnum\c@pgf@counta=0\relax%
	\else%
		\ifnum\pgfutil@tempcnta=0\relax%
			\pgf@strue%
		\else%
			\ifnum\pgfutil@tempcnta>0\relax%
				\ifnum\c@pgf@counta<\pgfutil@tempcnta%
				\else%
					\pgf@strue%
				\fi%
			\else%
				\ifnum\c@pgf@counta>\pgfutil@tempcnta%
				\else%
					\pgf@strue%
				\fi%
			\fi%
		\fi%
		\ifnum\pgfutil@tempcntb=0\relax%
			\pgf@ttrue%
		\else%
			\ifnum\pgfutil@tempcntb>0\relax%
				\ifnum\c@pgf@counta<\pgfutil@tempcntb%
				\else%
					\pgf@ttrue%
				\fi%
			\else%
				\ifnum\c@pgf@counta>\pgfutil@tempcntb%
				\else%
					\pgf@ttrue%
				\fi%
			\fi%
		\fi%
	\fi%
	\let\pgf@intersect@next=\pgfutil@secondoftwo%
	\ifpgf@s%
		\ifpgf@t%
			\let\pgf@intersect@next=\pgfutil@firstoftwo%
		\fi%
	\fi%
	\pgf@intersect@next%
}




\def\pgfintersectionoflineandcurve#1#2#3#4#5#6{%
	\pgf@intersect@solutions=0\relax%
	\pgf@intersectionoflineandcurve{#1}{#2}{#3}{#4}{#5}{#6}%
}

\def\pgf@intersectionoflineandcurve#1#2#3#4#5#6{%
	\pgf@intersectionofcurves%
		{\pgf@process{#1}}%
		{%
			\pgf@process{%
				\pgfpointadd{#1\relax\pgf@x=0.666666\pgf@x\pgf@y=0.666666\pgf@y}%
					{#2\relax\pgf@x=0.333333\pgf@x\pgf@y=0.333333\pgf@y}%
			}%
		}%
		{%
			\pgf@process{%
				\pgfpointadd{#1\relax\pgf@x=0.333333\pgf@x\pgf@y=0.333333\pgf@y}%
					{#2\relax\pgf@x=0.666666\pgf@x\pgf@y=0.666666\pgf@y}%
			}%
		}%
		{\pgf@process{#2}}%
		{\pgf@process{#3}}%
		{\pgf@process{#4}}%
		{\pgf@process{#5}}%
		{\pgf@process{#6}}%
}%

\def\pgf@intersectionofcurveandline#1#2#3#4#5#6{%
	\pgf@intersectionofcurves%
		{\pgf@process{#1}}%
		{\pgf@process{#2}}%
		{\pgf@process{#3}}%
		{\pgf@process{#4}}%
		{\pgf@process{#5}}%
		{%
			\pgf@process{%
				\pgfpointadd{#5\relax\pgf@x=0.666666\pgf@x\pgf@y=0.666666\pgf@y}%
					{#6\relax\pgf@x=0.333333\pgf@x\pgf@y=0.333333\pgf@y}%
			}%
		}%
		{%
			\pgf@process{%
				\pgfpointadd{#5\relax\pgf@x=0.333333\pgf@x\pgf@y=0.333333\pgf@y}%
					{#6\relax\pgf@x=0.666666\pgf@x\pgf@y=0.666666\pgf@y}%
			}%
		}%
		{\pgf@process{#6}}%
}%




\def\pgfintersectiontolerance{0.1pt}
\def\pgfintersectiontolerancefactor{0.1}



% Find the intersections of two bezier curves.
% 
% #1 - #4 = curve 1.
% #5 - #8 = curve 2.
% #9      = the solution number.
%
% There is no guarantee of ordering of solutions. If there are 
% no solutions, the origin is returned.
%
\def\pgfpointintersectionofcurves#1#2#3#4#5#6#7#8#9{%
	\pgf@intersect@solutions=0\relax%
	\pgf@intersectionofcurves%
		{\pgf@process{#1}}{\pgf@process{#2}}{\pgf@process{#3}}{\pgf@process{#4}}%
		{\pgf@process{#5}}{\pgf@process{#6}}{\pgf@process{#7}}{\pgf@process{#8}}%
	\pgfpointintersectionsolution{#9}%
}

% Return any intersection points of two curves C1 and C2.
% No order can be guaranteed for the solutions.
%
% #1, #2, #3, #4 - the points on C1 
% #5, #6, #7, #8 - the points on C2
%
% Returns:
%
% \pgf@intersect@solutions          - the number of solutions.
%	\pgfpointintersectionsolution{<S>} - the point for soultion S.
%
% (Sort of) use:
%
%	intersection(C1,C2)
%		S = {};
%	  intersection'(C1,C2);
%		return S;
%		
%	intersection'(C1,C2)
%		B1 = boundingbox(C1);
%		B2 = boundingbox(C2);
%		if intersect(B1,B2)
%			if (B1.width < q) and (B1.height < q) and
%        (B2.width < q) and (B2.height < q)
%				S = S + {average_of_all_points(B1,B2)}; \\ is there a better choice?
%			else
%				Q = subdivideLeft(C1);
%				R = subdivideRight(C1);
%				intersection'(C2,Q);
%				intersection'(C2,R);
%
% where q is a small value (tolerance).
%
\def\pgfintersectionofcurves#1#2#3#4#5#6#7#8{%
	\pgf@intersect@solutions=0\relax%
	\pgf@intersectionofcurves%
		{\pgf@process{#1}}{\pgf@process{#2}}{\pgf@process{#3}}{\pgf@process{#4}}%
		{\pgf@process{#5}}{\pgf@process{#6}}{\pgf@process{#7}}{\pgf@process{#8}}%
}%
\def\pgf@intersectionofcurves#1#2#3#4#5#6#7#8{%
	\begingroup%
		\dimendef\pgf@time@a=2\relax%
		\dimendef\pgf@time@aa=4\relax%
		\dimendef\pgf@time@b=6\relax%
		\dimendef\pgf@time@bb=8\relax%
		\pgf@time@a=0pt\relax%
		\pgf@time@aa=1pt\relax%
		\pgf@time@b=0pt\relax%
		\pgf@time@bb=1pt\relax%
		\let\pgf@intersect@subdivide@curve=\pgf@intersect@subdivide@curve@b%
		\let\pgf@curve@subdivde@after=\pgf@@intersectionofcurves%
		\pgf@@intersectionofcurves{#1}{#2}{#3}{#4}{#5}{#6}{#7}{#8}%
	\endgroup%
}

\def\pgf@@intersectionofcurves#1#2#3#4#5#6#7#8{%
	\pgf@intersect@boundingbox@reset%
	\pgf@intersect@boundingbox@update{#1}%
	\pgf@intersect@boundingbox@update{#2}%
	\pgf@intersect@boundingbox@update{#3}%
	\pgf@intersect@boundingbox@update{#4}%
	% (\pgf@xa, \pgf@ya) is lower-left
	% (\pgf@xb, \pgf@yb) is upper-right
	\edef\pgf@intersect@boundingbox@b{%
		\noexpand\pgf@x=\the\pgf@xa% 
		\noexpand\pgf@y=\the\pgf@ya%
		\noexpand\pgf@xa=\the\pgf@xb%
		\noexpand\pgf@ya=\the\pgf@yb%
	}%
	\pgf@intersect@boundingbox@reset%
	\pgf@intersect@boundingbox@update{#5}%
	\pgf@intersect@boundingbox@update{#6}%
	\pgf@intersect@boundingbox@update{#7}%
	\pgf@intersect@boundingbox@update{#8}%
	\edef\pgf@intersect@boundingbox@a{%
		\noexpand\pgf@xb=\the\pgf@xa%
		\noexpand\pgf@yb=\the\pgf@ya%
		\noexpand\pgf@xc=\the\pgf@xb%
		\noexpand\pgf@yc=\the\pgf@yb%
	}%	
	\pgf@intersect@boundingbox@a%
	\pgf@intersect@boundingbox@b%
	% check if the two bounding boxes overlap:
	\ifdim\pgf@xa<\pgf@xb%
	\else%
		\ifdim\pgf@x>\pgf@xc%
		\else%
			\ifdim\pgf@ya<\pgf@yb%
			\else%
				\ifdim\pgf@y>\pgf@yc%
				\else%
					% compute DIFFERENCE vectors:
					\advance\pgf@xc by-\pgf@xb%
					\advance\pgf@yc by-\pgf@yb%
					\advance\pgf@xa by-\pgf@x%
					\advance\pgf@ya by-\pgf@y%
					\let\pgf@intersect@subdivde=\relax%
					% check if both difference vectors are point wise
					% less than tolerance (i.e. |v|_infty < eps ).
					% That means that both bounding boxes are "small enough"
					\ifdim\pgf@xc<\pgfintersectiontolerance\relax%
						\ifdim\pgf@xa<\pgfintersectiontolerance\relax%
							\ifdim\pgf@yc<\pgfintersectiontolerance\relax%
								\ifdim\pgf@ya<\pgfintersectiontolerance\relax%
									\pgfextract@process\pgf@intersect@solution@candidate{%
										% set (x,y) = mean(the 4 points of the two bounding boxes):
										\pgf@intersect@boundingbox@a%
										\pgf@intersect@boundingbox@b%
										\pgf@x=0.25\pgf@x%
										\advance\pgf@x by0.25\pgf@xa%
										\advance\pgf@x by0.25\pgf@xb%
										\advance\pgf@x by0.25\pgf@xc%
										\pgf@y=0.25\pgf@y%
										\advance\pgf@y by0.25\pgf@ya%
										\advance\pgf@y by0.25\pgf@yb%
										\advance\pgf@y by0.25\pgf@yc%
									}%
									% We must avoid duplicate solutions.
									\let\pgf@intersect@subdivde=\pgf@stop%
									\pgf@ifsolution@duplicate\pgf@intersect@solution@candidate{}%
									{%
										\global\advance\pgf@intersect@solutions by1\relax%
										\begingroup
										\advance\pgf@time@a by\pgf@time@aa%
										\divide\pgf@time@a by2\relax%
										\advance\pgf@time@a by\pgf@intersect@time@offset pt\relax%
										\edef\pgf@intersect@time@a{\pgfmath@tonumber{\pgf@time@a}}%
										%
										\advance\pgf@time@b by\pgf@time@bb%
										\divide\pgf@time@b by2\relax%
										\advance\pgf@time@b by\pgf@intersect@time@offset@b pt\relax%
										\edef\pgf@intersect@time@b{\pgfmath@tonumber{\pgf@time@b}}%
										%
										\pgf@intersection@store@properties{pgfpoint@g@intersect@solution@\the\pgf@intersect@solutions}%
										\expandafter\global\expandafter\let%
											\csname pgfpoint@g@intersect@solution@\the\pgf@intersect@solutions\endcsname=%
												\pgf@intersect@solution@candidate%
										\ifpgf@intersect@sort%
											\expandafter\xdef%
											\csname pgf@g@intersect@solution@\the\pgf@intersect@solutions @time@a\endcsname%	
												{\pgf@intersect@time@a}%						
										\fi%
										\endgroup
									}%
								\fi%
							\fi%
						\fi%
					\fi%
					\ifx\pgf@intersect@subdivde\pgf@stop%
					\else%
						\pgf@intersect@subdivide@curve{#1}{#2}{#3}{#4}{#5}{#6}{#7}{#8}%
					\fi%
				\fi%
			\fi%
		\fi%
	\fi%
}

\def\pgf@intersect@subdivide@curve@b#1#2#3#4#5#6#7#8{%
	\begingroup%
		\advance\pgf@time@bb by\pgf@time@b\relax%
		\divide\pgf@time@bb by2\relax%
		\let\pgf@intersect@subdivide@curve=\pgf@intersect@subdivide@curve@a%
		\pgf@curve@subdivide@left{#5}{#6}{#7}{#8}{#1}{#2}{#3}{#4}%
	\endgroup%
	\begingroup%
		\advance\pgf@time@b by\pgf@time@bb\relax%
		\divide\pgf@time@b by2\relax%
		\let\pgf@intersect@subdivide@curve=\pgf@intersect@subdivide@curve@a%
		\pgf@curve@subdivide@right{#5}{#6}{#7}{#8}{#1}{#2}{#3}{#4}%
	\endgroup%
}

\def\pgf@intersect@subdivide@curve@a#1#2#3#4#5#6#7#8{%
	\begingroup%
		\advance\pgf@time@aa by\pgf@time@a\relax%
		\divide\pgf@time@aa by2\relax%
		\let\pgf@intersect@subdivide@curve=\pgf@intersect@subdivide@curve@b%
		\pgf@curve@subdivide@left{#5}{#6}{#7}{#8}{#1}{#2}{#3}{#4}%
	\endgroup%
	\begingroup%
		\advance\pgf@time@a by\pgf@time@aa\relax%
		\divide\pgf@time@a by2\relax%
		\let\pgf@intersect@subdivide@curve=\pgf@intersect@subdivide@curve@b%
		\pgf@curve@subdivide@right{#5}{#6}{#7}{#8}{#1}{#2}{#3}{#4}%
	\endgroup%
}

\def\pgf@intersect@boundingbox@reset{%
	\pgf@xa=16000pt\relax%
	\pgf@ya=16000pt\relax%
	\pgf@xb=-16000pt\relax%
	\pgf@yb=-16000pt\relax%
}

\def\pgf@intersect@boundingbox@update#1{%
	#1\relax%
	\ifdim\pgf@x<\pgf@xa\pgf@xa=\pgf@x\fi%
	\ifdim\pgf@y<\pgf@ya\pgf@ya=\pgf@y\fi%
	\ifdim\pgf@x>\pgf@xb\pgf@xb=\pgf@x\fi%
	\ifdim\pgf@y>\pgf@yb\pgf@yb=\pgf@y\fi%
}

% The following subroutines are part of a conversion from pgfbasic
% math to FPU. This transition is necessary due to the restricted
% accuracy of pgfbasic. In order to limit the error rate of the
% transition pgfbasic -> FPU, I chose to
% keep the old "pattern" of sorts \advance\pgf@xa by0.5\pgf@y etc and
% simply adapt to some FPU call.
%
% The following routines constitute the "adapter":

\def\pgf@float@adapter@setxy{%
	\pgfmathfloatparsenumber{\pgf@sys@tonumber\pgf@x}\let\pgf@fpu@x=\pgfmathresult
	\pgfmathfloatparsenumber{\pgf@sys@tonumber\pgf@y}\let\pgf@fpu@y=\pgfmathresult
}%
\def\pgf@float@adapter@mult#1=#2*#3{%
	\pgfmathfloatmultiplyfixed@{#3}{#2}%
	\let#1=\pgfmathresult
}%
\def\pgf@float@adapter@advance#1by#2*#3{%
	\pgfmathfloatmultiplyfixed@{#3}{#2}%
	\let\pgfutil@temp=\pgfmathresult
	\pgfmathfloatadd@{#1}{\pgfutil@temp}%
	\let#1=\pgfmathresult
}%

\def\pgf@float@adapter@tostring#1{%
	\pgfmathfloattofixed{#1}\edef#1{\pgfmathresult pt }%
}%

\def\pgf@curve@subdivide@left#1#2#3#4{%
	%
	% The left curve (from t=0 to t=.5) 
	%
	\begingroup
	#1\relax%
	\pgfutil@tempdima=\pgf@x%
	\pgfutil@tempdimb=\pgf@y%
	\pgf@float@adapter@setxy
	\pgf@float@adapter@mult\pgf@fpu@xa=.5*\pgf@fpu@x  \pgf@float@adapter@mult\pgf@fpu@ya=.5*\pgf@fpu@y%
	\pgf@float@adapter@mult\pgf@fpu@xb=.25*\pgf@fpu@x \pgf@float@adapter@mult\pgf@fpu@yb=.25*\pgf@fpu@y%
	\pgf@float@adapter@mult\pgf@fpu@xc=.125*\pgf@fpu@x\pgf@float@adapter@mult\pgf@fpu@yc=.125*\pgf@fpu@y%
	#2\relax%
	\pgf@float@adapter@setxy
	\pgf@float@adapter@advance\pgf@fpu@xa by.5*\pgf@fpu@x\pgf@float@adapter@advance\pgf@fpu@ya by.5*\pgf@fpu@y%
	\pgf@float@adapter@advance\pgf@fpu@xb by.5*\pgf@fpu@x\pgf@float@adapter@advance\pgf@fpu@yb by.5*\pgf@fpu@y%
	\pgf@float@adapter@advance\pgf@fpu@xc by.375*\pgf@fpu@x\pgf@float@adapter@advance\pgf@fpu@yc by.375*\pgf@fpu@y%
	#3\relax%
	\pgf@float@adapter@setxy
	\pgf@float@adapter@advance\pgf@fpu@xb by.25*\pgf@fpu@x\pgf@float@adapter@advance\pgf@fpu@yb by.25*\pgf@fpu@y%
	\pgf@float@adapter@advance\pgf@fpu@xc by.375*\pgf@fpu@x\pgf@float@adapter@advance\pgf@fpu@yc by.375*\pgf@fpu@y%
	#4\relax%
	\pgf@float@adapter@setxy
	\pgf@float@adapter@advance\pgf@fpu@xc by.125*\pgf@fpu@x\pgf@float@adapter@advance\pgf@fpu@yc by.125*\pgf@fpu@y%
	%
	\pgf@float@adapter@tostring\pgf@fpu@xa
	\pgf@float@adapter@tostring\pgf@fpu@ya
	\pgf@float@adapter@tostring\pgf@fpu@xb
	\pgf@float@adapter@tostring\pgf@fpu@yb
	\pgf@float@adapter@tostring\pgf@fpu@xc
	\pgf@float@adapter@tostring\pgf@fpu@yc
	\edef\pgf@marshal{%
		\noexpand\pgf@curve@subdivde@after%
			{\noexpand\pgf@x=\the\pgfutil@tempdima\noexpand\pgf@y=\the\pgfutil@tempdimb}%
			{\noexpand\pgf@x=\pgf@fpu@xa\noexpand\pgf@y=\pgf@fpu@ya}%
			{\noexpand\pgf@x=\pgf@fpu@xb\noexpand\pgf@y=\pgf@fpu@yb}
			{\noexpand\pgf@x=\pgf@fpu@xc\noexpand\pgf@y=\pgf@fpu@yc}%
	}%
	\expandafter
	\endgroup
	\pgf@marshal%
}

\def\pgf@curve@subdivide@right#1#2#3#4{%
	%
	% The right curve (from t=0.5 to t=1) 
	%
	\begingroup
	#1\relax%
	\pgf@float@adapter@setxy
	\pgf@float@adapter@mult\pgf@float@tmpa=.125*\pgf@fpu@x\pgf@float@adapter@mult\pgf@float@tmpb=.125*\pgf@fpu@y%
	#2\relax%
	\pgf@float@adapter@setxy
	\pgf@float@adapter@advance\pgf@float@tmpa by.375*\pgf@fpu@x\pgf@float@adapter@advance\pgf@float@tmpb by.375*\pgf@fpu@y%
	\pgf@float@adapter@mult\pgf@fpu@xa=.25*\pgf@fpu@x\pgf@float@adapter@mult\pgf@fpu@ya=.25*\pgf@fpu@y%
	#3\relax%
	\pgf@float@adapter@setxy
	\pgf@float@adapter@advance\pgf@float@tmpa by.375*\pgf@fpu@x\pgf@float@adapter@advance\pgf@float@tmpb by.375*\pgf@fpu@y%
	\pgf@float@adapter@advance\pgf@fpu@xa by.5*\pgf@fpu@x\pgf@float@adapter@advance\pgf@fpu@ya by.5*\pgf@fpu@y%
	\pgf@float@adapter@mult\pgf@fpu@xb=.5*\pgf@fpu@x\pgf@float@adapter@mult\pgf@fpu@yb=.5*\pgf@fpu@y%
	#4\relax%
	\pgf@float@adapter@setxy
	\pgf@float@adapter@advance\pgf@float@tmpa by.125*\pgf@fpu@x\pgf@float@adapter@advance\pgf@float@tmpb by.125*\pgf@fpu@y%
	\pgf@float@adapter@advance\pgf@fpu@xa by.25*\pgf@fpu@x\pgf@float@adapter@advance\pgf@fpu@ya by.25*\pgf@fpu@y%
	\pgf@float@adapter@advance\pgf@fpu@xb by.5*\pgf@fpu@x\pgf@float@adapter@advance\pgf@fpu@yb by.5*\pgf@fpu@y%
	\let\pgf@fpu@xc=\pgf@fpu@x\let\pgf@fpu@yc=\pgf@fpu@y%
	%
	\pgf@float@adapter@tostring\pgf@float@tmpa
	\pgf@float@adapter@tostring\pgf@float@tmpb
	\pgf@float@adapter@tostring\pgf@fpu@xa
	\pgf@float@adapter@tostring\pgf@fpu@ya
	\pgf@float@adapter@tostring\pgf@fpu@xb
	\pgf@float@adapter@tostring\pgf@fpu@yb
	\pgf@float@adapter@tostring\pgf@fpu@xc
	\pgf@float@adapter@tostring\pgf@fpu@yc
	\edef\pgf@marshal{%
		\noexpand\pgf@curve@subdivde@after%
			{\noexpand\pgf@x=\pgf@float@tmpa\noexpand\pgf@y=\pgf@float@tmpb}%
			{\noexpand\pgf@x=\pgf@fpu@xa\noexpand\pgf@y=\pgf@fpu@ya}
			{\noexpand\pgf@x=\pgf@fpu@xb\noexpand\pgf@y=\pgf@fpu@yb}
			{\noexpand\pgf@x=\pgf@fpu@xc\noexpand\pgf@y=\pgf@fpu@yc}%
	}%
	\expandafter
	\endgroup
	\pgf@marshal%
}


% A solution S1 is considered a duplicate of S2, if
% 
% |x1 - x2|f < q and |y1 - y2|f < q
%
% where q is a small value (tolerance).
%
% #1 - the solution.
%
\def\pgf@ifsolution@duplicate#1{%
	#1%
	\pgf@xa=\pgf@x%
	\pgf@ya=\pgf@y%
	\let\pgf@intersect@next=\pgfutil@secondoftwo%
	\pgfmathloop%
		\ifnum\pgfmathcounter>\pgf@intersect@solutions\relax%
		\else%			
			\pgf@ifsolution@duplicate@{\pgfmathcounter}%
	\repeatpgfmathloop%
	\pgf@intersect@next%
}

\def\pgf@ifsolution@duplicate@#1{%
	\pgf@process{\csname pgfpoint@g@intersect@solution@#1\endcsname}%
	\advance\pgf@x by-\pgf@xa%
	\advance\pgf@y by-\pgf@ya%
	\ifdim\pgf@x<0pt\relax\pgf@x=-\pgf@x\fi%
	\ifdim\pgf@y<0pt\relax\pgf@y=-\pgf@y\fi%
	%
	\pgf@x=\pgfintersectiontolerancefactor\pgf@x%
	\pgf@y=\pgfintersectiontolerancefactor\pgf@y%
	\ifdim\pgf@x<\pgfintersectiontolerance\relax%
		\ifdim\pgf@y<\pgfintersectiontolerance\relax%
			\let\pgf@intersect@next=\pgfutil@firstoftwo%
		\fi%
	\fi%
}%

\newif\ifpgf@intersect@solutions@sortfinish

% Sort solutions according to their time index.
%
\def\pgfintersectionsolutionsortbytime{%
	\pgf@intersect@solutions@sortfinishtrue%
	\pgfmathloop%
		\ifnum\pgfmathcounter=\pgfintersectionsolutions\relax%
		\else%
			\pgfutil@tempcnta=\pgfmathcounter%
			\advance\pgfutil@tempcnta by1\relax%
			\ifdim\csname pgf@intersect@solution@\pgfmathcounter @time@a\endcsname pt>%
				\csname pgf@intersect@solution@\the\pgfutil@tempcnta @time@a\endcsname pt\relax%
				\pgf@intersect@solutions@sortfinishfalse%
				%
				\pgfintersectionsolutionsortbytime@swap{pgfpoint@intersect@solution@\pgfmathcounter}%
					{pgfpoint@intersect@solution@\the\pgfutil@tempcnta}%
				%
				\pgfintersectionsolutionsortbytime@swap{pgf@intersect@solution@\pgfmathcounter @time@a}%
					{pgf@intersect@solution@\the\pgfutil@tempcnta @time@a}%
				%
				\pgfintersectionsolutionsortbytime@swap{pgf@intersect@solution@props@\pgfmathcounter}%
					{pgf@intersect@solution@props@\the\pgfutil@tempcnta}%
			\fi%
	\repeatpgfmathloop%
	\ifpgf@intersect@solutions@sortfinish%
	\else%
		\expandafter\pgfintersectionsolutionsortbytime%
	\fi%
}

\def\pgfintersectionsolutionsortbytime@swap#1#2{%
	\pgfutil@namelet{pgf@intersect@temp}{#1}%
	\pgfutil@namelet{#1}{#2}%
	\pgfutil@namelet{#2}{pgf@intersect@temp}%
}%

\endinput

pgfplotsoldpgfsupp_trig_format.code.tex
% This file contains patches to support 'trig format'
%
%%% This file is a copy of some part of PGF/Tikz.
%%% It has been copied here to provide :
%%%  - compatibility with older PGF versions
%%%  - availability of PGF contributions by Christian Feuersaenger
%%%    which are necessary or helpful for pgfplots.
%%%
%%% This file contains just the functionality for trig format (written by Christian Feuersaenger).
%%% 
% Support for the contents of this file will NOT be done by the PGF/TikZ team. 
% Please contact the author and/or maintainer of pgfplots (Christian Feuersaenger) if you need assistance in conjunction
% with the deployment of this patch or partial content of PGF. Note that the author and/or maintainer of pgfplots has no obligation to fix anything:
% This file comes without any warranty as the rest of pgfplots; there is no obligation for help.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\pgfkeys{
	/pgf/trig format/.is choice,
	/pgf/trig format/deg/.code={\def\pgfmath@trig@format@choice{0}},
	/pgf/trig format/rad/.code={\def\pgfmath@trig@format@choice{1}},
	/pgf/trig format/deg,
}

% Executes #1 if 'trig format=deg' and #2 otherwise.
\def\pgfmathiftrigonometricusesdeg#1#2{%
	\if0\pgfmath@trig@format@choice
		#1%
	\else
		#2%
	\fi
}%

\def\pgfmath@scale@rad@to@deg#1{%
    #1=57.29577#1\relax% 57.29577 = 360/(2*pi)
}%
\def\pgfmath@scale@deg@to@rad#1{%
    #1=3.14159#1% 
    \divide#1180\relax%
}%

\def\pgfmathsin@#1{%
  % Let #1 = a.b
  % Then sin(#1) \approx (1-b)*sin(a) + b*sin(a+1)
  %
  \begingroup%
    \expandafter\pgfmath@x#1pt\relax%
	\if1\pgfmath@trig@format@choice
		% trig format=rad
		\pgfmath@scale@rad@to@deg\pgfmath@x
	\fi
    \advance\pgfmath@x-90pt\relax%
    \afterassignment\pgfmath@gobbletilpgfmath@
    \expandafter\c@pgfmath@counta\the\pgfmath@x\relax\pgfmath@
    \divide\c@pgfmath@counta360\relax%
    \multiply\c@pgfmath@counta-360\relax%
    \advance\pgfmath@x\c@pgfmath@counta pt\relax%
    \ifdim\pgfmath@x<0pt\relax\pgfmath@x-\pgfmath@x\fi%
    \ifdim\pgfmath@x<180pt\relax%
    \else
      \pgfmath@x-\pgfmath@x%
      \advance\pgfmath@x360pt\relax%
    \fi%
    % Now 0 <= x < 179. So split x into integer and decimal...
    %
    \afterassignment\pgfmath@xa%
    \expandafter\c@pgfmath@counta\the\pgfmath@x\relax%
    %
    % ...if #1 is an integer, don't do anything fancy.
    \ifdim\pgfmath@xa=0pt%
      \expandafter\pgfmath@x\csname pgfmath@cos@\the\c@pgfmath@counta\endcsname pt\relax%
    \else%
      \pgfmath@x-\pgfmath@xa%
      \advance\pgfmath@x1pt\relax%
      \expandafter\pgfmath@x\csname pgfmath@cos@\the\c@pgfmath@counta\endcsname\pgfmath@x%
      \advance\c@pgfmath@counta1\relax%
      \ifnum\c@pgfmath@counta=181\relax\c@pgfmath@counta179\relax\fi%
      \expandafter\advance\expandafter\pgfmath@x\csname pgfmath@cos@\the\c@pgfmath@counta\endcsname\pgfmath@xa%
    \fi%
    \pgfmath@returnone\pgfmath@x%
  \endgroup
}

% \pgfmathcos
% 
% Calculate the cosine of #1 (in degrees).
%
\def\pgfmathcos@#1{%
  % Let x = a.b
  % Then cos(x) \approx (1-b)*cos(a) + b*cos(a+1)
  %
  \begingroup%
    \expandafter\pgfmath@x#1pt\relax%
	\if1\pgfmath@trig@format@choice
		% trig format=rad
		\pgfmath@scale@rad@to@deg\pgfmath@x
	\fi
    \afterassignment\pgfmath@gobbletilpgfmath@%
    \expandafter\c@pgfmath@counta\the\pgfmath@x\relax\pgfmath@% 
    \divide\c@pgfmath@counta360\relax%
    \multiply\c@pgfmath@counta-360\relax%
    \advance\pgfmath@x\c@pgfmath@counta pt\relax%
    \ifdim\pgfmath@x<0pt\relax\pgfmath@x-\pgfmath@x\fi%
    \ifdim\pgfmath@x<180pt\relax%
    \else%
      \pgfmath@x-\pgfmath@x%
      \advance\pgfmath@x360pt\relax%
    \fi%
    % Now 0 <= x < 179. So split x into integer and decimal...
    %
    \afterassignment\pgfmath@xa%
    \expandafter\c@pgfmath@counta\the\pgfmath@x\relax%
    %
    % ...if #1 is an integer, don't do anything fancy.
    \ifdim\pgfmath@xa=0pt%
      \expandafter\pgfmath@x\csname pgfmath@cos@\the\c@pgfmath@counta\endcsname pt%
    \else%
      \pgfmath@x-\pgfmath@xa%
      \advance\pgfmath@x1pt\relax%
      \expandafter\pgfmath@x\csname pgfmath@cos@\the\c@pgfmath@counta\endcsname\pgfmath@x%
      \advance\c@pgfmath@counta1\relax%
      \ifnum\c@pgfmath@counta=181\relax\c@pgfmath@counta179\relax\fi%
      \expandafter\advance\expandafter\pgfmath@x\csname pgfmath@cos@\the\c@pgfmath@counta\endcsname\pgfmath@xa%
    \fi%
    \pgfmath@returnone\pgfmath@x%
  \endgroup%
}

\def\pgfmathasin@#1{%
  \begingroup%
    \pgfmath@x=#1pt %
    \pgfmath@xa\pgfmath@x%
    \edef\pgf@temp{\pgf@sys@tonumber\pgfmath@x}%
    % compute lossless '*1000' operation:
    \expandafter\pgfmath@multiply@thousand\pgf@temp 000\relax
    \pgfmath@x=\pgfmathresult pt %
    \ifdim\pgfmath@x<0pt\relax%
      \pgfmath@x-\pgfmath@x%
    \fi%
    \pgfmath@table@lookup{\pgfmath@x}{pgfmath@acos@}{1001}%
    \pgfmath@x=-\pgfmath@x
    \advance\pgfmath@x90pt\relax%
    \ifdim\pgfmath@xa<0pt\relax%
      \pgfmath@x-\pgfmath@x%
    \fi%
	\if1\pgfmath@trig@format@choice
		% trig format=rad
		\pgfmath@scale@deg@to@rad\pgfmath@x
	\fi
    \pgfmath@returnone\pgfmath@x%
  \endgroup%
}
\def\pgfmathacos@#1{%
  \begingroup%
    \pgfmath@x#1pt\relax%
    \pgfmath@xa\pgfmath@x%
    \edef\pgf@temp{\pgf@sys@tonumber\pgfmath@x}%
    % compute lossless '*1000' operation:
    \expandafter\pgfmath@multiply@thousand\pgf@temp 000\relax
    \pgfmath@x=\pgfmathresult pt %
    \ifdim\pgfmath@x<0pt\relax%
      \pgfmath@x-\pgfmath@x%
    \fi%
    \pgfmath@table@lookup{\pgfmath@x}{pgfmath@acos@}{1001}%
    \ifdim\pgfmath@xa<0pt\relax%
      \pgfmath@x-\pgfmath@x%
      \advance\pgfmath@x by180pt\relax%
    \fi%
	\if1\pgfmath@trig@format@choice
		% trig format=rad
		\pgfmath@scale@deg@to@rad\pgfmath@x
	\fi
    \pgfmath@returnone\pgfmath@x%
  \endgroup%
}

\def\pgfmathatan@#1{%
  \begingroup%
    \expandafter\pgfmath@x#1pt\relax%
    \pgfmath@xa\pgfmath@x%
    \ifdim\pgfmath@x<0pt\relax%
      \pgfmath@x-\pgfmath@x%
    \fi%
    \pgfmath@xb\pgfmath@x%
    \ifdim\pgfmath@x>1pt\relax%
      \edef\pgfmath@temp{\pgfmath@tonumber{\pgfmath@x}}%
      \pgfmathreciprocal@{\pgfmath@temp}%
      \pgfmath@x\pgfmathresult pt\relax%
    \fi%
    % compute lossless '*1000' operation:
    \edef\pgf@temp{\pgf@sys@tonumber\pgfmath@x}%
    \expandafter\pgfmath@multiply@thousand\pgf@temp 000\relax
    \pgfmath@x=\pgfmathresult pt %
    \pgfmath@table@lookup{\pgfmath@x}{pgfmath@atan@}{1001}%xxx
    \ifdim\pgfmath@xb>1pt\relax%
      \pgfmath@x=-\pgfmath@x%
      \advance\pgfmath@x90pt%
    \fi%
    \ifdim\pgfmath@xa<0pt\relax%
      \pgfmath@x-\pgfmath@x%
    \fi%
	\if1\pgfmath@trig@format@choice
		% trig format=rad
		\pgfmath@scale@deg@to@rad\pgfmath@x
	\fi
    \pgfmath@returnone\pgfmath@x%
  \endgroup%
}

\expandafter\def\csname pgfmathatan2@\endcsname#1#2{%
  % Note: first parameter is y (!), second is x (!)
  \begingroup%
    \pgfmath@y=#1pt\relax%
    \ifdim\pgfmath@y<0pt\relax%
      \pgfmath@y=-\pgfmath@y%
    \fi%
    \ifdim\pgfmath@y<0.001pt\relax%
      \ifdim#2pt<0pt\relax%
        \pgfmath@x=-180pt\relax%
      \else%
        \ifdim#2pt>0pt\relax%
          \pgfmath@x=0pt\relax%
        \else%
          \ifdim#1pt<0pt%
            \pgfmath@x=-90pt\relax%
          \else%
            \pgfmath@x=90pt\relax%
          \fi%
        \fi%
      \fi%
    \else%
      \pgfmathabs@{#1}\let\pgfmath@tempa\pgfmathresult%
      \pgfmathabs@{#2}\let\pgfmath@tempb\pgfmathresult%
      \ifdim\pgfmath@tempa pt>\pgfmath@tempb pt%
        \pgfmathdivide@{#2}{\pgfmath@tempa}%
        \expandafter\pgfmathatan@\expandafter{\pgfmathresult}%
        \pgfmath@x=90pt%
        \advance\pgfmath@x by-\pgfmathresult pt\relax%
      \else%
        \pgfmathdivide@{\pgfmath@tempa}{#2}%
        \expandafter\pgfmathatan@\expandafter{\pgfmathresult}%
        \pgfmath@x=\pgfmathresult pt\relax%
        \ifdim#2pt<0pt%
          \advance\pgfmath@x by180pt\relax%
        \fi%
      \fi%
      \ifdim#1pt<0pt\relax%
        \pgfmath@x=-\pgfmath@x%
      \fi%
    \fi%
	\if1\pgfmath@trig@format@choice
		% trig format=rad
		\pgfmath@scale@deg@to@rad\pgfmath@x
	\fi
    \pgfmath@returnone\pgfmath@x%
  \endgroup%    
}

% FPU:


\let\pgfmath@basic@sin@=\pgfmathsin@
\let\pgfmath@basic@cos@=\pgfmathcos@
\let\pgfmath@basic@tan@=\pgfmathtan@
\let\pgfmath@basic@atan@=\pgfmathatan@
\let\pgfmath@basic@asin@=\pgfmathasin@
\let\pgfmath@basic@acos@=\pgfmathacos@
\let\pgfmath@basic@cot@=\pgfmathcot@
\let\pgfmath@basic@sec@=\pgfmathsec@
\let\pgfmath@basic@cosec@=\pgfmathcosec@

% Computes #1(#2) where #1 is a trigonometric function, i.e.
% #1(#2) = #1( #2 + r*360 )
%
% #1 is a one-argument macro which assigns \pgfmathresult.
\def\pgfmathfloatTRIG@#1#2{%
	\if0\pgfmath@trig@format@choice
		% trig format=deg
		\expandafter\ifx\csname pgfmathfloatTRIG@NUM\endcsname\relax%
			% Lazy evaluation:
			\pgfmathfloatcreate{1}{3.6}{2}%
			\global\let\pgfmathfloatTRIG@NUM=\pgfmathresult
			\pgfmathfloatcreate{1}{2.77777777777778}{-3}%
			\global\let\pgfmathfloatTRIG@NUM@INV=\pgfmathresult
		\fi
		\pgfmathfloatmodknowsinverse@{#2}{\pgfmathfloatTRIG@NUM}{\pgfmathfloatTRIG@NUM@INV}%
	\else
		% trig format=rad
		\expandafter\ifx\csname pgfmathfloatTRIG@rad@NUM\endcsname\relax%
			% Lazy evaluation:
			\pgfmathfloatcreate{1}{6.28318530717959}{0}%
			\global\let\pgfmathfloatTRIG@rad@NUM=\pgfmathresult
			\pgfmathfloatcreate{1}{1.59154943091895}{-1}%
			\global\let\pgfmathfloatTRIG@rad@NUM@INV=\pgfmathresult
		\fi
		\pgfmathfloatmodknowsinverse@{#2}{\pgfmathfloatTRIG@rad@NUM}{\pgfmathfloatTRIG@rad@NUM@INV}%
	\fi
	\pgfmathfloattofixed@{\pgfmathresult}%
	\expandafter#1\expandafter{\pgfmathresult}%
	\pgfmathfloatparsenumber{\pgfmathresult}%
}%

\def\pgfmathfloatsin@#1{\pgfmathfloatTRIG@\pgfmath@basic@sin@{#1}}
\let\pgfmathfloatsin=\pgfmathfloatsin@
\def\pgfmathfloatcos@#1{\pgfmathfloatTRIG@\pgfmath@basic@cos@{#1}}
\let\pgfmathfloatcos=\pgfmathfloatcos@
\def\pgfmathfloatsec@#1{\pgfmathfloatTRIG@\pgfmath@basic@cos@{#1}\pgfmathfloatreciprocal@{\pgfmathresult}}
\let\pgfmathfloatsec=\pgfmathfloatsec@
\def\pgfmathfloatcosec@#1{\pgfmathfloatTRIG@\pgfmath@basic@sin@{#1}\pgfmathfloatreciprocal@{\pgfmathresult}}
\let\pgfmathfloatcosec=\pgfmathfloatcosec@

\def\pgfmathfloatatan@#1{%
	\begingroup
	\expandafter\ifx\csname pgfmathfloatatan@TMP\endcsname\relax% 
		\pgfmathfloatcreate{1}{1.6}{4}%
		\global\let\pgfmathfloatatan@TMP=\pgfmathresult
		\pgfmathfloatcreate{2}{1.6}{4}%
		\global\let\pgfmathfloatatan@TMPB=\pgfmathresult
	\fi
	\pgfmathfloatgreaterthan@{#1}{\pgfmathfloatatan@TMP}%
	\ifpgfmathfloatcomparison
		\pgfmathiftrigonometricusesdeg{%
			\pgfmathfloatcreate{1}{9.0}{1}%
		}{%
			\pgfmathfloatcreate{1}{1.570796326794}{0}%
		}%
	\else
		\pgfmathfloatlessthan{#1}{\pgfmathfloatatan@TMPB}%
		\ifpgfmathfloatcomparison
			\pgfmathiftrigonometricusesdeg{%
				\pgfmathfloatcreate{2}{9.0}{1}%
			}{%
				\pgfmathfloatcreate{2}{1.570796326794}{0}%
			}%
		\else
			\pgfmathfloattofixed@{#1}%
			\expandafter\pgfmath@basic@atan@\expandafter{\pgfmathresult}%
			\pgfmathfloatparsenumber{\pgfmathresult}%
		\fi
	\fi
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%
\endinput

pgfplots.paths.code.tex
%--------------------------------------------
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2007-2012 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------
%

\newif\ifpgfplots@path@replace@ellipse

\def\pgfplots@install@path@replacements{%
	\ifpgfplots@path@replace@ellipse
		\let\tikz@do@circle=\pgfplots@path@@tikz@do@circle
		\expandafter\def\expandafter\pgfinterruptpicture\expandafter{\pgfinterruptpicture
			\let\tikz@do@circle=\pgfplots@path@@tikz@do@circle@orig
		}%
	\fi
}%

\let\pgfplots@path@@tikz@do@circle@orig=\tikz@do@circle

% This is a replacement for \tikz@do@circle which replaces the "xy"
% coordinate system by one which is compatible with pgfplots.
\def\pgfplots@path@@tikz@do@circle#1#2{%
  \begingroup
  \ifpgfplots@usefpu
	\pgfkeys{/pgf/fpu,/pgf/fpu/output format=fixed}%
  \fi
  \pgfmathparse{#1}%
  \let\tikz@ellipse@x=\pgfmathresult%
  \ifpgfmathunitsdeclared%
    \pgfmathparse{#2}%
    \let\tikz@ellipse@y=\pgfmathresult%
    \ifpgfmathunitsdeclared%
      \pgfpathellipse{\pgfpointorigin}{%
        \pgfqpoint{\tikz@ellipse@x pt}{0pt}}{\pgfpoint{0pt}{\tikz@ellipse@y pt}}%
    \else%
      \PackageError{tikz}{You cannot mix dimensions and dimensionless values in an ellipse}{}%
    \fi%
  \else%
    \pgfmathparse{#2}%
    \let\tikz@ellipse@y=\pgfmathresult%
    \ifpgfmathunitsdeclared%
      \PackageError{tikz}{You cannot mix dimensions and dimensionless values in an ellipse}{}%
    \else%
      \pgfpathellipse{\pgfpointorigin}
	  	{\pgfplotspointaxisdirectionxy{\tikz@ellipse@x}{0}}
		{\pgfplotspointaxisdirectionxy{0}{\tikz@ellipse@y}}%
    \fi%
  \fi%
  \endgroup
}

pgfplotsplothandlers.code.tex
%--------------------------------------------
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2010 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------

% 1. OVERVIEW
%
% Plot handlers are extended versions of the plot handlers of PGF with
% backwards compatibility.
%
% To remind ourselfes: PGF plot handlers work like this
% \pgfplotstreamstart
% \pgfplotstreampoint{...}
% \pgfplotstreampoint{...}
% \pgfplotstreampoint{...}
% \pgfplotstreampoint{...}
% \pgfplotstreamend
%
% and that's it.
%
% PGFPlots plot handlers also contain these three macros. The tasks
% are (of course) the same. In addition, they support a set of further
% macros for every plot handler:
%
% \pgfplotsplothandlersurveystart
% \pgfplotsplothandlersurveypoint
% \pgfplotsplothandlersurveyend
%
% and serialization methods
% \pgfplotsplothandlerserializepointto
% \pgfplotsplothandlerdeserializepointfrom
% \pgfplotsplothandlerserializestateto
% \pgfplotsplothandlerdeserializepointfrom
%
% in addition, there are utility macros
% \pgfplotsplothandlersurveydifflen#1#2
% \pgfplotsplothandlersurveypointattime#1#2#3
%
% The idea is as follows:
% During \addplot, PGFPLots performs a survey phase. Survey means:
% nothing will be drawn, only stats will be collected. In this phase,
% the \pgfplotsplothandlersurvey* methods will be invoked; followed by
% a serialization.
%
% Then, when every plot has been surveyed, PGFPlots calls
% \pgfplotsplothandlerdeserializestatefrom{<serialized state>}
% \pgfplotstreamstart
% foreach <serizalized point> {
% 	\pgfplotsplothandlerdeserializepointfrom{<serialized point>}
% 	apply data transformations 
% 	handle plot marks
% 	\pgfplotstreampoint{\pgfplotsqpointxy{<x>}{<y}}
% }
% \pgfplotstreamend
%
% See below for details about the survey phase and the visualization
% phase and the API of an axis.
%
% Thus, the PGF basic level streams can (but don't need to) make use
% of the macros assigned by the
% \pgfplotsplothandlerdeserializepointfrom and
% \pgfplotsplothandlerdeserializestatefrom.
%
% Furthermore, a plot handler *can* redefine any of the survey and/or
% serialization methods to add further functionality. But it doesn't
% need to, it's ok if it only relies on x,y as standard pgf plot
% handlers do.
%
% If it overwrites something, it should do so in its main method, the
% one in which it also defines the \pgf@plotstreamstart etc. methods
% (see pgfmoduleplot.code.tex for example). BUT: do NOT overwrite
% these methods globally!
%
% 2. A Description of the two phases:
%
% THE SURVEY PHASE:
%   The survey phase works as follows.
%   PRECONDITION:
%   	- we are `inside' of an axis.
%   	- \addplot starts the survey phase.
%
%   The following happens:
%   	- the plot handler is determined and activated such that its
%   	methods are usable ("class is instantiated")
%   	- \pgfplots@PREPARE@COORD@STREAM is the internal, low level
%   	entry point where pgfplots controls the survey phase.
%   	- the coordinate input routine is initialised. It issues a
%   	series of commands (all within the *same* TeX scope):
%   		\pgfplots@coord@stream@start
%   		\pgfplots@coord@stream@coord
%   		\pgfplots@coord@stream@coord
%   		\pgfplots@coord@stream@coord
%   		\pgfplots@coord@stream@coord
%   		\pgfplots@coord@stream@coord
%   		\pgfplots@coord@stream@coord
%   		...
%   		\pgfplots@coord@stream@end
%   	- \pgfplotsplothandlersurveystart is called in
%   	\pgfplots@coord@stream@start.
%   	- \pgfplots@coord@stream@coord calls
%   	\pgfplotsplothandlersurveypoint
%   	- \pgfplots@coord@stream@end calls
%   	\pgfplotsplothandlersurveyend
%   	\pgfplotsplothandlerserializestateto<\macro>
%   	Furthermore, it remembers the <\macro> such that it can be
%   	deserialized later.
%   Then, the survey phase ends. The main point of interest is the
%   \pgfplotsplothandlersurveypoint routine, especially its
%   communication with the axis. It is described below.
%
%   POSTCONDITION:
%   	- the state of the axis is now aware of the new plot (limits,
%   	stacking, ...).
%   	- The plot's survey state is stored using its serialized
%   	representation.
%
% THE VISUALIZATION PHASE:
% FIXME
%
% 2.1 The API of an axis
%
% As described above, the coordinate input routine fires a lot of
% \pgfplots@coord@stream@coord commands, which, in turn, invoke
% \pgfplotsplothandlersurveypoint. Somehow this should update the
% axis' state to reflect each point. But the 'data point' is a rather
% abstract thing. Usually, it will contain at least (x,y) (or maybe z)
% coordinates. But it may be more complex.
%
% So, the coordinate input routine provides whatever the user has
% chosen. Let's assume, we are using \addplot table. Then, we can 
% access every cell in the current row (using \thisrow{<colname>} for
% example). The plot handler knows how to extract its information from
% this state. In general, the following steps are taken:
% - the plot handler assembles coordinates.
% - every assembled coordinate should be reported to the axis by
%   defining \pgfplots@current@point@[xyz] to its coordinates and
%   calling
%   \pgfplotsaxisparsecoordinate{}
%   This will apply coordinate filters, parse the single coordinates
%   and apply high level transformations and any logarithms.
%   It is some sort of advanced coordinate parser which works only for 
%   (x,y) or for (x,y,z).
%   It yields (x,y,z). But the axis might need to change its
%   components! Thus, you also need to call
%   \pgfplotsaxispreparecoordinate{}.
%   This will, for example, apply the "stack plots" feature or the
%   'data cs' feature.
%
%   If necessary, the plot handler calls
%   \pgfplotsaxisparsecoordinate{} and
%   \pgfplotsaxispreparecoordinate{} multiple times, once for each
%   encountered coordinate.
%
%	It might occasionally be too much to call
%	\pgfplotsaxispreparecoordinate.
%
%   It might happen that a coordinate filter discards a coordinate.
%   This is returned in the \ifpgfplotsaxisparsecoordinateok boolean
%   and has to be checked by the plot handler.
%
% - the plot handler knows which of the coordinates contribute to the
%   final plot. It invokes
%   \ifpgfplotsaxisparsecoordinateok
%   	\pgfplotsaxisupdatelimitsforcoordinate{<x>}{<y>}{<z>}
%   \fi
%   for each of these coordinates. This has to be done for final
%   coordinates only, i.e. after \pgfplotsaxispreparecoordinate.
%
% - eventually, the plot handler is satisfied and considers a data
%   point as "readily surveyed". It is allowed if this does *not*
%   happen inside of \pgfplotsplothandlersurveypoint, but it must
%   happen before \pgfplotsplothandlersurveyend is finished.
%   
%   The plot handler invokes \pgfplotsaxisdatapointsurveyed.
%   This tells the axis that it can perform its own surveying tasks
%   (see below) and furthermore, that it can serialize the data point.
%   Consequently, it will invoke
%   \pgfplotsplothandlerserializepointto{<\macro>} 
%   and it will remember that \macro internally. This serialization is
%   employed to place plot marks and to apply z buffering techniques
%   (that's why it is done by the axis and not by the plot handler on
%   its own).
%
%   The axis does its own surveying task, initiated by
%   \pgfplotsaxisdatapointsurveyed (which is, turn, invoked by the
%   plot handler). This command handles the |point meta| feature, that
%   is: it queries the |point meta| input source and updates the meta
%   limits. Furthermore, the error bar feature is processed at this
%   point (using the final data point's (x,y,z) coordinates as basis).
%   The |xtick=data| feature is also prepared at this stage.
%
% - Later, the coordinate input routine invokes
%   \pgfplots@coord@stream@end indicating the end-of-input. This will
%   finalize the survey phase.
%
% A simple example looks like this:
% \pgfplotsplothandlersurveystart: does nothing in the simple example.
% \pgfplotsplothandlersurveypoint:
%   parses the input format somehow to get (x,y,z) in raw, symbolic format
%   calls \pgfplotsaxisparsecoordinate
% 	calls \pgfplotsaxispreparecoordinate
% 	calls \ifpgfplotsaxisparsecoordinateok	\pgfplotsaxisupdatelimitsforcoordinate{<x>}{<y>}{<z} \fi
% 	calls \pgfplotsaxisdatapointsurveyed
% \pgfplotsplothandlersurveyend: does nothing in the simple example.
%
% In fact, this is more or less the initial configuration used for
% lineto or similar plot handlers.
%
% 2.2 Further Survey Phase API functions
% 	\pgfplotssurveyphaseinputclass
% 	expands to the actual name of the input method (like
% 	'coordinates', 'expression' or 'table')
%
% 	\pgfplotsplothandlernotifyscanlinecomplete
% Called whenever an end-of-scanline marker has been processed, i.e.
% whenever the 'empty line' key has been triggered. The default is to
% do nothing.
%
%   \pgfplotsaxissurveysetpointmeta
% processes the 'point meta' key, i.e. it assigns
% \pgfplots@current@point@meta. This macro can only be called once for
% each coordinate (it will be deactivated afterwards). PGFPlots calls
% it in \pgfplotsaxisdatapointsurveyed .
%
%   \pgfplotsplothandlersurveyaddoptions{<options>}
% which allows to change the current plot style from within API
% functions. It sets <options> and remembers them for the
% visualization phase.
%
%   \pgfplotsaxisupdatelimitsforpointmeta{<meta>},
% provided there is a point meta input handler (which is numeric).
% Otherwise, the command is equal to \relax.
%
%
% 3. Details about the VISUALIZATION phase
%
% The visualization phase consists of
% <installation of the plot handler>
% \pgfplotstreamstart
% foreach serialized coordinate {
% 	pgfplots calls \pgfplotsplothandlerdeserializestatefrom{<serialized repr>}
% 	if coordinate is empty ("unbounded")
% 		pgfplots call \pgfplotsplothandlervisualizejump
% 	else
% 		pgfplots calls \pgfplotsaxisvisphasetransformcoordinate
% 		pgfplots calls \pgfplotsaxisvisphasepreparedatapoint
% 		pgfplots calls either \pgfplotsqpointxyz or \pgfplotsqpointxy
% 	fi
% 	\pgfplotstreampoint
% }
% \pgfplotstreamend
%
% User defined plot handlers might need to invoke
% \pgfplotsaxisvisphasetransformcoordinate on their own.
%
% During the visualization phase, the following macros can be used:
%
% - \pgfplotsaxisvisphasetransformpointmeta to set up point meta.
% Use this only if there *is* point meta, see
% \pgfplotsaxisifhaspointmeta{<true code>}{<false code>}.
%
% - \pgfplotsaxisvisphasegetpoint
%   does not take arguments. It takes the current point as input and
%   sets \pgf@x, \pgf@y to the final result.
%
% 4. API Functions of pgfplots to work with the visualization phases
%
% \pgfplotsifissurveyphase{<true code>}{<false code>}
% \pgfplotsifisvisualizationphase{<true code>}{<false code>}
%
% \pgfplotsaxisfilteredcoordsaway
%   This macro expands to '1' if all points have been surveyed
%   successfully. It expands to '0' if at least one point has been
%   filtered away (for whatever reasons). This does not apply to
%   jumps.
% \pgfplotsaxisplothasjumps
% 	This macro expands to '1' if the current plot has jumps and '0'
% 	if not.During the visualization phase, a jump is usually indicated
% 	by an empty coordinate.
%

\def\pgfplotssurveyphaseinputclass{direct}

\def\pgfplotsplothandlers@tikz@with@snap@to@nearest{%
	\pgfplothandlerdiscard,%
	\pgfplothandlermark,%
	\pgfplothandlermarklisted,%
	\pgfplothandlerxbar,%
	\pgfplothandlerybar,%
	\pgfplothandlerxbarinterval,%
	\pgfplothandlerybarinterval%
}%

\def\pgfplotsplothandlers@tikz@std{%
	\pgfplothandlerdiscard,%
	\pgfplothandlermark,%
	\pgfplothandlermarklisted,%
	\pgfplothandlerxbar,%
	\pgfplothandlerybar,%
	\pgfplothandlerxbarinterval,%
	\pgfplothandlerybarinterval,%
	\pgfplothandlerlineto,%
	\pgfplothandlercurveto,%
	\pgfplothandlerconstantlineto,%
	\pgfplothandlerconstantlinetomarkright,%
	\pgfplothandlerconstantlinetomarkmid,%
	\pgfplothandlerpolarcomb,%
	\pgfplothandlerjumpmarkmid,%
	\pgfplothandlerjumpmarkleft,%
	\pgfplothandlerjumpmarkright%
}%

% Defines \pgfplotsretval to be the csname for the BACKUP of plot
% handler #1.
%
% For example:
% \pgfplotsplothandlers@get@tikz@backup@name{\pgfplothandlerlineto}
% will return \pgfplotsretval={\\pgfplothandlerlineto@tikz} 
% (up to \escapechar)
\def\pgfplotsplothandlers@get@tikz@backup@name#1{%
	\begingroup
		%\escapechar=-1 % drop the leading backslash
		\expandafter\gdef\expandafter\pgfplotsretval\expandafter{\csname \string#1@tikz\endcsname}%
		\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%

% Takes the CURRENT \tikz@plot@handler and checks if it is an UNPATCHED tikz plot
% handler. If so, it replaced it with the correct patched version.
%
% The motivation is that uf \tikz@plot@handler has been set outside of
% an axis, it will not reflect the most recent changes (which are only
% applied within an axis).
\def\pgfplotsplothandlers@init@map@to@patched@versions{%
	% iterate through all tikz plot handlers...
	\expandafter\pgfplotsutilforeachcommasep\expandafter{\pgfplotsplothandlers@tikz@std}%
	\as\pgfplots@loc@TMPa{%
		% ... get the name of the backup (see \pgfplotsplothandlers@init)
		\expandafter\pgfplotsplothandlers@get@tikz@backup@name\pgfplots@loc@TMPa
		\expandafter\ifx\pgfplotsretval\tikz@plot@handler
			% AH! \tikz@plot@handler is the same as some backup name! 
			% Replace it:
			\expandafter\let\expandafter\tikz@plot@handler\pgfplots@loc@TMPa
		\fi
	}%
}%

\def\pgfplotsplothandlers@init{%
	\def\pgfplotsplothandlers@init@##1{%
		\pgfplotsutil@add@to@macro##1{%
			\let\pgfplotsplothandlersurveydifflen=\pgfplotsplothandlersurveydifflen@snaptonearest
			\let\pgfplotsplothandlersurveypointattime=\pgfplotsplothandlersurveypointattime@snaptonearest
		}%
	}%
	\def\pgfplotsplothandlers@init@@##1{%
		% create backup:
		%
		% if ##1 = \pgfplothandlerlineto, this defines
		% \pgfplothandlerlineto@tikz as backup.
		\pgfplotsplothandlers@get@tikz@backup@name{##1}%
		\expandafter\let\pgfplotsretval=##1%
		%
		%
		% assign more suitable names:
		\pgfplotsutil@add@to@macro##1{%
			\begingroup
			\escapechar=-1 % drop the leading backslash
			\edef\pgfplotsplothandlername{\string##1}%
			\pgfmath@smuggleone\pgfplotsplothandlername
			\endgroup
		}%
	}%
	% Patch all TikZ plot handlers:
	% this here also creates backups
	\expandafter\pgfplotsutilforeachcommasep\expandafter{\pgfplotsplothandlers@tikz@std}%
	\as\pgfplots@loc@TMPa{%
		\expandafter\pgfplotsplothandlers@init@@\expandafter{\pgfplots@loc@TMPa}%
	}%
	%
	% Patch only selected ones:
	\expandafter\pgfplotsutilforeachcommasep\expandafter{\pgfplotsplothandlers@tikz@with@snap@to@nearest}%
	\as\pgfplots@loc@TMPa{%
		\expandafter\pgfplotsplothandlers@init@\expandafter{\pgfplots@loc@TMPa}%
	}%
	%
	\if1\b@pgfplots@compat@bar@width@units
	\else
		\def\pgfplotbarwidth{\pgfplots@bar@width@not@in@context}%
		\def\pgfplotbarshift{\pgfplots@bar@shift@not@in@context}%
		\pgfplotsutil@add@to@macro\pgfplothandlerxbar{%
			\def\pgfplotbarwidth{\pgfplots@xbar@width}%
			\def\pgfplotbarshift{\pgfplots@xbar@shift}%
		}%
		\pgfplotsutil@add@to@macro\pgfplothandlerybar{%
			\def\pgfplotbarwidth{\pgfplots@ybar@width}%
			\def\pgfplotbarshift{\pgfplots@ybar@shift}%
		}%
	\fi
	%
	\pgfplotsplothandlers@init@map@to@patched@versions
	%
}%

\def\pgfplots@xbar@width{pgfplotsxbarwidth}
\def\pgfplots@ybar@width{pgfplotsybarwidth}
\def\pgfplots@xbar@shift{pgfplotsxbarshift}
\def\pgfplots@ybar@shift{pgfplotsybarshift}
\def\pgfplots@bar@width@not@in@context{pgfplotsbarwidthgeneric}
\def\pgfplots@bar@shift@not@in@context{pgfplotsbarshiftgeneric}

\pgfplotsmathdeclarepseudoconstant{pgfplotsxbarwidth}{\pgfplots@bar@mathparse@{y}{bar width}}%
\pgfplotsmathdeclarepseudoconstant{pgfplotsybarwidth}{\pgfplots@bar@mathparse@{x}{bar width}}%
\pgfplotsmathdeclarepseudoconstant{pgfplotsxbarshift}{\pgfplots@bar@mathparse@{y}{bar shift}}%
\pgfplotsmathdeclarepseudoconstant{pgfplotsybarshift}{\pgfplots@bar@mathparse@{x}{bar shift}}%
\pgfplotsmathdeclarepseudoconstant{pgfplotsbarwidthgeneric}{\pgfplots@bar@mathparse@{N}{bar width}}%
\pgfplotsmathdeclarepseudoconstant{pgfplotsbarshiftgeneric}{\pgfplots@bar@mathparse@{N}{bar shift}}%

\def\pgfplots@bar@mathparse@#1#2{%
	\pgfmathparse{\pgfkeysvalueof{/pgf/#2}}%
	\ifpgfmathunitsdeclared
	\else
		\edef\pgfplots@bar@direction@choice@{#1}%
		\if N\pgfplots@bar@direction@choice@%
			\if a\pgfplots@bar@direction@choice
			\else
				\if x\pgfplots@bar@direction@choice
					\def\pgfplots@bar@direction@choice@{y}%
				\else
					\if y\pgfplots@bar@direction@choice
						\def\pgfplots@bar@direction@choice@{x}%
					\else
						\pgfplotsthrow{invalid argument}{\pgfplots@bar@direction@choice@}{Sorry, the value of 'bar direction' is invalid}\pgfeov%
					\fi
				\fi
			\fi
		\fi
		\if N\pgfplots@bar@direction@choice@%
			\pgfplots@bar@mathparse@error{#1}{#2}%
		\else
			\let\pgfplots@loc@TMPa=\pgfmathresult
			\csname pgfplotstransformdirection\pgfplots@bar@direction@choice@\endcsname{\pgfplots@loc@TMPa}%
			\let\pgfplots@loc@TMPa=\pgfmathresult
			\if\pgfplots@bar@direction@choice@ x%	
				\pgfqpointxy@orig{\pgfplots@loc@TMPa}{0}%
				\edef\pgfmathresult{\pgf@sys@tonumber\pgf@x}%
			\else
				\pgfqpointxy@orig{0}{\pgfplots@loc@TMPa}%
				\edef\pgfmathresult{\pgf@sys@tonumber\pgf@y}%
			\fi
			%\edef\pgfplots@loc@TMPa{{\pgf@sys@tonumber\pgf@x}{\pgf@sys@tonumber\pgf@y}}%
			%\expandafter\pgfmathveclen@\pgfplots@loc@TMPa
		\fi
	\fi
}%

\def\pgfplots@bar@mathparse@error#1#2{%
	\pgfplotsthrow{invalid argument}{\pgfplots@bar@direction@choice@}{Sorry, the value '#2=\pgfkeysvalueof{/pgf/#2}' is given in terms of a unit -- but I do not know which axis! Next steps: either (a) set one of 'xbar' or 'ybar' before evaluating the value of '#2' or (b) define 'bar direction=x or y'}\pgfeov%
}%

% Resets the plot handler routines.
%
% This is necessary before installing a new plot handler!
\def\pgfplotsresetplothandler{%
	\let\pgfplotsplothandlersurveystart=\pgfplotsplothandlersurveystart@default
	\let\pgfplotsplothandlername=\pgfplotsplothandlername@default
	\let\pgfplotsplothandlersurveyend=\pgfplotsplothandlersurveyend@default
	\let\pgfplotsplothandlersurveypoint=\pgfplotsplothandlersurveypoint@default
	\let\pgfplotsplothandlerpointtokeys=\pgfplotsplothandlerpointtokeys@default
	\let\pgfplotsplothandlerserializepointto=\pgfplotsplothandlerserializepointto@default
	\let\pgfplotsplothandlerdeserializepointfrom=\pgfplotsplothandlerdeserializepointfrom@default
	\let\pgfplotsplothandlerserializestateto=\pgfplotsplothandlerserializestateto@default
	\let\pgfplotsplothandlerdeserializestatefrom=\pgfplotsplothandlerdeserializestatefrom@default
	\let\pgfplotsplothandlervisualizejump=\pgfplotsplothandlervisualizejump@default
	\let\pgfplotsplothandlernotifyscanlinecomplete=\relax
	\let\pgfplotsplothandlersurveydifflen=\pgfplotsplothandlersurveydifflen@default
	\let\pgfplotsplothandlersurveypointattime=\pgfplotsplothandlersurveypointattime@default
	\let\pgfplotsplothandlertransformslopedattime=\pgfplotsplothandlertransformslopedattime@default
	\let\pgfplotsplothandlerifcurrentpointcanbefirstlast=\pgfplotsplothandlerifcurrentpointcanbefirstlast@default
	%
	\let\pgfplotsplothandlersurveybeforesetpointmeta=\pgfplotsplothandlersurveybeforesetpointmeta@default
	\let\pgfplotsplothandlersurveyaftersetpointmeta=\pgfplotsplothandlersurveyaftersetpointmeta@default
}%

\def\pgfplotsplothandlersurveybeforesetpointmeta@default{}
\def\pgfplotsplothandlersurveyaftersetpointmeta@default{}

% \pgfplotsplothandlersurveystart
\def\pgfplotsplothandlersurveystart@default{}%

% \pgfplotsplothandlername
\def\pgfplotsplothandlername@default{%
	[tikz@plot@handler: \meaning\pgf@plotstreamstart]%
}%

% \pgfplotsplothandlerifcurrentpointcanbefirstlast : can be used to
% check if the current point of a plot handler can be the global first
% or last segment.
% It will execute #1 if that is the case and #2 if not.
\def\pgfplotsplothandlerifcurrentpointcanbefirstlast@default#1#2{#1}%


% \pgfplotsplothandlersurveyend
% Called at the end of each survey phase.
\def\pgfplotsplothandlersurveyend@default{}
\let\pgfplotsplothandlernotifyscanlinecomplete=\relax%

% \pgfplotsplothandlersurveypoint is called for each encountered data
% point.
%
% The data point as such is available using the current state of any
% macros which are assigned during the survey phase (during \addplot).
% This includes any table macros etc.
% PGFPlots stores the x,y and z coordinates into \pgfplots@current@point@[xyz]. 
% The point meta coordinate is in \pgfplots@current@point@meta.
%
% Note that since any currently assigned macro can be used here, the
% new DV engine of PGF is also valid (and will be supported
% eventually). This DV engine stores data point entries in keys,
% namely those in the key path /data point. See the pgf manual.
\def\pgfplotsplothandlersurveypoint@default{%
	% reset it. NOTE: this migh be done multiple times. But better one
	% too much than one too few...
	\def\pgfplots@set@perpointmeta@done{0}%
	%
	\pgfplotsplothandlersurveypoint@default@noreset@of@pointmeta
}%
\def\pgfplotsplothandlersurveypoint@default@noreset@of@pointmeta{%
	\pgfplotsaxisparsecoordinate
	\pgfplotsaxispreparecoordinate
	\ifpgfplotsaxisparsecoordinateok
		\pgfplotsaxisupdatelimitsforcoordinate\pgfplots@current@point@x\pgfplots@current@point@y\pgfplots@current@point@z
	\fi
	\pgfplotsaxisdatapointsurveyed
}%

% \pgfplotsplothandlerserializepointto{<\macro>}
% should save a complete data point to <\macro> such that it can be
% de-serialized later.
%
% #1: a macro name. Will be filled with (expandable) data.
% 	The format can be arbitrary, but you should be able to extra it.
%
% @PRECONDITION
% 	this macro will be invoked in a context where the current data
% 	point has been processed completely, including any preparations.
% 	The required data which should be saved depends on the plot
% 	handler. Usually, all plot handlers require
% 	\pgfplots@current@point@[xyz] and \pgfplots@current@point@meta.
%   This macro should only assign keys which have been defined or
%   validated by any of the plot handler relevant methods (including
%   the de-serialization or survey methods).
\def\pgfplotsplothandlerserializepointto@default#1{%
	% Store normalized point for list:
	% We need
	% xi,yi,zi;
	% where zi may be empty. 
	%
	% Note that per-point meta information is stored in
	% \pgfplotsaxisserializedatapoint .
	\edef#1{\pgfplots@current@point@x,\pgfplots@current@point@y,\pgfplots@current@point@z}%
}%

% \pgfplotsplothandlerdeserializepointfrom{<\macro>}
% the counterpart for \pgfplotsplothandlerserializepointto.
% It restores the state as it was before the serialization.
%
% #1: the serialized information.
\def\pgfplotsplothandlerdeserializepointfrom@default#1{%
	\expandafter\pgfplotsplothandlerdeserializepointfrom@default@#1\relax
}%

% \pgfplotsplothandlerpointtokeys{<key prefix>}
%
% Takes the current point and copies its values to a set of keys.
%
% For example, if the current point has the three coordinates x=1,
% y=2, z=3,
% \pgfplotsplothandlerpointtokeys{/data point/first/}
% will define the keys
% /data point/first/x/.initial=1
% /data point/first/y/.initial=2
% /data point/first/z/.initial=3
%
\def\pgfplotsplothandlerpointtokeys@default#1{%
	\pgfkeyslet{#1/x}\pgfplots@current@point@x
	\pgfkeyslet{#1/y}\pgfplots@current@point@y
	\pgfkeyslet{#1/z}\pgfplots@current@point@z
}%

\def\pgfplotsplothandlerdeserializepointfrom@default@#1,#2,#3\relax{%
	\def\pgfplots@current@point@x{#1}%
	\def\pgfplots@current@point@y{#2}%
	\def\pgfplots@current@point@z{#3}%
}%
% \pgfplotsplothandlerserializestateto{<\macro>}
% should save the state of the current plot handler such that it can
% be de-serialized later.
%
% The state does usually NOT contain a coordinate stream, this is
% accomplished by \pgfplotsplothandlerserializepointto.
%
% #1: a macro name. Can be filled with anything, including
% non-expandable macro invocations.
\def\pgfplotsplothandlerserializestateto@default#1{%
	\def#1{}%
}%

%
\def\pgfplotsplothandlerdeserializestatefrom@default#1{%
	#1%
}%

\def\pgfplotsplothandlervisualizejump@default{%
	\pgfplotstreamend
	\pgfplotstreamstart
}%

% \pgfplotsplothandlersurveypointattime#1#2#3
%
% sets the current environment to a point which is between points #2
% and #3, using the fraction #1.
%
% #1 a fraction (a number between 0 and 1) in the format of
% \pgfplotscoordmath{default}
% #2 a serialized point denoting the start
% #3 a serialized point denoting the end
%
% In other words: #1 = 0.0 should result in #2 and #1 = 1.0 should
% result in #3.
%
% POSTCONDITION: the current point will be set to the point
% in-between. The current point is set in terms of logical coordinates
% (i.e. \pgfplots@current@point@x and its variants)
\def\pgfplotsplothandlersurveypointattime@default#1#2#3{%
	\begingroup
	\pgfplotsplothandlerdeserializepointfrom{#2}%
	\let\pgfplots@last@x=\pgfplots@current@point@x
	\let\pgfplots@last@y=\pgfplots@current@point@y
	\let\pgfplots@last@z=\pgfplots@current@point@z
	\pgfplotsplothandlerdeserializepointfrom{#3}%
	%
	\def\pgfplots@loc@TMPa##1{%
		\pgfplotscoordmath{##1}{op}{subtract}{{\csname pgfplots@current@point@##1\endcsname}{\csname pgfplots@last@##1\endcsname}}%
		\let\pgfplots@diff=\pgfmathresult
		\pgfplotscoordmath{##1}{parsenumber}{#1}%
		\pgfplotscoordmath{##1}{op}{multiply}{{\pgfmathresult}{\pgfplots@diff}}%
		\pgfplotscoordmath{##1}{op}{add}{{\csname pgfplots@last@##1\endcsname}{\pgfmathresult}}%
		\expandafter\let\csname pgfplots@current@point@##1\endcsname=\pgfmathresult
	}%
	\pgfplots@loc@TMPa x%
	\pgfplots@loc@TMPa y%
	\ifpgfplots@curplot@threedim
		\pgfplots@loc@TMPa z%
	\fi
	\xdef\pgfplots@glob@TMPb{%
		\noexpand\def\noexpand\pgfplots@current@point@x{\pgfplots@current@point@x}%
		\noexpand\def\noexpand\pgfplots@current@point@y{\pgfplots@current@point@y}%
		\noexpand\def\noexpand\pgfplots@current@point@z{\pgfplots@current@point@z}%
	}%
	\endgroup
	\pgfplots@glob@TMPb
}%

% \pgfplotsplothandlersurveydifflen#1#2
%
% computes the length between two points which are given in logical
% coordinates. 
% #1 a serialized point
% #2 a serialized point
%
% The return value is assigned to \pgfmathresult in
% \pgfplotscoordmath{default} format.
\def\pgfplotsplothandlersurveydifflen@default#1#2{%
	\begingroup
		\pgfplotsplothandlerdeserializepointfrom{#1}%
		\let\pgfplots@last@x=\pgfplots@current@point@x
		\let\pgfplots@last@y=\pgfplots@current@point@y
		\let\pgfplots@last@z=\pgfplots@current@point@z
		\pgfplotsplothandlerdeserializepointfrom{#2}%
		\pgfplotscoordmathparsemacro{default}\pgfplots@last@x
		\pgfplotscoordmathparsemacro{default}\pgfplots@last@y
		\pgfplotscoordmathparsemacro{default}\pgfplots@current@point@x
		\pgfplotscoordmathparsemacro{default}\pgfplots@current@point@y
		\ifpgfplots@curplot@threedim
			\pgfplotscoordmathparsemacro{default}\pgfplots@last@z
			\pgfplotscoordmathparsemacro{default}\pgfplots@current@point@z
		\fi
		\pgfplotscoordmath{default}{op}{subtract}{{\pgfplots@current@point@x}{\pgfplots@last@x}}%
		\pgfplotscoordmath{default}{op}{multiply}{{\pgfmathresult}{\pgfmathresult}}%
		\let\pgfplots@diff@x=\pgfmathresult
		\pgfplotscoordmath{default}{op}{subtract}{{\pgfplots@current@point@y}{\pgfplots@last@y}}%
		\pgfplotscoordmath{default}{op}{multiply}{{\pgfmathresult}{\pgfmathresult}}%
		\let\pgfplots@diff@y=\pgfmathresult
		\pgfplotscoordmath{default}{op}{add}{{\pgfplots@diff@x}{\pgfplots@diff@y}}%
		\let\pgfplots@len=\pgfmathresult
		\ifpgfplots@curplot@threedim
			\pgfplotscoordmath{default}{op}{subtract}{{\pgfplots@current@point@z}{\pgfplots@last@z}}%
			\pgfplotscoordmath{default}{op}{multiply}{{\pgfmathresult}{\pgfmathresult}}%
			\let\pgfplots@diff@z=\pgfmathresult
			\pgfplotscoordmath{default}{op}{add}{{\pgfplots@len}{\pgfplots@diff@z}}%
			\let\pgfplots@len=\pgfmathresult
		\fi
		\pgfplotscoordmath{default}{op}{sqrt}{{\pgfplots@len}}%
		\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%

% \pgfplotsplothandlertransformslopedattime{<time fraction>}{<start>}{<end>}
%
% Installs a PGF rotation matrix such that it fits the gradient of the
% current plot segment between <start> and <end>.
%
% #1: a fraction such that 0.0 is <start> and 1.0 is <end>
% #2: the <start> point (a macro containing the result of \pgfplotsplothandlerserializepointto)
% #3: the <end> point   (a macro containing the result of \pgfplotsplothandlerserializepointto)
%
\def\pgfplotsplothandlertransformslopedattime@default#1#2#3{%
    \pgf@process{%
		\pgfplotsplothandlerdeserializepointfrom{#2}%
		\pgfplotsaxisvisphasegetpoint
	}%
    \pgf@xa=\pgf@x% xb/yb = start point
    \pgf@ya=\pgf@y%
    \pgf@process{%
		\pgfplotsplothandlerdeserializepointfrom{#3}%
		\pgfplotsaxisvisphasegetpoint
	}%
    \advance\pgf@x by-\pgf@xa%
    \advance\pgf@y by-\pgf@ya%
    \ifpgfallowupsidedownattime%
    \else%
      \ifdim\pgf@x<0pt%   
        \pgf@x=-\pgf@x%
        \pgf@y=-\pgf@y%
      \fi%
    \fi%
    \pgfpointnormalised{}% x/y = normalised vector
    \pgf@ya=-\pgf@y%
    \pgftransformcm%
    {\pgf@sys@tonumber{\pgf@x}}{\pgf@sys@tonumber{\pgf@y}}%
    {\pgf@sys@tonumber{\pgf@ya}}{\pgf@sys@tonumber{\pgf@x}}{\pgfpointorigin}%
}%



\pgfplotsresetplothandler

% The following two methods constitutes implementations for
% 'node[pos=<faction>]' which do not interpolate. They only snap to
% the nearest coordinate.
%
% For example, \addplot[scatter] ... node[pos=0.5] {}  should use a
% unit distance and should not interpolate between scatter points.
\def\pgfplotsplothandlersurveydifflen@snaptonearest#1#2{%
	% FIXME : this implies that #1 and #2 are "adjacent" in the
	% coordinate stream!
	\pgfplotscoordmath{default}{one}%
}%
\def\pgfplotsplothandlersurveypointattime@snaptonearest#1#2#3{%
	\pgfplotscoordmath{default}{parsenumber}{0.5}%
	\let\pgfplots@loc@TMPa=\pgfmathresult
	\pgfplotscoordmath{default}{parsenumber}{#1}%
	\pgfplotscoordmath{default}{if less than}{\pgfmathresult}{\pgfplots@loc@TMPa}{%
		\pgfplotsplothandlerdeserializepointfrom{#2}%
	}{%
		\pgfplotsplothandlerdeserializepointfrom{#3}%
	}%
}%
% ==================================

% Defines 
% - a generic update limits routine,
%   \pgfplotsaxisupdatelimitsforcoordinate#1#2#3
%   if #3 is empty, it will assume a 2d point, otherwise a 3d point
%   and the axis will be three dimensional as well.
%   During \addplot, this auto-detection will be disabled in favor of
%   the '\addplot3' versus' \addplot' syntax.
%
\def\pgfplots@prepare@axis@API{%
	\pgfplots@curplot@threedimtrue
	\pgfplots@prepare@axis@API@
	\let\pgfplotsaxisupdatelimitsforcoordinatethreedim=\pgfplotsaxisupdatelimitsforcoordinate@
	\let\pgfplotsaxisparsecoordinatethreedim=\pgfplotsaxisparsecoordinate@
	%
	\pgfplots@curplot@threedimfalse
	\pgfplots@prepare@axis@API@
	\let\pgfplotsaxisupdatelimitsforcoordinatetwodim=\pgfplotsaxisupdatelimitsforcoordinate@
	\let\pgfplotsaxisparsecoordinatetwodim=\pgfplotsaxisparsecoordinate@
	%
	\def\pgfplotsaxisupdatelimitsforcoordinate##1##2##3{%
		\pgfplots@ifempty{##3}{%
			\pgfplotsaxisupdatelimitsforcoordinatetwodim{##1}{##2}{}%
		}{%
			\global\pgfplots@threedimtrue
			\pgfplotsaxisupdatelimitsforcoordinatethreedim{##1}{##2}{##3}%
		}%
	}%
	\def\pgfplotsaxisparsecoordinate{%
		\ifx\pgfplots@current@point@z\pgfutil@empty
			\pgfplotsaxisparsecoordinatetwodim
		\else
			\global\pgfplots@threedimtrue
			\pgfplotsaxisparsecoordinatethreedim%
		\fi
	}%
}%
\def\pgfplots@prepare@axis@API@{%
	\begingroup
	%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	\let\E=\noexpand
	% Setup Just-In-Time-Macro Compilation:
	% I compile a set of macros which is highly optimized for this
	% particular axis configuration.
	%
	% \pgfplotsaxisupdatelimitsforcoordinate
	% Updates the current x and y limits for point (#1,#2).
	%
	% To eliminate all those case distinctions, it is created with
	% 'edef' and a lot of '\noexpand' calls here:
	%
	%
	% The point coordinates are given in floating point format (FIXME)
	%
	% Please note that if user specified limits are given, automatic
	% limits are only applied to points which fall into the user specified
	% clipping region.
	%
	% PRECONDITIONS:
	% - the input coordinates have been parsed correctly (floating point
	%   format for linear axis, log applied for logarithmic ones)
	%
	% Arguments:
	% #1,#2,#3 the x,y and z coordinate. z is ignored for 2d plots.
	\xdef\pgfplotsaxisupdatelimitsforcoordinate@##1##2##3{%
%\E\tracingmacros=2\E\tracingcommands=2
%\E\pgfplots@message{Updating limits for (##1,##2) ...}%
		%
		% VIM SEARCH PATTERN: 
		%   [^E]\zs\\\ze[^E]
		% -> this finds '\' which is neither '\E' nor is it prefixed
		%  by 'E'.
		%
		%
		%
		\E\pgfplots@update@limits@for@one@point@ISCLIPPEDfalse
		% check whether we need to clip limits:
		\ifpgfplots@clip@limits
			\ifpgfplots@autocompute@xmin
			\else
				\ifpgfplots@xislinear
					\E\pgfmathfloatlessthan@{##1}{\E\pgfplots@xmin}%
					\E\ifpgfmathfloatcomparison
						\E\pgfplots@update@limits@for@one@point@ISCLIPPEDtrue
					\E\fi
				\else
					\E\pgfplotsmathlessthan{##1}{\E\pgfplots@xmin}%
					\E\ifpgfmathfloatcomparison
						\E\pgfplots@update@limits@for@one@point@ISCLIPPEDtrue
					\E\fi
				\fi
			\fi
			\ifpgfplots@autocompute@xmax
			\else
				\ifpgfplots@xislinear
					\E\pgfmathfloatlessthan@{\E\pgfplots@xmax}{##1}%
					\E\ifpgfmathfloatcomparison
						\E\pgfplots@update@limits@for@one@point@ISCLIPPEDtrue
					\E\fi
				\else
					\E\pgfplotsmathlessthan{\E\pgfplots@xmax}{##1}%
					\E\ifpgfmathfloatcomparison
						\E\pgfplots@update@limits@for@one@point@ISCLIPPEDtrue
					\E\fi
				\fi
			\fi
			\ifpgfplots@autocompute@ymin
			\else
				\ifpgfplots@yislinear
					\E\pgfmathfloatlessthan@{##2}{\E\pgfplots@ymin}%
					\E\ifpgfmathfloatcomparison
						\E\pgfplots@update@limits@for@one@point@ISCLIPPEDtrue
					\E\fi
				\else
					\E\pgfplotsmathlessthan{##2}{\E\pgfplots@ymin}%
					\E\ifpgfmathfloatcomparison
						\E\pgfplots@update@limits@for@one@point@ISCLIPPEDtrue
					\E\fi
				\fi
			\fi
			\ifpgfplots@autocompute@ymax
			\else
				\ifpgfplots@yislinear
					\E\pgfmathfloatlessthan@{\E\pgfplots@ymax}{##2}%
					\E\ifpgfmathfloatcomparison
						\E\pgfplots@update@limits@for@one@point@ISCLIPPEDtrue
					\E\fi
				\else
					\E\pgfplotsmathlessthan{\E\pgfplots@ymax}{##2}%
					\E\ifpgfmathfloatcomparison
						\E\pgfplots@update@limits@for@one@point@ISCLIPPEDtrue
					\E\fi
				\fi
			\fi
			\ifpgfplots@curplot@threedim
				\ifpgfplots@autocompute@zmin
				\else
					\ifpgfplots@zislinear
						\E\pgfmathfloatlessthan@{##3}{\E\pgfplots@zmin}%
						\E\ifpgfmathfloatcomparison
							\E\pgfplots@update@limits@for@one@point@ISCLIPPEDtrue
						\E\fi
					\else
						\E\pgfplotsmathlessthan{##3}{\E\pgfplots@zmin}%
						\E\ifpgfmathfloatcomparison
							\E\pgfplots@update@limits@for@one@point@ISCLIPPEDtrue
						\E\fi
					\fi
				\fi
				\ifpgfplots@autocompute@zmax
				\else
					\ifpgfplots@zislinear
						\E\pgfmathfloatlessthan@{\E\pgfplots@zmax}{##3}%
						\E\ifpgfmathfloatcomparison
							\E\pgfplots@update@limits@for@one@point@ISCLIPPEDtrue
						\E\fi
					\else
						\E\pgfplotsmathlessthan{\E\pgfplots@zmax}{##3}%
						\E\ifpgfmathfloatcomparison
							\E\pgfplots@update@limits@for@one@point@ISCLIPPEDtrue
						\E\fi
					\fi
				\fi
			\fi
		\fi
		%
		%
		%
		% Update limits:
		\E\ifpgfplots@update@limits@for@one@point@ISCLIPPED
		\E\else
			\ifpgfplots@autocompute@xmin
				\ifpgfplots@xislinear
					\E\pgfplotsmathfloatmin{\E\pgfplots@xmin}{##1}%
					\E\global\E\let\E\pgfplots@xmin=\E\pgfmathresult
				\else
					\E\pgfplotsmathmin{\E\pgfplots@xmin}{##1}%
					\E\global\E\let\E\pgfplots@xmin=\E\pgfmathresult
				\fi
			\fi
			\ifpgfplots@autocompute@xmax
				\ifpgfplots@xislinear
					\E\pgfplotsmathfloatmax{\E\pgfplots@xmax}{##1}%
					\E\global\E\let\E\pgfplots@xmax=\E\pgfmathresult
				\else
					\E\pgfplotsmathmax{\E\pgfplots@xmax}{##1}%
					\E\global\E\let\E\pgfplots@xmax=\E\pgfmathresult
				\fi
			\fi
			\ifpgfplots@autocompute@ymin
				\ifpgfplots@yislinear
					\E\pgfplotsmathfloatmin{\E\pgfplots@ymin}{##2}%
					\E\global\E\let\E\pgfplots@ymin=\E\pgfmathresult
				\else
					\E\pgfplotsmathmin{\E\pgfplots@ymin}{##2}%
					\E\global\E\let\E\pgfplots@ymin=\E\pgfmathresult
				\fi
			\fi
			\ifpgfplots@autocompute@ymax
				\ifpgfplots@yislinear
					\E\pgfplotsmathfloatmax{\E\pgfplots@ymax}{##2}%
					\E\global\E\let\E\pgfplots@ymax=\E\pgfmathresult
				\else
					\E\pgfplotsmathmax{\E\pgfplots@ymax}{##2}%
					\E\global\E\let\E\pgfplots@ymax=\E\pgfmathresult
				\fi
			\fi
			\ifpgfplots@curplot@threedim
				\ifpgfplots@autocompute@zmin
					\ifpgfplots@zislinear
						\E\pgfplotsmathfloatmin{\E\pgfplots@zmin}{##3}%
						\E\global\E\let\E\pgfplots@zmin=\E\pgfmathresult
					\else
						\E\pgfplotsmathmin{\E\pgfplots@zmin}{##3}%
						\E\global\E\let\E\pgfplots@zmin=\E\pgfmathresult
					\fi
				\fi
				\ifpgfplots@autocompute@zmax
					\ifpgfplots@zislinear
						\E\pgfplotsmathfloatmax{\E\pgfplots@zmax}{##3}%
						\E\global\E\let\E\pgfplots@zmax=\E\pgfmathresult
					\else
						\E\pgfplotsmathmax{\E\pgfplots@zmax}{##3}%
						\E\global\E\let\E\pgfplots@zmax=\E\pgfmathresult
					\fi
				\fi
			\fi
		\E\fi
		%
		% Compute data range:
		\ifpgfplots@autocompute@all@limits
			% the data range will be acquired simply from the axis
			% range, see below!
		\else
			% Attention: it is only done for linear axis!
			\ifpgfplots@xislinear
				\E\pgfplotsmathfloatmin{\E\pgfplots@data@xmin}{##1}%
				\E\global\E\let\E\pgfplots@data@xmin=\E\pgfmathresult
				\E\pgfplotsmathfloatmax{\E\pgfplots@data@xmax}{##1}%
				\E\global\E\let\E\pgfplots@data@xmax=\E\pgfmathresult
			\fi
			\ifpgfplots@yislinear
				\E\pgfplotsmathfloatmin{\E\pgfplots@data@ymin}{##2}%
				\E\global\E\let\E\pgfplots@data@ymin=\E\pgfmathresult
				\E\pgfplotsmathfloatmax{\E\pgfplots@data@ymax}{##2}%
				\E\global\E\let\E\pgfplots@data@ymax=\E\pgfmathresult
			\fi
			\ifpgfplots@curplot@threedim
				\ifpgfplots@zislinear
					\E\pgfplotsmathfloatmin{\E\pgfplots@data@zmin}{##3}%
					\E\global\E\let\E\pgfplots@data@zmin=\E\pgfmathresult
					\E\pgfplotsmathfloatmax{\E\pgfplots@data@zmax}{##3}%
					\E\global\E\let\E\pgfplots@data@zmax=\E\pgfmathresult
				\fi
			\fi
		\fi
%\E\pgfplots@message{Updated limits: (\E\pgfplots@xmin,\E\pgfplots@ymin) rectangle  (\E\pgfplots@xmax,\E\pgfplots@ymax).}%
%
%\E\tracingmacros=0\E\tracingcommands=0
	}%
	%
	% A routine which parses a coordinate.
	% Here, 'coordinate' means (x,y) for a two dimensional plot and
	% '(x,y,z)' for a three dimensional one.
	%
	% The preparation consists of
	% - filtering.
	% - coordinate parsing and high level transformations.
	% - logs.
	%
	% It might happen that \pgfplotsaxisparsecoordinate is called
	% multiple times for a single data "point" (for example, a quiver
	% point might call it for the point where the vector starts and
	% where the vector ends).
	% 
	% @PRECONDITION
	% 	- the plot's survey phase is running (has already been started)
	% 	- \pgfplots@current@point@[xyz] contains the coordinates of the
	% 	point. I assume they are unparsed.
	%
	%
	% @POSTCONDITION
	% 	- the axis' state will be updated.
	% 	- the \pgfplots@current@point@[xyz] macros will contain parsed data.
	% 	- \ifpgfplotsaxisparsecoordinateok will be true if and only
	% 	if the data point has not been filtered away. If it has been
	% 	filtered away, \pgfplots@current@point@[xyz] will be empty.
	% 	- \pgfplots@current@point@[xyz]@unfiltered contain unparsed
	% 	data.
	%
	% @see \pgfplotsaxispreparecoordinate
	% @see \pgfplotsaxisdatapointsurveyed
	\xdef\pgfplotsaxisparsecoordinate@{%
		% These things are necessary for error bars and are available
		% as public results in math parser invocations (for meta and
		% filters)
		\E\let\E\pgfplots@current@point@x@unfiltered=\E\pgfplots@current@point@x
		\E\let\E\pgfplots@current@point@y@unfiltered=\E\pgfplots@current@point@y
		\E\let\E\pgfplots@current@point@z@unfiltered=\E\pgfplots@current@point@z
		\E\def\E\pgfplots@unbounded@dir{}%
		%
		\E\pgfplots@invoke@prefilter
		%
		\E\expandafter\E\pgfplots@prepare@xcoord\E\expandafter{\E\pgfplots@current@point@x}%
		\E\expandafter\E\pgfplots@invoke@filter\E\expandafter{\E\pgfmathresult}{x}%
		\E\let\E\pgfplots@current@point@x=\E\pgfmathresult
		%
		\E\expandafter\E\pgfplots@prepare@ycoord\E\expandafter{\E\pgfplots@current@point@y}%
		\E\expandafter\E\pgfplots@invoke@filter\E\expandafter{\E\pgfmathresult}{y}%
		\E\let\E\pgfplots@current@point@y=\E\pgfmathresult
		%
		\ifpgfplots@curplot@threedim
			\E\expandafter\E\pgfplots@prepare@zcoord\E\expandafter{\E\pgfplots@current@point@z}%
			\E\expandafter\E\pgfplots@invoke@filter\E\expandafter{\E\pgfmathresult}{z}%
			\E\let\E\pgfplots@current@point@z=\E\pgfmathresult
		\fi
		%
		\E\pgfplots@invoke@filter@xyz
		%
		\E\ifx\E\pgfplots@current@point@x\E\pgfutil@empty
		\E\else
			% parse for numbers. Note that this might cause
			% unnecessary overhead of logs (which are already
			% normalized unless someone provided filters). But do it
			% anyway to ensure that filters produce valid output.
			\E\pgfplotscoordmath{x}{parsenumber}{\E\pgfplots@current@point@x}%
			\E\let\E\pgfplots@current@point@x=\E\pgfmathresult
			\E\pgfplotscoordmath{x}{if is bounded}{\E\pgfplots@current@point@x}%
				{}%
				{% this clears nan, inf and -inf points.
					\E\let\E\pgfplots@current@point@x=\E\pgfutil@empty
					\E\def\E\pgfplots@unbounded@dir{x}%
				}%
		\E\fi
		%
		\E\ifx\E\pgfplots@current@point@y\E\pgfutil@empty
		\E\else
			\E\pgfplotscoordmath{y}{parsenumber}{\E\pgfplots@current@point@y}%
			\E\let\E\pgfplots@current@point@y=\E\pgfmathresult
			\E\pgfplotscoordmath{y}{if is bounded}{\E\pgfplots@current@point@y}%
				{}%
				{% this clears nan, inf and -inf points.
					\E\let\E\pgfplots@current@point@y=\E\pgfutil@empty
					\E\def\E\pgfplots@unbounded@dir{y}%
				}%
		\E\fi
		%
		\ifpgfplots@curplot@threedim
			%
			\E\ifx\E\pgfplots@current@point@z\E\pgfutil@empty
			\E\else
				\E\pgfplotscoordmath{z}{parsenumber}{\E\pgfplots@current@point@z}%
				\E\let\E\pgfplots@current@point@z=\E\pgfmathresult
				\E\pgfplotscoordmath{z}{if is bounded}{\E\pgfplots@current@point@z}%
					{}%
					{% this clears nan, inf and -inf points.
						\E\let\E\pgfplots@current@point@z=\E\pgfutil@empty
						\E\def\E\pgfplots@unbounded@dir{z}%
					}%
			\E\fi
		\fi
		%
		% check if coordinates are bounded:
		\E\pgfplotsaxisparsecoordinateoktrue
		\E\ifx\E\pgfplots@current@point@x\E\pgfutil@empty
			\E\pgfplotsaxisparsecoordinateokfalse
		\E\else
			\E\ifx\E\pgfplots@current@point@y\E\pgfutil@empty
				\E\pgfplotsaxisparsecoordinateokfalse
			\E\else
				\ifpgfplots@curplot@threedim
					\E\ifx\E\pgfplots@current@point@z\E\pgfutil@empty
						\E\pgfplotsaxisparsecoordinateokfalse
					\E\fi
				\fi
			\E\fi
		\E\fi
		%
	}%
	%
	\endgroup
}%

% ==================================
% The quiver plot handler.
% It draws a lot of arrows.
% Its input is (x_i,y_i); (u_i,v_i) for data point i and it draws a
% vector in direction (u_i,v_i) starting from (x_i,y_i) .
% It also supports 3D arrows (involving z_i and w_i).
 
\newif\ifpgfplots@quiver@usetikz
\newif\ifpgfplots@quiver@updatelimits

\pgfplotsset{
	% The 'quiver' plot handler for two- and three dimensional plots.
	%
	% User Interface:
	% use /pgfplots/quiver to enable the plot handler.
	% Then, provide `quiver/u value' or `quiver/u' to 
	% tell where to find the 'x' coordinates of the vectors, and similarly
	% for 'v' and 'w' instead of 'u'.
	quiver/.code={%
		\let\tikz@plot@handler=\pgfplotsplothandlerquiver
		\pgfqkeys{/pgfplots/quiver}{quiver legend,#1}%
	},%
	quiver/u value*/.initial=0,
	quiver/v value*/.initial=0,
	quiver/w value*/.initial=0,
	quiver/u value is expr/.initial=0,
	quiver/v value is expr/.initial=0,
	quiver/w value is expr/.initial=0,
	quiver/quiver legend/.style={
		/pgfplots/legend image code/.code={%
			\draw[x=0.6cm,y=0cm,z=0pt,##1,
				/pgfplots/quiver/before arrow/.add code={}{
					% quiver is a pgfplots-specific plot-handler. We need to
					% fix the additional input data somehow.
					%
					% this is an *absolute* coordinate, interpreted
					% relative to 'x', 'y', 'z'
					\def\pgfplots@quiver@u{1}%
					\def\pgfplots@quiver@v{1}%
					\def\pgfplots@quiver@w{1}%
				},%
			] 
				plot coordinates {
					(0cm,0cm) 
				};%
		}%
	},
	quiver/u filter/.code=,
	quiver/v filter/.code=,
	quiver/w filter/.code=,
	quiver/u value/.code	=\pgfplots@set@source@for{quiver/u}{#1}{0},%
	quiver/u/.code			=\pgfplots@set@source@for{quiver/u}{#1}{1},%
	quiver/v value/.code	=\pgfplots@set@source@for{quiver/v}{#1}{0},%
	quiver/v/.code			=\pgfplots@set@source@for{quiver/v}{#1}{1},%
	quiver/w value/.code	=\pgfplots@set@source@for{quiver/w}{#1}{0},%
	quiver/w/.code			=\pgfplots@set@source@for{quiver/w}{#1}{1},%
	quiver/before arrow/.code=,
	quiver/after arrow/.code=,
	quiver/every arrow/.style={},
	quiver/arrow color/.initial=,
	quiver/scale arrows/.initial=1,
	quiver/update limits/.is if=pgfplots@quiver@updatelimits,
	quiver/update limits=true,
	quiver/colored/.code={%
		\def\pgfplots@loc@TMPa{#1}%
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\pgfkeyslet{/pgfplots/quiver/arrow color}\pgfplots@loc@TMPa
			\pgfkeysalso{/pgfplots/set point meta if empty=f(x)}%
		\fi
	},%
	quiver/colored/.default=mapped color,
}%

\def\pgfplots@set@source@for#1#2#3{%
	\pgfkeyssetvalue{/pgfplots/#1 value*}{#2}%
	\pgfkeyssetvalue{/pgfplots/#1 is expr}{#3}%
}%
% To be used to create a simple parser for keys initialised by
% \pgfplots@set@source@for:
%
% #1: the key path (relative to /pgfplots/) of the data.
%     Can be empty in which case /pgfplots/#2 is used to access data.
% #2: the key name of the data
% #3: a macro name which be will defined to be a parser for the data.
%
% The parser will check whether the '#2 is expr' key is set.
% Furthermore, it defines /data point/#2 to be the result.
%
% Example:
% \pgfplots@set@source@for{hist/data}{...}
%
% ->
%  \pgfplots@prepare@source@parser@for{hist/}{data}\parser
%
%  then, invoking \parser
%  will define \pgfmathresult to be the argument provided to
%  \pgfplots@set@source@for.
\def\pgfplots@prepare@source@parser@for#1#2#3{%
	\pgfkeyslet{/data point/#1#2}\pgfutil@empty%
	%
	\pgfkeysgetvalue{/pgfplots/#1#2 value*}\pgfplots@loc@TMPa
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		% assume the '/data point/#1#2' is set by some input
		% routine.
		% Invoke math parser in this case.
		\pgfkeyssetvalue{/pgfplots/#1#2 is expr}{1}%
	\else
		\pgfkeyslet{/data point/#1#2}\pgfplots@loc@TMPa
	\fi
	\def#3{%
		\edef\pgfmathresult{\pgfkeysvalueof{/data point/#1#2}}%
%\message{parse coordinate #1#2 (\pgfmathresult) ...^^J}%
	}%
	%
	%
	\pgfkeysifdefined{/pgfplots/#1#2 coord trafo/.@cmd}{%
		\pgfkeysgetvalue{/pgfplots/#1#2 coord trafo/.@cmd}\pgfplots@loc@TMPa
		\ifx\pgfplots@loc@TMPa\pgfplots@empty@command@key
		\else
			\t@pgfplots@toka=\expandafter{#3}%
			\t@pgfplots@tokb={%
				\def\pgfplots@loc@TMPa{\pgfkeysvalueof{/pgfplots/#1#2 coord trafo/.@cmd}}%
				\expandafter\pgfplots@loc@TMPa\expandafter{\pgfmathresult}\pgfeov%
			}%
			\t@pgfplots@tokc={%
				\ifx\pgfmathresult\pgfutil@empty
				\else
					\pgfmathfloatparsenumber{\pgfmathresult}%
				\fi
			}%
			\edef#3{%
				\the\t@pgfplots@toka
				\the\t@pgfplots@tokb
				\the\t@pgfplots@tokc
			}%
		\fi
	}{}%
	%
	\t@pgfplots@toka=\expandafter{#3}%
	\if1\pgfkeysvalueof{/pgfplots/#1#2 is expr}%
		\t@pgfplots@tokc={%
			\ifx\pgfmathresult\pgfutil@empty
			\else
				\pgfmathparse{\pgfmathresult}%
			\fi
		}%
	\else
		\t@pgfplots@tokc={%
			\ifx\pgfmathresult\pgfutil@empty
			\else
				\pgfmathfloatparsenumber{\pgfmathresult}%
			\fi
		}%
	\fi
	\edef#3{%
		\the\t@pgfplots@toka
		\the\t@pgfplots@tokc
	}%
	%
	\pgfkeysgetvalue{/pgfplots/#1#2 filter/.@cmd}\pgfplots@loc@TMPa
	\ifx\pgfplots@loc@TMPa\pgfplots@empty@command@key
	\else
		\t@pgfplots@toka=\expandafter{#3}%
		\t@pgfplots@tokb={%
			\def\pgfplots@loc@TMPa{\pgfkeysvalueof{/pgfplots/#1#2 filter/.@cmd}}%
			\expandafter\pgfplots@loc@TMPa\expandafter{\pgfmathresult}\pgfeov%
		}%
		\t@pgfplots@tokc={%
			\ifx\pgfmathresult\pgfutil@empty
			\else
				\pgfmathfloatparsenumber{\pgfmathresult}%
			\fi
		}%
		\edef#3{%
			\the\t@pgfplots@toka
			\the\t@pgfplots@tokb
			\the\t@pgfplots@tokc
		}%
	\fi
	%
	\iftrue
		\t@pgfplots@toka=\expandafter{#3}%
		\t@pgfplots@tokc={%
%\message{parse coordinate (#1#2) = \pgfmathresult.^^J}%
		}%
		\edef#3{%
			\the\t@pgfplots@toka
			\the\t@pgfplots@tokc
		}%
	\fi
}%

% Invokes /pgfplots/#1 coord inv trafo  on \pgfmathresult if that key
% exists.
% #1 the argument is in float (will become the 'default' coordmath
% eventually).
%
% On output, it should either '#1' if there was no coord inv trafo or
% the result of the trafo.
\def\pgfplots@coord@trafo@inv@for#1{%
	\def\pgfplots@loc@TMPb{/pgfplots/#1 coord inv trafo/.@cmd}%
	\pgfkeysifdefined{\pgfplots@loc@TMPb}{%
		\pgfkeysgetvalue{\pgfplots@loc@TMPb}\pgfplots@loc@TMPa
		\ifx\pgfplots@loc@TMPa\pgfplots@empty@command@key
		\else
			\pgfmathfloattofixed{\pgfmathresult}%
			\expandafter\pgfplots@loc@TMPa\expandafter{\pgfmathresult}\pgfeov
		\fi
	}{}%
}
% Like \pgfplots@coord@trafo@inv@for, but for the normal trafo
% direction
\def\pgfplots@coord@trafo@for#1{%
	\def\pgfplots@loc@TMPb{/pgfplots/#1 coord trafo/.@cmd}%
	\pgfkeysifdefined{\pgfplots@loc@TMPb}{%
		\pgfkeysgetvalue{\pgfplots@loc@TMPb}\pgfplots@loc@TMPa
		\ifx\pgfplots@loc@TMPa\pgfplots@empty@command@key
		\else
			\expandafter\pgfplots@loc@TMPa\expandafter{\pgfmathresult}\pgfeov
		\fi
	}{}%
}
\def\pgfplotsplothandlerquiver{%
	\pgfplotsresetplothandler
	\let\pgf@plotstreamstart=\pgfplotsplothandlervisbegin@quiver
	\let\pgfplotsplothandlersurveystart=\pgfplotsplothandlersurveystart@quiver
	\let\pgfplotsplothandlersurveypoint=\pgfplotsplothandlersurveypoint@quiver
	\let\pgfplotsplothandlerserializepointto=\pgfplotsplothandlerserializepointto@quiver
	\let\pgfplotsplothandlerdeserializepointfrom=\pgfplotsplothandlerdeserializepointfrom@quiver
	\let\pgfplotsplothandlerpointtokeys=\pgfplotsplothandlerpointtokeys@quiver
	\let\pgfplotsplothandlerquiver@vis@hook=\pgfutil@empty
	%
	\ifpgfplots@xislinear \else \pgfplotsplothandlerquivererror \fi
	\ifpgfplots@yislinear \else \pgfplotsplothandlerquivererror\fi
	\pgfplotsifcurplotthreedim{%
		\ifpgfplots@zislinear \else \pgfplotsplothandlerquivererror \fi
	}{}%
}%
\def\pgfplotsplothandlerquivererror{\pgfplots@error{Sorry, quiver plots for logarithmic axes are not yet implemented. In fact, the implementation does something -- but it will probably change in future releases. Contact the mailing list if you have questions}}%

\def\pgfplotsplothandlersurveystart@quiver{%
	\pgfkeysgetvalue{/pgfplots/quiver/scale arrows}\pgfplots@quiver@scale
	\ifx\pgfplots@quiver@scale\pgfutil@empty
	\else
		\def\pgfplots@loc@TMPa{1}%
		\ifx\pgfplots@loc@TMPa\pgfplots@quiver@scale
			\let\pgfplots@quiver@scale=\pgfutil@empty
		\else
			\pgfmathparse{\pgfplots@quiver@scale}%
			\pgfmathfloatparsenumber\pgfplots@quiver@scale
			\let\pgfplots@quiver@scale=\pgfmathresult
		\fi
	\fi
	%
	\pgfplots@prepare@source@parser@for@quiver u\pgfplots@quiver@prepare@u%
	\pgfplots@prepare@source@parser@for@quiver v\pgfplots@quiver@prepare@v%
	\pgfplots@prepare@source@parser@for@quiver w\pgfplots@quiver@prepare@w%
}%

\def\pgfplots@prepare@source@parser@for@quiver#1#2{%
	\pgfplots@prepare@source@parser@for{quiver/}{#1}{#2}%
	\t@pgfplots@toka=\expandafter{#2}%
	\t@pgfplots@tokb=\expandafter{\csname pgfplots@quiver@#1\endcsname}%
	\edef#2{%
		\the\t@pgfplots@toka
		\noexpand\let\the\t@pgfplots@tokb=\noexpand\pgfmathresult
		\ifx\pgfplots@quiver@scale\pgfutil@empty
		\else
			\noexpand\pgfmathfloatmultiply@{\pgfplots@quiver@scale}{\the\t@pgfplots@tokb}%
			\noexpand\let\the\t@pgfplots@tokb=\noexpand\pgfmathresult
		\fi
	}%
}%

\def\pgfplotsplothandlersurveypoint@quiver{%
	\pgfplots@quiver@prepare@u
	\pgfplots@quiver@prepare@v
	\pgfplotsifcurplotthreedim{%
		\pgfplots@quiver@prepare@w
	}{%
		\let\pgfplots@quiver@w=\pgfutil@empty
	}%
	\pgfplotsaxisparsecoordinate
	\pgfplotsaxispreparecoordinate
	\ifpgfplotsaxisparsecoordinateok
		\pgfplotsaxisupdatelimitsforcoordinate\pgfplots@current@point@x\pgfplots@current@point@y\pgfplots@current@point@z
		%
		\pgfmathadd@{\pgfplots@quiver@u}{\pgfplots@current@point@x}%
		\let\pgfplots@quiver@u=\pgfmathresult
		\pgfmathadd@{\pgfplots@quiver@v}{\pgfplots@current@point@y}%
		\let\pgfplots@quiver@v=\pgfmathresult
		\pgfplotsifcurplotthreedim{%
			\pgfmathadd@{\pgfplots@quiver@w}{\pgfplots@current@point@z}%
			\let\pgfplots@quiver@w=\pgfmathresult
		}{}%
		\ifpgfplots@quiver@updatelimits
			\pgfplotsaxisupdatelimitsforcoordinate\pgfplots@quiver@u\pgfplots@quiver@v\pgfplots@quiver@w
		\fi
	\fi
	\pgfplotsaxisdatapointsurveyed
}%
\def\pgfplotsplothandlerserializepointto@quiver#1{%
	\edef#1{\pgfplots@current@point@x,\pgfplots@current@point@y,\pgfplots@current@point@z>\pgfplots@quiver@u,\pgfplots@quiver@v,\pgfplots@quiver@w}%
}%
\def\pgfplotsplothandlerdeserializepointfrom@quiver#1{%
	\expandafter\pgfplotsplothandlerdeserializepointfrom@quiver@#1\relax
}%
\def\pgfplotsplothandlerdeserializepointfrom@quiver@#1,#2,#3>#4,#5,#6\relax{%
	\def\pgfplots@current@point@x{#1}%
	\def\pgfplots@current@point@y{#2}%
	\def\pgfplots@current@point@z{#3}%
	\def\pgfplots@quiver@u{#4}%
	\def\pgfplots@quiver@v{#5}%
	\def\pgfplots@quiver@w{#6}%
}%
\def\pgfplotsplothandlerpointtokeys@quiver#1{%
	\pgfplotsplothandlerpointtokeys@default
	\pgfkeyslet{#1/u}\pgfplots@quiver@u
	\pgfkeyslet{#1/v}\pgfplots@quiver@v
	\pgfkeyslet{#1/w}\pgfplots@quiver@w
}%
\def\pgfplotsplothandlervisbegin@quiver{%
	\def\pgfplots@quiver@has@handled@point@meta{0}%
	\pgfkeysgetvalue{/pgfplots/quiver/arrow color}\pgfplots@quiver@color
	\ifx\pgfplots@quiver@color\pgfutil@empty
	\else
		% prepare the color data and define 'mapped color':
		\def\pgfplots@quiver@has@handled@point@meta{1}%
		\expandafter\def\expandafter\pgfplotsplothandlerquiver@vis@hook\expandafter{%
			\pgfplotsplothandlerquiver@vis@hook
			\pgfplotsaxisvisphasetransformpointmeta
			\pgfplotscolormapdefinemappedcolor{\pgfplotspointmetatransformed}%
		}%
		% SEE BELOW AS WELL FOR HOW TO ENABLE THE COLOR.
	\fi
	%
	%
	\pgfkeysgetvalue{/pgfplots/quiver/every arrow/.@cmd}\pgfplots@quiver@everyarrow
	\ifx\pgfplots@quiver@everyarrow\pgfplots@empty@style@key
		% use PGF basic level methods to set the 'arrow color':
		\ifx\pgfplots@quiver@color\pgfutil@empty
		\else
			\expandafter\def\expandafter\pgfplotsplothandlerquiver@vis@hook\expandafter{%
				\pgfplotsplothandlerquiver@vis@hook
				\pgfsetstrokecolor{\pgfkeysvalueof{/pgfplots/quiver/arrow color}}%
				% for arrow heads:
				\pgfsetfillcolor{\pgfkeysvalueof{/pgfplots/quiver/arrow color}}%
			}%
		\fi
	\else
		% 'every arrow' should provide a high level user interface.
		% Use tikz instead of pgf. This is slower, but more powerfull.
		\pgfplots@quiver@usetikztrue
		\pgfplotsaxisifhaspointmeta{%
			% ASSERT(mapped color is available)
			\if0\pgfplots@quiver@has@handled@point@meta%
				% -> define mapped color
				\expandafter\def\expandafter\pgfplotsplothandlerquiver@vis@hook\expandafter{%
					\pgfplotsplothandlerquiver@vis@hook
					\pgfplotsaxisvisphasetransformpointmeta
					\pgfplotscolormapdefinemappedcolor{\pgfplotspointmetatransformed}%
				}%
				\def\pgfplots@quiver@has@handled@point@meta{1}%
			\fi
		}{}%
		% use tikz methods to set the 'arrow color':
		\ifx\pgfplots@quiver@color\pgfutil@empty
		\else
			\t@pgfplots@toka=\expandafter{\pgfplots@quiver@color}%
			\edef\pgfplots@loc@TMPa{\noexpand\pgfkeysalso{/pgfplots/quiver/every arrow/.prefix style={\the\t@pgfplots@toka}}}%
			\pgfplots@loc@TMPa
		\fi
	\fi
	%
	\global\let\pgf@plotstreampoint=\pgfplotsplothandlerquiver@vis%
	\global\let\pgf@plotstreamspecial=\pgfutil@gobble%
	\global\let\pgf@plotstreamend=\relax
}%

\def\pgfplotsplothandlerquiver@vis#1{%
	\pgfkeysvalueof{/pgfplots/quiver/before arrow/.@cmd}\pgfeov
	\pgfplotsplothandlerquiver@vis@hook
	\ifpgfplots@quiver@usetikz
		\draw[/pgfplots/quiver/every arrow] \pgfextra{\pgfplotsplothandlerquiver@vis@path{#1}};
	\else
		\pgfplotsplothandlerquiver@vis@path{#1}%
		\pgfusepath{stroke}%
	\fi
	\pgfkeysvalueof{/pgfplots/quiver/after arrow/.@cmd}\pgfeov
}%
\def\pgfplotsplothandlerquiver@vis@path#1{%
	\pgfpathmoveto{#1}%
	\pgfplotsaxisvisphasetransformcoordinate\pgfplots@quiver@u\pgfplots@quiver@v\pgfplots@quiver@w
	\pgfpathlineto{%
		\pgfplotsifcurplotthreedim{%
			\pgfplotsqpointxyz\pgfplots@quiver@u\pgfplots@quiver@v\pgfplots@quiver@w
		}{%
			\pgfplotsqpointxy\pgfplots@quiver@u\pgfplots@quiver@v
		}%
	}%
}%

\newif\ifpgfplotsplothandlerhistogram@intervals
\newif\ifpgfplotsplothandlerhistogram@cumulative
\newif\ifpgfplotsplothandlerhistogram@density
\pgfplotsset{
	hist/.code={%
		\let\tikz@plot@handler=\pgfplotsplothandlerhistogram
		\pgfqkeys{/pgfplots/hist}{#1}%
	},
	hist/data value/.code	=\pgfplots@set@source@for{hist/data}{#1}{0},%
	hist/data/.code			=\pgfplots@set@source@for{hist/data}{#1}{1},%
	hist/data filter/.code=,
	hist/data value=\pgfkeysvalueof{/data point/y},
%	hist/data=y,
	hist/data min/.initial=\pgfkeysvalueof{/pgfplots/xmin},
	hist/data max/.initial=\pgfkeysvalueof{/pgfplots/xmax},
	hist/bins/.initial=10,
	hist/intervals/.is if=pgfplotsplothandlerhistogram@intervals,
	hist/intervals/.default=true,
	hist/intervals=true,
	hist/cumulative/.is if=pgfplotsplothandlerhistogram@cumulative,
	hist/cumulative/.default=true,
	hist/density/.is if=pgfplotsplothandlerhistogram@density,
	hist/density/.default=true,
	hist/density=false,
	hist/handler/.style={/tikz/ybar interval},
	hist/symbolic coords/.style={%
		/pgfplots/symbolic coords={hist/data}{A,B,C,D,E,F,G,H,I,J},
		/pgfplots/symbolic coords={x}{A,B,C,D,E,F,G,H,I,J},
	},%
}%
\def\pgfplotsplothandlerhistogram{%
	\pgfplotsresetplothandler
	\def\pgf@plotstreamstart{%
		\pgfplotsset{/pgfplots/hist/handler}%
		\pgfplotsresetplothandler
		\tikz@plot@handler
		\pgf@plotstreamstart
	}%
	%
	% let \pgfplotsplothandlername to the one of the handler.
	% Note that \pgfplotsplothandlername is the *visualization* layer
	\begingroup
		\pgfplotsset{/pgfplots/hist/handler}%
		\pgfplotsresetplothandler
		\tikz@plot@handler
		\xdef\pgfplots@glob@TMPa{\pgfplotsplothandlername}%
	\endgroup
	\let\pgfplotsplothandlername=\pgfplots@glob@TMPa%
	%
	\let\pgfplotsplothandlersurveypoint=\pgfplotsplothandlersurveypoint@hist
	\let\pgfplotsplothandlersurveystart=\pgfplotsplothandlersurveystart@hist
	\let\pgfplotsplothandlersurveyend=\pgfplotsplothandlersurveyend@hist
}%
\def\pgfplotsplothandlersurveystart@hist{%
	\pgfplots@prepare@source@parser@for{hist/}{data}{\pgfplotsplothandlerhistogram@parse}%
	%
	\pgfkeysgetvalue{/pgfplots/hist/data min}\pgfmathresult
	\edef\pgfmathresult{\pgfmathresult}%
	\ifx\pgfmathresult\pgfutil@empty\else
		\pgfplots@coord@trafo@for{hist/data}%
	\fi
	\edef\pgfplotsplothandlerhistogram@datamin{\pgfmathresult}%
	%
	\pgfkeysgetvalue{/pgfplots/hist/data max}\pgfmathresult
	\edef\pgfmathresult{\pgfmathresult}%
	\ifx\pgfmathresult\pgfutil@empty\else
		\pgfplots@coord@trafo@for{hist/data}%
	\fi
	\edef\pgfplotsplothandlerhistogram@datamax{\pgfmathresult}%
	%
	\ifx\pgfplotsplothandlerhistogram@datamin\pgfutil@empty
		\pgfmathfloatcreate{1}{1.0}{2147483645}%
		\let\pgfplotsplothandlerhistogram@datamin=\pgfmathresult
		\def\pgfplotsplothandlerhistogram@datamin@autocompute{1}%
	\else
		\pgfmathfloatparsenumber{\pgfplotsplothandlerhistogram@datamin}%
		\let\pgfplotsplothandlerhistogram@datamin=\pgfmathresult
		\def\pgfplotsplothandlerhistogram@datamin@autocompute{0}%
	\fi
	\ifx\pgfplotsplothandlerhistogram@datamax\pgfutil@empty
		\pgfmathfloatcreate{2}{1.0}{2147483645}%
		\let\pgfplotsplothandlerhistogram@datamax=\pgfmathresult
		\def\pgfplotsplothandlerhistogram@datamax@autocompute{1}%
	\else
		\pgfmathfloatparsenumber{\pgfplotsplothandlerhistogram@datamax}%
		\let\pgfplotsplothandlerhistogram@datamax=\pgfmathresult
		\def\pgfplotsplothandlerhistogram@datamax@autocompute{0}%
	\fi
	%
	\edef\pgfplotsplothandlerhistogram@Nfixed{\pgfkeysvalueof{/pgfplots/hist/bins}}%
	\c@pgf@counta=\pgfplotsplothandlerhistogram@Nfixed\relax
	\advance\c@pgf@counta by-1
	\edef\pgfplotsplothandlerhistogram@Nmax{\the\c@pgf@counta}%
	%
	\pgfmathfloatparsenumber{\pgfplotsplothandlerhistogram@Nfixed}%
	\let\pgfplotsplothandlerhistogram@N=\pgfmathresult
	%
	\pgfplotsapplistXnewempty\pgfp@hist@@
	\def\c@pgfplotsplothandlerhistogram@num{0}%
	\c@pgfplots@coordindex=0
}%

\def\pgfplotsplothandlersurveypoint@hist@limits{%
	\if1\pgfplotsplothandlerhistogram@datamin@autocompute
		\pgfplotsmathfloatmin{\pgfplots@current@point@data}{\pgfplotsplothandlerhistogram@datamin}%
		\let\pgfplotsplothandlerhistogram@datamin=\pgfmathresult
	\fi
	%
	\if1\pgfplotsplothandlerhistogram@datamax@autocompute
		\pgfplotsmathfloatmax{\pgfplots@current@point@data}{\pgfplotsplothandlerhistogram@datamax}%
		\let\pgfplotsplothandlerhistogram@datamax=\pgfmathresult
	\fi
}%
\def\pgfplotsplothandlersurveypoint@hist{%
	% Note that at this point, the coordinate filtering does NOT
	% apply. Perhaps it should...
	\pgfplotsplothandlerhistogram@parse
	\let\pgfplots@current@point@data=\pgfmathresult
	%
	\ifx\pgfplots@current@point@data\pgfutil@empty
	\else
		\pgfmathfloatiffinite\pgfplots@current@point@data{%
			\pgfplotsplothandlersurveypoint@hist@limits
			%
			\pgfplotsutil@advancestringcounter\c@pgfplotsplothandlerhistogram@num
			%
			% store parsed result.
			\edef\pgfmathresult{{\pgfplots@current@point@data}}%
			\expandafter\pgfplotsapplistXpushback\expandafter{\pgfmathresult}\to\pgfp@hist@@
		}{%
		}%
	\fi
	\advance\c@pgfplots@coordindex by1
}%
\def\pgfplotsplothandlersurveyend@hist{%
	\ifnum\c@pgfplotsplothandlerhistogram@num>0
		\expandafter\pgfplotsplothandlersurveyend@hist@
	\fi
}%
\def\pgfplotsplothandlersurveyend@hist@{%
	\pgfmathfloatsubtract@{\pgfplotsplothandlerhistogram@datamax}{\pgfplotsplothandlerhistogram@datamin}%
	\let\pgfplotsplothandlerhistogram@range=\pgfmathresult
	\pgfmathfloatdivide@{\pgfplotsplothandlerhistogram@range}{\pgfplotsplothandlerhistogram@N}%
	\let\pgfplotsplothandlerhistogram@h=\pgfmathresult
	\pgfmathfloatreciprocal@{\pgfplotsplothandlerhistogram@h}%
	\let\pgfplotsplothandlerhistogram@invh=\pgfmathresult
	%
	\pgfplotsarraynewempty{pgfp@hist}%
	\pgfplotsarrayresize{pgfp@hist}{\pgfplotsplothandlerhistogram@Nfixed}%
	\pgfplotsarrayforeachungrouped{pgfp@hist}\as\pgfplots@hist@count{%
		\pgfplotsarrayset{\pgfplotsarrayforeachindex}\of{pgfp@hist}\to{0}%
	}%
	%
	\pgfplotsapplistXlet\pgfplots@hist@data=\pgfp@hist@@
	\pgfplotsapplistXnewempty\pgfp@hist@@
	\expandafter\pgfplotsplothandlersurveyend@hist@loop\pgfplots@hist@data\pgfplots@EOI
	\let\pgfplots@hist@data=\relax
	%
	
	% Calculate total count
	\c@pgf@counta=0
	\pgfplotsarrayforeachungrouped{pgfp@hist}\as\pgfplots@hist@count{%
		\advance\c@pgf@counta by\pgfplots@hist@count\relax	
		\def\pgfplots@loc@TMPa{\pgfplotsarrayset{\pgfplotsarrayforeachindex}\of{pgfp@hist}\to}%
	}%
	\pgfmathfloatparsenumber{\the\c@pgf@counta}%
	\let\pgfp@hist@totalcount=\pgfmathresult
	\pgfmathfloatreciprocal@{\pgfp@hist@totalcount}%
	\let\pgfp@hist@totalcount@inv=\pgfmathresult
	%
	\ifpgfplotsplothandlerhistogram@cumulative
		\c@pgf@counta=0
		\pgfplotsarrayforeachungrouped{pgfp@hist}\as\pgfplots@hist@count{%
			\advance\c@pgf@counta by\pgfplots@hist@count\relax
			\def\pgfplots@loc@TMPa{\pgfplotsarrayset{\pgfplotsarrayforeachindex}\of{pgfp@hist}\to}%
			\ifpgfplotsplothandlerhistogram@density
				\pgfmathfloatparsenumber{\the\c@pgf@counta}%
				\pgfmathfloatmultiply@{\pgfmathresult}{\pgfp@hist@totalcount@inv}%
				\pgfmathfloattosci@{\pgfmathresult}%
				\expandafter\pgfplots@loc@TMPa\expandafter{\pgfmathresult}%
			\else
				\expandafter\pgfplots@loc@TMPa\expandafter{\the\c@pgf@counta}%
			\fi
		}%
	\fi%
	%
	%% Density histogram
	% Divide count in each bin by (totalcount*range/bins)
	\ifpgfplotsplothandlerhistogram@density
		\ifpgfplotsplothandlerhistogram@cumulative
		\else
			\pgfmathfloatmultiply@{\pgfp@hist@totalcount@inv}{\pgfplotsplothandlerhistogram@invh}%
			\let\pgfp@hist@totalcount@times@h@inv=\pgfmathresult
% FIXME : this here is a patch suggestion for 
% https://sourceforge.net/tracker/?func=detail&atid=1060656&aid=3609245&group_id=224188
%
% FIXME : this line would actually compute relative frequencies...
% might not be too bad at all, but is no density 
%\let\pgfp@hist@totalcount@times@h@inv=\pgfp@hist@totalcount@inv
			\pgfplotsarrayforeachungrouped{pgfp@hist}\as\pgfplots@hist@count{%
				\pgfmathfloatparsenumber{\pgfplots@hist@count}%
				\pgfmathfloatmultiply@{\pgfmathresult}{\pgfp@hist@totalcount@times@h@inv}%
				\pgfmathfloattosci@{\pgfmathresult}%
				\def\pgfplots@loc@TMPa{\pgfplotsarrayset{\pgfplotsarrayforeachindex}\of{pgfp@hist}\to}%
				\expandafter\pgfplots@loc@TMPa\expandafter{\pgfmathresult}%
			}%
		\fi
	\fi
	%
	%% End density histogram
	\pgfplots@curplot@threedimfalse
	%
	\pgfplotsset{/pgfplots/hist/handler}%
	\pgfplotsresetplothandler
	\tikz@plot@handler
	%
	\pgfplotsplothandlersurveystart
	%
	\let\pgfplots@current@point@z=\pgfutil@empty
	\pgfplotsarrayforeachungrouped{pgfp@hist}\as\pgfplots@hist@count{%
		\pgfplotsplothandlerhistgetintervalstartfor\pgfplotsarrayforeachindex
		\pgfplotsplothandlerhist@invtrafo
		\let\pgfplots@current@point@x\pgfmathresult%
		\let\pgfplots@current@point@y\pgfplots@hist@count%
%\message{Survey point (\pgfplots@current@point@x,\pgfplots@current@point@y)^^J}%
		\pgfplotsplothandlersurveypoint
	}%
	\ifpgfplotsplothandlerhistogram@intervals
		% replicate last count.
		\let\pgfmathresult\pgfplotsplothandlerhistogram@datamax%
		\pgfplotsplothandlerhist@invtrafo
		\let\pgfplots@current@point@x\pgfmathresult%
		\let\pgfplots@current@point@y\pgfplots@hist@count%
%\message{Survey point (\pgfplots@current@point@x,\pgfplots@current@point@y)^^J}%
		\pgfplotsplothandlersurveypoint
	\fi
	%
	\pgfplotsplothandlersurveyend
}
\def\pgfplotsplothandlerhist@invtrafo{%
	% This here might be inefficient, because
	% there needs to be a compatible "x coord trafo" as well -- and
	% that transformation will (most likely) do the very same thing as
	% the hist/data coord trafo. 
	%
	% But I did not find a way to combine the transformations
	% automatically without resorting to hackery.
	%
	% And: the performance impact might (hopefully) be small...
	\pgfplots@coord@trafo@inv@for{hist/data}%
}%
\def\pgfplotsplothandlersurveyend@hist@loop#1{%
	\def\pgfplots@loc@TMPa{#1}%
	\ifx\pgfplots@loc@TMPa\pgfplots@EOI
	\else
		\pgfplotsplothandlerhistgetbinfor@{#1}%
		\expandafter\pgfplotsplothandlerhistadvancebin\expandafter{\pgfmathresult}%
		%
		\expandafter\pgfplotsplothandlersurveyend@hist@loop
	\fi
}%
\def\pgfplotsplothandlerhistadvancebin#1{%
	\pgfplotsarrayselect{#1}\of{pgfp@hist}\to\pgfplots@loc@TMPa%
	\pgfplotsutil@advancestringcounter\pgfplots@loc@TMPa
	\pgfplotsarrayletentry{#1}\of{pgfp@hist}=\pgfplots@loc@TMPa
}%
\def\pgfplotsplothandlerhistgetintervalstartfor#1{%
	\pgfmathfloatparsenumber{#1}%
	\expandafter\pgfplotsplothandlerhistgetintervalstartfor@\expandafter{\pgfmathresult}%
}%
\def\pgfplotsplothandlerhistgetintervalstartfor@#1{%
	\pgfmathfloatmultiply@{\pgfplotsplothandlerhistogram@h}{#1}%
	\expandafter\pgfmathfloatadd@\expandafter{\pgfmathresult}{\pgfplotsplothandlerhistogram@datamin}%
}%
\def\pgfplotsplothandlerhistgetbinfor#1{%
	\pgfmathfloatparsenumber{#1}%
	\expandafter\pgfplotsplothandlerhistgetbinfor@\expandafter{\pgfmathresult}%
}%

\def\pgfplotsplothandlerhistsettol#1{%
	\begingroup
	\pgfmathfloatparsenumber{#1}%
	\global\let\pgfplotsplothandlerhisttol@parsed=\pgfmathresult
	\endgroup
}%
\pgfplotsplothandlerhistsettol{1e-4}%

\def\pgfplotsplothandlerhistgetbinfor@#1{%
	\pgfmathfloatsubtract@{#1}{\pgfplotsplothandlerhistogram@datamin}%
	\expandafter\pgfmathfloatmultiply@\expandafter{\pgfmathresult}{\pgfplotsplothandlerhistogram@invh}%
	\expandafter\pgfmathfloatadd@\expandafter{\pgfmathresult}{\pgfplotsplothandlerhisttol@parsed}%
	\pgfmathfloattofixed{\pgfmathresult}%
	\afterassignment\pgfplots@gobble@until@relax
	\c@pgf@counta=\pgfmathresult\relax
	\ifnum\pgfplotsplothandlerhistogram@Nfixed>\c@pgf@counta
		\ifnum\c@pgf@counta<0
			\def\pgfmathresult{0}%
		\else
			\def\pgfmathresult{\the\c@pgf@counta}%
		\fi
	\else
		\let\pgfmathresult=\pgfplotsplothandlerhistogram@Nmax
	\fi
}%


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
%
% Contour plots
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5

\newif\ifpgfplotsplothandlercontour@labels
\newif\ifpgfplotsplothandlercontour@filled

\def\pgfplotsplothandlercontour@axis@set@inverse#1#2#3#4{%
	\pgfplotsutilifstringequal{#1}{#4}{%
		\expandafter\def\csname pgfplotsplothandlercontour@axis@inv@#4\endcsname{x}%
	}{%
		\pgfplotsutilifstringequal{#2}{#4}{%
			\expandafter\def\csname pgfplotsplothandlercontour@axis@inv@#4\endcsname{y}%
		}{%
			\pgfplotsutilifstringequal{#3}{#4}{%
		\expandafter\def\csname pgfplotsplothandlercontour@axis@inv@#4\endcsname{z}%
			}{%
				\pgfplotsthrow{invalid argument}{\pgfplots@loc@TMPa}{Sorry, the choice axes={#1}{#2}{#3} is illegal. Please use only values x, y, and z and ensure that there is a 1:1 correspondence}\pgfeov%
			}%
		}%
	}%
}

\pgfplotsset{
	contour prepared/.code={%
		\let\tikz@plot@handler=\pgfplotsplothandlercontourprepared
		\pgfqkeys{/pgfplots/contour}{%
			every contour plot,
			#1,%
		}%
	},
	contour prepared filled/.style={%
		/pgfplots/contour prepared={draw color=mapped color!80!black,labels=false,filled=true},
	},
	% FIXME : should use \tikz@plot@handler instead of just the
	% visualization thing!
	contour/handler/.style={/tikz/sharp plot},
	contour prepared format/.is choice,
	contour prepared format/standard/.code=	{\def\pgfplotsplothandlercontourprepared@format{s}},
	contour prepared format/matlab/.code=	{\def\pgfplotsplothandlercontourprepared@format{m}},
	contour prepared format/standard,
	contour/draw color/.initial=mapped color,
	contour/fill color/.initial=mapped color,
	contour/label distance/.initial=70pt,
	contour/label node code/.code={%
		\node {\pgfmathprintnumber{#1}};
	},%
	contour/labels/.is if=pgfplotsplothandlercontour@labels,
	contour/labels=true,
	contour/filled/.is if=pgfplotsplothandlercontour@filled,
	contour/filled/.default=true,
	% EXPERIMENTAL: WILL CHANGE EVENTUALLY!
	% this is (only) used for contour filled:
	% data limits={(xmin,ymin,zmin,cmin) (xmax,ymax,ymax,cmax}
	contour/data limits/.initial=,% FIXME EXPERIMENTAL
	contour/every contour plot/.style={
		/pgfplots/legend image post style={sharp plot},
	},
	contour/every contour label/.style={%
		sloped,%
		transform shape,%
		inner sep=2pt,
		font=\scriptsize,
		every node/.style={mapped color!50!black,fill=white},%
		/pgf/number format/relative*={\pgfplotspointmetarangeexponent},%
		%every node/.style={yshift=10pt},%
	},
	contour/labels over line/.style={
		/pgfplots/contour/every contour label/.append style={%
			every node/.append style={%
				fill=none,
				anchor=base,
				yshift=1pt,
			},
		},
	},
	contour/contour label style/.style={
		/pgfplots/contour/every contour label/.append style={#1}},
	%
	%
	%  Styles to actually *compute* the contour.
	%  These are mostly placeholders here: As long as the
	%  algorithm is not ready, we have to resort to external tools.
	%
	%  Shared parameters:
	contour/number/.initial=5,
	contour/levels/.initial=,
	%
	%
	contour/contour dir/.is choice,
	contour/contour dir/x/.style={/pgfplots/contour/axes={y}{z}{x}},
	contour/contour dir/y/.style={/pgfplots/contour/axes={x}{z}{y}},
	contour/contour dir/z/.style={/pgfplots/contour/axes={x}{y}{z}},
	contour/axes/.code args={#1#2#3}{%
		\edef\pgfplotsplothandlercontour@axis@x{#1}%
		\edef\pgfplotsplothandlercontour@axis@y{#2}%
		\edef\pgfplotsplothandlercontour@axis@z{#3}%
		%
		\edef\pgfplots@loc@TMPa{{\pgfplotsplothandlercontour@axis@x}{\pgfplotsplothandlercontour@axis@y}{\pgfplotsplothandlercontour@axis@z}}%
		%
		\expandafter\pgfplotsplothandlercontour@axis@set@inverse\pgfplots@loc@TMPa{x}%
		\expandafter\pgfplotsplothandlercontour@axis@set@inverse\pgfplots@loc@TMPa{y}%
		\expandafter\pgfplotsplothandlercontour@axis@set@inverse\pgfplots@loc@TMPa{z}%
		%
	},%
	contour/contour dir=z,
	%
	%
	% Interface to external tools:
	contour external/.code={%
		\edef\tikz@plot@handler{\noexpand\pgfplotsplothandlercontourexternal}%
		\pgfqkeys{/pgfplots/contour external}{%
			every contour plot,
			#1%
		}%
	},
	contour external/scanline marks/.is choice,
	contour external/scanline marks/false/.code={\def\pgfplotsplothandlercontourexternal@scanlinemode{0}},
	contour external/scanline marks/if in input/.code={\def\pgfplotsplothandlercontourexternal@scanlinemode{1}},
	contour external/scanline marks/required/.code={\def\pgfplotsplothandlercontourexternal@scanlinemode{2}},
	contour external/scanline marks/true/.code={\def\pgfplotsplothandlercontourexternal@scanlinemode{2}},
	contour external/scanline marks/if in input,
	contour external/output point meta/.initial=,
	contour external/file/.initial=,% auto-generate
	contour external/script extension/.initial=script,
	contour external/script/.initial=,% not yet initialised
	contour external/cmd/.initial=,% not yet initialised
	contour external/.search also=/pgfplots/contour,
	contour gnuplot/.style={
		contour external={%
			scanline marks=required,
			script={
				unset surface; 
				\ifx\thecontourlevels\empty
				set cntrparam levels \thecontournumber;
				\else
				set cntrparam levels discrete \thecontourlevels;
				\fi
				set contour; 
				set table \"\outfile\"; 
				splot \"\infile\";
			},
			cmd={gnuplot \"\script\"},
			#1,%
		},
	},
}%

\def\pgfplotsplothandlercontourprepared{%
	\pgfplotsresetplothandler
	\pgfplotsset{empty line=jump}%
	\let\pgf@plotstreamstart=\pgfplotsplothandlervisstart@contour
	\let\pgfplotsplothandlersurveystart=\pgfplotsplothandlersurveystart@contour
	\let\pgfplotsplothandlersurveyend=\pgfplotsplothandlersurveyend@contour
	\let\pgfplotsplothandlersurveypoint=\pgfplotsplothandlersurveypoint@contour
	\if m\pgfplotsplothandlercontourprepared@format
		\let\pgfplotsplothandlersurveystart=\pgfplotsplothandlersurveystart@contourmatlabformat
		\let\pgfplotsplothandlersurveypoint=\pgfplotsplothandlersurveypoint@contourmatlabformat
		\pgfplotsaxisifhaspointmeta{}{%
			\pgfplotsset{/pgfplots/point meta=explicit}%
		}%
	\fi
	\pgfplotsplothandlercontour@prepare@point@meta
	\def\pgfplotsplothandlersurveybeforesetpointmeta{%
		% ensure that 'point meta=z' respects 'axes={y}{z}{x}' -- it
		% should assign the 'x' coordinate as point meta!
		% To this end, we have to convert to reordered axes
		% temporarily.
		\pgfplotsplothandlersurveypoint@contour@axes@std@to@reordered
		\pgfplotsplothandlersurveybeforesetpointmeta@default
	}%
	\def\pgfplotsplothandlersurveyaftersetpointmeta{%
		\pgfplotsplothandlersurveyaftersetpointmeta@default
		% ... and undo the reordering after point meta has been set:
		\pgfplotsplothandlersurveypoint@contour@axes@reordered@to@std
	}
}%

\def\pgfplotsplothandlersurveystart@contour{%
	\pgfplotsplothandlersurveystart@default
	%
	\pgfplotsplothandlersurveypoint@contour@prepare@axes x%
	\pgfplotsplothandlersurveypoint@contour@prepare@axes y%
	\pgfplotsplothandlersurveypoint@contour@prepare@axes z%
}%

\def\pgfplotsplothandlercontour@prepare@point@meta{%
	\ifpgfplots@curplot@threedim
		\pgfplotsset{/pgfplots/set point meta if empty=z}%
	\else
		\pgfplotsaxisifhaspointmeta{}{%
			\pgfkeysgetvalue{/pgfplots/table/meta index}\pgfplots@loc@TMPa
			\ifx\pgfplots@loc@TMPa\pgfutil@empty
% FIXME : this here is reasonable, but it should be sanity checked!
				\pgfkeyssetvalue{/pgfplots/table/meta index}{2}%
			\fi
			\pgfplotsset{/pgfplots/set point meta if empty=explicit}%
		}%
		%\pgfplots@error{Sorry, 'contour external' requires \string\addplot3 (or a non-empty `point meta' used as label data)}%
	\fi
	\def\pgfplotsplothandlercontour@empty@pointmeta@error@@{0}%
}%
\def\pgfplotsplothandlercontour@empty@pointmeta@error{%
	\if0\pgfplotsplothandlercontour@empty@pointmeta@error@@
		\def\pgfplotsplothandlercontour@empty@pointmeta@error@@{1}%
		\def\pgfplots@current@point@meta{0}%
		\pgfplotsthrow{invalid argument}{\pgfplots@current@point@meta}{Sorry, contour plots require non--empty `point meta'. Please use '\string\addplot3[contour ...] together with 'view={0}{90}' or provide a valid 'point meta=<value>' (for example `<value>=z'?)}\pgfeov%
	\fi
}%

\def\pgfplotsplothandlersurveystart@contourmatlabformat{%
	\def\c@pgfplotsplothandlercontourprepared@matlabformat@cur{0}%
	\def\c@pgfplotsplothandlercontourprepared@matlabformat@count{0}%
	\pgfmathfloatparsenumber{nan}%
	\let\pgfplotsplothandlercontourprepared@matlabformat@meta=\pgfmathresult
	%
	\pgfplotsplothandlersurveystart@contour
}
\def\pgfplotsplothandlersurveypoint@contourmatlabformat{%
	\ifnum\c@pgfplotsplothandlercontourprepared@matlabformat@cur=\c@pgfplotsplothandlercontourprepared@matlabformat@count\relax
		\pgfmathfloatparsenumber{\pgfplots@current@point@y}%
		\pgfmathfloattoint\pgfmathresult
		\let\c@pgfplotsplothandlercontourprepared@matlabformat@count=\pgfmathresult
		\def\c@pgfplotsplothandlercontourprepared@matlabformat@cur{0}%
		%
		\pgfmathfloatparsenumber{\pgfplots@current@point@x}%
		\let\pgfplots@loc@TMPa=\pgfplotsplothandlercontourprepared@matlabformat@meta
		\let\pgfplotsplothandlercontourprepared@matlabformat@meta=\pgfmathresult
		%
		\ifx\pgfplots@loc@TMPa\pgfplotsplothandlercontourprepared@matlabformat@meta
			% oh. We have two successive segments of the SAME contour
			% level. Call the jump handler:
			\pgfplotsscanlinecomplete
		\fi
		%
	\else
		\let\pgfplots@current@point@z=\pgfplotsplothandlercontourprepared@matlabformat@meta
		\let\pgfplots@current@point@meta=\pgfplotsplothandlercontourprepared@matlabformat@meta
		\pgfplotsplothandlersurveypoint@contour
		\pgfplotsutil@advancestringcounter\c@pgfplotsplothandlercontourprepared@matlabformat@cur
	\fi
}%

\def\pgfplotsplothandlersurveypoint@contour{%
	%
	\pgfplotsplothandlersurveypoint@contour@axes@reordered@to@std
	%
	\pgfplotsplothandlersurveypoint@default
}

\def\pgfplotsplothandlersurveyend@contour{%
	\pgfplotsplothandlercontour@init@limits
	\ifx\pgfplotsplothandlercontour@limits@low@meta\pgfutil@empty
	\else
		\pgfplotsaxisupdatelimitsforpointmeta\pgfplotsplothandlercontour@limits@low@meta
	\fi
}%

\def\pgfplotsplothandlervisstart@contour{%
	%
	\ifpgfplotsplothandlercontour@labels
		\pgfkeysgetvalue{/pgfplots/contour/label distance}\pgfplotsplothandlercontour@labeldist
		\pgfmathparse{\pgfplotsplothandlercontour@labeldist}%
		\edef\pgfplotsplothandlercontour@labeldist{\pgfmathresult pt}%
		%
		\pgfplotsapplistXnewempty\pgfplotsplothandlercontour@storedlabels
		\let\pgfplotsplothandlercontour@handlesplinesegment=\pgfplotsplothandlercontour@handlesplinesegment@forlabels
	\else
		\def\pgfplotsplothandlercontour@handlesplinesegment##1##2##3{}%
	\fi
	%
	\ifpgfplotsplothandlercontour@filled
		\pgfseteorule
		\let\pgfplotsplothandlercontour@sequence@sort@cmp=\pgfutil@empty
		\pgfplotsapplistXnewempty\pgfplotsplothandlercontour@stored@lastcontourpath
		\pgfplotsplothandlercontour@init@limits
	\fi
	%
	\pgfplotsresetplothandler
	\pgfplotsset{/pgfplots/contour/handler}%
	\tikz@plot@handler
	%
	\def\pgfplotsplothandlercontour@haspendingjump{0}%
	\let\pgfplotsplothandlervisualizejump=\pgfplotsplothandlercontour@jump
	%
	\let\pgfplotsplothandlercontour@handler@start=\pgf@plotstreamstart
	\let\pgfplotsplothandlercontour@lastcontour=\pgfutil@empty
	\global\let\pgf@plotstreampoint=\pgfplotsplothandlercontour@streampoint
	\global\let\pgf@plotstreamend=\pgfplotsplothandlercontour@streamend
}%

\def\pgfplotsplothandlercontour@jump{%
	\def\pgfplotsplothandlercontour@haspendingjump{1}%
}%

\def\pgfplotsplothandlercontour@streamend{%
	\ifx\pgfplotsplothandlercontour@lastcontour\pgfutil@empty
	\else
		%
		\def\pgfplotsplothandlercontour@haspendingjump{0}% important! (this is a different case than a jump)
		\pgfplotsplothandlercontour@finishcontourline
		%
		\ifpgfplotsplothandlercontour@filled
			\if0\pgfplotsplothandlercontour@processed@outer
				\pgfplotsplothandlercontour@stream@bbcontour
				\pgfplotsplothandlercontour@finishcontourline
			\fi
		\fi
		%
		\ifpgfplotsplothandlercontour@labels
			\scope[/pgfplots/contour/every contour label]
			\let\pgfplots@restore@drawmodes=\relax% FIXME : necessary?
			\pgfplotsapplistXlet\pgfplotsplothandlercontour@storedlabels@=\pgfplotsplothandlercontour@storedlabels
			\pgfplotsapplistXnewempty\pgfplotsplothandlercontour@storedlabels
			\expandafter\pgfplotsplothandlercontourplacelabels\pgfplotsplothandlercontour@storedlabels@\pgfplots@EOI
			\endscope
		\fi
	\fi
}%
\def\pgfplotsplothandlercontour@check@bbcontour{%
	\ifpgfplotsplothandlercontour@filled
		\if0\pgfplotsplothandlercontour@processed@outer
			\pgfplotscoordmath{meta}{if less than}
				{\pgfplotsplothandlercontour@act@contour}
				{\pgfplotsplothandlercontour@limits@low@meta}
				{%
					% TRUE!
					\pgfplotsplothandlercontour@stream@bbcontour@inbetween
				}{}%
		\fi
	\fi
}%
\def\pgfplotsplothandlercontour@stream@bbcontour@inbetween{%
	\def\pgfplotsplothandlercontour@processed@outer{1}%
}%

\def\pgfplotsplothandlercontour@stream@bbcontour{%
%\message{contour: processing OUTER data limit contour...}%
	\def\pgfplotsplothandlercontour@haspendingjump{0}% important
	%
	% forbid labels:
	\let\pgfplotsplothandlercontour@stream@bbcontour@oldlabelsetting=\pgfplotsplothandlercontour@handlesplinesegment
	\def\pgfplotsplothandlercontour@handlesplinesegment##1##2##3{}%
	%
	\let\pgfplots@current@point@meta=\pgfplotsplothandlercontour@limits@low@meta
	\pgfplotsplothandlercontour@streampoint{%
		\pgfplotsplothandlerpointxyz
			\pgfplotsplothandlercontour@limits@low@x
			\pgfplotsplothandlercontour@limits@low@y
			\pgfplotsplothandlercontour@limits@low@z
	}%
	\pgfplotsplothandlercontour@streampoint{%
		\pgfplotsplothandlerpointxyz
			\pgfplotsplothandlercontour@limits@high@x
			\pgfplotsplothandlercontour@limits@low@y
			\pgfplotsplothandlercontour@limits@low@z
	}%
	\pgfplotsplothandlercontour@streampoint{%
		\pgfplotsplothandlerpointxyz
			\pgfplotsplothandlercontour@limits@high@x
			\pgfplotsplothandlercontour@limits@high@y
			\pgfplotsplothandlercontour@limits@low@z
	}%
	\pgfplotsplothandlercontour@streampoint{%
		\pgfplotsplothandlerpointxyz
			\pgfplotsplothandlercontour@limits@low@x
			\pgfplotsplothandlercontour@limits@high@y
			\pgfplotsplothandlercontour@limits@low@z
	}%
	\pgfplotsplothandlercontour@streampoint{%
		\pgfplotsplothandlerpointxyz
			\pgfplotsplothandlercontour@limits@low@x
			\pgfplotsplothandlercontour@limits@low@y
			\pgfplotsplothandlercontour@limits@low@z
	}%
	\def\pgfplotsplothandlercontour@processed@outer{1}%
	%
	% restore labels:
	\let\pgfplotsplothandlercontour@handlesplinesegment=\pgfplotsplothandlercontour@stream@bbcontour@oldlabelsetting
}%
\def\pgfplotsplothandlercontourplacelabels#1{%
	\def\pgfplots@loc@TMPa{#1}%
	\ifx\pgfplots@loc@TMPa\pgfplots@EOI
	\else
		%
		\pgfplotsplothandlercontourplacelabels@act#1\relax
		%
		\expandafter\pgfplotsplothandlercontourplacelabels
	\fi
}%
\def\pgfplotsplothandlercontourplacelabels@act#1,#2;#3,#4;#5\relax{%
	\begingroup
	\def\pgfplots@current@point@meta{#5}%
	\pgfplotsaxisvisphasetransformpointmeta
	\pgfplotscolormapdefinemappedcolor{\pgfplotspointmetatransformed}%
	%
	\pgftransformlineattime{0.5}{\pgfqpoint{#1}{#2}}{\pgfqpoint{#3}{#4}}%
	\pgfkeysvalueof{/pgfplots/contour/label node code/.@cmd}#5\pgfeov
	\endgroup
}%

\def\pgfplotsplothandlercontour@streampoint#1{%
	\pgf@process{#1}%
	% remember point:
	\edef\pgfplotsplothandlercontour@act@canvas{\pgf@x=\the\pgf@x\space\pgf@y=\the\pgf@y\space}%
	%
	\let\pgfplotsplothandlercontour@act@contour=\pgfplots@current@point@meta
	\ifx\pgfplotsplothandlercontour@act@contour\pgfutil@empty
		% oh. No Z data!? That should not happen!
		\pgfplotsplothandlercontour@empty@pointmeta@error
	\fi
	\ifx\pgfplotsplothandlercontour@lastcontour\pgfutil@empty
		% oh. its the very first point.
		\def\pgfplotsplothandlercontour@haspendingjump{0}% important! (this is a different case than a jump)
		\pgfplotsplothandlercontour@preparenewcontourline
	\else
		\ifx\pgfplotsplothandlercontour@lastcontour\pgfplotsplothandlercontour@act@contour
			% belongs to the same contour.
			\if1\pgfplotsplothandlercontour@haspendingjump
				\pgfplotsplothandlercontour@finishcontourline
				\pgfplotsplothandlercontour@preparenewcontourline
			\fi
		\else
			% oh, a new contour line.
			\def\pgfplotsplothandlercontour@haspendingjump{0}% important! (this is a different case than a jump)
			\pgfplotsplothandlercontour@finishcontourline
			\pgfplotsplothandlercontour@check@bbcontour
			\pgfplotsplothandlercontour@preparenewcontourline
		\fi
	\fi
	%
	%
	% handle difference vector for label placement:
	\ifx\pgfplotsplothandlercontour@lastcanvas\pgfutil@empty
	\else
		\pgfplotsplothandlercontour@handlesplinesegment
			{\pgfplotsplothandlercontour@lastcanvas}
			{\pgfplotsplothandlercontour@act@canvas}%
			{\pgfplotsplothandlercontour@act@contour}%
	\fi
	%
	\pgfplotsplothandlercontour@handler@streampoint{\pgfplotsplothandlercontour@act@canvas}%
	\let\pgfplotsplothandlercontour@lastlastcanvas=\pgfplotsplothandlercontour@lastcanvas
	\let\pgfplotsplothandlercontour@lastcanvas=\pgfplotsplothandlercontour@act@canvas
	\let\pgfplotsplothandlercontour@lastcontour=\pgfplotsplothandlercontour@act@contour
	%
	\ifpgfplotsplothandlercontour@filled
		\t@pgfplots@toka=\expandafter{\expandafter{\pgfplotsplothandlercontour@act@canvas}}%
		\expandafter\pgfplotsapplistXpushback\expandafter\pgf@plotstreampoint\the\t@pgfplots@toka
			\to\pgfplotsplothandlercontour@stored@lastcontourpath
	\fi
	%
	\ifx\pgf@plotstreampoint\pgfplotsplothandlercontour@streampoint
	\else
		\let\pgfplotsplothandlercontour@handler@streampoint=\pgf@plotstreampoint
	\fi
	\global\let\pgf@plotstreampoint=\pgfplotsplothandlercontour@streampoint
	\global\let\pgf@plotstreamend=\pgfplotsplothandlercontour@streamend
	% ATTENTION : if the low level plot handler introduces extra
	% levels of scopes, this *will* fail!
}%

%
% #1 : source
% #2 : target
% #3 : contour value
\def\pgfplotsplothandlercontour@handlesplinesegment@forlabels#1#2#3{%
	#2%
	\pgf@xb=\pgf@x
	\pgf@yb=\pgf@y
	#1%
	\pgf@xc=\pgf@x
	\pgf@yc=\pgf@y
	\pgfpointdiff
		{\pgf@x=\pgf@xc \pgf@y=\pgf@yc}
		{\pgf@x=\pgf@xb \pgf@y=\pgf@yb}%
	\edef\pgfplots@loc@TMPa{{\pgf@sys@tonumber\pgf@x}{\pgf@sys@tonumber\pgf@y}}%
	\expandafter\pgfmath@basic@veclen@\pgfplots@loc@TMPa
	\pgf@xa=\pgfmathresult pt
	%
	\advance\pgf@xa by\pgfplotsplothandlercontour@len\relax
	\edef\pgfplotsplothandlercontour@len{\the\pgf@xa}%
%\message{contour(\pgfplotsplothandlercontour@act@contour): cur len=\pgfplotsplothandlercontour@len > \pgfplotsplothandlercontour@labeldist ? [segment from #1--#2];}%
	\ifdim\pgf@xa>\pgfplotsplothandlercontour@labeldist\relax
		\def\pgfplotsplothandlercontour@haslabel{1}%
		\edef\pgfplots@loc@TMPa{{\the\pgf@xc,\the\pgf@yc;\the\pgf@xb,\the\pgf@yb;{#3}}}%
		\expandafter\pgfplotsapplistXpushback\expandafter{\pgfplots@loc@TMPa}\to\pgfplotsplothandlercontour@storedlabels
		\advance\pgf@xa by-\pgfplotsplothandlercontour@labeldist\relax
		\edef\pgfplotsplothandlercontour@len{\the\pgf@xa\relax}%
	\fi
}%

% #1: the transformed point meta of the last contour.
\def\pgfplotsplothandlercontour@filled@assert@is@sorted#1{%
	\ifx\pgfplotsplothandlercontour@lastcontour\pgfutil@empty
	\else
		\ifx\pgfplotsplothandlercontour@sequence@sort@cmp\pgfutil@empty
			% we need to determine the sorting:
			\pgfplotscoordmath{float}{if less than}{\pgfplotsplothandlercontour@lastcontour}{\pgfplots@current@point@meta}{%
				\def\pgfplotsplothandlercontour@sequence@sort@cmp{+}%
			}{%
				\pgfplotscoordmath{float}{if less than}{\pgfplots@current@point@meta}{\pgfplotsplothandlercontour@lastcontour}{%
					\def\pgfplotsplothandlercontour@sequence@sort@cmp{-}%
				}{%
					% undecided - the contours have the same label.
				}%
			}%
		\else
			\if +\pgfplotsplothandlercontour@sequence@sort@cmp
				\pgfplotscoordmath{float}{if less than}{\pgfplots@current@point@meta}{\pgfplotsplothandlercontour@lastcontour}{%
					\pgfplotsplothandlercontour@filled@assert@is@sorted@fail{ASCENDING}%
				}{%
				}%
			\else
				\pgfplotscoordmath{float}{if less than}{\pgfplotsplothandlercontour@lastcontour}{\pgfplots@current@point@meta}{%
					\pgfplotsplothandlercontour@filled@assert@is@sorted@fail{DESCENDING}%
				}{%
				}%
			\fi
		\fi
	\fi
}%
\def\pgfplotsplothandlercontour@filled@assert@is@sorted@fail#1{%
	\begingroup
	\pgfplotscoordmath{float}{tostring}{\pgfplots@current@point@meta}%
	\let\offending=\pgfmathresult
	\pgfplotscoordmath{float}{tostring}{\pgfplotsplothandlercontour@lastcontour}%
	\let\lastcontour=\pgfmathresult
	\pgfplots@error{Sorry, filled contours implicitly assume that the contour levels are SORTED (in the given case, they appear to be sorted in #1 order). Please make sure your input data has sorted contour levels. The offending level is \offending; the previous contour level is \lastcontour}%
	\endgroup
}
\def\pgfplotsplothandlercontour@preparenewcontourline{%
	\if0\pgfplotsplothandlercontour@haspendingjump
%\message{PREPARE NEW CONTOUR LEVEL (\pgfplots@current@point@meta).}%
		% a completely new level has been
		% started, not due to jumps inside of one level.
		%
		\let\pgfplotspointmetatransformed@lastcontour=\pgfplotspointmetatransformed
		% thus, we need to compute 'mapped color':
		\pgfplotsaxisvisphasetransformpointmeta
		\pgfplotscolormapdefinemappedcolor{\pgfplotspointmetatransformed}%
		\pgfsetstrokecolor{\pgfkeysvalueof{/pgfplots/contour/draw color}}%
		\ifpgfplotsplothandlercontour@filled
			\pgfplotsplothandlercontour@filled@assert@is@sorted{\pgfplotspointmetatransformed@lastcontour}%
			\pgfsetfillcolor{\pgfkeysvalueof{/pgfplots/contour/fill color}}%
		\fi
		%
		% furthermore, we need to handle the 'filled' style:
		\ifpgfplotsplothandlercontour@filled
			\pgfplotsapplistXlet\pgfplotsplothandlercontour@stored@lastcontourpath@=\pgfplotsplothandlercontour@stored@lastcontourpath
			% flush:
			\pgfplotsapplistXnewempty\pgfplotsplothandlercontour@stored@lastcontourpath
			%
			% process it:
			\ifx\pgfplotsplothandlercontour@stored@lastcontourpath@\pgfutil@empty
				% oh. This here is the very first contour. Nothing to do!
			\else
				% ok. This here is the i'th contour level, i>0.
				% Thus, we have the 'i-1'th contour stored.
				% REPLICATE its path to fill the space between the (i-1)'th contour and the i'th one!
				\let\pgf@plotstreamstart=\pgfplotsplothandlercontour@handler@start
				\pgf@plotstreamstart
				\pgfplotsplothandlercontour@stored@lastcontourpath@
				\pgf@plotstreamend
			\fi
		\fi
	\else
%\message{PREPARE NEW CONTOUR for the already begun level \pgfplots@current@point@meta.}%
		\ifpgfplotsplothandlercontour@filled
			\pgfplotsapplistXpushback\pgf@plotstreamstart\to\pgfplotsplothandlercontour@stored@lastcontourpath
		\fi
	\fi
	%
	\let\pgfplotsplothandlercontour@lastcanvas=\pgfutil@empty
	\let\pgfplotsplothandlercontour@lastlastcanvas=\pgfutil@empty
	\ifpgfplotsplothandlercontour@labels
		\def\pgfplotsplothandlercontour@haslabel{0}%
		% 
		% this here means that 20% of labeldist are already there.
		% it moves the first label nearer to its start.
		\pgf@xa=\pgfplotsplothandlercontour@labeldist\relax
		\pgf@xa=0.2\pgf@xa
		\edef\pgfplotsplothandlercontour@len{\the\pgf@xa}%
	\fi
	\def\pgfplotsplothandlercontour@haspendingjump{0}%
	%
	\pgfplotsplothandlercontour@handler@start
	\let\pgfplotsplothandlercontour@handler@end=\pgf@plotstreamend
	\let\pgfplotsplothandlercontour@handler@streampoint=\pgf@plotstreampoint
}%
\def\pgfplotsplothandlercontour@finishcontourline{%
	\ifpgfplotsplothandlercontour@labels
		\if0\pgfplotsplothandlercontour@haslabel
			\ifx\pgfplotsplothandlercontour@lastlastcanvas\pgfutil@empty
			\else
				% force a label:
%\message{FORCING A LABEL for contour \pgfplotsplothandlercontour@lastcontour\space from (\pgfplotsplothandlercontour@lastlastcanvas --\pgfplotsplothandlercontour@lastcanvas)}%
				\edef\pgfplotsplothandlercontour@len{\pgfplotsplothandlercontour@labeldist}%
				\pgfplotsplothandlercontour@handlesplinesegment
					{\pgfplotsplothandlercontour@lastlastcanvas}
					{\pgfplotsplothandlercontour@lastcanvas}%
					{\pgfplotsplothandlercontour@lastcontour}%
			\fi
		\fi
	\fi
	\pgfplotsplothandlercontour@handler@end
	%
%	\ifpgfplotsplothandlercontour@filled
%		\pgfpathclose % FIXME  this is, in general, not good enough.
%	\fi
	\if0\pgfplotsplothandlercontour@haspendingjump
%\message{usepath{} to finalize level \pgfplotsplothandlercontour@lastcontour.}%
		% flush paths if the complete contour level is ready.
		% do *not* flush paths if we have just a new part of the
		% existing contour level.
		%
		% This makes a difference for the filled contour.
		\ifpgfplotsplothandlercontour@filled
			\pgfusepath{fill,stroke}%
		\else
			\pgfusepath{stroke}%
		\fi
	\else
%\message{usepath{} for level \pgfplotsplothandlercontour@lastcontour.}%
		\ifpgfplotsplothandlercontour@filled
			\pgfplotsapplistXpushback\pgf@plotstreamend\to\pgfplotsplothandlercontour@stored@lastcontourpath
		\fi
	\fi
}%

\def\pgfplotsplothandlercontour@init@limits{%
	\def\pgfplotsplothandlercontour@processed@outer{0}%
	\let\pgfplotsplothandlercontour@limits@low@meta=\pgfutil@empty
	\let\pgfplotsplothandlercontour@limits@low@x=\pgfutil@empty
	\let\pgfplotsplothandlercontour@limits@low@y=\pgfutil@empty
	\let\pgfplotsplothandlercontour@limits@low@z=\pgfutil@empty
	\let\pgfplotsplothandlercontour@limits@high@meta=\pgfutil@empty
	\let\pgfplotsplothandlercontour@limits@high@x=\pgfutil@empty
	\let\pgfplotsplothandlercontour@limits@high@y=\pgfutil@empty
	\let\pgfplotsplothandlercontour@limits@high@z=\pgfutil@empty
	%
	\pgfkeysgetvalue{/pgfplots/contour/data limits}\pgfplots@loc@TMPa
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\def\pgfplotsplothandlercontour@processed@outer{1}%
	\else
		\expandafter\pgfplotsplothandlercontour@init@limits@getboundingboxlow\pgfplots@loc@TMPa\pgfplots@EOI
	\fi
%\message{contour: I processed data limits to MIN = (\pgfplotsplothandlercontour@limits@low@x,\pgfplotsplothandlercontour@limits@low@y,\pgfplotsplothandlercontour@limits@low@z;\pgfplotsplothandlercontour@limits@low@meta) and MAX = (\pgfplotsplothandlercontour@limits@high@x,\pgfplotsplothandlercontour@limits@high@y,\pgfplotsplothandlercontour@limits@high@z;\pgfplotsplothandlercontour@limits@high@meta).}%
}%
\def\pgfplotsplothandlercontour@init@limits@getboundingboxlow(#1,#2,#3,#4){%
	\def\pgfplotsplothandlercontour@init@limits@cur{low}%
	\pgfplotsplothandlercontour@init@limits@read(#1,#2,#3,#4)%
	\pgfutil@ifnextchar(%
		\pgfplotsplothandlercontour@init@limits@getboundingboxhigh
		{\pgfplots@error{Sorry, 'data limits=(xmin,ymin,zmin,contourmin) (xmax,ymax,zmax,contourmax)' has been expected, not \pgfkeysvalueof{/pgfplots/contour/data limits}}\pgfplots@gobble@until@EOI}%
}%
\def\pgfplotsplothandlercontour@init@limits@getboundingboxhigh(#1,#2,#3,#4){%
	\def\pgfplotsplothandlercontour@init@limits@cur{high}%
	\pgfplotsplothandlercontour@init@limits@read(#1,#2,#3,#4)%
	\pgfutil@gobble
}%
\def\pgfplotsplothandlercontour@init@limits@read(#1,#2,#3,#4){%
	% FIXME : logs and trafos and user interface!
	\pgfplotscoordmath{x}{parsenumber}{#1}%
	\pgfplotscoordmath{x}{datascaletrafo}\pgfmathresult
	\expandafter\let\csname pgfplotsplothandlercontour@limits@\pgfplotsplothandlercontour@init@limits@cur @x\endcsname=\pgfmathresult
	%
	\pgfplotscoordmath{y}{parsenumber}{#2}%
	\pgfplotscoordmath{y}{datascaletrafo}\pgfmathresult
	\expandafter\let\csname pgfplotsplothandlercontour@limits@\pgfplotsplothandlercontour@init@limits@cur @y\endcsname=\pgfmathresult
	%
	\ifpgfplots@curplot@threedim
		\pgfplotscoordmath{z}{parsenumber}{#3}%
		\pgfplotscoordmath{z}{datascaletrafo}\pgfmathresult
		\expandafter\let\csname pgfplotsplothandlercontour@limits@\pgfplotsplothandlercontour@init@limits@cur @z\endcsname=\pgfmathresult
	\fi
	%
	\pgfplotscoordmath{meta}{parsenumber}{#4}%
	\expandafter\let\csname pgfplotsplothandlercontour@limits@\pgfplotsplothandlercontour@init@limits@cur @meta\endcsname=\pgfmathresult
}%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% contour external implementation
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\def\pgfplotsplothandlercontourexternal{%
	\pgfplotsresetplothandler
	\def\pgfplotsplothandlername{contour external}%
	%
	\pgfplotsplothandlercontour@prepare@point@meta
	%
	\let\pgfplotsplothandlersurveystart=\pgfplotsplothandlersurveystart@contourexternal
	\def\pgf@plotstreamstart{%
		\pgfplotsplothandlercontourprepared
		\pgf@plotstreamstart
	}%
}%
\gdef\c@pgfplotsplothandlersurveystart@contourexternal@fileno{0}%
\def\pgfplotsplothandlersurveystart@contourexternal{%
	%
	\pgfkeysgetvalue{/pgfplots/contour external/file}\pgfplotsplothandlercontourexternal@file
	%
	\ifx\pgfplotsplothandlercontourexternal@file\pgfutil@empty
		\pgfutil@ifundefined{pgfactualjobname}{%
			\let\pgfplots@loc@TMPa=\jobname
		}{%
			% be compatible with external lib:
			\let\pgfplots@loc@TMPa=\pgfactualjobname
		}%
		\edef\pgfplotsplothandlercontourexternal@file{\pgfplots@loc@TMPa_contourtmp\c@pgfplotsplothandlersurveystart@contourexternal@fileno}%
		\pgfplotsutil@advancestringcounter@global\c@pgfplotsplothandlersurveystart@contourexternal@fileno
	\fi
	%
	\if0\pgfplotsplothandlercontourexternal@scanlinemode
		\pgfplotsset{plot to file/scanline marks/false}%
	\else	
		\pgfplotsset{plot to file/scanline marks/if in input}% the choice 'always' is unaware of existing end-of-scanline marks
	\fi
	\pgfplotsplothandlertofile{\pgfplotsplothandlercontourexternal@file.dat}%
	\pgfplotsplothandlersurveystart
	\let\pgfplotsplothandlersurveypoint@tofile=\pgfplotsplothandlersurveypoint
	\let\pgfplotsplothandlersurveyend@tofile=\pgfplotsplothandlersurveyend
	\let\pgfplotsplothandlersurveypoint=\pgfplotsplothandlersurveypoint@contourexternal
	\let\pgfplotsplothandlersurveyend=\pgfplotsplothandlersurveyend@contourexternal
	%
	\pgfplotsplothandlersurveypoint@contour@prepare@axes x%
	\pgfplotsplothandlersurveypoint@contour@prepare@axes y%
	\pgfplotsplothandlersurveypoint@contour@prepare@axes z%
}%

% #1: either x, y, or z
% POSTCONDITION:
% 	The following three macros are defined:
%   \pgfplotsplothandlersurveypoint@contour@set@axes@x
%   \pgfplotsplothandlersurveypoint@contour@set@axes@y
%   \pgfplotsplothandlersurveypoint@contour@set@axes@z
%   they take no arguments and assign their result to \pgfmathresult.
\def\pgfplotsplothandlersurveypoint@contour@prepare@axes#1{%
	\expandafter\edef\csname pgfplotsplothandlersurveypoint@contour@set@axes@#1\endcsname{%
		\noexpand\let\noexpand\pgfmathresult=\expandafter\noexpand\csname pgfplots@current@point@\csname pgfplotsplothandlercontour@axis@#1\endcsname\endcsname
	}%
	\expandafter\edef\csname pgfplotsplothandlersurveypoint@contour@set@axes@@#1\endcsname{%
		\noexpand\let\noexpand\pgfmathresult=\expandafter\noexpand\csname pgfplots@current@point@\csname pgfplotsplothandlercontour@axis@inv@#1\endcsname\endcsname
	}%
	%
%\message{axes #1: STD -> \expandafter\meaning\csname pgfplotsplothandlersurveypoint@contour@set@axes@#1\endcsname^^J}%
%\message{axes #1: INV -> \expandafter\meaning\csname pgfplotsplothandlersurveypoint@contour@set@axes@@#1\endcsname^^J}%
}

\def\pgfplotsplothandlersurveypoint@contour@axes@reordered@to@std{%
	\pgfplotsplothandlersurveypoint@contour@set@axes@@x
	\let\pgfplotsplothandlersurveypoint@contour@set@axes@x@=\pgfmathresult
	%
	\pgfplotsplothandlersurveypoint@contour@set@axes@@y
	\let\pgfplotsplothandlersurveypoint@contour@set@axes@y@=\pgfmathresult
	%
	\pgfplotsplothandlersurveypoint@contour@set@axes@@z
	\let\pgfplotsplothandlersurveypoint@contour@set@axes@z@=\pgfmathresult
	%
	\let\pgfplots@current@point@x=\pgfplotsplothandlersurveypoint@contour@set@axes@x@
	\let\pgfplots@current@point@y=\pgfplotsplothandlersurveypoint@contour@set@axes@y@
	\let\pgfplots@current@point@z=\pgfplotsplothandlersurveypoint@contour@set@axes@z@
}%
\def\pgfplotsplothandlersurveypoint@contour@axes@std@to@reordered{%
	\pgfplotsplothandlersurveypoint@contour@set@axes@x
	\let\pgfplotsplothandlersurveypoint@contour@set@axes@x@=\pgfmathresult
	%
	\pgfplotsplothandlersurveypoint@contour@set@axes@y
	\let\pgfplotsplothandlersurveypoint@contour@set@axes@y@=\pgfmathresult
	%
	\pgfplotsplothandlersurveypoint@contour@set@axes@z
	\let\pgfplotsplothandlersurveypoint@contour@set@axes@z@=\pgfmathresult
	%
	\let\pgfplots@current@point@x=\pgfplotsplothandlersurveypoint@contour@set@axes@x@
	\let\pgfplots@current@point@y=\pgfplotsplothandlersurveypoint@contour@set@axes@y@
	\let\pgfplots@current@point@z=\pgfplotsplothandlersurveypoint@contour@set@axes@z@
}%

\def\pgfplotsplothandlersurveypoint@contourexternal{%
	% temporarily disable updates to point meta limits. They should be
	% updated during the contour prepared processing.
	\let\pgfplotsplothandlercontourexternal@orig@perpointlimits@limits=\pgfplots@set@perpointmeta@limits
	\let\pgfplots@set@perpointmeta@limits=\relax
	%
	\pgfplotsaxissurveysetpointmeta
	\let\pgfplots@current@point@z=\pgfplots@current@point@meta
	%
	\let\pgfplots@set@perpointmeta@limits=\pgfplotsplothandlercontourexternal@orig@perpointlimits@limits
	%
	\pgfplotsplothandlersurveypoint@contour@axes@std@to@reordered
	%
%\message{contour gnuplot: collecting point (\pgfplots@current@point@x,\pgfplots@current@point@y,\pgfplots@current@point@z) [\pgfplots@current@point@meta]...}%
	\pgfplotsplothandlersurveypoint@tofile
}%

{
\catcode`\`=12
\catcode`\'=12
\catcode`\"=12
\catcode`\|=12
\catcode`\;=12
\catcode`\:=12
\catcode`\#=12
\gdef\pgfplotsplothandlersurveyend@contourexternal{%
	\pgfplotsplothandlersurveyend@tofile
	\if2\pgfplotsplothandlercontourexternal@scanlinemode
		\if0\pgfplotsplothandlertofilegeneratedscanlinemarks
			\pgfplots@error{Sorry, processing the input stream did not lead to end-of-scanline markers; the generated temporary file for 'contour external' does not contain any of them (indicating that matrix structure is lost). To fix this, you have the following options:^^J - Insert end-of-scanline markers into your input data (i.e. empty lines),^^J - provide two of the three options 'mesh/rows=<num matrix rows>, mesh/cols=<num matrix cols>, mesh/num points=<total number points>'}%
		\fi
	\fi
	%
	\begingroup
	\let\numcoords=\pgfplots@current@point@coordindex%
	\pgfplotsautocompletemeshkeys
	\def\"{"}%
	\def\|{|}%
	\def\;{;}%
	\def\:{:}%
	\def\#{#}%
	\def\'{'}%
	\def\`{`}%
	\edef\ordering{\pgfplots@plot@mesh@ordering}%
	\edef\infile{\pgfplotsplothandlercontourexternal@file.dat}%
	\edef\outfile{\pgfplotsplothandlercontourexternal@file.table}%
	\edef\script{\pgfplotsplothandlercontourexternal@file.\pgfkeysvalueof{/pgfplots/contour external/script extension}}%
	\edef\thecontourlevels{\pgfkeysvalueof{/pgfplots/contour/levels}}%
	\edef\thecontournumber{\pgfkeysvalueof{/pgfplots/contour/number}}%
	\immediate\openout\w@pgf@writea=\script
	\immediate\write\w@pgf@writea{\pgfkeysvalueof{/pgfplots/contour external/script}}%
	\immediate\closeout\w@pgf@writea
	%
	\immediate\write18{\pgfkeysvalueof{/pgfplots/contour external/cmd}}%
	\endgroup
	%
	%
	\pgfplotsplothandlercontourprepared
	% the PREPARE steps in the coord stream start/end have already
	% been done. we only need to init the plot handler survey
	% start/end:
	\def\pgfplots@coord@stream@start{\pgfplotsplothandlersurveystart}%
	\def\pgfplots@coord@stream@end{\pgfplotsplothandlersurveyend}%
	\pgfkeysgetvalue{/pgfplots/contour external/output point meta}\pgfplots@loc@TMPa
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\ifpgfplots@curplot@threedim
			\pgfplotssetpointmetainput{z}{}%
		\else
			\pgfplotssetpointmetainput{explicit}{}%
		\fi
	\else
		\expandafter\pgfplots@pgfkeys@set@point@meta@value\expandafter{\pgfplots@loc@TMPa}%
	\fi
	\pgfplots@addplotimpl@file@streamit{\pgfplotsplothandlercontourexternal@file.table}%
	\closein\r@pgfplots@reada
}%
}

		



% the `plot unprocessed to file' plot handler simply copies the input data
% UNPROCESSED to an output file.
%
% I use it as helper tool for `contour gnuplot'.
%
% this cannot be combined with other plot handlers unless the other
% plot handlers controls that explicitly
%
% Immediately after the survey ends, this plot handler will set
% \pgfplotsplothandlertofilegeneratedscanlinemarks to '1' or '0'.
\pgfplotsset{
	plot unprocessed to file/.code={
		\edef\tikz@plot@handler{\noexpand\pgfplotsplothandlertofile{#1}}%
	},
	plot to file/scanline marks/.is choice,
	plot to file/scanline marks/false/.code={\def\pgfplotsplothandlertofile@scanlinemarks{0}},
	plot to file/scanline marks/if in input/.code={\def\pgfplotsplothandlertofile@scanlinemarks{1}},
	plot to file/scanline marks/always/.code={\def\pgfplotsplothandlertofile@scanlinemarks{2}},
	plot to file/scanline marks/true/.code={\def\pgfplotsplothandlertofile@scanlinemarks{2}},
	plot to file/scanline marks/if in input,
	plot to file/col sep/.initial=\pgfplots@SPACE,
	plot to file/end-of-scanline content/.initial=,
}

\def\pgfplotsplothandlertofile#1{%
	\edef\pgfplotsplothandlertofile@name{#1}%
	\pgfplotsresetplothandler
	\pgfplotsset{empty line=scanline}%
	\let\pgfplotsplothandlersurveystart=\pgfplotsplothandlersurveystart@tofile
	\def\pgfplotsplothandlername{plot to file}%
	\let\pgfplotsplothandlersurveyend=\pgfplotsplothandlersurveyend@tofile
	\let\pgfplotsplothandlersurveypoint=\pgfplotsplothandlersurveypoint@tofile
	\let\pgfplotsplothandlernotifyscanlinecomplete=\pgfplotsplothandlernotifyscanlinecomplete@tofile
	%
	\if1\pgfplotsplothandlertofile@scanlinemarks
		% plot to file/scanline marks=if in input
		% check if we have mesh input:
		\def\pgfplots@loc@TMP@has@mesh@information{0}%
		\pgfkeysgetvalue{/pgfplots/mesh/rows}\pgfplots@loc@TMPa
		\pgfkeysgetvalue{/pgfplots/mesh/cols}\pgfplots@loc@TMPb
		\pgfkeysgetvalue{/pgfplots/mesh/num points}\pgfplots@loc@TMPc
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
			\ifx\pgfplots@loc@TMPc\pgfutil@empty
			\else
				% has rows and num points:
				\def\pgfplots@loc@TMP@has@mesh@information{1}%
			\fi
		\else
			\ifx\pgfplots@loc@TMPb\pgfutil@empty
				\ifx\pgfplots@loc@TMPc\pgfutil@empty
				\else
					% has cols and num points:
					\def\pgfplots@loc@TMP@has@mesh@information{1}%
				\fi
			\else
				% has rows,cols:
				\def\pgfplots@loc@TMP@has@mesh@information{1}%
			\fi
		\fi
		\if1\pgfplots@loc@TMP@has@mesh@information
			% activate 'plot to file/scanline marks=always
			% --> we have the required information!
			\def\pgfplotsplothandlertofile@scanlinemarks{2}%
		\fi
	\fi
	% NO \else here!
	\if2\pgfplotsplothandlertofile@scanlinemarks
		% plot to file/scanline marks=always
		\pgfplotsautocompletemeshkeys%
		\def\c@pgfplotsplothandlertofile@scanlinelength{0}%
		\if\pgfplots@plot@mesh@ordering0%
			% ordering = x varies= rowwise -> scanline is cols!
			\pgfkeysgetvalue{/pgfplots/mesh/cols}\c@pgfplotsplothandlertofile@expectedscanline
		\else
			% ordering = y varies = colwise: scanline is rows!
			\pgfkeysgetvalue{/pgfplots/mesh/rows}\c@pgfplotsplothandlertofile@expectedscanline
		\fi
	\fi
	\pgfplotsplothandlertofile@scanlinependingfalse
	\pgfkeysgetvalue{/pgfplots/plot to file/col sep}\pgfplotsplothandlertofile@colsep
	\pgfkeysgetvalue{/pgfplots/plot to file/end-of-scanline content}\pgfplotsplothandlertofile@scanlinemark
	%
	%
	\def\pgfplotsplothandlertofilegeneratedscanlinemarks{0}%
}%
\def\pgfplotsplothandlertofile@scanlinemarks@check{%
	\if2\pgfplotsplothandlertofile@scanlinemarks
		% plot to file/scanline marks=always
		\pgfplotsutil@advancestringcounter\c@pgfplotsplothandlertofile@scanlinelength
		\ifnum\c@pgfplotsplothandlertofile@scanlinelength=\c@pgfplotsplothandlertofile@expectedscanline
			\def\c@pgfplotsplothandlertofile@scanlinelength{0}%
			\pgfplotsplothandlernotifyscanlinecomplete@tofile
		\fi
	\fi
}%
\newif\ifpgfplotsplothandlertofile@scanlinepending
\def\pgfplotsplothandlernotifyscanlinecomplete@tofile{%
	\if0\pgfplotsplothandlertofile@scanlinemarks
	\else
		\pgfplotsplothandlertofile@scanlinependingtrue
	\fi
}%
\def\pgfplotsplothandlersurveypoint@tofile{%
	\ifpgfplotsplothandlertofile@scanlinepending
		\def\pgfplotsplothandlertofilegeneratedscanlinemarks{1}%
		\immediate\write\w@pgf@writea{\pgfplotsplothandlertofile@scanlinemark}% end-of-scanline
		\pgfplotsplothandlertofile@scanlinependingfalse
	\fi
	\pgfplotscoordmath{x}{parsenumber}{\pgfplots@current@point@x}%
	\pgfplotscoordmath{x}{tostring}{\pgfmathresult}%
	\let\pgfplots@current@point@x=\pgfmathresult
	%
	\pgfplotscoordmath{y}{parsenumber}{\pgfplots@current@point@y}%
	\pgfplotscoordmath{y}{tostring}{\pgfmathresult}%
	\let\pgfplots@current@point@y=\pgfmathresult
	%
	\ifpgfplots@curplot@threedim
		\pgfplotscoordmath{z}{parsenumber}{\pgfplots@current@point@z}%
		\pgfplotscoordmath{z}{tostring}{\pgfmathresult}%
		\let\pgfplots@current@point@z=\pgfmathresult
	\fi
	%
	\pgfplotsaxissurveysetpointmeta
	\pgfplotsaxisifhaspointmeta{%
		\pgfplotscoordmath{meta}{tostring}{\pgfplots@current@point@meta}%
		\let\pgfplots@current@point@meta=\pgfmathresult
	}{}%
	%
	\immediate\write\w@pgf@writea{%
		\pgfplots@current@point@x\pgfplotsplothandlertofile@colsep
		\pgfplots@current@point@y\pgfplotsplothandlertofile@colsep
		\ifpgfplots@curplot@threedim\pgfplots@current@point@z\pgfplotsplothandlertofile@colsep\fi
		\pgfplots@current@point@meta
	}%
	\advance\c@pgfplots@coordindex by1
	\pgfplotsplothandlertofile@scanlinemarks@check
}%
\def\pgfplotsplothandlersurveyend@tofile{%
	\immediate\closeout\w@pgf@writea
}%
\def\pgfplotsplothandlersurveystart@tofile{%
	\immediate\openout\w@pgf@writea=\pgfplotsplothandlertofile@name\relax
}%


\input pgfplotsmeshplothandler.code.tex

pgfplots.revision.tex
\begingroup
\catcode`\-=12
\catcode`\/=12
\catcode`\.=12
\catcode`\:=12
\catcode`\+=12
\catcode`\-=12
\gdef\pgfplotsrevision{1.11-3-g4c99d7a}
\gdef\pgfplotsversion{1.11}
\gdef\pgfplotsversiondatetime{2014-08-04 12:47:48 +0200}
\gdef\pgfplotsrevisiondatetime{2014-08-06 16:56:04 +0200}
\gdef\pgfplots@glob@TMPa#1-#2-#3 #4\relax{#1/#2/#3}
\xdef\pgfplotsversiondate{\expandafter\pgfplots@glob@TMPa\pgfplotsversiondatetime\relax}
\xdef\pgfplotsrevisiondate{\expandafter\pgfplots@glob@TMPa\pgfplotsrevisiondatetime\relax}
\endgroup

pgfplots.scaling.code.tex
%--------------------------------------------
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2007-2012 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------

% PRECONDITION: 
% 	- final axis limits are given in transformed range
% 	-  \pgfplots@set@default@size@options has been invoked before
% POSTCONDITION: 
% 	- the current x,y and z unit vectors are defined properly;
% 	- the fast-access registers are initialised for the axis limits,
%	- the following macros are assigned:
%		\pgfplots@[xyz]@veclength
%		\pgfplots@[xyz]@inverseveclength
%		\pgfplotspointxaxis
%		\pgfplotspointyaxis
%		\pgfplotspointzaxis
%		\pgfplotspointcenter
%		\pgfplotspointminminmin
%
\def\pgfplots@initsizes{%
	% INIT.
	%
	%
	\pgfplots@xmin@reg=\pgfplots@xmin pt %
	\pgfplots@xmax@reg=\pgfplots@xmax pt %
	\pgfplots@ymin@reg=\pgfplots@ymin pt %
	\pgfplots@ymax@reg=\pgfplots@ymax pt %
	\ifpgfplots@threedim
		\pgfplots@zmin@reg=\pgfplots@zmin pt %
		\pgfplots@zmax@reg=\pgfplots@zmax pt %
	\fi
	%
	%-----------------------------------------
	% PROCESS THE 'width' and 'height' options
	%-----------------------------------------
	%
	%
	\pgfkeysgetvalue{/pgfplots/view/az}{\pgfplots@view@az}%
	\pgfkeysgetvalue{/pgfplots/view/el}{\pgfplots@view@el}%
	\ifpgfplots@threedim
	\else
		\let\pgfplots@view@el=\pgfutil@empty
		\let\pgfplots@view@az=\pgfutil@empty
	\fi
	\ifx\pgfplots@view@az\pgfutil@empty
		% Note that in presence of "x,y,z" options, the
		% \pgfplots@set@default@size@options RESETS /pgfplots/view/az.
		%
		%\let\pgfplots@rectangle@width=\pgfutil@empty
		%\let\pgfplots@rectangle@height=\pgfutil@empty
		\pgfplotsmathvectorfromstring{0,0,1}{default}%
		\let\pgfplots@view@dir@threedim=\pgfplotsretval
		%
		\ifx\pgfplots@x\pgfutil@empty
			\ifx\pgfplots@width\pgfutil@empty
				\pgfplots@error{INTERNAL LOGIC ERROR! WIDTH NOT SET}%
			\fi
		\fi
		%
		\ifx\pgfplots@y\pgfutil@empty
			\ifx\pgfplots@height\pgfutil@empty
				\pgfplots@error{INTERNAL LOGIC ERROR! HEIGHT NOT SET}%
			\fi
		\fi
		\ifpgfplots@threedim
			\def\pgfplots@tmp@Zscale{1}%
		\else
			\def\pgfplots@tmp@Zscale{0}%
		\fi
		%
		\pgfplots@initsizes@setunitvector{x}{0}{1}{\pgfplots@tmp@xisaxisparallel}%
		\pgfplots@initsizes@setunitvector{y}{1}{1}{\pgfplots@tmp@yisaxisparallel}%
		\pgfplots@initsizes@setunitvector{z}{2}{\pgfplots@tmp@Zscale}{\pgfplots@loc@TMPc}%
		%
		\pgfplots@scaling@changewidthheight@for@enlargelimits@by@dimension%
		%
		\pgfplots@scale@plotbox@to@widthheight
	\else
		% 3D case by `view':
		\let\pgfplots@x=\pgfutil@empty
		\let\pgfplots@y=\pgfutil@empty
		\let\pgfplots@z=\pgfutil@empty
		\pgfplotssetaxesfromazel{\pgfplots@view@az}{\pgfplots@view@el}{\pgfplots@tmp@xisaxisparallel}%
		%
		\pgfplots@scaling@changewidthheight@for@enlargelimits@by@dimension%
		%
		\pgfplots@scale@plotbox@to@widthheight
		\if1\pgfplots@tmp@xisaxisparallel%
			\def\pgfplots@tmp@yisaxisparallel{1}%
		\fi
	\fi
	\pgfplots@computeunitvectorlengths
	%
	\pgfplots@scaling@apply@enlargelimits@by@dimension{x}%
	\pgfplots@scaling@apply@enlargelimits@by@dimension{y}%
	\ifpgfplots@threedim
		\pgfplots@scaling@apply@enlargelimits@by@dimension{z}%
	\fi
	%
	\ifpgfplots@threedim
		\pgfplotsgetnormalforcurrentview
	\fi
%\message{Pgfplots debug: initialised unit vectors to x=(\the\pgf@xx,\the\pgf@xy), y=(\the\pgf@yx,\the\pgf@yy), z=(\the\pgf@zx,\the\pgf@zy), n = (\pgfplots@view@dir@threedim). Limits are x=\pgfplots@xmin:\pgfplots@xmax, y=\pgfplots@ymin:\pgfplots@ymax^^J }%
	%
	\let\pgfplotsmathfloatviewdepthxyz@=\pgfplotsmathfloatviewdepthxyz@infigure
	\let\pgfplotsmathviewdepthxyz@=\pgfplotsmathviewdepthxyz@infigure
	%
	\pgfplotsmath@ifzero{\pgfplots@x@veclength}{\pgfplots@hide@xtrue\pgfplots@shownothingof@xtrue}{}%
	\pgfplotsmath@ifzero{\pgfplots@y@veclength}{\pgfplots@hide@ytrue\pgfplots@shownothingof@ytrue}{}%
	\ifpgfplots@threedim
		\pgfplotsmath@ifzero{\pgfplots@z@veclength}{\pgfplots@hide@ztrue\pgfplots@shownothingof@ztrue}{}%
	\else
		\if1\pgfplots@tmp@xisaxisparallel%
			\if1\pgfplots@tmp@yisaxisparallel%
				% Optimize for axis-parallel case!
				% puh. Did not make any measureable difference!? Ok...
				\let\pgfplotsqpointxy=\pgfplotsqpointxy@orthogonal
			\fi
		\fi
	\fi
}

% Defines \pgfmathresult to be the desired width without axis labels.
%
\def\pgfplots@initsizes@get@width@withoutlabels{%
	\pgfplots@initsizes@handle@label@const{\pgfplots@width}{45pt}{width}%
}

% Defines \pgfmathresult to be the desired height without axis labels.
\def\pgfplots@initsizes@get@height@withoutlabels{%
	\pgfplots@initsizes@handle@label@const{\pgfplots@height}{45pt}{height}%
}

\def\pgfplots@initsizes@handle@label@const#1#2#3{%
	\begingroup
	\pgf@xa=#1\relax
	% EXPECTED WIDTH = X = \pgfplots@width
	% ACTUAL WIDTH = c + x * (xmax-xmin)
	% where c is a CONSTANT (for the axis labels/tick labels).
	% -> \pgfplots@tmpXscale = (X - c) / (x *(xmax-xmin))
	%
	% \pgf@xa := X-c:
	\ifpgfplots@scale@only@axis
	\else
		\advance\pgf@xa by-#2 % FIXME determine 'c' correctly!
	\fi
	\ifdim\pgf@xa<0pt
		\pgfplots@error{Error: Plot #3 `#1' is too small. This cannot be implemented while maintaining constant size for labels. Sorry, label sizes are only approximate. You will need to adjust your #3.}%
		\pgf@xa=0pt
	\fi
	\edef\pgfmathresult{\the\pgf@xa}%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%

% #1: axis
\def\pgfplots@axis@apply@post@scale#1{%
	%
	\pgfkeysgetvalue{/pgfplots/#1 post scale}\pgfplots@loc@TMPd
	\ifx\pgfplots@loc@TMPd\pgfutil@empty
	\else
		\pgfmathparse{\csname pgfplots@target@unit@scale@#1x\endcsname*\pgfplots@loc@TMPd}%
		\expandafter\let\csname pgfplots@target@unit@scale@#1x\endcsname=\pgfmathresult
		%
		\pgfmathparse{\csname pgfplots@target@unit@scale@#1y\endcsname*\pgfplots@loc@TMPd}%
		\expandafter\let\csname pgfplots@target@unit@scale@#1y\endcsname=\pgfmathresult
	\fi
}

% Takes azimuth (horizontal angle) '#1' and elongation (vertical
% angle) '#2' (both in degrees) and computes 
% x,y and z vectors which define the view in the direction
% defined by '#1' and '#2'.
%
% 'azimuth' means a rotation around the viewport's x axis. 'elongation' means
% a rotation around the original coordinate system's z axis.
%
% The method works by computing 
% Az = [ cos(azimuth) -sin(azimuth) 0; ...
%     sin(azimuth) cos(azimuth) 0; ...
%     0 0 1 ];
% 
%
% Ax = [ 1 0 0; ...
%     0 cos(elevation) -sin(elevation) ;...
%     0 sin(elevation) cos(elevation) ];
%
% v= Ax * Az;
% = [ ...
% 	cosaz  -sinaz cosel  sinaz sinel; ...
% 	sinaz  cosaz cosel   -sinel cosaz; ...
% 	0	  sinel         cosel ];
%
% Then, we use the rotated XZ plane as viewport, that means 
%   xvec = v * [1 0 0]' = <first column of v>
%   zvec = v * [0 0 1]' = <third column of v>
% and we define the projection onto the twodimensional surface
% spanned by 'xvec' and 'zvec' as
%   P( q ) = [ q^T xvec,  q^T zvec ]'
% for q in R^3.
% As a consequence, we compute the three unit vectors as
%  x = P( [1 0 0] )
%  	 = [ cosaz,  sinaz sinel ]'
%  y = P( [0 1 0] )
%    = [ sinaz,  -sinel cosaz ]'
%  z = P( [0 0 1] )
%    = [ 0,  cosel]'
%
% Furthermore, the 3D view vector which points into the direction of the view
% is
%   n = v * [0 1 0 ]' = <second column of v> =  [-sinaz cosel,  cosaz cosel,  sinel]' 
% because the normal view point was the XZ plane with y as its normal
% vector.
% The 3D vector n is returned by this routine as well - it is
% necessary for some kind of z buffering (determining what is
% foreground and what is background).
%
% INPUT:
% - #1 : azimuth ("yaw")
% - #2 : elevation ("pitch")
% OUTPUT:
% - #3 : a macro which will be set to '1' if and only if 
%      the viewport is the standard XY axis (i.e. azimuth=0, elevation=90).
% - [xyz] vectors,
%   \pgfplots@view@dir@threedim will contain the three components
%   of 'n' (without the suffix 'pt', but in units of 'pt') (see
%   \pgfplotsmathvectorfromstring).
\def\pgfplotssetaxesfromazel#1#2#3{%
	\begingroup
	\pgfmathparse{#1}%
	\let\pgfplots@az=\pgfmathresult
	\pgfmathparse{#2}%
	\edef\pgfplots@el{-\pgfmathresult}%
	\pgfmathsin@{\pgfplots@az}%
	\let\sinaz=\pgfmathresult
	\pgfmathcos@{\pgfplots@az}%
	\let\cosaz=\pgfmathresult
	\pgfmathsin@{\pgfplots@el}%
	\let\sinel=\pgfmathresult
	\pgfmathcos@{\pgfplots@el}%
	\let\cosel=\pgfmathresult
	% x:
	\pgfmathmultiply@{\sinaz}{\sinel}%
	\xdef\pgfplots@glob@TMPa{\noexpand\pgfqpoint{\cosaz pt}{\pgfmathresult pt}}%
	% y:
	\pgfmathmultiply@{-\sinel}{\cosaz}%
	\xdef\pgfplots@glob@TMPb{\noexpand\pgfqpoint{\sinaz pt}{\pgfmathresult pt}}%
	% z:
	\xdef\pgfplots@glob@TMPc{\noexpand\pgfqpoint{0pt}{\cosel pt}}%
	%
	\pgfkeysgetvalue{/pgfplots/x dir/value}\pgfplots@loc@dirvalue@x
	\pgfkeysgetvalue{/pgfplots/y dir/value}\pgfplots@loc@dirvalue@y
	\pgfkeysgetvalue{/pgfplots/z dir/value}\pgfplots@loc@dirvalue@z
	\if r\pgfplots@loc@dirvalue@x
		\t@pgfplots@toka=\expandafter{\pgfplots@glob@TMPa}%
		\xdef\pgfplots@glob@TMPa{\noexpand\pgfqpointscale{-1}{\the\t@pgfplots@toka}}%
	\fi
	\if r\pgfplots@loc@dirvalue@y
		\t@pgfplots@toka=\expandafter{\pgfplots@glob@TMPb}%
		\xdef\pgfplots@glob@TMPb{\noexpand\pgfqpointscale{-1}{\the\t@pgfplots@toka}}%
	\fi
	\if r\pgfplots@loc@dirvalue@z
		\t@pgfplots@toka=\expandafter{\pgfplots@glob@TMPc}%
		\xdef\pgfplots@glob@TMPc{\noexpand\pgfqpointscale{-1}{\the\t@pgfplots@toka}}%
	\fi
	%
	% Process 'plot box ratio':
	\def\pgfplots@extract@plot@box@ratio##1##2##3##4\pgfplots@EOI{%
		\pgfmathparse{##1}\let\pgfplots@plotboxratio@x=\pgfmathresult
		\pgfmathparse{##2}\let\pgfplots@plotboxratio@y=\pgfmathresult
		\pgfmathparse{##3}\let\pgfplots@plotboxratio@z=\pgfmathresult
	}%
	\def\pgfplots@extract@plot@box@ratio@spaces##1 ##2 ##3 ##4\pgfplots@EOI{%
		\pgfplots@extract@plot@box@ratio{##1}{##2}{##3}{##4}\pgfplots@EOI
	}%
	\pgfkeysgetvalue{/pgfplots/plot box ratio}\pgfplots@loc@TMPa
	% Auto-determine input format which is either '{x}{y}{z}' or 'x y z'
	\def\pgfplots@loc@TMPb{%
		\pgfutil@ifnextchar\bgroup{%
			\pgfplots@loc@tmptrue
			\pgfplots@gobble@until@EOI
		}{%
			\pgfplots@loc@tmpfalse
			\pgfplots@gobble@until@EOI
		}%
	}%
	\expandafter\pgfplots@loc@TMPb\pgfplots@loc@TMPa\pgfplots@EOI
	\ifpgfplots@loc@tmp
		% Ah- braces format.
		\edef\pgfplots@loc@TMPa{\pgfplots@loc@TMPa{1}{1}{1}}%
		\expandafter\pgfplots@extract@plot@box@ratio\pgfplots@loc@TMPa\pgfplots@EOI
	\else
		% Ah- space-separated
		\edef\pgfplots@loc@TMPa{\pgfplots@loc@TMPa\space 1 1 1}%
		\expandafter\pgfplots@extract@plot@box@ratio@spaces\pgfplots@loc@TMPa\pgfplots@EOI
	\fi
	%
	% process it:
	\ifdim\pgfplots@plotboxratio@x pt=1pt
	\else
		\t@pgfplots@toka=\expandafter{\pgfplots@glob@TMPa}%
		\xdef\pgfplots@glob@TMPa{\noexpand\pgfqpointscale{\pgfplots@plotboxratio@x}{\the\t@pgfplots@toka}}%
	\fi
	\ifdim\pgfplots@plotboxratio@y pt=1pt
	\else
		\t@pgfplots@toka=\expandafter{\pgfplots@glob@TMPb}%
		\xdef\pgfplots@glob@TMPb{\noexpand\pgfqpointscale{\pgfplots@plotboxratio@y}{\the\t@pgfplots@toka}}%
	\fi
	\ifdim\pgfplots@plotboxratio@z pt=1pt
	\else
		\t@pgfplots@toka=\expandafter{\pgfplots@glob@TMPc}%
		\xdef\pgfplots@glob@TMPc{\noexpand\pgfqpointscale{\pgfplots@plotboxratio@z}{\the\t@pgfplots@toka}}%
	\fi
	%
	% n (3D!)
	\pgfmathmultiply@{-\sinaz}{\cosel}%
	\let\pgfmathresultNx=\pgfmathresult
	\pgfmathmultiply@{\cosaz}{\cosel}%
	\xdef\pgfplots@glob@TMPd{{\pgfmathresultNx}{\pgfmathresult}{\sinel}}%
	\endgroup
%\message{Setting x,y and z from {#1}{#2} to^^J x = \meaning\pgfplots@glob@TMPa,^^J y = \meaning\pgfplots@glob@TMPb,^^J z = \meaning\pgfplots@glob@TMPc,^^J n = \pgfplots@glob@TMPd.^^J}%
	\pgfsetxvec{\pgfplots@glob@TMPa}%
	\pgfsetyvec{\pgfplots@glob@TMPb}%
	\pgfsetzvec{\pgfplots@glob@TMPc}%
	\def\pgfplots@loc@TMPa##1##2##3{%
		\pgfplotsmathvectorfromstring{##1,##2,##3}{default}%
		\let\pgfplots@view@dir@threedim=\pgfplotsretval
	}%
	\expandafter\pgfplots@loc@TMPa\pgfplots@glob@TMPd\relax
	\def#3{0}%
}%

% Takes the current plot box, defined by the actual PGF x,y and z unit
% vectors, and re-scales it such that it fits into the 
% width and height of the axis (as they have been provided by the
% user).
%
% @see \pgfplots@scale@axisbox@to@widthheight
% @see\pgfplots@scaleaxes@to@BB
\def\pgfplots@scale@plotbox@to@widthheight{%
	\pgfplots@initsizes@get@width@withoutlabels
	\let\pgfplots@loc@TMPa=\pgfmathresult
	\pgfplots@initsizes@get@height@withoutlabels
	%
	\edef\pgfplots@loc@TMPa{{\pgfplots@loc@TMPa}{\pgfmathresult}}%
	\expandafter\pgfplots@scaleaxes@to@BB\pgfplots@loc@TMPa
}


% Takes the current PGF x,y and z unit vectors and scales them such
% that the bounding box of the final image has width #1 and height #2.
%
% The relative length of the input vectors is important for the 3D case: it
% will be scaled as-is. 
%
% PRECONDITION
% 	- the x, y and z unit vectors have been set to the proper
% 	DIRECTIONS. Their relative vector lengths are set-up properly
% 	(i.e. y is twice as large as x and half as large as z or so).
%	- the \ifpgfplots@threedim boolean is set.
%	- the data limits have been initialised and transformed according
%	to the data transformation.
%	- the data transformation has ONLY been applied to the axis limits
%	(not other axis inputs). It may be changed by this method.
% 
% POSTCONDITION
% 	- the unit vectors have been re-scaled such that the final plot
% 	has the desired dimensions.
% 	- the @veclength and @inverseveclength have been initialized
\def\pgfplots@scaleaxes@to@BB#1#2{%
	\if0\pgfplots@scale@mode@choice
		% scale mode=auto
		\def\pgfplots@scale@mode@choice{2}% stretch to fill
	\fi
	\pgfplots@scaleaxes@to@BB@{#1}{#2}%
	% NOTE: we have not yet computed the lengths of unit vectors. In
	% addition, we have not yet updated the normal vector.
}%

% DEPRECATED:
\def\pgfplots@rescale@view@dir{%
	\expandafter\ifx\csname pgfplots@view@dir@threedim\endcsname\relax
	\else
		% At this point, we ALREADY HAVE a normal vector. However, it
		% might be skewed due to the scaling.
		%
		% -> recompute normal vector. In earlier versions, I tried to
		% rescale it - but that was too complicated (for me). This
		% here produces correct results, and it is a correct approach
		% anyway.
		\pgfplotsgetnormalforcurrentview
	\fi
}%

% \pgfplots@BB@for@plotbox@get@unit@scales@for@limits{#1}{#2}{#3}:
% a helper tool which computes individual unit vector scales in order
% to respect the limits.
%
% This method ignores width/height; its purpose is only to make sure
% that [xmin,xmax] fits into the CURRENT plot box. 
%
% In this context, each unit vector is supposed to be scaled such that
% width/height fit if xmin=0 and xmax=1.
%
% #1 [output] a macro name which will contain the INVERSE scale for x
% #2 [output] a macro name which will contain the INVERSE scale for y
% #3 [output] a macro name which will contain the INVERSE scale for z
% 
\def\pgfplots@BB@for@plotbox@get@unit@scales@for@limits#1#2#3{%
	\if1\b@pgfplots@plotbox@xisunit
		% Consequently, we have to multiply  with 1/(max-min):
		% compute 1/(xmax - xmin) in float for more recent versions (see /pgfplots/compat/scaling).
		% I observed that it is much more accurate 
		\pgfmathsubtract@{\pgfplots@xmax}{\pgfplots@xmin}%
	\else
		\def\pgfmathresult{1}%
	\fi
	\let#1=\pgfmathresult
	%
	\if1\b@pgfplots@plotbox@yisunit
		\pgfmathsubtract@{\pgfplots@ymax}{\pgfplots@ymin}%
	\else
		\def\pgfmathresult{1}%
	\fi
	\let#2=\pgfmathresult
	%
	\ifpgfplots@threedim
		\if1\b@pgfplots@plotbox@zisunit
			\pgfmathsubtract@{\pgfplots@zmax}{\pgfplots@zmin}%
		\else
			\def\pgfmathresult{1}%
		\fi
	\else
		\def\pgfmathresult{1}%
	\fi
	\let#3=\pgfmathresult
}%
\def\pgfplots@BB@for@plotbox{%
	\ifpgfplots@threedim
		\pgfpathmoveto{\pgfqpointxyz\pgfplots@plotbox@xmin\pgfplots@plotbox@ymin\pgfplots@plotbox@zmin}%
		\pgfpathmoveto{\pgfqpointxyz\pgfplots@plotbox@xmin\pgfplots@plotbox@ymin\pgfplots@plotbox@zmax}%
		\pgfpathmoveto{\pgfqpointxyz\pgfplots@plotbox@xmin\pgfplots@plotbox@ymax\pgfplots@plotbox@zmin}%
		\pgfpathmoveto{\pgfqpointxyz\pgfplots@plotbox@xmin\pgfplots@plotbox@ymax\pgfplots@plotbox@zmax}%
		\pgfpathmoveto{\pgfqpointxyz\pgfplots@plotbox@xmax\pgfplots@plotbox@ymin\pgfplots@plotbox@zmin}%
		\pgfpathmoveto{\pgfqpointxyz\pgfplots@plotbox@xmax\pgfplots@plotbox@ymin\pgfplots@plotbox@zmax}%
		\pgfpathmoveto{\pgfqpointxyz\pgfplots@plotbox@xmax\pgfplots@plotbox@ymax\pgfplots@plotbox@zmin}%
		\pgfpathmoveto{\pgfqpointxyz\pgfplots@plotbox@xmax\pgfplots@plotbox@ymax\pgfplots@plotbox@zmax}%
	\else
		\pgfpathmoveto{\pgfqpointxy\pgfplots@plotbox@xmin\pgfplots@plotbox@ymin}%
		\pgfpathmoveto{\pgfqpointxy\pgfplots@plotbox@xmin\pgfplots@plotbox@ymax}%
		\pgfpathmoveto{\pgfqpointxy\pgfplots@plotbox@xmax\pgfplots@plotbox@ymin}%
		\pgfpathmoveto{\pgfqpointxy\pgfplots@plotbox@xmax\pgfplots@plotbox@ymax}%
	\fi
}%



% Returns width and height of the current plot box
% (the path produced by \pgfplots@BB@for@plotbox).
%
% PRECONDITION: \pgfplots@BB@for@plotbox is defined to produce a path
% for the plot box
%
% POSTCONDITION: \pgfplotsretval contains the with and
% \pgfplotsretvalb contains the height
\def\pgfplots@get@dimension@of@BB{%
	\begingroup
	\pgfinterruptboundingbox
	%
	% the result of this call will be used to scale to target
	% dimensions. If we omit \pgftransformreset here, we might
	% accidentally UNDO the PGF transformation matrix (compare by 
	% writing \tikzpicture[scale=0.5] before the axis).
	\pgftransformreset
	%
	% STEP 1: compute the bounding box for the plot box.
	\pgfplots@BB@for@plotbox
	%
	% TMPa = width
	\pgf@xa=\pgf@pathmaxx
	\advance\pgf@xa by-\pgf@pathminx
	% TMPb = height
	\pgf@xb=\pgf@pathmaxy
	\advance\pgf@xb by-\pgf@pathminy
	\xdef\pgfplots@glob@TMPa{%
		\def\noexpand\pgfplotsretval{\the\pgf@xa}%
		\def\noexpand\pgfplotsretvalb{\the\pgf@xb}%
	}%
	\pgfusepath{discard}%
	\endpgfinterruptboundingbox
	\endgroup
	\pgfplots@glob@TMPa
}%

\def\pgfplots@scaleaxes@to@BB@prepare@plotbox@limits{%
	\def\b@pgfplots@rescale@x{1}%
	\def\b@pgfplots@rescale@y{1}%
	\def\b@pgfplots@rescale@z{1}%
	%
	\pgfplots@scaleaxes@to@BB@prepare@plotbox@limits@ x%
	\pgfplots@scaleaxes@to@BB@prepare@plotbox@limits@ y%
	\pgfplots@scaleaxes@to@BB@prepare@plotbox@limits@ z%
}%

\def\pgfplots@scaleaxes@to@BB@prepare@plotbox@limits@#1{%
	\expandafter\ifx\csname pgfplots@#1\endcsname\pgfutil@empty
		% Ah - we have no unit vector in this direction. 
		\expandafter\def\csname pgfplots@plotbox@#1min\endcsname{0}%
		\expandafter\def\csname pgfplots@plotbox@#1max\endcsname{1}%
		\expandafter\def\csname b@pgfplots@plotbox@#1isunit\endcsname{1}%
	\else
		% we have a unit vector... prepare for limits. Note that the
		% unit vector has been prepared for data scaling already.
		\pgfutil@namelet{pgfplots@plotbox@#1min}{pgfplots@#1min}%
		\pgfutil@namelet{pgfplots@plotbox@#1max}{pgfplots@#1max}%
		\expandafter\def\csname b@pgfplots@plotbox@#1isunit\endcsname{0}%
		\if2\pgfplots@scale@mode@choice
			% scale mode=stretch to fill
			% do NOT rescale unit vectors for stretch to fill :
			\expandafter\def\csname b@pgfplots@rescale@#1\endcsname{0}%
		\fi
	\fi
	\expandafter\def\csname b@pgfplots@unitvec@is@zero@#1\endcsname{0}%
	\ifdim\csname pgf@#1x\endcsname=0pt %
		\ifdim\csname pgf@#1y\endcsname=0pt %
			\expandafter\def\csname b@pgfplots@unitvec@is@zero@#1\endcsname{1}%
		\fi
	\fi
}


\def\pgfplots@scaleaxes@to@BB@#1#2{%
	\begingroup
%\message{SCALING: scale mode choice = \pgfplots@scale@mode@choice^^J}%
	%
	\pgfplots@scaleaxes@to@BB@prepare@plotbox@limits
	\def\pgfplots@target@limitrescale@x{1}%
	\def\pgfplots@target@limitrescale@y{1}%
	\def\pgfplots@target@limitrescale@z{1}%
	\if1\pgfplots@scale@mode@choice
		% scale mode=none
		\def\xscale{1}%
		\def\yscale{1}%
		\def\pgfplots@target@unit@scale@inv@x{1}%
		\def\pgfplots@target@unit@scale@inv@y{1}%
		\def\pgfplots@target@unit@scale@inv@z{1}%
	\else
		%
		% This here CAN cause anisotropic (different) scaling factors.
		\pgfplots@BB@for@plotbox@get@unit@scales@for@limits
			{\pgfplots@target@unit@scale@inv@x}
			{\pgfplots@target@unit@scale@inv@y}
			{\pgfplots@target@unit@scale@inv@z}%
		%
%\message{got scales to fit limits into BB: x=1/\pgfplots@target@unit@scale@inv@x, y=1/\pgfplots@target@unit@scale@inv@y, z=1/\pgfplots@target@unit@scale@inv@z^^J}%
		%
		\if3\pgfplots@scale@mode@choice
			% scale mode=scale uniformly
			% 
			% We need to recompensate in case the previous method chose
			% different unit scaling scalings:
			\pgfplots@BB@for@plotbox@get@unit@scales@compensated@axis@limits
				{\pgfplots@target@unit@scale@inv@x}
				{\pgfplots@target@unit@scale@inv@y}
				{\pgfplots@target@unit@scale@inv@z}
				{\pgfplots@target@limitrescale@x}{\pgfplots@target@limitrescale@y}{\pgfplots@target@limitrescale@z}%
			%
			%\pgfplots@BB@update@cumulative@limit@compensations
		\fi
%\message{adjusted scales for 'scale mode': x=1/\pgfplots@target@unit@scale@inv@x, y=1/\pgfplots@target@unit@scale@inv@y, z=1/\pgfplots@target@unit@scale@inv@z;  ^^J   axis limit componsation scales x=\pgfplots@target@limitrescale@x, y=\pgfplots@target@limitrescale@y, z=\pgfplots@target@limitrescale@z^^J}%
		%
		% ATTENTION: this MODIFIES \pgfplots@target@limitrescale@x and its
		% variants directly - and it needs the input values.
		\pgfplots@get@scale@horiz@and@vert
			{#1}%
			{#2}%
			{\xscale}%
			{\yscale}% yscale
			{\pgfplots@target@limitrescale@x}%
			{\pgfplots@target@limitrescale@y}%
			{\pgfplots@target@limitrescale@z}%
%\message{Got W/H scale for all x components: \xscale; for all y components: \xscale; ^^J   axis limit componsation scales x=1/\pgfplots@target@limitrescale@x, y=1/\pgfplots@target@limitrescale@y, z=1/\pgfplots@target@limitrescale@z^^J}%
		% Ok, we know the W,H scalings now.
		%
		%
		%
		\pgfplots@apply@unit@ratio
			{\pgfplots@target@unit@scale@inv@x}
			{\pgfplots@target@unit@scale@inv@y}
			{\pgfplots@target@unit@scale@inv@z}
			{\pgfplots@target@limitrescale@x@}{\pgfplots@target@limitrescale@y@}{\pgfplots@target@limitrescale@z@}%
		\pgfplots@BB@update@cumulative@limit@compensations
		%
%\message{adjusted scales for 'unit vector ratio': x=1/\pgfplots@target@unit@scale@inv@x, y=1/\pgfplots@target@unit@scale@inv@y, z=1/\pgfplots@target@unit@scale@inv@z;  ^^J   axis limit componsation scales x=\pgfplots@target@limitrescale@x, y=\pgfplots@target@limitrescale@y, z=\pgfplots@target@limitrescale@z^^J}%
	\fi
	%
	%
	\pgfplots@scaling@minimize@limitrescale%
	%
	%
	\pgfplots@scaling@adjust@datascaling%
%\message{adjusted scales for data scale trafo: x=1/\pgfplots@target@unit@scale@inv@x, y=1/\pgfplots@target@unit@scale@inv@y, z=1/\pgfplots@target@unit@scale@inv@z;  ^^J   axis limit componsation scales x=\pgfplots@target@limitrescale@x, y=\pgfplots@target@limitrescale@y, z=\pgfplots@target@limitrescale@z;^^J  data scale trafo exponents x=\pgfplots@target@datascaletrafo@x@exponent@old -> \pgfplots@target@datascaletrafo@x@exponent, y=\pgfplots@target@datascaletrafo@y@exponent@old -> \pgfplots@target@datascaletrafo@y@exponent, z=\pgfplots@target@datascaletrafo@z@exponent@old -> \pgfplots@target@datascaletrafo@z@exponent^^J}%
	%
	\pgfplots@scaling@compute@final@scales%
			{\xscale}{\yscale}%
			{\pgfplots@target@unit@scale@inv@x}%
			{\pgfplots@target@unit@scale@inv@y}%
			{\pgfplots@target@unit@scale@inv@z}%
	%
	\pgfplots@axis@apply@post@scale{x}%
	\pgfplots@axis@apply@post@scale{y}%
	\ifpgfplots@threedim
		\pgfplots@axis@apply@post@scale{z}%
	\fi
	%
	% and finally, resize limits appropriately and add all cumulative limit compensations:
	\xdef\pgfplots@glob@TMPa{%
		%
		\pgf@xx=\pgfplots@target@unit@scale@xx\pgf@xx
		\pgf@xy=\pgfplots@target@unit@scale@xy\pgf@xy
		%
		\pgf@yx=\pgfplots@target@unit@scale@yx\pgf@yx
		\pgf@yy=\pgfplots@target@unit@scale@yy\pgf@yy
		%
		\ifpgfplots@threedim
			\pgf@zx=\pgfplots@target@unit@scale@zx\pgf@zx
			\pgf@zy=\pgfplots@target@unit@scale@zy\pgf@zy
		\fi
		%
		\noexpand\pgfplots@apply@datascaletrafo@change@{x}{\pgfplots@target@datascaletrafo@x@exponent}%
		\noexpand\pgfplots@apply@datascaletrafo@change@{y}{\pgfplots@target@datascaletrafo@y@exponent}%
		\noexpand\pgfplots@apply@datascaletrafo@change@{z}{\pgfplots@target@datascaletrafo@z@exponent}%
		%
		\noexpand\pgfplots@apply@unit@vector@rescale@keep@size{x}{\pgfplots@target@limitrescale@x}%
		\noexpand\pgfplots@apply@unit@vector@rescale@keep@size{y}{\pgfplots@target@limitrescale@y}%
		\noexpand\pgfplots@apply@unit@vector@rescale@keep@size{z}{\pgfplots@target@limitrescale@z}%
		%
		\noexpand\pgfplots@notify@final@scalings{%
			x unit scale=\pgfplots@target@unit@scale@x,%
			y unit scale=\pgfplots@target@unit@scale@y,%
			z unit scale=\pgfplots@target@unit@scale@z,%
			x datatrafo exponent=\pgfplots@target@datascaletrafo@x@exponent,%
			y datatrafo exponent=\pgfplots@target@datascaletrafo@y@exponent,%
			z datatrafo exponent=\pgfplots@target@datascaletrafo@z@exponent,%
			x limit rescale=\pgfplots@target@limitrescale@x,%
			y limit rescale=\pgfplots@target@limitrescale@y,%
			z limit rescale=\pgfplots@target@limitrescale@z,%
		}%
	}%
	\endgroup
	\pgfplots@glob@TMPa
}%

% Checks for the case the ALL (visible) limit compensation scales are
% bigger than one (for example x = 1.22, y = 2). In such a case, we
% want to MINIMIZE the rescaling. This can happen if unit vector ratio
% is active.
%
% In our example, we want to use limit rescaling factors x = 1, y = 2/1.22
% and, consequently, unit rescaling factors x *= 1.22, y *= 1.22 .
%
% This method checks for the case and applies the rescaling if
% necessary.
%
\def\pgfplots@scaling@minimize@limitrescale{%
	% boolean allLimitScalesAreBiggerThanOne;
	\pgfplots@loc@tmptrue
	\if0\b@pgfplots@unitvec@is@zero@x
		\ifdim\pgfplots@target@limitrescale@x pt<1.002pt %
			\pgfplots@loc@tmpfalse
		\fi
	\fi
	\if0\b@pgfplots@unitvec@is@zero@y
		\ifdim\pgfplots@target@limitrescale@y pt<1.002pt %
			\pgfplots@loc@tmpfalse
		\fi
	\fi
	\if0\b@pgfplots@unitvec@is@zero@z
		\ifdim\pgfplots@target@limitrescale@z pt<1.002pt %
			\pgfplots@loc@tmpfalse
		\fi
	\fi
	%
	\ifpgfplots@loc@tmp
		\begingroup
		% Ah -- all non-vanishing limit rescaling factors are BIGGER
		% THAN ONE.
		% In this case, we can save some rescalings!
		%
		% Search for the smallest rescaling factor.
		\let\pgfplots@smallest=\pgf@x
		\pgfplots@smallest=16000pt %
		\def\pgfplots@smallest@arg{}%
		\if0\b@pgfplots@unitvec@is@zero@x
			\pgf@xa=\pgfplots@target@limitrescale@x pt %
			\ifdim\pgf@xa<\pgfplots@smallest%
				\pgfplots@smallest=\pgf@xa
				\def\pgfplots@smallest@arg{x}%
			\fi
		\fi
		\if0\b@pgfplots@unitvec@is@zero@y
			\pgf@xa=\pgfplots@target@limitrescale@y pt %
			\ifdim\pgf@xa<\pgfplots@smallest%
				\pgfplots@smallest=\pgf@xa
				\def\pgfplots@smallest@arg{y}%
			\fi
		\fi
		\if0\b@pgfplots@unitvec@is@zero@z
			\pgf@xa=\pgfplots@target@limitrescale@z pt %
			\ifdim\pgf@xa<\pgfplots@smallest%
				\pgfplots@smallest=\pgf@xa
				\def\pgfplots@smallest@arg{z}%
			\fi
		\fi
		%
		% OK. We have the smallest scaling factor. It is > 1.
		\pgfplotscoordmath{default}{parsenumber}{\pgfplots@target@limitrescale@x}%
		\let\pgfplots@target@limitrescale@x=\pgfmathresult
		\pgfplotscoordmath{default}{parsenumber}{\pgfplots@target@limitrescale@y}%
		\let\pgfplots@target@limitrescale@y=\pgfmathresult
		%
		%
		\pgfplotscoordmath{default}{parsenumber}{\pgfplots@target@unit@scale@inv@x}%
		\let\pgfplots@target@unit@scale@inv@x=\pgfmathresult
		\pgfplotscoordmath{default}{parsenumber}{\pgfplots@target@unit@scale@inv@y}%
		\let\pgfplots@target@unit@scale@inv@y=\pgfmathresult
		%
		\if0\b@pgfplots@unitvec@is@zero@z
			\pgfplotscoordmath{default}{parsenumber}{\pgfplots@target@limitrescale@z}%
			\let\pgfplots@target@limitrescale@z=\pgfmathresult
			\pgfplotscoordmath{default}{parsenumber}{\pgfplots@target@unit@scale@inv@z}%
			\let\pgfplots@target@unit@scale@inv@z=\pgfmathresult
		\fi
		%
		\pgfplotscoordmath{default}{op}{reciprocal}{{\csname pgfplots@target@limitrescale@\pgfplots@smallest@arg\endcsname}}%
		\let\scale=\pgfmathresult
		%
		\pgfplotsforeachentryinCSV\value{%
			\pgfplots@target@unit@scale@inv@x,%
			\pgfplots@target@unit@scale@inv@y,%
			\pgfplots@target@limitrescale@x,%
			\pgfplots@target@limitrescale@y%
		}{%
			\pgfplotscoordmath{default}{op}{multiply}{{\scale}{\value}}%
			\pgfplotscoordmath{default}{tofixed}{\pgfmathresult}%
			\expandafter\let\value=\pgfmathresult
		}%
		\if0\b@pgfplots@unitvec@is@zero@z
			\pgfplotsforeachentryinCSV\value{%
				\pgfplots@target@unit@scale@inv@z,%
				\pgfplots@target@limitrescale@z%
			}{%
				\pgfplotscoordmath{default}{op}{multiply}{{\scale}{\value}}%
				\pgfplotscoordmath{default}{tofixed}{\pgfmathresult}%
				\expandafter\let\value=\pgfmathresult
			}%
		\fi
		%
		\xdef\pgfplots@glob@TMPa{%
			\noexpand\def\noexpand\pgfplots@target@unit@scale@inv@x{\pgfplots@target@unit@scale@inv@x}%
			\noexpand\def\noexpand\pgfplots@target@unit@scale@inv@y{\pgfplots@target@unit@scale@inv@y}%
			\noexpand\def\noexpand\pgfplots@target@unit@scale@inv@z{\pgfplots@target@unit@scale@inv@z}%
			\noexpand\def\noexpand\pgfplots@target@limitrescale@x{\pgfplots@target@limitrescale@x}%
			\noexpand\def\noexpand\pgfplots@target@limitrescale@y{\pgfplots@target@limitrescale@y}%
			\noexpand\def\noexpand\pgfplots@target@limitrescale@z{\pgfplots@target@limitrescale@z}%
		}%
		\endgroup
		\pgfplots@glob@TMPa
%
%\message{adjusted scales by minimizing common scaling factors: x=1/\pgfplots@target@unit@scale@inv@x, y=1/\pgfplots@target@unit@scale@inv@y, z=1/\pgfplots@target@unit@scale@inv@z;  ^^J   axis limit componsation scales x=\pgfplots@target@limitrescale@x, y=\pgfplots@target@limitrescale@y, z=\pgfplots@target@limitrescale@z;^^J}%
	\fi
}%

% Defines 
% \pgfplots@target@unit@scale@xx
% \pgfplots@target@unit@scale@xy
% \pgfplots@target@unit@scale@yx
% \pgfplots@target@unit@scale@yy
% \pgfplots@target@unit@scale@zx
% \pgfplots@target@unit@scale@zy
% %
% \pgfplots@target@unit@scale@x
% \pgfplots@target@unit@scale@y
% \pgfplots@target@unit@scale@z
% by combining the input args.
%
% #1: the scale to be applied to ALL x components
% #2: the scale to be applied to ALL y components
% #3: the scale to be applied to x unit
% #4: the scale to be applied to y unit
% #5: the scale to be applied to z unit
\def\pgfplots@scaling@compute@final@scales#1#2#3#4#5{%
	% ##1: the axis (x,y,or z)
	% ##2: the horizontal scale
	% ##3: the vertical scale
	% ##4: the inverse unit scale for this axis
	\def\pgfplots@loc@TMPa##1##2##3##4{%
		\pgfplotscoordmath{\pgfplots@compat@scaling@coordmath}{parsenumber}{##2}%
		\let\xscale@@=\pgfmathresult
		\pgfplotscoordmath{\pgfplots@compat@scaling@coordmath}{parsenumber}{##3}%
		\let\yscale@@=\pgfmathresult
		\pgfplotscoordmath{\pgfplots@compat@scaling@coordmath}{parsenumber}{##4}%
		\let\unitscale@inv@@=\pgfmathresult
		%
		% NOTE : it *would* be more efficient to use
		% 1/\unitscale@inv@@ in the routines above. BUT THAT IS NOT BACKWARDS COMPATIBLE.
		% Leave it this way!
		\pgfplotscoordmath{\pgfplots@compat@scaling@coordmath}{op}{reciprocal}{{\unitscale@inv@@}}%
		\let\unitscale@@=\pgfmathresult
		\pgfplotscoordmath{\pgfplots@compat@scaling@coordmath}{tofixed}{\pgfmathresult}%
		\expandafter\let\csname pgfplots@target@unit@scale@##1\endcsname=\pgfmathresult
		%
		%
		\ifx\pgfplots@compat@scaling@coordmath@final\pgfplots@compat@scaling@coordmath
		\else
			% backwards compatibility is such a burden.... :-(
			%
			% earlier versions relied on TeX's dimen arithmetics to
			% multiply the final scales. Make sure we do the same -
			% rounding errors on unit vectors are instable, i.e. the
			% errors add up considerably.
			\pgfplotscoordmath{\pgfplots@compat@scaling@coordmath@final}{parsenumber}{\xscale@@}%
			\let\xscale@@=\pgfmathresult
			\pgfplotscoordmath{\pgfplots@compat@scaling@coordmath@final}{parsenumber}{\yscale@@}%
			\let\yscale@@=\pgfmathresult
			\pgfplotscoordmath{\pgfplots@compat@scaling@coordmath@final}{parsenumber}{\unitscale@@}%
			\let\unitscale@@=\pgfmathresult
			\pgfplotscoordmath{\pgfplots@compat@scaling@coordmath@final}{parsenumber}{\unitscale@inv@@}%
			\let\unitscale@inv@@=\pgfmathresult
		\fi
		%
		\ifpgfplots@threedim
			% backw. compatibility: this is how it used to be in 3d
			% axes:
			\pgfplotscoordmath{\pgfplots@compat@scaling@coordmath@final}{op}{multiply}{{\xscale@@}{\unitscale@@}}%
			\pgfplotscoordmath{\pgfplots@compat@scaling@coordmath@final}{tofixed}{\pgfmathresult}%
			\expandafter\let\csname pgfplots@target@unit@scale@##1x\endcsname=\pgfmathresult
			%
			\pgfplotscoordmath{\pgfplots@compat@scaling@coordmath@final}{op}{multiply}{{\yscale@@}{\unitscale@@}}%
			\pgfplotscoordmath{\pgfplots@compat@scaling@coordmath@final}{tofixed}{\pgfmathresult}%
			\expandafter\let\csname pgfplots@target@unit@scale@##1y\endcsname=\pgfmathresult
		\else
			% backw. compatibility: 2d axes used divide in earlier
			% versions, not reciprocal. Believe it or not; for
			% \pgfplots@compat@scaling@coordmath=pgfbasic, it makes a
			% visible difference of about 2-3pt in the complete figure
			% size.
			\pgfplotscoordmath{\pgfplots@compat@scaling@coordmath@final}{op}{divide}{{\xscale@@}{\unitscale@inv@@}}%
			\pgfplotscoordmath{\pgfplots@compat@scaling@coordmath@final}{tofixed}{\pgfmathresult}%
			\expandafter\let\csname pgfplots@target@unit@scale@##1x\endcsname=\pgfmathresult
			%
			\pgfplotscoordmath{\pgfplots@compat@scaling@coordmath@final}{op}{divide}{{\yscale@@}{\unitscale@inv@@}}%
			\pgfplotscoordmath{\pgfplots@compat@scaling@coordmath@final}{tofixed}{\pgfmathresult}%
			\expandafter\let\csname pgfplots@target@unit@scale@##1y\endcsname=\pgfmathresult
		\fi
		%
	}%
	\if1\b@pgfplots@rescale@x
		\pgfplots@loc@TMPa{x}{\xscale}{\yscale}{#3}%
	\else
		\pgfplots@loc@TMPa{x}{1}{1}{#3}%
	\fi
	%
	\if1\b@pgfplots@rescale@y
		\pgfplots@loc@TMPa{y}{\xscale}{\yscale}{#4}%
	\else
		\pgfplots@loc@TMPa{y}{1}{1}{#4}%
	\fi
	%
	\ifpgfplots@threedim
		\if1\b@pgfplots@rescale@z
			\pgfplots@loc@TMPa{z}{\xscale}{\yscale}{#5}%
		\else
			\pgfplots@loc@TMPa{z}{1}{1}{#5}%
		\fi
	\else
		\def\pgfplots@target@unit@scale@z{0}%
		\def\pgfplots@target@unit@scale@zx{0}%
		\def\pgfplots@target@unit@scale@zy{0}%
		\def\pgfplots@target@unit@scale@inv@z{inf}%
	\fi
	%
}%

\def\pgfplots@notify@final@scalings#1{%
	\pgfkeys{/pgfplots/scaling/.cd,	
		.unknown/.code={%
%\message{setting key '\pgfkeyscurrentkey' to {##1}^^J}
			\pgfkeyssetvalue{\pgfkeyscurrentkey}{##1}%
		},
		#1%
	}%
}%

% #1: either x,y, or z
% #2: the new exponent
\def\pgfplots@apply@datascaletrafo@change@#1#2{%
	\pgfplots@if{pgfplots@apply@datatrafo@#1}{%
		\pgfplotscoordmath{#1}{datascaletrafo get params}%
		\edef\pgfplots@loc@TMPa{\expandafter\pgfutil@firstoftwo\pgfmathresult}%
		\edef\pgfplots@loc@TMPb{#2}%
		\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
			% ok; the data scale trafo did not change at all - we
			% still have the same exponent.
		\else
			% Ah - we have a new data scale trafo!
			\pgfplotscoordmath{#1}{datascaletrafo inverse}{\csname pgfplots@#1min\endcsname}%
			\let\pgfplots@loc@TMPa=\pgfmathresult
			\pgfplotscoordmath{#1}{datascaletrafo inverse}{\csname pgfplots@#1max\endcsname}%
			\let\pgfplots@loc@TMPb=\pgfmathresult
			%
			% first: determine the optimal shift (which is the
			% transformed lower limit):
			\pgfplotscoordmath{#1}{datascaletrafo set params}{#2}{0}%
			\pgfplotscoordmath{#1}{datascaletrafo}{\pgfplots@loc@TMPa}%
			%
			% ok, finalize the data trafo:
			\pgfplotscoordmath{#1}{datascaletrafo set params}{#2}{\pgfmathresult}%
			%
			% ... and recompute axis limits:
			\pgfplotscoordmath{#1}{datascaletrafo}{\pgfplots@loc@TMPa}%
			\expandafter\let\csname pgfplots@#1min\endcsname=\pgfmathresult
			\pgfplotscoordmath{#1}{datascaletrafo}{\pgfplots@loc@TMPb}%
			\expandafter\let\csname pgfplots@#1max\endcsname=\pgfmathresult
		\fi
	}{}%
}%

% Inspects the limit enlargement factors and reinitializes the data
% scale transformations.
%
% The purpose of this method is to avoid "dimension too large" if the
% factors exceed certain limits.
%
% INPUT:
%  \pgfplots@target@limitrescale@x and its variants for y and z
%  \pgfplots@target@unit@scale@inv@x and its variants for y and z
%
% OUTPUT:
%  \pgfplots@target@datascaletrafo@x@exponent and its variants for y and z
%     -> contains NEW datascaletrafo exponents 
%  \pgfplots@target@datascaletrafo@x@exponent@old and its variants for y and z
%     -> contains OLD datascaletrafo exponents
%  \pgfplots@target@unit@scale@inv@x and its variants for y and z
%     -> contains (modified) unit vector scales
\def\pgfplots@scaling@adjust@datascaling{%
	\pgfplots@scaling@adjust@datascaling@for x%
	\pgfplots@scaling@adjust@datascaling@for y%
	\pgfplots@scaling@adjust@datascaling@for z%
}
\def\pgfplots@scaling@adjust@datascaling@for#1{%
	\pgfplots@if{pgfplots@apply@datatrafo@#1}{%
		\pgfplotscoordmath{#1}{datascaletrafo get params}%
		\def\pgfplots@loc@TMPa##1##2{%
			\expandafter\def\csname pgfplots@target@datascaletrafo@#1@exponent\endcsname{##1}%
			\expandafter\def\csname pgfplots@target@datascaletrafo@#1@exponent@old\endcsname{##1}%
		}%
		\expandafter\pgfplots@loc@TMPa\pgfmathresult
		\pgf@xa=\csname pgfplots@target@limitrescale@#1\endcsname pt
		\ifdim\pgf@xa>5pt %
			% We want to enlarge axis limits considerably! 
			%
			\pgfplots@scaling@adjust@datascaling@for@get@compensation{\pgf@xa}%
			%
			% Ok, make sure that we do not get "dimension too large"
			% by adjusting the data scale trafo.
			%
			% Note that the data scale trafo has (only) been applied
			% to axis limits, so we have to reapply it before these
			% changes can take effect:
			\pgf@xa=\csname pgfplots@target@unit@scale@inv@#1\endcsname pt
			\divide\pgf@xa by\pgfplotsretval\relax %
			\expandafter\edef\csname pgfplots@target@unit@scale@inv@#1\endcsname{\pgf@sys@tonumber\pgf@xa}%
			%
			\c@pgf@countd=\csname pgfplots@target@datascaletrafo@#1@exponent\endcsname\relax
			\advance\c@pgf@countd by-\pgfplotsretvalb\relax %
			\expandafter\edef\csname pgfplots@target@datascaletrafo@#1@exponent\endcsname{\the\c@pgf@countd}%
		\fi
	}{%
		\expandafter\def\csname pgfplots@target@datascaletrafo@#1@exponent\endcsname{0}%
		\expandafter\def\csname pgfplots@target@datascaletrafo@#1@exponent@old\endcsname{0}%
	}%
}

% Returns 
%  \pgfplotsretval -> the absolute scaling 
%  \pgfplotsretvalb -> the log10 of the scaling
\def\pgfplots@scaling@adjust@datascaling@for@get@compensation#1{
	\ifdim#1<100pt %
		\def\pgfplotsretval{10}%
		\def\pgfplotsretvalb{1}%
	\else
		\ifdim#1<1000pt %
			\def\pgfplotsretval{100}%
			\def\pgfplotsretvalb{2}%
		\else
			\ifdim#1<10000pt %
				\def\pgfplotsretval{1000}%
				\def\pgfplotsretvalb{3}%
			\else
				% too much for this approach anyway... and probably no
				% use-case at all.
				\def\pgfplotsretval{1000}%
				\def\pgfplotsretvalb{3}%
			\fi
		\fi
	\fi
}%

% Computes the initial scale from a plot box of unit size to the
% desired with and height.
%
% #1 the desired width
% #2 the desired height
% #3 [output] a macro which will contain the horizontal (x) scale
% #4 [output] a macro which will contain the vertical (y) scale
% #5 [input/output] a macro which, on input, contains the x axis limit compensation scale
%    which is required to select a single unit vector scale without
%    reducing the plots dimension (without actually respecting the
%    final dimension). On output, the input has been multiplied by
%    some additional x limit componensation scale (selected by scale
%    uniformly strategy).
% #6 [input/output] a macro which will contain a y axis limit
% compensation scale; it works in the same way as #5
% #7 [input/output] a macro which will contain a z axis limit
% compensation scale; it works in the same way as #5
\def\pgfplots@get@scale@horiz@and@vert#1#2#3#4#5#6#7{%
	\begingroup
	\edef\pgfplots@target@limitrescale@x{#5}%
	\edef\pgfplots@target@limitrescale@y{#6}%
	\edef\pgfplots@target@limitrescale@z{#7}%
	\pgfplots@get@dimension@of@BB
	\pgf@xa=\pgfplotsretval\relax
	\pgf@xb=\pgfplotsretvalb\relax
	\pgf@ya=#1\relax
	\pgf@yb=#2\relax
	\edef\w{\pgf@sys@tonumber\pgf@xa}%
	\edef\h{\pgf@sys@tonumber\pgf@xb}%
	\edef\W{\pgf@sys@tonumber\pgf@ya}%
	\edef\H{\pgf@sys@tonumber\pgf@yb}%
%\message{PGFPLOTS: the current unit vectors result in a UNIT BB of (\the\pgf@xa,\the\pgf@xb). Scaling it to (\the\pgf@ya,\the\pgf@yb)...^^J}%
	\ifcase\pgfplots@scale@mode@choice
		% scale mode=auto  does not happen here
	\or
		% scale mode=none  does not happen here
	\or
		% scale mode=stretch to fill
		% 
		% This is very simple:
		%
		% Compute individual scaling factors for X and Y
		% such that the UNIT-BB will have size #1,#2. Keep limits.
		\pgfmathdivide@{\W}{\w}%
		\let\scalex=\pgfmathresult
		%
		\pgfmathdivide@{\H}{\h}%
		\let\scaley=\pgfmathresult
		% 
		% no changes to the axis limits - we only rescale units.
		\def\pgfplots@target@limitrescale@x@{1}%
		\def\pgfplots@target@limitrescale@y@{1}%
		\def\pgfplots@target@limitrescale@z@{1}%
		\pgfplots@BB@update@cumulative@limit@compensations
	\or
		% scale mode=scale uniformly
		% compute ONE common scale for both, X and Y - and satisfy
		% width/height constraints by adjusting the axis limits.
		%
		% The idea is as follows:
		% we WANT to have width W and height H.
		% The constraint is that each unit vector must get the same
		% scale -- but the axis limits can receive individual
		% compensation scales. But it should "look reasonable well".
		%
		% currently, we have 
		% w = r_x e_xx  + r_y e_yx + rz e_zx  (with e_zx = 0 typically)
		% h = r_x e_xy  + r_y e_yy + rz e_zy
		%
		% where r_x, r_y, r_z are the maximal range of the data in
		% x,y,z respectively. Depending on the context of this method,
		% they are either 1 (relative coords) or
		% (xmax-xmin) (absolute coords).
		%
		% Now, search for a set of real numbers 
		% Rx, Ry, Rz, s
		% such that
		% W = (Rx r_x) (s e_xx)  + (Ry r_y) (s e_yx)  + (Rz r_z) (s e_zx)
		% H = (Rx r_x) (s e_xy)  + (Ry r_y) (s e_yy)  + (Rz r_z) (s e_zy)
		%
		% clearly, the solution is not unique.
		% ONE choice is to employ the fact that e_zx = 0  (or, for 2d
		% plots, e_zx=0, e_zy=0 and e_yx=0):
		%
		% in that case, we can compute s such that the equation for W
		% is satisfied and compensate only the limit r_z, i.e. to
		% choose
		% s := W / w,    (scale to satisfy width constraint)
		% Rx := Ry := 1  (keep limits in X and Y)
		% Rz = ( H - s (w - r_z e_zy) ) / (s r_z e_zy)    (adjust z limit to satisfy height constraint)
		%
		% This approach works well if W < H . If W > H, it will look
		% bad: Rz will be less than 1, causing the limit to become
		% smaller. This, in turn, will clip away parts of the image.
		%
		% 
		%
		% Another solution is to make it the other way: to keep the
		% limit r_z, but to reduce the size and enlarge the other
		% limits to satisfy the size constraints. This solution is
		% considerably more involved; it requires to solve a nonlinear
		% set of equations.
		%
		% Formally, this second solution uses
		% Rz := 1       (no limit componensation scale for z -- keep z limit)
		% R:= Rx := Ry  (same limit componensation scale for both X and Y)
		% R and s still need to be determined from the two equations for W
		% and H.
		%
		% Substituting the given choices into the equations for W and H, we find
		%
		% R = W / (s w)
		%
		% s = H * (R * (h-r_z e_zy) + r_z e_zy)^-1
		%
		% Here, we employed the definition of 'h', see above. The
		% equations are non-linear.
		%
		% ATTENTION: we assume that the datascaletrafo set params
		% method has been called with THE SAME SCALE IN EACH
		% DIRECTION.
		\if0\pgfplots@scaleuniformly@choice
			% scale uniformly strategy=auto
			\pgfplots@get@scale@horiz@and@vert@scaleuniformly@of@optimal@strategy
		\else
			\pgfplots@get@scale@horiz@and@vert@scaleuniformly
			\pgfplots@BB@update@cumulative@limit@compensations
		\fi
	\fi
	%
	\xdef\pgfplots@glob@TMPa{%
		\noexpand\def\noexpand#3{\scalex}%
		\noexpand\def\noexpand#4{\scaley}%
		\noexpand\def\noexpand#5{\pgfplots@target@limitrescale@x}%
		\noexpand\def\noexpand#6{\pgfplots@target@limitrescale@y}%
		\noexpand\def\noexpand#7{\pgfplots@target@limitrescale@z}%
	}%
	\endgroup
	\pgfplots@glob@TMPa
}%

% This is the implementation for 'scale uniformly strategy=auto'.
%
% It works by finding the strategy which involves the minimal scaling
% overhead.
%
% To this end, it computes the result for each 'scale uniformly
% strategy', and computes a cost function. The one with optimal cost
% function wins, and its results are returned.
%
% The cost function is the overal scaling which is applied to AXIS
% LIMITS. It works as follows:
% 1. if a choice requires to REDUCE the axis limits in order to
% fulfill all constraints, it is neglected (using maximal cost 16000).
% Reducing axis limits may clip away information.
% 
% 2. if a choice requires to ENLARGE some axis limits, its cost is the
% sum of the individual scaling factors (even if they are are one -
% who cares).
%
% Note that this method *is* relevant and the optimization appears to
% be necessary. 
% Examples are
%   unittest_scalemode_2d_standard_1.tex
% and perhaps
%   unittest_scalemode_2d_standard_0.tex 
% and more involved 3d examples are also available.
%
% My first guess was that it is sufficient to decide the optimal
% strategy in advance by comparing the target width and the target
% height - but that proved to be insufficient: it leads to correct
% results, but wastes too much space (i.e. enlarges limits too much).
%
% ATTENTION: the cost function INCLUDES RESULTS OF 
%	\pgfplots@BB@for@plotbox@get@unit@scales@for@limits and its
%	corrector
%	\pgfplots@BB@for@plotbox@get@unit@scales@compensated@axis@limits.
%
% More precisely, it relies on already computes limit compensation
% factors which do not depend on the target width/target height: both
% \pgfplots@BB@for@plotbox@get@unit@scales@compensated@axis@limits and
% this implementation of  'scale uniformly strategy' can be used to compute 
% the cost of a strategy.
% 
\def\pgfplots@get@scale@horiz@and@vert@scaleuniformly@of@optimal@strategy{%
	\begingroup
		\def\mathclass{default}%
		\pgfplotscoordmath{\mathclass}{max limit}%
		\let\pgfplots@cost@for@choice@superhigh=\pgfmathresult%
		%
		% private helpers to compute the cost. 
		\def\pgfplots@scalestrategy@compute@cost{%
			\begingroup
			% ATTENTION: this call changes
			% '\pgfplots@target@limitrescale@x' and its variants.
			% Restore its value after the iteration:
			\pgfplots@BB@update@cumulative@limit@compensations
			\pgfplotscoordmath{\mathclass}{one}%
			\let\ONE=\pgfmathresult
			\pgfplotscoordmath{\mathclass}{parsenumber}{\pgfplots@target@limitrescale@x}%
			\let\X=\pgfmathresult
			\pgfplotscoordmath{\mathclass}{parsenumber}{\pgfplots@target@limitrescale@y}%
			\let\Y=\pgfmathresult
			\ifpgfplots@threedim
				\pgfplotscoordmath{\mathclass}{parsenumber}{\pgfplots@target@limitrescale@z}%
				\let\Z=\pgfmathresult
			\else
				\let\Z=\pgfplots@target@limitrescale@z
			\fi
			%
			% If one of the resulting limit compensation scales is
			% less than 1, we can immediately skip it - we do not want
			% to risk to clip away image content.
			\pgfplotscoordmath{\mathclass}{if less than}{\X}{\ONE}{%
				\let\pgfplots@cost@for@choice=\pgfplots@cost@for@choice@superhigh
			}{%
				\pgfplotscoordmath{\mathclass}{if less than}{\Y}{\ONE}{%
					\let\pgfplots@cost@for@choice=\pgfplots@cost@for@choice@superhigh
				}{%
					\ifpgfplots@threedim
						\pgfplotscoordmath{\mathclass}{if less than}{\Z}{\ONE}{%
							\let\pgfplots@cost@for@choice=\pgfplots@cost@for@choice@superhigh
						}{%
							% ah - 3 limit scales >= 1. Good, assign cost:
							\pgfplots@scalestrategy@compute@cost@
						}%
					\else
						% ah - all limit scales >=1. Good, assign cost:
						\pgfplots@scalestrategy@compute@cost@
					\fi
				}%
			}%
%\message{scale uniformly strategy=auto: '\pgfplots@tostring@scaleuniformlystrategy{\pgfplots@scaleuniformly@choice}' has cost \pgfplots@cost@for@choice\space(limit rescaling factors x=\X, y=\Y, z=\Z)^^J}%
			\xdef\pgfplots@glob@TMPa{%
				\noexpand\def\noexpand\pgfplots@scaleuniformly@choice{\pgfplots@scaleuniformly@choice}%
				\noexpand\def\noexpand\scalex{\scalex}%
				\noexpand\def\noexpand\scaley{\scaley}%
				\noexpand\def\noexpand\pgfplots@target@limitrescale@x{\pgfplots@target@limitrescale@x}%
				\noexpand\def\noexpand\pgfplots@target@limitrescale@y{\pgfplots@target@limitrescale@y}%
				\noexpand\def\noexpand\pgfplots@target@limitrescale@z{\pgfplots@target@limitrescale@z}%
			}%
			\pgfmath@smuggleone\pgfplots@cost@for@choice
			% keep in mind that this scope IS NECESSARY: we have
			% changed the target quantities
			% \pgfplots@target@limitrescale@x and its variants!
			\endgroup
			\let\pgfplots@scalestrategy@values=\pgfplots@glob@TMPa
		}%
		\def\pgfplots@scalestrategy@compute@cost@{%
			\pgfplotscoordmath{\mathclass}{op}{add}{{\X}{\Y}}%
			\ifpgfplots@threedim
				\pgfplotscoordmath{\mathclass}{op}{add}{{\pgfmathresult}{\Z}}%
			\fi
			\let\pgfplots@cost@for@choice=\pgfmathresult
		}%
		%
		% compute initial cost:
		\def\pgfplots@scaleuniformly@choice{3}% change horizontal limits
		\pgfplots@get@scale@horiz@and@vert@scaleuniformly
		\pgfplots@scalestrategy@compute@cost
		%
		% init minimum:
		\let\pgfplots@cost@for@choice@arg=\pgfplots@scalestrategy@values
		\let\pgfplots@cost@for@choice@sofar=\pgfplots@cost@for@choice%
		%
		% compute cost of next strategy:
		\def\pgfplots@scaleuniformly@choice{2}% change vertical limits
		\pgfplots@get@scale@horiz@and@vert@scaleuniformly
		\pgfplots@scalestrategy@compute@cost
		%
		% update minimum:
		\pgfplotscoordmath{\mathclass}{if less than}{\pgfplots@cost@for@choice}{\pgfplots@cost@for@choice@sofar}{%
			\let\pgfplots@cost@for@choice@arg=\pgfplots@scalestrategy@values
			\let\pgfplots@cost@for@choice@sofar=\pgfplots@cost@for@choice%
		}{%
		}%
		%
		\ifx\pgfplots@cost@for@choice@sofar\pgfplots@cost@for@choice@superhigh
			% the algorithm discarded every available strategy.
			\def\pgfplots@scaleuniformly@choice{1}% fall back to 'units only'
			\pgfplots@get@scale@horiz@and@vert@scaleuniformly
			\pgfplots@scalestrategy@compute@cost
			\let\pgfplots@cost@for@choice@arg=\pgfplots@scalestrategy@values
			\let\pgfplots@cost@for@choice@sofar=\pgfplots@cost@for@choice%
		\fi
		%
		%
	\global\let\pgfplots@glob@TMPa=\pgfplots@cost@for@choice@arg
	\endgroup
	\pgfplots@glob@TMPa
%\message{scale uniformly strategy=auto: choosing '\pgfplots@tostring@scaleuniformlystrategy{\pgfplots@scaleuniformly@choice}'^^J}%
}

\def\pgfplots@tostring@scaleuniformlystrategy#1{%
	% scale uniformly strategy:
	\ifcase#1\relax 
		auto
	\or
		units only
	\or
		change vertical limits
	\or
		change horizontal limits
	\fi
}
% Does the work for 'scale mode=scale uniformly' inside of
% \pgfplots@get@scale@horiz@and@vert.
%
% It returns its result into \pgfplots@target@limitrescale@x@ (i.e.
% with an extra '@')
\def\pgfplots@get@scale@horiz@and@vert@scaleuniformly{%
	\ifcase\pgfplots@scaleuniformly@choice\relax
		% scale uniformly strategy=auto does not happen here.
	\or
		% scale uniformly strategy=units only
		\pgfplots@scaleuniformly@onlyunits
	\or
		% scale uniformly strategy=change vertical limits
		%
		% first, scale to the width ...
		\pgfplots@scaleuniformly@onlyunits@{\w}{\W}%
		% ... and change (only) vertical limits to get the "correct"
		% height:
		\ifdim\pgf@zy=0pt
			\ifdim\pgf@yx=0pt
				\pgfplots@prepare@vertical@rescaling@for@scale@uniformly@in@dir{y}\returninto\pgfplots@target@limitrescale@y@
			\else
				\pgfplots@scale@uniformly@fallback
			\fi
		\else
			\ifdim\pgf@zx=0pt
				\pgfplots@prepare@vertical@rescaling@for@scale@uniformly@in@dir{z}\returninto\pgfplots@target@limitrescale@z@
			\else
				\pgfplots@scale@uniformly@fallback
			\fi
		\fi
	\or
		% scale uniformly strategy=change horizontal limits
		\ifdim\pgf@zy=0pt
			\ifdim\pgf@yx=0pt
				\ifdim\pgf@xy=0pt
					% special 2d routine with explicit solution
					\pgfplots@scaleuniformly@change@horizontal@limits@twodim
						{\scalex}
						{\pgfplots@target@limitrescale@x@}
						{\pgfplots@target@limitrescale@y@}
						{\pgfplots@target@limitrescale@z@}%
				\else
					\pgfplots@scale@uniformly@fallback
				\fi
			\else
				\pgfplots@scale@uniformly@fallback
			\fi
		\else
			\ifdim\pgf@zx=0pt
				\pgfplots@scaleuniformly@change@horizontal@limits
					{\scalex}
					{\pgfplots@target@limitrescale@x@}
					{\pgfplots@target@limitrescale@y@}
					{\pgfplots@target@limitrescale@z@}%
			\else
				\pgfplots@scale@uniformly@fallback
			\fi
		\fi
		\let\scaley=\scalex
	\fi
}

\def\pgfplots@scaleuniformly@onlyunits{%
	% scale to the smaller target dimension:
	\ifdim\W pt<\H pt %
		\pgfplots@scaleuniformly@onlyunits@{\w}{\W}%
	\else
		\pgfplots@scaleuniformly@onlyunits@{\h}{\H}%
	\fi
}%

% #1 : the actual dimension
% #2 : the target dimension
\def\pgfplots@scaleuniformly@onlyunits@#1#2{%
	\def\pgfplots@target@limitrescale@x@{1}%
	\def\pgfplots@target@limitrescale@y@{1}%
	\def\pgfplots@target@limitrescale@z@{1}%
	\pgfmathdivide@{#2}{#1}%
	\let\scalex=\pgfmathresult
	\let\scaley=\scalex % we *need* the same unit scale.
}%

% Computes 'scale uniformly strategy=change horizontal limits'.
% This is a complicated solution, see the documentation in the
% implementation for 
% 'scale mode=scale uniformly'
%
% #1 [output] a macro which will contain the (uniform) scale for the
% unit vectors
% #2 [output] a macro which will contain a x axis limit compensation scale
% #3 [output] a macro which will contain a x axis limit compensation scale
% #4 [output] a macro which will contain a x axis limit compensation scale
\def\pgfplots@scaleuniformly@change@horizontal@limits#1#2#3#4{%
	\begingroup
	%
	\pgfplots@BB@for@plotbox@getunitheight{\pgf@xc}{z}%
	%
	% compute the rest in floating point - intermediate results may
	% become too huge for TeX.
	\pgfplotscoordmath{default}{parsenumber}{\expandafter\pgf@sys@tonumber\csname pgf@xc\endcsname}%
	\let\M=\pgfmathresult
	%
	\pgfplotscoordmath{default}{parsenumber}{\w}%
	\let\w=\pgfmathresult
	\pgfplotscoordmath{default}{parsenumber}{\W}%
	\let\W=\pgfmathresult
	\pgfplotscoordmath{default}{parsenumber}{\h}%
	\let\h=\pgfmathresult
	\pgfplotscoordmath{default}{parsenumber}{\H}%
	\let\H=\pgfmathresult
	\pgfplotscoordmath{default}{op}{divide}{{\W}{\w}}%
	\let\Wwinv=\pgfmathresult
	\pgfplotscoordmath{default}{op}{subtract}{{\h}{\M}}%
	\let\hminusM=\pgfmathresult
	%
	\pgfplotscoordmath{default}{one}%
	\let\S=\pgfmathresult%
	\let\R=\pgfmathresult%
	\let\Rx=\pgfmathresult
	\def\Rz{1}%
	%
	\def\pgfplots@hold@S@get@R{%
		\pgfplotscoordmath{default}{op}{divide}{{\Wwinv}{\S}}%
		\let\R=\pgfmathresult
%\message{updated R = \R\space ( S = \S ) ^^J}%
	}%
	\def\pgfplots@hold@R@get@S{%
		\pgfplotscoordmath{default}{op}{multiply}{{\R}{\hminusM}}%
		\pgfplotscoordmath{default}{op}{add}{{\pgfmathresult}{\M}}%
		\pgfplotscoordmath{default}{op}{divide}{{\H}{\pgfmathresult}}%
		\let\S=\pgfmathresult
%\message{updated S = \S\space ( R = \R ) ^^J}%
	}%
	%
	% This is the (most stupid) nonlinear method which is at hand:
	% fix point iteration.
	% choose R arbitrarily (R=1 seems adequate), solve for s. 
	% Then, fix s and solve for R. Then, fix R and
	% solve for s until convergence.
	\c@pgf@countc=0
	\pgfplotsloop{%
		\ifnum\c@pgf@countc<\pgfkeysvalueof{/pgfplots/scale uniformly strategy iter} %
			\pgfplotsloopcontinuetrue
		\else
			\pgfplotsloopcontinuefalse
		\fi
	}{%
		\pgfplots@hold@R@get@S \pgfplots@hold@S@get@R
		\advance\c@pgf@countc by1 %
	}%
	%
	\pgfplotscoordmath{default}{tofixed}{\R}\let\R=\pgfmathresult
	\pgfplotscoordmath{default}{tofixed}{\S}\let\S=\pgfmathresult
	\xdef\pgfplots@glob@TMPa{%
		\noexpand\def\noexpand#1{\S}%
		\noexpand\def\noexpand#2{\R}%
		\noexpand\def\noexpand#3{\R}%
		\noexpand\def\noexpand#4{\Rz}%
	}%
	\endgroup
	%
	\pgfplots@glob@TMPa
}%

% Computes 'scale uniformly strategy=change horizontal limits'.
% 
% This is a simplified closed solution assuming that e_xy=0 and e_yx = 0
%
% #1 [output] a macro which will contain the (uniform) scale for the
% unit vectors
% #2 [output] a macro which will contain a x axis limit compensation scale
% #3 [output] a macro which will contain a x axis limit compensation scale
% #4 [output] a macro which will contain a x axis limit compensation scale
\def\pgfplots@scaleuniformly@change@horizontal@limits@twodim#1#2#3#4{%
	\begingroup
	% Assuming that we have a standard 2d axis, i.e. 
	% e_zx = e_zy = 0,  e_xy = 0, and e_yx =0,
	% we can immediately compute a solution.
	%
	% In this case, we have the actual width
	% w = r_x e_xx  + r_y e_yx + rz e_zx
	%   = r_x e_xx
	% and actual height
	% h = r_x e_xy  + r_y e_yy + rz e_zy
	%   = r_y e_yy
	% and, consequently, desired width
	% W = (Rx r_x) (s e_xx)  + (Ry r_y) (s e_yx)  + (Rz r_z) (s e_zx)
	%   = (Rx r_x) (s e_xx)
	% and desired height
	% H = (Rx r_x) (s e_xy)  + (Ry r_y) (s e_yy)  + (Rz r_z) (s e_zy)
	%   = (Ry r_y) (s e_yy).
	% since this strategy changes horizontal limits (only), we have
	% Ry := 1.
	% We find
	% s : = H/h 
	% and
	% Rx : = W/w /s .
	%
	\pgfplotscoordmath{default}{parsenumber}{\w}%
	\let\w=\pgfmathresult
	\pgfplotscoordmath{default}{parsenumber}{\W}%
	\let\W=\pgfmathresult
	\pgfplotscoordmath{default}{parsenumber}{\h}%
	\let\h=\pgfmathresult
	\pgfplotscoordmath{default}{parsenumber}{\H}%
	\let\H=\pgfmathresult
	\pgfplotscoordmath{default}{op}{divide}{{\H}{\h}}%
	\let\S=\pgfmathresult
	\pgfplotscoordmath{default}{op}{divide}{{\W}{\w}}%
	\pgfplotscoordmath{default}{op}{divide}{{\pgfmathresult}{\S}}%
	\let\Rx=\pgfmathresult
	\def\Ry{1}%
	\def\Rz{1}%
	%
	\pgfplotscoordmath{default}{tofixed}{\Rx}\let\Rx=\pgfmathresult
	\pgfplotscoordmath{default}{tofixed}{\S}\let\S=\pgfmathresult
	\xdef\pgfplots@glob@TMPa{%
		\noexpand\def\noexpand#1{\S}%
		\noexpand\def\noexpand#2{\Rx}%
		\noexpand\def\noexpand#3{\Ry}%
		\noexpand\def\noexpand#4{\Rz}%
	}%
	\endgroup
	%
	\pgfplots@glob@TMPa
}%

\def\pgfplots@BB@update@cumulative@limit@compensations{%
%\message{  -> additional limit componensation scales x=\pgfplots@target@limitrescale@x@, y=\pgfplots@target@limitrescale@y@, z=\pgfplots@target@limitrescale@z@^^J}%
	% add limit compensation to what we have from earlier
	% operations:
	\pgfplotscoordmath{pgfbasic}{op}{multiply}{{\pgfplots@target@limitrescale@x@}{\pgfplots@target@limitrescale@x}}%
	\let\pgfplots@target@limitrescale@x=\pgfmathresult
	\pgfplotscoordmath{pgfbasic}{op}{multiply}{{\pgfplots@target@limitrescale@y@}{\pgfplots@target@limitrescale@y}}%
	\let\pgfplots@target@limitrescale@y=\pgfmathresult
	\pgfplotscoordmath{pgfbasic}{op}{multiply}{{\pgfplots@target@limitrescale@z@}{\pgfplots@target@limitrescale@z}}%
	\let\pgfplots@target@limitrescale@z=\pgfmathresult
}%

\def\pgfplots@scale@uniformly@fallback{%
	\ifpgfplots@scaleuniformly@warning
		\pgfplotswarning{scale uniformly unsupported}\pgfeov%
	\fi
	\pgfplots@scaleuniformly@onlyunits
}%

% This is part of the implementation of 'scale mode=scale uniformly'.
%
% Its purpose it to set up the initial scaling such that 
% 1. each unit vector gets the same scale
% 2. the axis limits are resized (enlarged) to keep the plot box ratio
% (as far as possible)
%
% It repairs the outcome of
% \pgfplots@BB@for@plotbox@get@unit@scales@for@limits .
%
% The assumption is that on input #1, #2, and #3 are the factors which
% would be used by stretch-to-fill in order to squeze the axis limits
% into the plot box defined by e_x, e_y, and e_z (the unit vectors).
%
% On output, #1, #2, and #3 will be modified such that *each has the
% same value*. The value will be chosen with care. More precisely, it
% is the *minimum* of {#1,#2,#3}.
%
% Clearly, 'scale mode=scale uniformly' has less freedom than
% strech-to-fill. In order to keep the plot box ratio intact (as far
% as possible), the axis limits will be rescaled to componsate for the
% ignored scaling factors. More precisely, if direction i is not the
% extremal value (as discussed in the last paragraph), the axis limits
% will be rescaled by #i/extremum .
%
%
%
% #1: on input, it contains the x unit scale which would be taken without the
% compensation. On output, it contains the x unit scale which *will* be
% used.
% #2: same as #1, but for y
% #3: same as #1, but for z
% #4: [output] a scale for use as argument of \pgfplots@apply@unit@vector@rescale@keep@size{x}{<arg>}
% #5: [output] a scale for use as argument of \pgfplots@apply@unit@vector@rescale@keep@size{y}{<arg>}
% #6: [output] a scale for use as argument of \pgfplots@apply@unit@vector@rescale@keep@size{z}{<arg>}
%
% The output arguments need to be applied before they take effect.
\def\pgfplots@BB@for@plotbox@get@unit@scales@compensated@axis@limits#1#2#3#4#5#6{%
	\begingroup
	% ATTENTION : this code ASSUMES that the datascaling trafo is
	% initialized with THE SAME SCALE IN EACH DIRECTION.
	% The data scaling also leads to (potentially non-uniform) scaling per component.
	%
	% Note that we could handle the datascaling here -- but we would
	% leave the supported number range easily. That's why that part of
	% the 'scale mode=scale uniformly' implementation has been moved
	% to \pgfplots@set@optimal@datatrafos@allaxes
	%
	% This here handles the limits only.
	\edef\pgfplots@scale@unitx{#1}%
	\edef\pgfplots@scale@unity{#2}%
	\edef\pgfplots@scale@unitz{#3}%
	%
	% compute extreme + arg extreme of these scales:
	\def\pgfplots@extreme@scale{-16300}%
	\def\pgfplots@extreme@scale@arg{NONE}%
	%
	\if0\b@pgfplots@unitvec@is@zero@x
		\ifdim\pgfplots@extreme@scale pt<\pgfplots@scale@unitx pt
			\let\pgfplots@extreme@scale=\pgfplots@scale@unitx
			\def\pgfplots@extreme@scale@arg{x}%
		\fi
	\fi
	\if0\b@pgfplots@unitvec@is@zero@y
		\ifdim\pgfplots@extreme@scale pt<\pgfplots@scale@unity pt
			\let\pgfplots@extreme@scale=\pgfplots@scale@unity
			\def\pgfplots@extreme@scale@arg{y}%
		\fi
	\fi
	\if0\b@pgfplots@unitvec@is@zero@z
		\ifdim\pgfplots@extreme@scale pt<\pgfplots@scale@unitz pt
			\let\pgfplots@extreme@scale=\pgfplots@scale@unitz
			\def\pgfplots@extreme@scale@arg{z}%
		\fi
	\fi
	%
	% Now, adjust axis limits to compensate for the effect: we still
	% want to have a plot box which is as close as possible to the
	% target plot box.
	\def\pgfplots@loc@TMPa##1##2{%
		\if0\csname b@pgfplots@unitvec@is@zero@##1\endcsname
			\if1\pgfplots@scaleuniformly@choice % FIXME : this appears to be too much. Disable this!?
				% ok, nothing to do for this direction.
				\pgfplotscoordmath{pgfbasic}{one}%
				\let##2=\pgfmathresult
			\else
				\if\pgfplots@extreme@scale@arg ##1%
					% ok, nothing to do for this direction.
					\pgfplotscoordmath{pgfbasic}{one}%
					\let##2=\pgfmathresult
				\else
					\pgfplotscoordmath{pgfbasic}{op}{divide}{{\pgfplots@extreme@scale}{\csname pgfplots@scale@unit##1\endcsname}}%
					% do not call apply@unit@rescale immediately because the
					% unit vectors may not be in their final state. Postpone until
					% they are final.
					\edef##2{\pgfmathresult}%
				\fi
			\fi
		\else
			\def##2{1}%
		\fi
	}%
	\pgfplots@loc@TMPa{x}{#4}%
	\pgfplots@loc@TMPa{y}{#5}%
	\pgfplots@loc@TMPa{z}{#6}%
	%
	\toks0=\expandafter{#4}%
	\toks1=\expandafter{#5}%
	\toks2=\expandafter{#6}%
	\xdef\pgfplots@glob@TMPa{%
		% same scale in each dir:
		\def\noexpand#1{\pgfplots@extreme@scale}%
		\def\noexpand#2{\pgfplots@extreme@scale}%
		\def\noexpand#3{\pgfplots@extreme@scale}%
		\def\noexpand#4{\the\toks0}%
		\def\noexpand#5{\the\toks1}%
		\def\noexpand#6{\the\toks2}%
	}%
	\endgroup
	\pgfplots@glob@TMPa
}

% #1 : a dimen register
% #2 : x, y, or z
\def\pgfplots@BB@for@plotbox@getunitheight#1#2{%
	#1=\csname pgfplots@plotbox@#2max\endcsname\csname pgf@#2y\endcsname
	\advance#1 by -\csname pgfplots@plotbox@#2min\endcsname\csname pgf@#2y\endcsname
	\ifdim#1<0pt %
		% we want to return a height. It is also bigger than 0.
		% the difference above may be negative if the unit points
		% downward (special combinations of view/h and view/v)
		#1=-#1\relax
	\fi
}%


% Modifies the AXIS LIMITS to ensure that a suitable width/height is
% achieved.
%
% This does NOT introduce a further scale to the unit vectors.
%
% #1: a direction (x,y, or z)
% #2: a macro name. It will be assigned globally. It will contain
% EXECUTABLE instructions which will modify the axis limits to fit the
% scaling.
%
% PRECONDITION: 
% - \pgfplots@glob@TMPa contains the already computed
% scaling factor for 'scale uniformly'
% - \pgf@xb is the actual height and \pgf@yb is the desired height
%   (set as in the scaling routine)
%
% POSTCONDITION:
% #2 will contain the argument <arg> for \pgfplots@apply@unit@vector@rescale@keep@size{#1}{<arg>}
\def\pgfplots@prepare@vertical@rescaling@for@scale@uniformly@in@dir#1\returninto#2{%
	% The strategy is as follows:
	% 1. I want to fit the axis into width #1 (\pgf@ya) and
	% height #1 (\pgf@yb).
	% 2. I want to MAINTAIN the unit vector ratio. 
	% 3. I want to MAINTAIN the unit vector directions.
	%
	% I already know the scaling factor to fit the width (it
	% is stored in \scalex = \scaley).
	% Let's call it "s".
	%
	% Consequently, a uniform scaling by "s" leads to the image
	% height
	% h = s* (r_x * e_xy + r_y * e_yy + r_z * e_zy)
	% where r_i = (imax - imin). This here is essentially the
	% same as the bounding box computation above (at least for
	% standart orthographic 3D axes).
	%
	% What I want now is to enlarge the limits such that I
	% have BOTH, width #1 AND height #2, without obscuring the
	% unit vector ratio. Recall that width #1 is already
	% given.
	%
	% This strategy achieves this goal by
	% modifying axis limits for an axis whose unit vector is
	% parallel to the canvas y axis, i.e. e_i = (0,*). 
	%
	% That means I have to introduce a SECOND scale s_z which
	% applies only to the Z unit vector (since e_z = (0,*) ).
	% If H = #2 is the desired height, I find the target
	% equation for s_z,
	%
	% H = s* r_x e_xy + s * r_y e_yy + s_z * s * r_z * e_zy
	% =>
	% s_z = ( H- s*r_x e_xy - s*r_y e_yy) / ( s * r_z * e_zy).
	%
	% Remember that 
	% s = \scalex
	% H = \H
	% h = r_x * e_xy + r_y * e_yy + r_z * e_zy  = \h
	% =>
	% s_z = ( H- s*( h - r_z * e_zy) ) / ( s * r_z * e_zy).
	% 
	\begingroup
	\pgfplots@BB@for@plotbox@getunitheight{\pgf@xc}{#1}%
	%
	% compute the rest in floating point - intermediate results may
	% become too huge for TeX.
	\pgfplotscoordmath{default}{parsenumber}{\expandafter\pgf@sys@tonumber\csname pgf@xc\endcsname}%
	\let\pgfplots@diff=\pgfmathresult
	%
	\pgfplotscoordmath{default}{parsenumber}{\scalex}%
	\let\pgfplots@s=\pgfmathresult
	%
	% this is a precondition of this method:
	\pgfplotscoordmath{default}{parsenumber}{\h}%
	\let\h=\pgfmathresult
	\pgfplotscoordmath{default}{parsenumber}{\H}%
	\let\H=\pgfmathresult
	%
	% compute counter := H - s * (h - (max-min))
	\pgfplotscoordmath{default}{op}{subtract}{{\h}{\pgfplots@diff}}%
	\pgfplotscoordmath{default}{op}{multiply}{{\pgfplots@s}{\pgfmathresult}}%
	\pgfplotscoordmath{default}{op}{subtract}{{\H}{\pgfmathresult}}%
	\let\pgfplots@counter=\pgfmathresult
	%
	% computer denom := s * (max-min)
	\pgfplotscoordmath{default}{op}{multiply}{{\pgfplots@s}{\pgfplots@diff}}%
	\let\pgfplots@denom=\pgfmathresult
	%
	\pgfplotscoordmath{default}{op}{divide}{{\pgfplots@counter}{\pgfplots@denom}}%
	\pgfplotscoordmath{default}{tofixed}{\pgfmathresult}%
	%
	% Now, s_z = \pgfmathresult .
	%
	% Now, adjust the z limits.
	% Note that \pgfplots@apply@unit@vector@rescale@keep@size
	% has a slightly different context; it assumes that the
	% unit vector has been rescaled, not the axis limits.
	% Consequently, the inverse of the scaling factor enters.
	% Since \pgfplots@apply@unit@vector@rescale@keep@size
	% expects the inverse of the scale, we can provide
	% \pgfmathresult:
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
	\let#2=\pgfmathresult
}

\def\pgfplots@computeunitvectorlengths{%
	\pgfplotsutil@edef@invoke\pgfmathveclen@{%
		{\pgf@sys@tonumber\pgf@xx}%
		{\pgf@sys@tonumber\pgf@xy}%
	}%
	\let\pgfplots@x@veclength=\pgfmathresult
	\pgfplotsmath@ifzero{\pgfplots@x@veclength}{%
		\def\pgfmathresult{infty}%
		% this case will be caught in \pgfplots@initsizes
	}{%
		\expandafter\pgfmath@basic@reciprocal@\expandafter{\pgfmathresult}%
	}%
	\let\pgfplots@x@inverseveclength=\pgfmathresult
	%
	\pgfplotsutil@edef@invoke\pgfmathveclen@{%
		{\pgf@sys@tonumber\pgf@yx}%
		{\pgf@sys@tonumber\pgf@yy}%
	}%
	\let\pgfplots@y@veclength=\pgfmathresult
	\pgfplotsmath@ifzero{\pgfplots@y@veclength}{%
		\def\pgfmathresult{infty}%
		% this case will be caught in \pgfplots@initsizes
	}{%
		\expandafter\pgfmath@basic@reciprocal@\expandafter{\pgfmathresult}%
	}%
	\let\pgfplots@y@inverseveclength=\pgfmathresult
	%
	\ifpgfplots@threedim
		\pgfplotsutil@edef@invoke\pgfmathveclen@{%
			{\pgf@sys@tonumber\pgf@zx}%
			{\pgf@sys@tonumber\pgf@zy}%
		}%
		\let\pgfplots@z@veclength=\pgfmathresult
		\pgfplotsmath@ifzero{\pgfplots@z@veclength}{%
			\def\pgfmathresult{infty}%
			% this case will be caught in \pgfplots@initsizes
		}{%
			\expandafter\pgfmath@basic@reciprocal@\expandafter{\pgfmathresult}%
		}%
		\let\pgfplots@z@inverseveclength=\pgfmathresult
	\else
		\def\pgfplots@z@veclength{0}%
		\def\pgfplots@z@inverseveclength{infty}%
	\fi
}%

% Defines \pgfplots@view@dir@threedim according to the actual
% configuration of x,y,z (2d) unit vectors, assuming the associated
% unit vectors form a right-handed-system.
%
% The algorithm works for standard three dimensional axes. It works as
% follows:
%
% First, observe that we have a normal direction N if all its
% multiples are mapped onto the same point in 2D canvas
% coordinates. In other words: all 3D coordinates which are mapped
% onto an arbitrary point in 2D canvas coordinates (take, for example,
% the origin (0,0)  ) are on a line in direction of N.
%
% We use this observation to compute the normal axis, i.e. we search
% for all points which are mapped onto the 2D canvas coordinate (0,0):
%  N_x e_xx + N_y e_yx + N_z e_zx = 0
%  N_x e_xy + N_y e_yy + N_z e_zy = 0.
% All solutions make up a linear space of dimension 1 (up to special
% cases). In the general case, we can chose an arbitrary  N_z != 0
% and reduce the linear system to
%  N_x e_xx + N_y e_yx = - N_z e_zx
%  N_x e_xy + N_y e_yy = - N_z e_zy.
% Choosing *any* N_z != 0, say, N_z=-1 (which corresponds to view
% from above) will lead to a vector parallel to the normal direction.
% But it might have the wrong sign.
%
% FIXME : this fails if one of e_x or e_y is zero.
%
% To find the correct sign for N, I have made several case
% distinctions to identify the cases when we have to multiply with -1.
% The key idea is to assume a right-handed-system of unit vectors;
% this is the condition which allows to determine the sign.
%
% Furthermore, I assume that e_z points to the top, i.e. that e_zy >0.
% Then, there are (mainly) four conditions on the signs of e_x and e_y
% which indicate that we are viewing from below and should switch the
% sign of N (keep in mind that our initial choice was N_z =-1, see above).
%
% The conditions can be identified by drawing a 3D box and
% identifying the corner which represents the lower left 3D limits.
%
% You can visualize these cases using
%--------------------------------------------------
% \pgfplotsset{
% 		separate axis lines,
% 		every outer x axis line/.append style= {-stealth},
% 		every outer y axis line/.append style= {-stealth},
% 		every outer z axis line/.append style= {-stealth},
% 		samples=2,shader=interp,title={view=\h,\v},
% 		domain=0:1,
% 		enlargelimits=false,
% 		view=\h\v,xlabel=x,ylabel=y,
% 		extra description/.code={%
% 			\node[draw,fill=white] at (axis cs:0,0,0) {};
% 		},
% }
% 
% \def\v{30}
% \foreach \h in {30,120,210,300} {
% \message{VIEW={\h}{\v}^^J}
% \begin{tikzpicture}
% 	\begin{axis}
% 	\addplot3[surf] {x};
% 	\end{axis}
% \end{tikzpicture}
% 
% }
% 
% \def\v{-30}
% \foreach \h in {30,120,210,300} {
% \message{VIEW={\h}{\v}^^J}
% \begin{tikzpicture}
% 	\begin{axis}
% 	\addplot3[surf] {x};
% 	\end{axis}
% \end{tikzpicture}
% 
% }
%-------------------------------------------------- 
%  The precise formulas can be found below in the source code.
%
% You can override this function by the /pgfplots/view dir key.
\def\pgfplotsgetnormalforcurrentview{%
	\pgfkeysgetvalue{/pgfplots/view dir}\pgfplots@loc@TMPc
	\ifx\pgfplots@loc@TMPc\pgfutil@empty
	\begingroup	
		% temporarily undo the effects of reversed axes -- we *really*
		% need a right-handed-coordinate system here:
		\if r\pgfkeysvalueof{/pgfplots/x dir/value}%
			\pgf@xx=-\pgf@xx
			\pgf@xy=-\pgf@xy
		\fi
		\if r\pgfkeysvalueof{/pgfplots/y dir/value}%
			\pgf@yx=-\pgf@yx
			\pgf@yy=-\pgf@yy
		\fi
		\if r\pgfkeysvalueof{/pgfplots/z dir/value}%
			\pgf@zx=-\pgf@zx
			\pgf@zy=-\pgf@zy
		\fi
		% FIRST: check for special cases.
		\let\pgfplots@view@dir@threedim=\pgfutil@empty%
		% Special case:
		% e_xx = e_xy = 0 
		%
		% i.e.:
		%
		%   ^
		%   | |---|
		%   z |   |
		%     |---|
		%       y->
		% 
		% In this case, N must be the x axis.
		\ifdim\pgf@xx=0pt %
			\ifdim\pgf@xy=0pt %
				\def\pgfplots@view@dir@threedim{-1,0,0}%
			\fi
		\fi
		% Special case:
		% e_yx = e_yy = 0 
		%
		% i.e.:
		%
		%   ^
		%   | |---|
		%   z |   |
		%     |---|
		%       x->
		% 
		% In this case, N must be the y axis.
		\ifdim\pgf@yx=0pt %
			\ifdim\pgf@yy=0pt %
				\def\pgfplots@view@dir@threedim{0,1,0}%
			\fi
		\fi
		% Special case:
		% e_xy = e_yy = 0  (i.e. one row)
		%
		% that is hard to draw, use view={30}{0} to see it. 
		% 
		% In this case, N_z must be 0 and we have a different system.
		\ifdim\pgf@xy=0pt %
			\ifdim\pgf@yy=0pt %
				\ifx\pgfplots@view@dir@threedim\pgfutil@empty
					% we have N_x e_xx + N_y e_yx = 0
					% Note that e_xx != 0 and e_yx != 0 (otherwise one
					% of our other special cases above would have
					% caught the case)
					% -> we have N_x = -N_y e_yx / e_xx and N_y
					%  arbitrary. only the sign needs to be fixed.
					\def\pgfplots@view@dir@threedim@z{0}%
					\def\pgfplots@view@dir@threedim@y{1}% fix it somehow. We correct the sign later.
					\edef\pgfplots@loc@TMPa{-(\pgfplots@view@dir@threedim@y) * \pgf@sys@tonumber\pgf@yx / (\pgf@sys@tonumber\pgf@xx)}%
					\pgfmathparse{\pgfplots@loc@TMPa}%
					\let\pgfplots@view@dir@threedim@x=\pgfmathresult
					%
					\def\pgfplots@scale{1}%
					% I identified these cases by comparing the
					% results with \pgfplots@scale{1} with those of
					% the view dir generated by
					% \pgfplotssetaxesfromazel (which has the correct quality of solution)
					\ifdim\pgf@zy>0pt %
						\ifdim\pgf@xx<0pt %
							\def\pgfplots@scale{-1}%
						\fi
					\else
						\ifdim\pgf@xx>0pt %
							\def\pgfplots@scale{-1}%
						\fi
					\fi
					\pgfmathmultiply@{\pgfplots@scale}{\pgfplots@view@dir@threedim@x}%
					\let\pgfplots@view@dir@threedim@x\pgfmathresult
					\pgfmathmultiply@{\pgfplots@scale}{\pgfplots@view@dir@threedim@y}%
					\let\pgfplots@view@dir@threedim@y\pgfmathresult
					\pgfmathmultiply@{\pgfplots@scale}{\pgfplots@view@dir@threedim@z}%
					\let\pgfplots@view@dir@threedim@z\pgfmathresult
					%
					\edef\pgfplots@view@dir@threedim{\pgfplots@view@dir@threedim@x,\pgfplots@view@dir@threedim@y,\pgfplots@view@dir@threedim@z}%
				\else
					% Ah - we already caught that special case above.
				\fi
			\fi
		\fi
		%
		% NOTE : the case e_xx = e_yx = 0 IS NO USE-CASE (would
		% require a rotated z axis which is forbidden currently)
		%
		\ifx\pgfplots@view@dir@threedim\pgfutil@empty
			\def\pgfplots@view@dir@threedim@z{-1}% hold it at some arbitrary value
			\pgf@xa=-\pgfplots@view@dir@threedim@z\pgf@zx
			\pgf@ya=-\pgfplots@view@dir@threedim@z\pgf@zy
			\edef\pgfplots@loc@TMPa{%
				{%
					{\pgf@sys@tonumber\pgf@xx}{\pgf@sys@tonumber\pgf@yx}%
					{\pgf@sys@tonumber\pgf@xy}{\pgf@sys@tonumber\pgf@yy}%
				}%
				{%
					{\pgf@sys@tonumber\pgf@xa}{\pgf@sys@tonumber\pgf@ya}%
				}%
			}%
			\expandafter\pgfutilsolvetwotwoleq\pgfplots@loc@TMPa
			\def\pgfplots@loc@TMPb##1##2{%
				\def\pgfplots@view@dir@threedim@x{##1}%
				\def\pgfplots@view@dir@threedim@y{##2}%
			}%
			\expandafter\pgfplots@loc@TMPb\pgfmathresult
			%
			% Identify if we need to switch the sign.
			% To verify that these cases are useful, I suggest visualizing
			% that stuff using the TeX code from above...
			%
			% I guess it is correct up to collapsing views (as you see, I
			% did not properly identify the cases with "=0" )
			\def\pgfplots@scale{1}%
			\ifdim\pgf@xx>0pt
				\ifdim\pgf@yx<0pt
				\else
					%
					\ifdim\pgf@xy<0pt
					\else
						\ifdim\pgf@yy<0pt
							\def\pgfplots@scale{-1}%
						\fi
					\fi
					%
				\fi
			\else
				\ifdim\pgf@xx<0pt
					\ifdim\pgf@yx>0pt
					\else
						%
						\ifdim\pgf@xy>0pt
						\else
							\ifdim\pgf@yy>0pt
								\def\pgfplots@scale{-1}%
							\fi
						\fi
						%
					\fi
				\fi
			\fi
			\ifdim\pgf@xy>0pt
				\ifdim\pgf@yy<0pt
				\else
					%
					\ifdim\pgf@xx>0pt
					\else
						\ifdim\pgf@yx>0pt
							\def\pgfplots@scale{-1}%
						\fi
					\fi
					%
				\fi
			\else
				\ifdim\pgf@xy<0pt
					\ifdim\pgf@yy>0pt
					\else
						%
						\ifdim\pgf@xx<0pt
						\else
							\ifdim\pgf@yx<0pt
								\def\pgfplots@scale{-1}%
							\fi
						\fi
						%
					\fi
				\fi
			\fi
			\pgfmathmultiply@{\pgfplots@scale}{\pgfplots@view@dir@threedim@x}%
			\let\pgfplots@view@dir@threedim@x\pgfmathresult
			\pgfmathmultiply@{\pgfplots@scale}{\pgfplots@view@dir@threedim@y}%
			\let\pgfplots@view@dir@threedim@y\pgfmathresult
			\pgfmathmultiply@{\pgfplots@scale}{\pgfplots@view@dir@threedim@z}%
			\let\pgfplots@view@dir@threedim@z\pgfmathresult
			%
			\pgfplotsmathvectorfromstring{\pgfplots@view@dir@threedim@x,\pgfplots@view@dir@threedim@y,\pgfplots@view@dir@threedim@z}{default}%
			\let\pgfplots@view@dir@threedim=\pgfplotsretval
			% normalize. This is not absolutely required -- but it is used
			% to accumulate point depth (for the mesh handler) in pgfmath
			% arithmetics. At least \pgfplotsmathviewdepthxyz should use
			% a properly scaled view dir.
			\pgfplotsmathvectorlength{\pgfplotsretval}{default}%
			\pgfplotscoordmath{default}{op}{reciprocal}{{\pgfplotsretval}}%
			\pgfplotsmathvectorscale{\pgfplots@view@dir@threedim}{\pgfmathresult}{default}%
		\else
			\pgfplotsmathvectorfromstring{\pgfplots@view@dir@threedim}{default}%
		\fi
		%
		\pgfmath@smuggleone\pgfplotsretval
	\endgroup
		\let\pgfplots@view@dir@threedim=\pgfplotsretval
	\else
		\def\pgfplots@loc@TMPb##1##2##3{%
			\pgfplotsmathvectorfromstring{##1,##2,##3}{default}%
			\let\pgfplots@view@dir@threedim=\pgfplotsretval
		}%
		\expandafter\pgfplots@loc@TMPb\pgfplots@loc@TMPc
	\fi
%\message{\string\pgfplotsgetnormalforcurrentview:  got (\pgfplots@view@dir@threedim)^^J}%
}%

% PRECONDITION:
% 	none
% POSTCONDITION:
% 	\pgfplots@default@aspect@ratio is set.
\def\pgfplots@compute@default@aspect@ratio{%
	\expandafter\pgfmath@x\axisdefaultwidth
	\expandafter\pgfmath@y\axisdefaultheight
	\pgfmathlog@invoke@expanded\pgfmathdivide@{%
		{\pgf@sys@tonumber{\pgfmath@x}}%
		{\pgf@sys@tonumber{\pgfmath@y}}%
	}%
	\let\pgfplots@default@aspect@ratio=\pgfmathresult
}

\def\pgfplots@ifneeds@one@uniform@datascale#1#2{%
	\if3\pgfplots@scale@mode@choice
		% scale mode=scale uniformly
		\def\pgfplots@loc@TMPa{1}%
		%
		% if we have at least one unit vector given explicitly, the
		% meaning changes: in that case, we can (and probably should)
		% use different data scale factors in each direction.
		\ifx\pgfplots@x\pgfutil@empty
		\else
			\def\pgfplots@loc@TMPa{0}%
		\fi
		\ifx\pgfplots@y\pgfutil@empty
		\else
			\def\pgfplots@loc@TMPa{0}%
		\fi
		\ifx\pgfplots@z\pgfutil@empty
		\else
			\def\pgfplots@loc@TMPa{0}%
		\fi
	\else
		\def\pgfplots@loc@TMPa{0}%
	\fi
	\if1\pgfplots@loc@TMPa
		#1%
	\else
		#2%
	\fi
}%

\def\pgfplots@set@default@size@options{%
	% The axes 'x' and 'y' vectors will be scaled such that the total
	% size is (\axisdefaultwidth, \axisdefaultheight).
	%
	% If the user specifies ONE of width OR height, 
	% the plot will be resized; keeping the aspect ratio.
	%
	\let\pgfplots@default@aspect@ratio=\pgfutil@empty
	\pgfkeysgetvalue{/pgfplots/x}{\pgfplots@x}%
	\pgfkeysgetvalue{/pgfplots/y}{\pgfplots@y}%
	\pgfkeysgetvalue{/pgfplots/z}{\pgfplots@z}%
	%\pgfkeysgetvalue{/pgfplots/viewdir}{\pgfplots@viewdir}%
	\pgfkeysgetvalue{/pgfplots/width}{\pgfplots@width}%
	\pgfkeysgetvalue{/pgfplots/height}{\pgfplots@height}%
	\ifx\pgfplots@width\pgfutil@empty
		\def\pgfplots@user@provided@width{0}%
	\else
		\def\pgfplots@user@provided@width{1}%
		\pgfmathparse{\pgfplots@width}%
		\edef\pgfplots@width{\pgfmathresult pt}%
	\fi
	\ifx\pgfplots@height\pgfutil@empty
		\def\pgfplots@user@provided@height{0}%
	\else
		\def\pgfplots@user@provided@height{1}%
		\pgfmathparse{\pgfplots@height}%
		\edef\pgfplots@height{\pgfmathresult pt}%
	\fi
	%
	% CASES:
	% W := 'width' option non-empty
	% H := 'height' option non-empty
	%
	% 		W H
	% 		0 0 -> \axisdefaultwidth 
	% 		0 1 -> determine width out of H and the default aspect ratio
	% 		1 X -> ok, use the user parameter.
	% -> KEEP ASPECT RATIO if just one W, or H is given!
	\ifx\pgfplots@width\pgfutil@empty
		\ifx\pgfplots@height\pgfutil@empty
			% The case W=0 H=0:
			\let\pgfplots@width=\axisdefaultwidth
			\let\pgfplots@height=\axisdefaultheight
		\else
			% The case W=0 H=1:
			\pgfplots@compute@default@aspect@ratio
			\expandafter\pgfmath@y\pgfplots@height
			\pgfmathlog@invoke@expanded\pgfmathmultiply@{%
				{\pgf@sys@tonumber{\pgfmath@y}}%
				{\pgfplots@default@aspect@ratio}%
			}%
			\edef\pgfplots@width{\pgfmathresult pt}%
		\fi
	\else
		\ifx\pgfplots@height\pgfutil@empty
			% The case W=1 H=0:
			\pgfplots@compute@default@aspect@ratio
			\expandafter\pgfmath@x\pgfplots@width
			\pgfmathlog@invoke@expanded\pgfmathdivide@{%
				{\pgf@sys@tonumber{\pgfmath@x}}%
				{\pgfplots@default@aspect@ratio}%
			}%
			\edef\pgfplots@height{\pgfmathresult pt}%
		\else
			% The case W=1 H=1:
		\fi
	\fi
	\pgfkeyslet{/pgfplots/width}{\pgfplots@width}%
	\pgfkeyslet{/pgfplots/height}{\pgfplots@height}%
	%
	\ifpgfplots@threedim
		\pgfplots@set@default@size@options@threedim
	\fi
	%
	\pgfplots@set@scale@mode
}

% This method must be called BEFORE THE DATASCALING is initialized.
\def\pgfplots@set@scale@mode{%
	\pgfkeysgetvalue{/pgfplots/unit vector ratio}\pgfplots@loc@TMPb
	\ifx\pgfplots@loc@TMPb\pgfutil@empty
	\else
		\ifcase\pgfplots@scale@mode@choice
			% 'scale mode'=auto
			\def\pgfplots@scale@mode@choice{3}% set to 'scale uniformly'
			%
			\if1\pgfplots@compat@scale@mode@compatible@mode
				% backwards compatibility mode...
				\ifpgfplots@threedim
					% ... for 3d: there is no backwards compatibility
					% mode here; it was plain wrong for 3d axes:
					% neither lengths nor angles have been correct.
					\pgfplots@compat@scale@mode@compatible@mode@warning
				\fi
			\fi
		\or
			% scale mode=none: keep it this way.
			\immediate\write-1{PGFPlots: scale mode=none  and unit vector ratio is incompatible. Ignoring unit vector ratio.^^J}%
		\or
			% scale mode=stretch to fill
			\immediate\write-1{PGFPlots: scale mode=stretch to fill  and unit vector ratio might produce unexpected results. Consider using scale mode=auto^^J}%
		\fi
	\fi
	%
}

\def\pgfplots@compat@scale@mode@compatible@mode@warning{%
	\pgfplotswarning{axis equal incompatible change}\pgfeov%
}%

\def\pgfplots@set@default@size@options@threedim{%
	\pgfplots@loc@tmpfalse
	\ifx\pgfplots@x\pgfutil@empty
	\else
		\pgfplots@loc@tmptrue
	\fi
	\ifx\pgfplots@y\pgfutil@empty
	\else
		\pgfplots@loc@tmptrue
	\fi
	\ifx\pgfplots@z\pgfutil@empty
	\else
		\pgfplots@loc@tmptrue
	\fi
	\ifpgfplots@loc@tmp
		% oh - we have at least one of the [xyz] unit vectors!
		% make sure all of them are there
		\ifx\pgfplots@x\pgfutil@empty
			\pgfplots@set@default@size@options@threedim@{x}{(1pt,0pt)}%
		\fi
		\ifx\pgfplots@y\pgfutil@empty
			\pgfplots@set@default@size@options@threedim@{y}{(0pt,1pt)}%
		\fi
		\ifx\pgfplots@z\pgfutil@empty
			\pgfplots@set@default@size@options@threedim@{z}{(0pt,1pt)}%
		\fi
		\pgfkeyslet{/pgfplots/view/az}\pgfutil@empty
		\pgfkeyslet{/pgfplots/view/el}\pgfutil@empty
	\fi
}
\def\pgfplots@set@default@size@options@threedim@#1#2{%
	\pgfplots@error{Sorry, a 3D axis needs either NONE or ALL of "x,y,z". I found partial information, but (at least) '#1' is lacking... please add '#1'}%
	\expandafter\def\csname pgfplots@#1\endcsname{#2}%
}

% A helper method for \pgfplots@initsizes which
% - applies the data scaling trafo to user arguments
% - sets calls pgfset#1vec
%
% #1: the vector to set (either 'x' or 'y')
% #2: the index of the vector to set (either 0 or 1)
% #3: the already precomputed temporary scale (see pgfplots@initsizes)
% #4: an output argument. It is a macro name which will be defined to
% '1' if and only if the finally set vector is parallel to the #1 axis
% of PGF, that means (x,0) for #1=x and (0,y) for #2=y.
\def\pgfplots@initsizes@setunitvector#1#2#3#4{%
	\pgfkeysgetvalue{/pgfplots/#1 dir/value}\pgfplots@loc@dirvalue
	\expandafter\let\expandafter\pgfplots@loc@TMPb\csname pgfplots@#1\endcsname
	\ifx\pgfplots@loc@TMPb\pgfutil@empty
		\def#4{1}% we have (#1,0) or (0,#1)
		%
%\message{Setting unitvector(#1) to auto-computed multiple of e_#2 ...}%
		\edef\pgfplots@loc@TMPa{#3}%
		\if r\pgfplots@loc@dirvalue
			\edef\pgfplots@loc@TMPa{-#3}%
		\fi
		\ifcase#2\relax
			\pgfsetxvec{\pgfqpoint{\pgfplots@loc@TMPa pt}{0pt}}%
		\or
			\pgfsetyvec{\pgfqpoint{0pt}{\pgfplots@loc@TMPa pt}}%
		\or
			\pgfsetzvec{\pgfqpoint{\pgfplots@loc@TMPa pt}{\pgfplots@loc@TMPa pt}}%
		\fi
	\else
		% Ok, we have a user-defined unit vector.
		%
		% That means we also need to apply the scaling trafo!
		%
		% 1. Check whether we have a complete vector of type (x,y):
		\expandafter\pgfutil@in@\expandafter(\expandafter{\pgfplots@loc@TMPb}%
		\ifpgfutil@in@
			% YES: we have (x,y):
			%
			\def#4{0}% we DON'T have (#1,0) or (0,#1). At least I think so.
			%
%\message{Setting unitvector(#1) to non-standard \csname pgfplots@#1\endcsname ...}%
			\def\pgfplots@loc@TMPa(##1,##2){%
				\pgfplotscoordmath{default}{parse}{##1}%
				\pgfplotscoordmath{default}{tofixed}{\pgfmathresult}%
				\let\pgfplots@loc@TMPb=\pgfmathresult
				\pgfplotscoordmath{default}{parse}{##2}%
				\pgfplotscoordmath{default}{tofixed}{\pgfmathresult}%
				\let\pgfplots@loc@TMPc=\pgfmathresult
				%
				\pgfplots@if{pgfplots@apply@datatrafo@#1}{%
					\pgfplotscoordmath{#1}{datascaletrafo noshift inverse to fixed}{\pgfplots@loc@TMPb}%
					\let\pgfplots@loc@TMPb=\pgfmathresult
					\pgfplotscoordmath{#1}{datascaletrafo noshift inverse to fixed}{\pgfplots@loc@TMPc}%
					\let\pgfplots@loc@TMPc=\pgfmathresult
				}{}%
				\csname pgfset#1vec\endcsname{%
					\pgfqpoint
						{\if r\pgfplots@loc@dirvalue -\fi\pgfplots@loc@TMPb pt}
						{\if r\pgfplots@loc@dirvalue -\fi\pgfplots@loc@TMPc pt}}%
			}%
			\expandafter\pgfplots@loc@TMPa\pgfplots@loc@TMPb%
			%
		\else
			% NO we simply have a scalar value.
			\def#4{1}% we have (#1,0) or (0,#1)
%\message{Setting unitvector(#1) to \csname pgfplots@#1\endcsname * e_{#2}...}%
			\pgfplots@if{pgfplots@apply@datatrafo@#1}{%
				\pgfplotscoordmath{default}{parse}{\csname pgfplots@#1\endcsname}%
				\pgfplotscoordmath{default}{tofixed}{\pgfmathresult}%
				\pgfplotscoordmath{#1}{datascaletrafo noshift inverse to fixed}{\pgfmathresult}%
				\edef\pgfplots@loc@TMPb{\pgfmathresult pt}%
			}{\relax}%
			\edef\pgfplots@loc@TMPb{\if r\pgfplots@loc@dirvalue -\fi\pgfplots@loc@TMPb}%
			\begingroup
				\pgf@xa=\pgfplots@loc@TMPb\relax
				\xdef\pgfplots@glob@TMPb{\pgf@sys@tonumber{\pgf@xa}}%
			\endgroup
			\ifcase#2\relax
				\pgfsetxvec{\pgfqpoint{\pgfplots@loc@TMPb}{0pt}}%
			\or
				\pgfsetyvec{\pgfqpoint{0pt}{\pgfplots@loc@TMPb}}%
			\or
				\pgfsetzvec{\pgfqpoint{\pgfplots@loc@TMPb}{\pgfplots@loc@TMPb}}%
			\fi
		\fi
	\fi
%\message{-> got unitvector(#1) = (\the\csname pgf@#1x\endcsname, \the\csname pgf@#1y\endcsname).^^J}%
}%

% Applies the 'axis equal' feature.
%
% PRECONDITION:
% 	- #1, #2, #3 contains the current scaling
% 	factors in x,y, z, resp. which are to be applied to unit vectors
% 	- neither unit vectors nor limits are in their final shape
% 	-  \pgfplots@set@default@size@options has been invoked before
%
% POSTCONDITION:
%   - #1, #2, #3 have been changed to accomodate unit vector ratio
%   - #4, #5, #6 [output] contain axis limit compensation scales
%
% There is just one algorithmic difficulty: the data scaling
% transformation. All unit vector length above are only meaningful in
% the UNTRANSFORMED range, so we have to mingle with the scaling
% transformation.
\def\pgfplots@apply@unit@ratio#1#2#3#4#5#6{%
	\begingroup
	\edef\pgfplots@target@unit@scale@inv@x{#1}%
	\edef\pgfplots@target@unit@scale@inv@y{#2}%
	\edef\pgfplots@target@unit@scale@inv@z{#3}%
	\def\pgfplots@target@limitrescale@x@{1}%
	\def\pgfplots@target@limitrescale@y@{1}%
	\def\pgfplots@target@limitrescale@z@{1}%
	%
	\pgfkeysgetvalue{/pgfplots/unit vector ratio}\pgfplots@unit@vector@ratio
	\ifx\pgfplots@unit@vector@ratio\pgfutil@empty
	\else
		\edef\pgfplots@unit@vector@ratio{\pgfplots@unit@vector@ratio\space1 1 }%
		%
		\expandafter\pgfplots@unit@vector@ratio@check@nop\pgfplots@unit@vector@ratio\pgfplots@EOI
		\ifpgfplots@loc@tmp
			%
			% Step 1: compute the unit vector which STAYS CONSTANT.
			%
			\pgfkeysgetvalue{/pgfplots/unit vector ratio axis}\pgfplots@apply@unit@ratio@reference
			\ifx\pgfplots@apply@unit@ratio@reference\pgfutil@empty
				\pgfplots@apply@unit@ratio@find@reference%
			\fi
			%
			% FIXME : I could spent some attention here to save work: 
			% both, unit ratios and the resulting scales are computed at
			% least twice (once in \pgfplots@apply@unit@ratio@find@reference and once in the
			% following).
			\expandafter\pgfplots@apply@unit@ratio@prepareratios\pgfplots@unit@vector@ratio\pgfplots@EOI
			%
%\message{USING REFERENCE UNIT VECTOR FROM \pgfplots@apply@unit@ratio@reference; ratio \pgfplots@unit@ratio@x\space \pgfplots@unit@ratio@y\space \pgfplots@unit@ratio@z.^^J}%
			%
			% Step 2: apply the scaling:
			\pgfplots@rescale@unit@vector@reltoreference{x}{\pgfplots@unit@ratio@x}%
			\pgfplots@rescale@unit@vector@reltoreference{y}{\pgfplots@unit@ratio@y}%
			\ifpgfplots@threedim
				\pgfplots@rescale@unit@vector@reltoreference{z}{\pgfplots@unit@ratio@z}%
			\fi
			%
		\else
%\message{Skipped application of 'unit vector ratio=\pgfkeysvalueof{/pgfplots/unit vector ratio}': it is already done by 'scale uniformly'.^^J}%
		\fi
	\fi
	\xdef\pgfplots@glob@TMPa{%
		\noexpand\def\noexpand#1{\pgfplots@target@unit@scale@inv@x}%
		\noexpand\def\noexpand#2{\pgfplots@target@unit@scale@inv@y}%
		\noexpand\def\noexpand#3{\pgfplots@target@unit@scale@inv@z}%
		\noexpand\def\noexpand#4{\pgfplots@target@limitrescale@x@}%
		\noexpand\def\noexpand#5{\pgfplots@target@limitrescale@y@}%
		\noexpand\def\noexpand#6{\pgfplots@target@limitrescale@z@}%
	}%
	\endgroup
	\pgfplots@glob@TMPa
}%

\def\pgfplots@appy@unit@ratio@reciprocal#1{%
	\pgfplotscoordmath{default}{parsenumber}{#1}%
	\pgfplotscoordmath{default}{op}{reciprocal}{{\pgfmathresult}}%
	\pgfplotscoordmath{default}{tofixed}{\pgfmathresult}%
}%

% Defines \ifpgfplots@loc@tmp := need to modify scaling factors
\def\pgfplots@unit@vector@ratio@check@nop#1 #2 #3 #4\pgfplots@EOI{%
	\pgfplots@loc@tmptrue
	\if3\pgfplots@scale@mode@choice
		% scale mode=scale uniformly
		\ifpgfplots@threedim
			\ifdim#1pt=#2pt
				\ifdim#1pt=#3pt
					% 'axis equal' is implicitly done by 'scale mode=scale
					% uniformly' anyway
					\pgfplots@loc@tmpfalse
				\fi
			\fi
		\else
			\ifdim#1pt=#2pt
				% 'axis equal' is implicitly done by 'scale mode=scale
				% uniformly' anyway
				\pgfplots@loc@tmpfalse
			\fi
		\fi
	\fi
	% activate the following line to deactivate optimization: [FIXME]
	%\pgfplots@loc@tmpfalse
}%

% This macro determines the reference axis for unit vector rescaling.
% The reference axis remains unscaled (it gets scaling factor 1 if you
% want it this way).
% 
% The other axes are scaled such that the desired unit vector ratios
% are fulfilled.
%
% The idea to select a reference axis is as follows:
% 1. Every unit vector scaling factor s should fulfill  s  <= 1.
% 2. Choose the reference axis such that the minimal amount of scaling
% is performed.
%
% The motivation for (1) is: if all involved scaling factors are at
% most 1, the resulting picture will only become *smaller*.
% Consequently, we can simply enlarge axis limits to restore the
% original width/height!
%
% The motivation for (2) is: a huge amount of scaling might reduce the
% size of the image too much. Of course, the figure will be enlarged
% to fit the original width/height, but most of it will be empty. So,
% use the smallest scaling.
%
% @POSTCONDITION The reference axis is stored in
% \pgfplots@apply@unit@ratio@reference .
%
% @see the key 'unit vector ratio axis=y' which allows to manually
% select the reference axis. This will illustrate what happens here.
\def\pgfplots@apply@unit@ratio@find@reference{%
	%
	\begingroup
	\let\pgfplots@ONE=\pgf@x
	\global\pgfplots@ONE=1.002pt
	%
	\def\pgfplots@optimum@sofar@axis{}%
	\let\pgfplots@optimum@sofar@value=\pgf@y
	\global\pgfplots@optimum@sofar@value=16000pt
	%
	%\pgfplots@apply@unit@ratio@find@reference@checkexplicitlimits
	%
	\ifx\pgfplots@optimum@sofar@axis\pgfutil@empty
		% set \pgfplots@loc@TMPa := 1 if and only if the axis is 3d
		\def\pgfplots@loc@TMPa{0}%
		\if0\b@pgfplots@unitvec@is@zero@z
			% ah, it IS 3d!
			\def\pgfplots@loc@TMPa{1}%
		\else
			% ok, 2d mode (includes view={0}{90})
			\def\pgfplots@loc@TMPa{0}%
		\fi
		\if1\pgfplots@loc@TMPa
			% 3D is more complicated than 2D:
			% for every fixed reference axis, we have to check *two*
			% scaling factors.
			%
			% Furthermore, the optimality condition (2) needs to be
			% performed on the maximum max{1-s_a, 1-s_b} provided both of
			% these numbers are positive.
			%
			\def\pgfplots@check@##1##2{%
				% PRECONDITION: \pgfplots@apply@unit@ratio@reference is defined.
				%
				% renormalize \pgfplots@unit@[xyz] :
				\expandafter\pgfplots@apply@unit@ratio@prepareratios\pgfplots@unit@vector@ratio\pgfplots@EOI
				%
				% compute s_a :
				\pgfplots@getscale@unit@vector@reltoreference ##1{\csname pgfplots@unit@ratio@##1\endcsname}%
				\let\pgfplots@scale@a=\pgfmathresult
				%
				% compute s_b :
				\pgfplots@getscale@unit@vector@reltoreference ##2{\csname pgfplots@unit@ratio@##2\endcsname}%
				\let\pgfplots@scale@b=\pgfmathresult
				%
				% check if the actual choice of
				% \pgfplots@apply@unit@ratio@reference is FEASIBLE.
				% That is the case if s_a <= 1  && s_b <= 1.
				% We check
				%  (1 - s_a >= 0 )  && ( 1 - s_b >= 0 )
				% instead, since I need the value 
				%   max( 1-s_a, 1-s_b )
				% anyway.
				\def\pgfplots@ref@is@feasible{1}%
				\pgf@xa=\pgfplots@ONE \advance\pgf@xa by-\pgfplots@scale@a pt
				\ifdim\pgf@xa<0sp
					\def\pgfplots@ref@is@feasible{0}%
				\else
					\pgf@xb=\pgfplots@ONE \advance\pgf@xb by-\pgfplots@scale@b pt
					\ifdim\pgf@xb<0sp
						\def\pgfplots@ref@is@feasible{0}%
					\fi
				\fi
				% compute max(1-s_a,1-s_b) into \pgf@xa:
				% pgf@xa= max(pgf@xa,pgf@xb):
				\ifdim\pgf@xb>\pgf@xa	\pgf@xa=\pgf@xb	\fi
				\if1\pgfplots@ref@is@feasible
					\ifdim\pgf@xa<\pgfplots@optimum@sofar@value
						% Ah, ok. The actual choice is BETTER as it
						% involves less scaling.
						%
						% Remember it!
						\let\pgfplots@optimum@sofar@axis=\pgfplots@apply@unit@ratio@reference
						\global\pgfplots@optimum@sofar@value=\pgf@xa
					\fi
				\fi
%\message{^^Junit vector ratio 3D searching reference: checking \pgfplots@apply@unit@ratio@reference. feasable=\pgfplots@ref@is@feasible. \if1\pgfplots@ref@is@feasible max=\the\pgf@xa. \fi Optimum so far: value =\the\pgfplots@optimum@sofar@value\space for axis \pgfplots@optimum@sofar@axis.^^J}%
			}%
			%
			% Check 'x' as reference :
			\def\pgfplots@apply@unit@ratio@reference{x}%
			\pgfplots@check@ yz%
			%
			% Check 'y' as reference :
			\def\pgfplots@apply@unit@ratio@reference{y}%
			\pgfplots@check@ xz%
			%
			% Check 'z' as reference :
			\def\pgfplots@apply@unit@ratio@reference{z}%
			\pgfplots@check@ xy%
			%
		\else
			% 2D is much simpler: find the scale s which fulfills s <= 1.
			% One of them MUST fulfill it.
			% 
			% try 'x' axis as reference:
			\def\pgfplots@apply@unit@ratio@reference{x}%
			%
			% renormalize:
			\expandafter\pgfplots@apply@unit@ratio@prepareratios\pgfplots@unit@vector@ratio\pgfplots@EOI
			%
			% compute scaling factor: 
			\pgfplots@getscale@unit@vector@reltoreference y\pgfplots@unit@ratio@y%
			% 
%\message{^^Junit vector ratio 2D searching reference: checking \pgfplots@apply@unit@ratio@reference. feasable=\pgfmathresult < 1: \ifdim\pgfmathresult pt <\pgfplots@ONE YES-> use x\else NO->use y\fi^^J}%
			% and check (1). The condition (2) is irrelevant; it is met
			% anyway.
			\ifdim\pgfmathresult pt<\pgfplots@ONE
				\def\pgfplots@optimum@sofar@axis{x}%
			\else
				\def\pgfplots@optimum@sofar@axis{y}%
			\fi
		\fi
	\else
%\message{^^Junit vector ratio chose \pgfplots@optimum@sofar@axis\space to fulfill explicitly provided limits (at least partially).^^J}%
	\fi
	%
	\ifx\pgfplots@optimum@sofar@axis\pgfutil@empty
		\if1\b@pgfplots@unitvec@is@zero@z
			\def\pgfplots@optimum@sofar@axis{y}%
		\else
			\def\pgfplots@optimum@sofar@axis{z}%
		\fi
		\pgfplotswarning{unit vector ratio axis undetermined}{\pgfplots@optimum@sofar@axis}\pgfeov%
	\fi
	\let\pgfplots@apply@unit@ratio@reference=\pgfplots@optimum@sofar@axis
	\pgfmath@smuggleone\pgfplots@apply@unit@ratio@reference
	\endgroup
}%
\def\pgfplots@apply@unit@ratio@find@reference@checkexplicitlimits{%
	\ifpgfplots@autocompute@ymax \else \def\pgfplots@optimum@sofar@axis{y}\fi
	\ifpgfplots@autocompute@ymin \else \def\pgfplots@optimum@sofar@axis{y}\fi
	\ifpgfplots@autocompute@xmax \else \def\pgfplots@optimum@sofar@axis{x}\fi
	\ifpgfplots@autocompute@xmin \else \def\pgfplots@optimum@sofar@axis{x}\fi
	\ifpgfplots@threedim
		\ifpgfplots@autocompute@zmax \else \def\pgfplots@optimum@sofar@axis{z}\fi
		\ifpgfplots@autocompute@zmin \else \def\pgfplots@optimum@sofar@axis{z}\fi
	\fi
}%

% This is ONLY applied to the value of 'unit vector ratio'. It does
% not touch the current axis scaling factors.
\def\pgfplots@apply@unit@ratio@prepareratios#1 #2 #3 #4\pgfplots@EOI{%
	\def\pgfplots@unit@ratio@x{#1}%
	\def\pgfplots@unit@ratio@y{#2}%
	\def\pgfplots@unit@ratio@z{#3}%
	%
	% 'unit vector ratio' is measured relative to the y axis for 2d
	% and relative to the z axis for 3d plots.
	% renormalize such that it is relative to
	% \pgfplots@apply@unit@ratio@reference.
	%
	% Furthermore, renormalize such that
	% unit@ratio@\pgfplots@apply@unit@ratio@reference is 1.
	\pgfmathreciprocal@{\csname pgfplots@unit@ratio@\pgfplots@apply@unit@ratio@reference\endcsname}%
	\let\pgfplots@loc@TMPa=\pgfmathresult
	\ifpgfplots@threedim
		\if z\pgfplots@apply@unit@ratio@reference
		\else
			\pgfmathmultiply@{\pgfplots@loc@TMPa}{\pgfplots@unit@ratio@z}%
			\let\pgfplots@loc@TMPa=\pgfmathresult
		\fi
		%
		\pgfmathmultiply@{\pgfplots@loc@TMPa}{\pgfplots@unit@ratio@x}%
		\let\pgfplots@unit@ratio@x=\pgfmathresult
		%
		\pgfmathmultiply@{\pgfplots@loc@TMPa}{\pgfplots@unit@ratio@y}%
		\let\pgfplots@unit@ratio@y=\pgfmathresult
		%
		\pgfmathmultiply@{\pgfplots@loc@TMPa}{\pgfplots@unit@ratio@z}%
		\let\pgfplots@unit@ratio@z=\pgfmathresult
	\else
		\if y\pgfplots@apply@unit@ratio@reference
		\else
			\pgfmathmultiply@{\pgfplots@loc@TMPa}{\pgfplots@unit@ratio@y}%
			\let\pgfplots@loc@TMPa=\pgfmathresult
		\fi
		%
		\pgfmathmultiply@{\pgfplots@loc@TMPa}{\pgfplots@unit@ratio@x}%
		\let\pgfplots@unit@ratio@x=\pgfmathresult
		%
		\pgfmathmultiply@{\pgfplots@loc@TMPa}{\pgfplots@unit@ratio@y}%
		\let\pgfplots@unit@ratio@y=\pgfmathresult
		%
		\def\pgfplots@unit@ratio@z{<unused>}%
	\fi
	%
}%


% Computes a new unit vector E_#1 for direction #1 such that
% ||E_#1|| = #2 * ||e_reference||.
% Here, #2 is a scaling factor and e_reference is a reference axis.
% The reference axis is stored in
% \pgfplots@apply@unit@ratio@reference, the macro contains one of
% {x,y,z}.
%
% The data limits for '#1' will be enlarged as well (for 'unit rescale
% keep size').
%
% #1 is the axis which should be scaled (i.e. #1 in {x,y,z}).
% It is allowed if #1 = \pgfplots@apply@unit@ratio@reference. In this
% case, you can provide a scale '#2' to rescale the axis.
%
% #2 is a desired scale, relative to
% \pgfplots@apply@unit@ratio@reference. #2 should be a number without
% unit.
%
% The parameter \pgfplots@apply@unit@ratio@reference is also one of
% {x,y,z}.
%
\def\pgfplots@rescale@unit@vector@reltoreference#1#2{%
	\def\pgfplots@loc@TMPa{0}%
	\if#1\pgfplots@apply@unit@ratio@reference
		\pgfplotsmath@ifapproxequal@dim{#2pt}{1pt}{0.0002pt}{%
		}{%
			\def\pgfplots@loc@TMPa{1}%
		}%
	\else
		\def\pgfplots@loc@TMPa{1}%
	\fi
	\if1\csname b@pgfplots@unitvec@is@zero@#1\endcsname
		\def\pgfplots@loc@TMPa{0}%
	\fi
	\if1\pgfplots@loc@TMPa
		%
		\pgfplots@getscale@unit@vector@reltoreference{#1}{#2}%
		\global\let\pgfplots@glob@TMPa=\pgfmathresult
		%
%\message{Rescaling '#1' by \pgfplots@glob@TMPa.^^J}%
		%
		\pgfmathdivide@{\csname pgfplots@target@unit@scale@inv@#1\endcsname}{\pgfplots@glob@TMPa}%
		\expandafter\let\csname pgfplots@target@unit@scale@inv@#1\endcsname=\pgfmathresult
		%
		\pgfmathreciprocal@\pgfplots@glob@TMPa
		\expandafter\let\csname pgfplots@target@limitrescale@#1@\endcsname=\pgfmathresult
		%
	\fi
}

% Updates the #1 axis limits such that the axis' dimensions
% stay the same after scaling the #1 unit vector by a scale 's'.
%
% PRECONDITION:
%   - the #1 unit vector has been rescaled by a factor s.
%   For example, e_xnew := e_x * 0.5 .
% 
% POSTCONDITION:
%   - the axis limits are enlarged by a factor 1/s such that 
%   1/s (#1max - #1min) * e_xnew = (#1max- #1min) * e_x.
%
% In other words, the unit vector rescale is componensated by
% modifying the axis limits: we want to add an absolute component 'd'
% to the range:
% 1/s (xmax - xmin ) = xmax - xmin +d 
% =>
% d = (1/s - 1) * (xmax - xmin)
%
% The only remaining thing to do is to distribute 'd' to 'xmax' and
% 'xmin'. Typically, 50% to each will be fine, I guess...
% 
% #1: either x, y or z. It denotes the direction which has been
% modified.
% #2: the INVERSE of the scaling factor, #2 = 1/s .
%
\def\pgfplots@apply@unit@vector@rescale@keep@size#1#2{%
	\ifdim#2pt=1pt
	\else
	\if0\pgfplots@unit@vector@rescale@keep@size
		% unit rescale keep size=false : do nothing. Ignore the
		% scaling request.
	\else
		% unit rescale keep size=true|unless limits declared
		%
%\message{'unit rescale keep size': Resizing data range for #1 by #2: from \csname pgfplots@#1min\endcsname:\csname pgfplots@#1max\endcsname\ to}%
		\pgfmathsubtract@{\csname pgfplots@#1max\endcsname}{\csname pgfplots@#1min\endcsname}%
		\begingroup
			\pgf@xa=\pgfmathresult pt
			\pgfmathsubtract@{#2}{1.0}%
			\pgf@xa=\pgfmathresult \pgf@xa% this is 'd'
			%
			% \pgfplots@glob@TMPb : will be subtracted from #1min
			% \pgfplots@glob@TMPc : will be added to #1max
			\pgfplots@if{pgfplots@autocompute@#1min}{%
				\pgfplots@if{pgfplots@autocompute@#1max}{%
					\pgf@xa=0.5 \pgf@xa
					\xdef\pgfplots@glob@TMPb{\pgf@sys@tonumber{\pgf@xa}}%
					\xdef\pgfplots@glob@TMPc{\pgfplots@glob@TMPb}%
				}{%
					\xdef\pgfplots@glob@TMPb{\pgf@sys@tonumber{\pgf@xa}}%
					\xdef\pgfplots@glob@TMPc{0.0}%
				}%
			}{%
				\pgfplots@if{pgfplots@autocompute@#1max}{%
					\xdef\pgfplots@glob@TMPb{0.0}%
					\xdef\pgfplots@glob@TMPc{\pgf@sys@tonumber{\pgf@xa}}%
				}{%
					\if1\pgfplots@unit@vector@rescale@keep@size
						% unit rescale keep size=true : FORCE
						% enlargement!
						\pgf@xa=0.5 \pgf@xa
						\xdef\pgfplots@glob@TMPb{\pgf@sys@tonumber{\pgf@xa}}%
						\xdef\pgfplots@glob@TMPc{\pgfplots@glob@TMPb}%
					\else
						% unit rescale keep size=unless limits declared: 
						% do not scale - all limits are declared
						% explicitly
						\xdef\pgfplots@glob@TMPb{0.0}%
						\xdef\pgfplots@glob@TMPc{0.0}%
					\fi
				}%
			}%
		\endgroup
		\pgfmathsubtract@{\csname pgfplots@#1min\endcsname}{\pgfplots@glob@TMPb}%
		\expandafter\global\expandafter\let\csname pgfplots@#1min\endcsname=\pgfmathresult
		\pgfmathadd@{\csname pgfplots@#1max\endcsname}{\pgfplots@glob@TMPc}%
		\expandafter\global\expandafter\let\csname pgfplots@#1max\endcsname=\pgfmathresult
%\message{\csname pgfplots@#1min\endcsname:\csname pgfplots@#1max\endcsname. [- \pgfplots@glob@TMPb; + \pgfplots@glob@TMPc]^^J}%
		%
		% Update auxiliary data members:
		\pgfplots@visphase@notify@changeofcanvaslimits{#1}%
	\fi
	\fi
}%

% #1: an axis which should be scaled
% #2: the desired final ratio  ||e_#1||/||e_ref||
\def\pgfplots@getscale@unit@vector@reltoreference#1#2{%
	% 
	% If the datascaling transformation is active (which is almost
	% everytime the case here), we have a transformation
	% T^{-1}(x)= 10^scale * x
	% with different scales for every axis.
	%
	% If the datascaling transformation is NOT active, scale is 0
	% and T^{-1} = Identity.
	%
	% Note that the datascaling transformation also has
	% translations (shifts). These are not important here.
	%
	% Goal:
	% compute E_#1 such that
	%   #2* || T^{-1} e_ref || = || T^{-1} E_#1 ||
	% where T^{-1} is the data scaling transformation and e_ref the
	% reference unit vector. Keep in mind that there are
	% *different* data scaling transformations for each axis.
	%
	% We are given e_ref and e_#1 and the desired aspect ratio
	% between e_ref and E_#1, which is available as #2.
	%
	% So: T^{-1} E_#1 :=  s* T^{-1} e_#1 where 
	%  s = #2 * ||T^{-1} e_ref|| / || T^{-1} e_#1 || 
	%    = |10^{scale_ref}| / |10^{scale_#1}| * #2 * || e_ref|| / ||e_#1||.
	% 
	% Then, E_#1 = T ( T^{-1} E_#1 ) = s * e_#1.
	%
	% -> compute 's'! 
	%
	% Part 1: compute
	% #2 * ||e_ref|| / ||e_#1||.
	%
	\def\pgfplots@loc@TMPa{1}%
	\if1\csname b@pgfplots@unitvec@is@zero@#1\endcsname
		\def\pgfplots@loc@TMPa{0}%
	\else
		\if1\csname b@pgfplots@unitvec@is@zero@\pgfplots@apply@unit@ratio@reference\endcsname
			\def\pgfplots@loc@TMPa{0}%
		\fi
	\fi
	\if0\pgfplots@loc@TMPa
		\def\pgfmathresult{16001}%
	\else
		% note that  x^{-1} / y^{-1}  == ( x/y )^{-1} == y/x .
		% consequently, we can use our @inv@[xyz] values here:
		\pgfmathdivide@
			{\csname pgfplots@target@unit@scale@inv@#1\endcsname}%
			{\csname pgfplots@target@unit@scale@inv@\pgfplots@apply@unit@ratio@reference\endcsname}
		\pgfmathmultiply@
			{\pgfmathresult}%
			{#2}%
		\global\let\pgfplots@glob@TMPa=\pgfmathresult
		% 
		% also compute 1/s, required as temporary value:
		%\pgfmathmultiply@
		%	{\csname pgfplots@\pgfplots@apply@unit@ratio@reference @inverseveclength\endcsname}
		%	{\csname pgfplots@target@unit@scale@#1\endcsname}%
		%\ifdim#2pt=1pt
		%\else
		%	\pgfmathdivide@{\pgfmathresult}{#2}%
		%\fi
		%\global\let\pgfplots@glob@TMPb=\pgfmathresult
		%
		% Part 2: handle data scaling trafo scales:
		\begingroup
			\def\pgfplots@tmp@exponentref{0}%
			\def\pgfplots@tmp@exponentK{0}%
			\pgfplots@if{pgfplots@apply@datatrafo@\pgfplots@apply@unit@ratio@reference }{%
				\pgfplots@letcsname{pgfplots@tmp@exponentref}={pgfplots@data@scale@trafo@EXPONENT@\pgfplots@apply@unit@ratio@reference }%
			}{}%
			\pgfplots@if{pgfplots@apply@datatrafo@#1}{%
				\pgfplots@letcsname{pgfplots@tmp@exponentK}={pgfplots@data@scale@trafo@EXPONENT@#1}%
			}{}%
			\c@pgf@counta=\pgfplots@tmp@exponentref\relax
			\advance\c@pgf@counta by-\pgfplots@tmp@exponentK\relax
			\ifnum\c@pgf@counta=0
			\else
				\pgfplotsmathmultiplypowten@{\pgfplots@glob@TMPa}{\c@pgf@counta}%
				\global\let\pgfplots@glob@TMPa=\pgfmathresult
			%	\pgfplotsmathmultiplypowten@{\pgfplots@glob@TMPb}{-\c@pgf@counta}%
			%	\global\let\pgfplots@glob@TMPb=\pgfmathresult
			\fi
			\xdef\pgfplots@glob@TMPc{\the\c@pgf@counta}%
		\endgroup
		\let\pgfmathresult=\pgfplots@glob@TMPa
	\fi
%\message{\string\pgfplots@getscale@unit@vector@reltoreference{#1}{#2} (reference \pgfplots@apply@unit@ratio@reference) = \pgfmathresult.^^J}%
}

% helper for \pgfplots@check@and@apply@datatrafo@for.
\def\pgfplots@compute@number@order@for@trafo@isdimen#1\tocount#2{%
	\edef\pgfplots@loc@TMPa{\pgf@sys@tonumber{#1}}%
	\pgfmathfloatparsenumber{\pgfplots@loc@TMPa}%
	\expandafter\pgfmathfloat@decompose@E\pgfmathresult\relax#2
	\advance#2 by1\relax
}

% helper for \pgfplots@check@and@apply@datatrafo@for.
% 
\def\pgfplots@compute@number@order@for@trafo@isfloat#1\tocount#2{%
	\pgfmathfloatparsenumber{#1}%
	\expandafter\pgfmathfloat@decompose@E\pgfmathresult\relax#2\relax
	\advance#2 by1
}

\def\pgfplots@if@is@float@zero#1#2#3{%
	\pgfmathfloatparsenumber{#1}%
	\pgfmathfloatgetflags{\pgfmathresult}{\c@pgf@countd}%
	\ifnum\c@pgf@countd=0 %
		% ah - it *is* 0.0:
		#2%
	\else
		#3%
	\fi
}

% Initialises the data scale transformation such that it is optimal
% for direction #1 (using its axis limits and the target scaling size).
%
% Note that it will not be applied in any way; and it may still be
% modified.
%
% PRECONDITION:
%   - all axis limits are available in float representation
%   - \pgfplots@set@default@size@options has been called before
% POSTCONDITION:
%   - the scaling transformation is set up,
\def\pgfplots@set@optimal@datatrafo@for@#1{%
	\pgfplots@if{pgfplots@apply@datatrafo@#1}{%
		% initialise data scale transformation 
		%   T(x) = 10^{q-m} * x
		%
		\ifpgfplots@disabledatascaling
			% this here is a waste of time, because the NO-OP trafo
			% will be applied to all coordinates. One could really
			% safe a lot of CPU time when disabledatascaling is enabled...
			% but it requires so much extra cases; I really don't want
			% that!
			\gdef\pgfplots@glob@TMPa{0}%
			\gdef\pgfplots@glob@TMPb{0}%
		\else
			\begingroup
				\let\data@max@order=\c@pgf@counta
				\let\data@cur@order=\c@pgf@countb
				\let\data@dimen=\pgf@xa
				\let\data@tmp=\pgf@xb
				\let\data@dimen@order=\c@pgf@countc
				\let\data@EXPONENT=\c@pgf@countd
				\expandafter\let\expandafter\pgfplots@display@min@float\csname pgfplots@#1min\endcsname
				\expandafter\let\expandafter\pgfplots@display@max@float\csname pgfplots@#1max\endcsname
				\expandafter\let\expandafter\pgfplots@data@min@float\csname pgfplots@data@#1min\endcsname
				\expandafter\let\expandafter\pgfplots@data@max@float\csname pgfplots@data@#1max\endcsname
				\ifpgfplots@autocompute@all@limits
				\else
					\pgfplotscoordmath{#1}{max}{\pgfplots@display@max@float}{\pgfplots@data@max@float}%
					\let\pgfplots@data@max@float=\pgfmathresult
					\pgfplotscoordmath{#1}{min}{\pgfplots@display@min@float}{\pgfplots@data@min@float}%
					\let\pgfplots@data@min@float=\pgfmathresult
				\fi
				%
%\message{minmax = [\pgfplots@data@min@float,\pgfplots@data@max@float]^^J}%
				% Step 1: compute 'm', the data order
				\pgfplots@if@is@float@zero{\pgfplots@data@min@float}{%
					\pgfplots@if@is@float@zero{\pgfplots@data@max@float}{%
						\data@max@order=1 % both are zero. ok.
						% Note that this is '1' due to backwards
						% compatibility.
					}{%
						% one of them is zero. Take the other one!
						\pgfplots@compute@number@order@for@trafo@isfloat
							\pgfplots@data@max@float
							\tocount\data@cur@order
						\data@max@order=\data@cur@order
					}%
				}{%
					\pgfplots@if@is@float@zero{\pgfplots@data@max@float}{%
						% one of them is zero. Take the other one!
						\pgfplots@compute@number@order@for@trafo@isfloat
							\pgfplots@data@min@float
							\tocount\data@cur@order
						\data@max@order=\data@cur@order
					}{%
						% none of them is zero. Compute MAX:
						\pgfplots@compute@number@order@for@trafo@isfloat
							\pgfplots@data@min@float
							\tocount\data@cur@order
						\data@max@order=\data@cur@order
						\pgfplots@compute@number@order@for@trafo@isfloat
							\pgfplots@data@max@float
							\tocount\data@cur@order
						\ifnum\data@cur@order>\data@max@order
							\data@max@order=\data@cur@order
						\fi
					}%
				}%
				%
				%
				%
				% Step 2: compute 'q', the #1-size of the axis.
				%\expandafter\ifx\csname pgfplots@#1\endcsname\pgfutil@empty
					% We have 'width' or 'height' (I always have them).
					%
					% Use the order of these parameters.
					\def\pgfplots@loc@TMPa{#1}%
					\def\pgfplots@loc@TMPb{x}%
					\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
						\data@dimen=\pgfplots@width\relax
					\else
						\if1\pgfplots@compat@scaling@zunitfix@enable
							\data@dimen=\pgfplots@height\relax
						\else
							% this code here belongs to versions up to
							% 1.3.1.
							% It is now deprecated and produces small
							% pixel differences.
							\def\pgfplots@loc@TMPb{y}%
							\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
								\data@dimen=\pgfplots@height\relax
							\else
								\data@dimen=42pt % this is actually different from 1.3.1: there, it was UNDEFINED.
							\fi
						\fi
					\fi
					\pgfplots@compute@number@order@for@trafo@isdimen
						\data@dimen
						\tocount\data@dimen@order
					% This here is to avoid inaccuracies in the final
					% axis rectangle size, see \pgfplots@initsizes:
					%\advance\data@dimen@order by-1
				%\else
					% FIXME:
					% we have either the 'x=1cm' or 'y=1cm' option!
					% How should I initialise the trafo!?
				%	\data@dimen@order=3
				%\fi
				%
%\message{Direction #1: data max order=\the\data@max@order;  data dimen order=\the\data@dimen@order. ^^J}%
				\data@EXPONENT=\data@dimen@order
				\advance\data@EXPONENT by-\data@max@order
				% Now, I introduce a loop which shall avoid cancellation of
				% significant digits.
				%
				% Harmless Example: 
				%  if we have data shift = -3 and 
				%  max = 2e6, min = 1e6, then max-min = 1e6; T(max)-T(min) = 1e3 which is ok.
				%  In this case, the loop won't change anything.
				%
				% Critical Example:
				%  if we have data shift = -3 and
				%  max = 1980, min = 1930 then 
				%    T(max) = 1.98 and T(min) = 1.93
				%  and thus T(max)-T(min) = 0.05 . 
				%  Considering that this is the axis range
				%  in which tick labels and plot points need to be computed, we
				%  only have two or three digits left! That happens because the
				%  prefix '19' is common and is cancelled in the subtraction.
				%  Idea: while T(max)-T(min) < O(10^2) -> increase shift by +1
				%  (and make sure that T(max) < MAX_VALID_TEX_NUMBER).
				%
				\def\pgfplotscoordmathnotifydatascalesetfor##1{}% disable temporarily. We are just testing it.
				\pgfplots@loop@CONTINUEtrue
				\pgfutil@loop
				\pgfplotscoordmath{#1}{datascaletrafo set params}{\the\data@EXPONENT}{0}%
				\pgfplotscoordmath{#1}{datascaletrafo}{\pgfplots@data@min@float}%
				\let\pgfplots@min@fixed=\pgfmathresult
				\ifpgfplots@loop@CONTINUE
					\pgfplotscoordmath{#1}{datascaletrafo}{\pgfplots@data@max@float}%
					\let\pgfplots@max@fixed=\pgfmathresult
					\data@tmp=\pgfplots@max@fixed pt
%\message{Current trafo EXPONENT for #1 direction: \the\data@EXPONENT; original #1 data limits: [\pgfplots@data@min@float:\pgfplots@data@max@float]; current transformed #1 limits: [\pgfplots@min@fixed:\pgfplots@max@fixed]; cancellation check max-min running...^^J}%
					\ifdim\data@tmp<0pt
						% I need absolute values here:
						\multiply\data@tmp by-1\relax
					\fi
					\pgfmathsubtract@{\pgfplots@max@fixed}{\pgfplots@min@fixed}%
					\data@dimen=\pgfmathresult pt
					\pgfplots@loop@CONTINUEfalse
					\ifdim\data@tmp<1500pt % a multiplication with '10' results in max = 15000 which is the upper limit.
						\ifdim\data@dimen<100pt % I guess if max-min = O(100), we have quite good accuracy
							\ifdim\data@dimen<0.0001pt
							\else
								\advance\data@EXPONENT by1
								\pgfplots@loop@CONTINUEtrue
							\fi
						\fi
					\fi
					%--------------------------------------------------
					% \ifdim\data@dimen>1200pt% FIXME : is this here ok!? CHECK IT!
					% 	\ifdim\data@dimen>7999pt
					% 		\advance\data@EXPONENT by-2
					% 	\else
					% 		\advance\data@EXPONENT by-1
					% 	\fi
					% 	\pgfplots@loop@CONTINUEfalse
					% \fi
					%-------------------------------------------------- 
				\pgfutil@repeat
				\xdef\pgfplots@glob@TMPa{\the\data@EXPONENT}%
				\xdef\pgfplots@glob@TMPb{\pgfplots@min@fixed}%
			\endgroup
		\fi
		% COMPLETE INITIALISATION:
%\message{Initialising the data scale transformation in direction #1 to 10^\pgfplots@glob@TMPa*#1 - \pgfplots@glob@TMPb...^^J}%
		\pgfplotscoordmath{#1}{datascaletrafo set params}{\pgfplots@glob@TMPa}{\pgfplots@glob@TMPb}%
	}{%
		% case apply trafo == false:
		\pgfplotscoordmath{#1}{datascaletrafo set params}{0}{0}%
	}%
}


\def\pgfplots@set@optimal@datatrafos@allaxes{%
	\pgfplots@letcsname pgfplots@xmin@unscaled@as@float={pgfplots@xmin}%
	\pgfplots@letcsname pgfplots@xmax@unscaled@as@float={pgfplots@xmax}%
	%
	\pgfplots@letcsname pgfplots@ymin@unscaled@as@float={pgfplots@ymin}%
	\pgfplots@letcsname pgfplots@ymax@unscaled@as@float={pgfplots@ymax}%
	%
	\pgfplots@letcsname pgfplots@zmin@unscaled@as@float={pgfplots@zmin}%
	\pgfplots@letcsname pgfplots@zmax@unscaled@as@float={pgfplots@zmax}%
	%
	\pgfplots@ifneeds@one@uniform@datascale{%
		% Ah - we have to ensure that there is ONE common scale for
		% each unit (x, y, and z have the same).
		%
		% In this case, we need to choose one of the transformations
		% and apply it to all axes -- such that each axis gets the
		% same scale.
		%
		% this mode is used for axis equal and its variants.
		%
		% The strategy to fix the transformation is as follows:
		% 1. we assume that axis limits will be enlarged in order to
		% satisfy 'scale uniformly'. 
		% 2. we assume that the LARGEST axis limit dominates the
		% others.
		% 3. if one of the axes does not have datascaling (i.e. is
		% log scale), we disable all other datascalings.
		%
		% Consequently, we search for the axis with the largest limit
		% - and copy its data scaling to all other axes. If one of the
		% axes is log, that one overrules it and all data scaling
		% effects are disabled..
		\begingroup
		\let\pgfplots@data@scale@trafo@EXPONENT@common=\pgfutil@empty
		\def\pgfplots@data@scale@trafo@EXPONENT@common@arg{-}% this should not match anything in this context.
		\pgfplots@if{pgfplots@apply@datatrafo@x}{%
		}{%
			\def\pgfplots@data@scale@trafo@EXPONENT@common{{0}{0}}% disable scaling!
		}%
		\pgfplots@if{pgfplots@apply@datatrafo@y}{%
		}{%
			\def\pgfplots@data@scale@trafo@EXPONENT@common{{0}{0}}% disable scaling!
		}%
		\ifpgfplots@threedim
			\pgfplots@if{pgfplots@apply@datatrafo@z}{%
			}{%
				\def\pgfplots@data@scale@trafo@EXPONENT@common{{0}{0}}% disable scaling!
			}%
		\fi
		\ifx\pgfplots@data@scale@trafo@EXPONENT@common\pgfutil@empty
			% ah - we still need to compute one. ok, search for the
			% largest limit.
			%
			\pgfplots@get@axis@with@largest@limits
			\let\pgfplots@data@scale@trafo@EXPONENT@common@arg=\pgfplotsretval
			%
			% ok, compute data scaling transformation for the target axis:
			\expandafter\pgfplots@set@optimal@datatrafo@for@\pgfplots@data@scale@trafo@EXPONENT@common@arg%
			%
			\pgfplotscoordmath{\pgfplots@data@scale@trafo@EXPONENT@common@arg}{datascaletrafo get params}%
			\let\pgfplots@data@scale@trafo@EXPONENT@common=\pgfmathresult%
		\else
			% hm. early-out - we already have the scaling trafo.
			% return it.
		\fi
		\global\let\pgfplots@glob@TMPa=\pgfplots@data@scale@trafo@EXPONENT@common
		\global\let\pgfplots@glob@TMPb=\pgfplots@data@scale@trafo@EXPONENT@common@arg
		\endgroup
		%
		\xdef\pgfplots@glob@TMPc{\expandafter\pgfutil@firstoftwo\pgfplots@glob@TMPa}%
%\message{using datascaletrafo of axis '\pgfplots@glob@TMPb' for each axis.^^J}%
		%
		\def\pgfplots@loc@TMPd##1{%
			\if ##1\pgfplots@glob@TMPb
				% we need to set the scaling trafo for the target direction
				% (was lost after \endgroup)
				\def\pgfplots@loc@TMPa{\pgfplotscoordmath{##1}{datascaletrafo set params}}%
				\expandafter\pgfplots@loc@TMPa\pgfplots@glob@TMPa%
			\else
				\pgfplotscoordmath{##1}{datascaletrafo set params}{\pgfplots@glob@TMPc}{0}%
				\pgfplotscoordmath{##1}{datascaletrafo}{\csname pgfplots@##1min\endcsname}%
%\message{Initialising the data scale transformation in direction ##1 to 10^\pgfplots@glob@TMPc*##1 - \pgfmathresult...^^J}%
				\pgfplotscoordmath{##1}{datascaletrafo set params}{\pgfplots@glob@TMPc}{\pgfmathresult}%
			\fi
		}%
		\pgfplots@loc@TMPd x%
		\pgfplots@loc@TMPd y%
		\ifpgfplots@threedim
			\pgfplots@loc@TMPd z%
		\fi
	}{%
		% optimize individually:
		\pgfplots@set@optimal@datatrafo@for@ x%
		\pgfplots@set@optimal@datatrafo@for@ y%
		\ifpgfplots@threedim
			\pgfplots@set@optimal@datatrafo@for@ z%
		\fi
	}%
	%
}%

% Defines \pgfplotsretval to be one of x, y, or z, such that the
% return value indicates the axis with largest untransformed axis
% limits.
\def\pgfplots@get@axis@with@largest@limits{%
	\begingroup
	\let\pgfplotsretval@extreme=\pgfutil@empty
	\let\pgfplotsretval@extreme@arg=\pgfutil@empty
	\def\pgfplots@@##1{%
		% compute axis range for axis ##1 ...
		\pgfplotscoordmath{default}{parsenumber}{\csname pgfplots@##1min\endcsname}%
		\let\pgfplots@loc@TMPa=\pgfmathresult
		\pgfplotscoordmath{default}{parsenumber}{\csname pgfplots@##1max\endcsname}%
		\pgfplotscoordmath{default}{op}{subtract}{{\pgfmathresult}{\pgfplots@loc@TMPa}}%
		% ... ok, it is in \pgfmathresult.
		\let\candidate=\pgfmathresult
		\ifx\pgfplotsretval@extreme@arg\pgfutil@empty
			% ah: no extreme value so far. use ours.
			\def\pgfplotsretval@extreme@arg{##1}%
			\let\pgfplotsretval@extreme=\candidate
		\else
			\pgfplotscoordmath{default}{if less than}{\pgfplotsretval@extreme}{\candidate}{%
				% update extreme value:
				\def\pgfplotsretval@extreme@arg{##1}%
				\let\pgfplotsretval@extreme=\candidate
			}{%
			}%
		\fi
	}%
	\pgfplots@@ x%
	\pgfplots@@ y%
	\ifpgfplots@threedim
		\pgfplots@@ z%
	\fi
	\let\pgfplotsretval=\pgfplotsretval@extreme@arg
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%

% Initialises the data scale transformation and applies it to any
% user specified options.
%
% PRECONDITION:
%   - all axis limits are available in float representation
%   - \pgfplots@set@default@size@options has been called before
%   - the scaling transformation for direction x is set up
%   (\pgfplots@set@optimal@datatrafo@for@),
% POSTCONDITION:
%   - all axis limits are transformed, but no other axis inputs.
%
% Unit vectors and other axis input parameters will be scaled later.
%
% @see \pgfplots@check@and@apply@datatrafo@for
\def\pgfplots@apply@datatrafo@to@axis@limits#1{%
	\pgfplots@if{pgfplots@apply@datatrafo@#1}{%
		% Transform axis limits:
%\message{#1- display limits BEFORE data transformation: [\csname pgfplots@#1min\endcsname:\csname pgfplots@#1max\endcsname]^^J}%
		\pgfplotscoordmath{#1}{datascaletrafo}{\csname pgfplots@#1min\endcsname}%
		\expandafter\global\expandafter\let\csname pgfplots@#1min\endcsname=\pgfmathresult
		%
		\pgfplotscoordmath{#1}{datascaletrafo}{\csname pgfplots@#1max\endcsname}%
		\expandafter\global\expandafter\let\csname pgfplots@#1max\endcsname=\pgfmathresult
%\message{#1- display limits after data transformation: [\csname pgfplots@#1min\endcsname:\csname pgfplots@#1max\endcsname]^^J}%
	}{%
		% case apply trafo == false:
		\expandafter\let\csname pgfplots@#1min@unscaled@as@float\endcsname=\pgfutil@empty
		\expandafter\let\csname pgfplots@#1max@unscaled@as@float\endcsname=\pgfutil@empty
	}%
}

pgfplotsstackedplots.code.tex
%--------------------------------------------
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2007-2013 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------

%
% This file contains the implementation for stacked plots.
%
% Stacked plots always keep record of the last plotted coordinates.
% Any new plot will be ADDED on top of the last plotted coordinates.
% 
% Terminology: "last plotted coordinates" are called "zero levels"
% because they actually work like shifts.
%
% Programming Structure:
%
% 1. We keep TWO lists of coordinates: a list of CURRENT zero level
% coordinates and a list of NEXT zero level coordinates.
%
% The first one will be queried whenever a zero level coordinate is
% requested.
%
% The second one will be used to form zero levels for the next plot.
%
% 2. At the beginning and end of the survey phase of each plot, the lists in 1.) are
% initialised properly.
%
% 3.1 While plot coordinates are processed during the survey phase, the following methods
% interact with the stacked API:
% \pgfplots@stacked@preparepoint@inmacro
% 	-> compute the 'stacked' sum.
% 	This may need to be done with floating point arithmetics because
% 	the data scaling trafo is not yet initialised
% \pgfplots@stacked@rememberzerolevelpoint@for@next@plot
% \pgfplots@stacked@getnextzerolevelpoint
%
%
% 3.2 during the final visualization phase, we have
% \pgfplots@stacked@visphasepreparedatapoint
% 	-> takes coordinates as they will be given to Tikz. This method is
% 	used to 
% 		- communicate zero level coordinates to Tikz
% 		- implement the 'closed paths' option (allows filled stacked plots).
%
% 4. Zero levels are communicated to Tikz by
% \pgfplots@stacked@initzerolevelhandler. This routine initialises an
% input stream for Tikz plot handlers which produces a sequence of
% zero levels. It is used by [xy]comb and [xy]bar.
%
%

\let\pgfplots@stacked@zerolevelpoint@x=\pgfutil@empty
\let\pgfplots@stacked@zerolevelpoint@y=\pgfutil@empty

% this value is populated during the survey phase. It will be copied
% to the visualization phase, i.e. it will be serialized along with
% the survey'ed state:
\newif\ifpgfplots@stacked@isfirstplot
\newif\ifpgfplots@stacked@isinitialised

% Pre-initialisation.
% Needs to be called before the first call to
% \pgfplots@stacked@beginplot.
\def\pgfplots@stacked@initialise{%
	\gdef\pgfplots@stacked@coordcount{-1}%
	\pgfplots@stacked@isfirstplottrue
	\pgfplots@stacked@isinitialisedtrue
}%

% Cleanup method. Truncates any global variables to reduce string
% space.
\def\pgfplots@stacked@finalize{%
	\global\pgfplotslistnewempty\pgfplots@stacked@zerolevellist
	\global\pgfplotslistnewempty\pgfplots@stacked@nextzerolevellist
	\pgfplots@stacked@isinitialisedfalse
}%

% (Re)defines the macro \pgfplots@stacked@getnextzerolevelpoint
% at the beginning of each plot.
%
% The macro \pgfplots@stacked@getnextzerolevelpoint fills
% \pgfplots@stacked@zerolevelpoint@[xy].
%
% ATTENTION: call \pgfplots@stacked@initialise before the first call
% of beginplot!
%
% ATTENTION: install this before 'visualization depends on' - it
% modifies \pgfplotsaxisserializedatapoint@private
\def\pgfplots@stacked@beginplot{%
%\message{pgfplots@stacked@beginplot: PLOT STARTED.}%
	\ifpgfplots@stacked@isinitialised
	\else
		\pgfplots@error{LOGIC ERROR: please call \string\pgfplots@stacked@initialise.}%
	\fi
	\def\pgfplots@stacked@zerolevel@current{}%
	\pgfplots@stacked@prepare@value@serialization
	% accumulate this command here for \closedcycle:
	\ifpgfplots@stacked@isfirstplot
		\global\pgfplotslistnewempty\pgfplots@stacked@zerolevellist
		% only work with float if its really necessary - for
		% example if the scaling trafo which maps to pgfmath is
		% not yet initialised.
		\ifpgfplots@datascaletrafo@initialised % FIXME : should be '!ifsurvey'
			\def\pgfplots@stacked@zerolevelpoint@x{0}%
			\def\pgfplots@stacked@zerolevelpoint@y{0}%
			\def\pgfplots@stacked@zerolevelpoint@z{0}%
		\else
			% note that log plots are special: their "stacked zero" is
			% computed with \pgfplotscoordmath{default}
			%
			\pgfplots@if{pgfplots@xislinear}{\pgfplotscoordmath{x}{zero}}{\pgfplotscoordmath{default}{zero}}%
			\let\pgfplots@stacked@zerolevelpoint@x=\pgfmathresult
			%
			\pgfplots@if{pgfplots@yislinear}{\pgfplotscoordmath{y}{zero}}{\pgfplotscoordmath{default}{zero}}%
			\let\pgfplots@stacked@zerolevelpoint@y=\pgfmathresult
			%
			\pgfplots@if{pgfplots@xislinear}{\pgfplotscoordmath{z}{zero}}{\pgfplotscoordmath{default}{zero}}%
			\let\pgfplots@stacked@zerolevelpoint@z=\pgfmathresult
		\fi
		%
		\def\pgfplots@stacked@getnextzerolevelpoint{}% will remain constant anyway.
	\else
		{\globaldefs=1
		\pgfplotslistcopy\pgfplots@stacked@nextzerolevellist\to\pgfplots@stacked@zerolevellist
		}%
		\def\pgfplots@stacked@getnextzerolevelpoint{%
			\pgfplotslistcheckempty\pgfplots@stacked@zerolevellist
			\ifpgfplotslistempty
				\pgfplots@stacked@wrong@count@error
			\else
				{\globaldefs=1
				\pgfplotslistpopfront\pgfplots@stacked@zerolevellist\to\pgfmathresult
				}%
				\expandafter\pgfplots@stacked@parsezerolevelpoint\expandafter{\pgfmathresult}%
			\fi
		}%
	\fi
	\global\pgfplotslistnewempty\pgfplots@stacked@nextzerolevellist
}%

% ATTENTION: install this before 'visualization depends on' - it
% modifies \pgfplotsaxisserializedatapoint@private
\def\pgfplots@stacked@visphase@beginplot{%
%\message{pgfplots@stacked@beginplot: VISUALIZATION OF PLOT STARTED (phase = \pgfplots@visphase@name).^^J}%
	\let\pgfplots@stacked@closedcycle@impl=\pgfutil@empty
	\pgfplots@stacked@prepare@value@serialization
}%

\def\pgfplots@stacked@prepare@value@serialization{%
	% This here is SIMILAR to 'visualization depends on'.
	%
	% The only difference is that 'visualization depends on' expands
	% its arguments whereas this one here does not.
	%
	\pgfplotsset{%
		visualization depends on=value \pgfplots@stacked@diff\as\pgfplots@stacked@diff
	}%
	%
	%
	% Modify the axis private parts such that a data point is
	% serialized to the form
	% {Z{<stacked zerolevel value>}{<point meta>};<x coordinate>,<y coordinate>,<z coordinate>}
	%
	% for example, a 2d data pont (0,1) without point meta is serialized to 
	% {Z{}{};0Y0.0e0],1Y1.0e0],}
	%
	% The deserialization looks for the magic token 'Z'. The next
	% parameter is the zero level of the data point, the following one
	% the "old" private serialization stuff (typically just point
	% meta).
	%
	% Note that the zero level of a data point might have its own zero
	% level (grand father) ... this would be part here as well, even
	% if it is useless (?). This causes recursive references to all
	% zero levels... and more memory for stacked plots.
	%
	% The zero'th level has an empty zero level point.
	\expandafter\def\expandafter\pgfplotsaxisserializedatapoint@private\expandafter{%
		\pgfplotsaxisserializedatapoint@private
		\t@pgfplots@toka=\expandafter{\pgfplots@stacked@zerolevel@current}%
		\t@pgfplots@tokb=\expandafter{\pgfplotsretval}%
		\edef\pgfplotsretval{%
			Z{\the\t@pgfplots@toka}%
			{\the\t@pgfplots@tokb}%
		}%
	}%
	%
	\pgfutil@ifundefined{pgfplotsaxisdeserializedatapointfrom@private@backup@}{}{%
		\pgfplots@error{Illegal internal state encountered: the stacked plots serialization preparation has been invoked twice}%
	}%
	\let\pgfplotsaxisdeserializedatapointfrom@private@backup@=\pgfplotsaxisdeserializedatapointfrom@private
	\def\pgfplotsaxisdeserializedatapointfrom@private##1{%
		\pgfplotsaxisdeserializedatapointfrom@private@stacked@##1%
	}%
}%

\def\pgfplotsaxisdeserializedatapointfrom@private@stacked@ Z#1#2{%
	\def\pgfplots@stacked@zerolevel{#1}%
	\pgfplotsaxisdeserializedatapointfrom@private@backup@{#2}%
}%

\def\pgfplots@stacked@parsezerolevelpoint#1{%
	\begingroup
	\pgfplotsaxisdeserializedatapointfrom#1% no braces here!
%	\pgfplotsplothandlerdeserializepointfrom{#1}%
	\pgfplots@stacked@smuggle
	\endgroup
	% the value of \pgfplots@stacked@zerolevel@current will be configured as
	% "visualization depends on".
	% In other words: it is available later-on.
	\def\pgfplots@stacked@zerolevel@current{#1}%
}

\def\pgfplots@stacked@smuggle\endgroup{%
	\xdef\pgfplots@glob@TMPb{%
		\noexpand\def\noexpand\pgfplots@stacked@zerolevelpoint@x{\pgfplots@current@point@x}%
		\noexpand\def\noexpand\pgfplots@stacked@zerolevelpoint@y{\pgfplots@current@point@y}%
		\noexpand\def\noexpand\pgfplots@stacked@zerolevelpoint@z{\pgfplots@current@point@z}%
	}%
	\endgroup
	\pgfplots@glob@TMPb
}%

\def\pgfplots@stacked@wrong@count@error{%
	\pgfplots@error{Sorry, pgfplots expects stacked plots to have exactly the same number of coordinates. Unfortunately, I encountered at plot with DIFFERENT NUMBERS OF COORDINATES. Please verify that 1. no point has been dropped by coordinate filters (for example log(0) or so) and 2. all plots have the same number of coordinates.}%
}%

\def\pgfplots@stacked@survey@endplot{%
%\message{Stacked plot survey phase end: isfirst = \ifpgfplots@stacked@isfirstplot true \else false\fi^^J}%
	\ifpgfplots@stacked@isfirstplot
		\pgfplotslistcheckempty\pgfplots@stacked@zerolevellist
		\ifpgfplotslistempty
		\else
			\pgfplots@stacked@wrong@count@error
		\fi
	\fi
	\ifpgfplots@stacked@isfirstplot
		\def\pgfplots@stacked@serialized@commands{\noexpand\pgfplots@stacked@isfirstplottrue}%
	\else
		\def\pgfplots@stacked@serialized@commands{\noexpand\pgfplots@stacked@isfirstplotfalse}%
	\fi
	\global\pgfplots@stacked@isfirstplotfalse
}%

\def\pgfplots@stacked@visphase@endplot{%
%\message{Stacked plot vis phase end: isfirst = \ifpgfplots@stacked@isfirstplot true \else false\fi^^J}%
	\ifpgfplots@stacked@isfirstplot
		\let\pgfplots@stacked@closedcycle@impl=\pgfplots@path@closed@cycle@std
	\else
		\t@pgfplots@tokc=\expandafter{\pgfplots@stacked@closedcycle@impl}%
		\edef\pgfplots@stacked@closedcycle@impl{%
			[mark=none,/utils/exec=\noexpand\pgfplots@try@mirror@plot@handler]
			--plot coordinates{\the\t@pgfplots@tokc}
			--cycle
		}%
	\fi
	\global\pgfplots@stacked@isfirstplotfalse
}%

% WARNING: when this method is called, NEITHER
% \ifpgfplots@stacked@isfirstplot NOR the zero level lists are
% initialised!
\def\pgfplots@stacked@initzerolevelhandler{%
	\if\pgfplots@stacked@dir x
		\pgfplotxzerolevelstream@@list
		\pgfplotyzerolevelstreamconstant{\pgfplots@ZERO@y}%
	\else
		\pgfplotxzerolevelstreamconstant{\pgfplots@ZERO@x}%
		\pgfplotyzerolevelstream@@list
	\fi
}%

% #1: a point as (x,y) (or (x,y,z) )
\def\pgfplots@stacked@rememberzerolevelpoint@for@next@plot#1{%
	\expandafter\pgfplotslistpushbackglobal\expandafter{#1}\to\pgfplots@stacked@nextzerolevellist
}

% Provides public access to zero levels into some key-value pairs.
% Returns the values into a set of keys in the /data point/ prefix.
%
% The values can be used in 'axis cs'.
\def\pgfplotspointgetzerolevelcoordinates{%
	\pgfplotspointgetnormalizedzerolevelcoordinates
	\pgfplotspointgetcoordinatesfromnormalized[path=/data point/zero]%
	\pgfplotspointgetcoordinatesfromnormalized[path=/data point/diff]%
}

% Same as \pgfplotsgetzerolevelcoordinates, but the resulting values
% are for use in 'normalized axis cs'.
%
% This works for both stacked plots and normal plots.
\def\pgfplotspointgetnormalizedzerolevelcoordinates{%
	\begingroup
	\ifpgfplots@stackedmode
		\ifx\pgfplots@stacked@zerolevel\pgfutil@empty
			\pgfplotspointgetnormalizedcoordinates%
			\pgfplotsutilforeachcommasep{x,y,z}\as\pgfplots@loc@TMPa{%
				\pgfkeysgetvalue{/data point/\pgfplots@loc@TMPa}\pgfplots@loc@TMPb
				\expandafter\let\csname pgfplots@current@point@\pgfplots@loc@TMPa\endcsname=\pgfplots@loc@TMPb
			}%
			\pgfplotscoordmath{\pgfplots@stacked@dir}{zero}%
			\expandafter\let\csname pgfplots@current@point@\pgfplots@stacked@dir\endcsname\pgfmathresult%
			%
			\let\pgfplots@current@point@meta=\pgfutil@empty
			\pgfkeyssetvalue{/data point/zero/auto}{1}%
		\else
			%
			\expandafter\pgfplotsaxisdeserializedatapointfrom\pgfplots@stacked@zerolevel%
			\pgfkeyssetvalue{/data point/zero/auto}{0}%
		\fi
		%
		\pgfplotscoordmath{x}{zero}\let\pgfplots@stacked@diff@x=\pgfmathresult%
		\pgfplotscoordmath{y}{zero}\let\pgfplots@stacked@diff@y=\pgfmathresult%
		\pgfplotscoordmath{z}{zero}\let\pgfplots@stacked@diff@z=\pgfmathresult%
		\pgfutil@namelet{pgfplots@stacked@diff@\pgfplots@stacked@dir}{pgfplots@stacked@diff}%
	\else
		% Ah - no stacked plot!? Well, than do "something useful":
		\pgfplotscoordmath{x}{zero}\let\pgfplots@current@point@x=\pgfmathresult%
		\pgfplotscoordmath{y}{zero}\let\pgfplots@current@point@y=\pgfmathresult%
		\pgfplotscoordmath{z}{zero}\let\pgfplots@current@point@z=\pgfmathresult%
		%
		\pgfplotspointgetnormalizedcoordinates%
		\pgfplotsutilforeachcommasep{x,y,z}\as\pgfplots@loc@TMPa{%
			\pgfkeysgetvalue{/data point/\pgfplots@loc@TMPa}\pgfplots@loc@TMPb
			\expandafter\let\csname pgfplots@stacked@diff@\pgfplots@loc@TMPa\endcsname=\pgfplots@loc@TMPb
		}%
		\pgfkeyssetvalue{/data point/zero/auto}{1}%
	\fi
	%
	\xdef\pgfplots@glob@TMPd{%
		\noexpand\pgfkeyssetvalue{/data point/zero/x}{\pgfplots@current@point@x}%
		\noexpand\pgfkeyssetvalue{/data point/zero/y}{\pgfplots@current@point@y}%
		\noexpand\pgfkeyssetvalue{/data point/zero/z}{\pgfplots@current@point@z}%
		\noexpand\pgfkeyssetvalue{/data point/zero/meta}{\pgfplots@current@point@meta}%
		\noexpand\pgfkeyssetvalue{/data point/zero/auto}{\pgfkeysvalueof{/data point/zero/auto}}%
		\noexpand\pgfkeyssetvalue{/data point/diff/x}{\pgfplots@stacked@diff@x}%
		\noexpand\pgfkeyssetvalue{/data point/diff/y}{\pgfplots@stacked@diff@y}%
		\noexpand\pgfkeyssetvalue{/data point/diff/z}{\pgfplots@stacked@diff@z}%
	}%
	\endgroup
	\pgfplots@glob@TMPd
%
%\message{pgfplotsgetzerolevelcoordinates returned x=\pgfkeysvalueof{/data point/zero/x}, y=\pgfkeysvalueof{/data point/zero/y}, diffx=\pgfkeysvalueof{/data point/diff/x}; diffy=\pgfkeysvalueof{/data point/diff/y}, diff=\pgfkeysvalueof{/data point/diff}^^J}%
}%

% PRECONDITION:
% 	Is in invoked inside of a coord preparation routine, that means
% 	- \pgfplots@current@point@[xyz] 
% 	- \ifpgfplots@curplot@threedim
% 	are all set properly.
\def\pgfplots@stacked@visphasepreparedatapoint{%
	\ifx\pgfplots@stacked@zerolevel\pgfutil@empty
		% this here is the case if we have the first encountered plot,
		% i.e. the one on which others are stacked.
		%
		% Note that it is not necessarily the first one which is
		% processed (compare reverse stacked plots).
		\if\pgfplots@stacked@dir x
			\edef\pgfplots@loc@TMPa{\pgfplots@logical@ZERO@x pt}%
		\else
			\edef\pgfplots@loc@TMPa{\pgfplots@logical@ZERO@y pt}%
		\fi
		\let\pgfplots@stacked@PGF@zerolevel\pgfplots@loc@TMPa
		%
	\else
		\begingroup
		%\expandafter\pgfplotsplothandlerdeserializepointfrom\expandafter{\pgfplots@stacked@zerolevel}%
		\expandafter\pgfplotsaxisdeserializedatapointfrom\pgfplots@stacked@zerolevel%
		%
		\pgfplots@stacked@logarithm@if@needed
		%
		% avoid endless recursion:
		\let\pgfplots@stacked@visphasepreparedatapoint=\relax
		\pgfplotsaxisvisphasegetpoint
		\edef\pgfplots@current@point@x{\the\pgf@x}%
		\edef\pgfplots@current@point@y{\the\pgf@y}%
		\pgfplots@stacked@smuggle
		\endgroup
		%
		\if\pgfplots@stacked@dir x
			\let\pgfplots@stacked@PGF@zerolevel=\pgfplots@stacked@zerolevelpoint@x%
		\else
			\let\pgfplots@stacked@PGF@zerolevel=\pgfplots@stacked@zerolevelpoint@y%
		\fi
		\t@pgfplots@toka=\expandafter{\pgfplots@stacked@closedcycle@impl}%
		\edef\pgfplots@stacked@closedcycle@impl{%
			(\pgfplots@stacked@zerolevelpoint@x,\pgfplots@stacked@zerolevelpoint@y)%
			\the\t@pgfplots@toka}%
	\fi
}%

% A special hook which is executed early in the visualization phase. 
% It will be invoked *before*
% \pgfplots@stacked@visphasepreparedatapoint!
%
% Its purpose is to clear the data if necessary, i.e. it implements 
% /pgfplots/stacked ignores zero
\def\pgfplots@stacked@visphase@stream@coord@{%
	\ifpgfplots@stacked@ignores@zero
		\edef\pgfplots@loc@TMPa{\pgfkeysvalueof{/pgfplots/stacked ignores zero/\pgfplots@visphase@name}}%
		\def\pgfplots@loc@TMPb{true}%
		% apply this feature only if it is active for the current
		% visualization phase:
		\ifx\pgfplots@loc@TMPb\pgfplots@loc@TMPa
			\ifx\pgfplots@current@point@x\pgfutil@empty% this implements `unbounded coords=jump', for example
			\else
				\pgfplotscoordmath{\pgfplots@stacked@dir}{if is}{\pgfplots@stacked@diff}{0}{%
					\let\pgfplots@current@point@x=\pgfutil@empty
					\let\pgfplots@current@point@y=\pgfutil@empty
					\let\pgfplots@current@point@z=\pgfutil@empty
				}{%
				}%
			\fi
		\fi
	\fi
}%

% PRECONDITION:
% 	Is in invoked inside of a coord preparation routine, that means
% 	- \pgfplots@current@point@[xyz] 
% 	- \ifpgfplots@curplot@threedim
% 	are all set properly.
%
% POSTCONDITION:
% 	- \pgfplots@current@point@[xyz] are adjusted.
\def\pgfplots@stacked@preparepoint@inmacro{%
	\pgfplots@stacked@getnextzerolevelpoint
	%
	\ifpgfplots@stacked@plus
		\def\pgfplots@stacked@op{add}%
	\else
		\def\pgfplots@stacked@op{subtract}%
	\fi
	%
	\pgfutil@namelet{pgfplots@stacked@diff}{pgfplots@current@point@\pgfplots@stacked@dir}%
	%
	\pgfplots@if{pgfplots@\pgfplots@stacked@dir islinear}{%
		\pgfplotscoordmath{\pgfplots@stacked@dir}{op}{\pgfplots@stacked@op}{%
			{\csname pgfplots@stacked@zerolevelpoint@\pgfplots@stacked@dir\endcsname}%
			{\csname pgfplots@current@point@\pgfplots@stacked@dir\endcsname}}%
	}{%
		% LOG. we need to compute log(zerolevel + current):
		% FIXME : this might work, but is is hackery - because the
		% coordmath framework handles log bases in a very stupid way.
		% improve it somehow!
		\edef\pgfmathresult{\csname pgfplots@current@point@\pgfplots@stacked@dir\endcsname}%
		\pgfplotscoordmath{\pgfplots@stacked@dir}{exp}{\pgfmathresult}%
		\pgfplotscoordmath{default}{parsenumber}{\pgfmathresult}%
		\expandafter\let\csname pgfplots@current@point@\pgfplots@stacked@dir\endcsname=\pgfmathresult
		\pgfplotscoordmath{default}{op}{\pgfplots@stacked@op}{%
			{\csname pgfplots@stacked@zerolevelpoint@\pgfplots@stacked@dir\endcsname}%
			{\csname pgfplots@current@point@\pgfplots@stacked@dir\endcsname}%
		}%
	}%
	%
	% for logs, I remember just zerolevel+current; not its log.
	\expandafter\let\csname pgfplots@current@point@\pgfplots@stacked@dir\endcsname=\pgfmathresult
	%
	% this here would also be ok, but it would only store the coords
	% of the zero level...
	%\pgfplotsplothandlerserializepointto\pgfplotsretval
%\message{serializing current value current value to \meaning\pgfplotsretval^^J}%
	%
	\begingroup
	%
	% without this line, the "zerolevel" would also know all its zero
	% levels recursively:
	\pgfplots@stacked@strip@parents@zerolevel
	%
	\pgfplotsaxisserializedatapointtostring
	\pgfplots@stacked@rememberzerolevelpoint@for@next@plot{\pgfplotsretval}%
	\endgroup
	%
	% 
	%
	\pgfplots@stacked@logarithm@if@needed
}

% 
% We store the normal values for zero levels. Consequently, we may
% need to (re)apply the log if we have a log axis. 
%
% I am unsure of whether log+stacked is useful at all.
\def\pgfplots@stacked@logarithm@if@needed{%
	\pgfplots@if{pgfplots@\pgfplots@stacked@dir islinear}{%
	}{%
		\pgfplotscoordmath{\pgfplots@stacked@dir}{log}{\csname pgfplots@current@point@\pgfplots@stacked@dir\endcsname}%
		\expandafter\let\csname pgfplots@current@point@\pgfplots@stacked@dir\endcsname=\pgfmathresult
	}%
}%

% you can \let this here to \relax if you want to gain access to all
% zero levels recursively:
\def\pgfplots@stacked@strip@parents@zerolevel{%
	\def\pgfplots@stacked@zerolevel@current{}%
}

% This here is a re-implementation of the stored plot processing.
%
% The idea is simple, although it requires quite some work:
%
% If we stack plots on top of each other, early drawing commands
% (early plots) will be OVERDRAWN by later drawing commands (later
% plots). This is especially unfortunate if we use filled bar plots
% or comb plots.
%
% IDEA: draw plots in REVERSE order. The positioning, styles and
% whatever must not be affected, only the sequence of drawing commands
% shall change.
%
% So, this command here reverses the list.
\def\pgfplots@stacked@finalize@stored@plots{%
	\pgfplotslistnewempty\pgfplots@stored@plotlist@reversed
	\begingroup
	\pgfplotslistforeachungrouped\pgfplots@stored@plotlist\as\pgfplots@loc@TMPa{%
		% Reverse sequence:
		\expandafter\pgfplotslistpushfront\pgfplots@loc@TMPa\to\pgfplots@stored@plotlist@reversed
	}%
	% Now, overwrite the original list:
	\global\let\pgfplots@stored@plotlist=\pgfplots@stored@plotlist@reversed
	\global\let\pgfplots@stored@plotlist@reversed=\relax
	\endgroup
}%

\def\pgfplots@stacked@path@closed@cycle{%
	\pgfplots@stacked@closedcycle@impl
}

% PGF interfaces:
%
% these are relatively simple right now: assuming that the zero-level
% streams are advanced if and only if the coordinate streams are
% advanced, we can simply inject the *currect* zero level rather than
% providing all at once.
\def\pgfplotxzerolevelstream@@list{%
	\def\pgf@plotxzerolevelstreamstart{%
		\gdef\pgf@plotxzerolevelstreamnext{%
			\global\pgf@x=\pgfplots@stacked@PGF@zerolevel\relax
		}%
	}%
	\def\pgf@plotxzerolevelstreamend{%
	}%
}%

\def\pgfplotyzerolevelstream@@list{%
	\def\pgf@plotyzerolevelstreamstart{%
		\gdef\pgf@plotyzerolevelstreamnext{%
			\global\pgf@x=\pgfplots@stacked@PGF@zerolevel\relax
		}%
	}%
	\def\pgf@plotyzerolevelstreamend{%
	}%
}%

pgfplotssysgeneric.code.tex
%--------------------------------------------
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2007/2008 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------

% NOTE: tex4ht support is lousy. For example, \tikz \node {$10^{-6}$};
% will already break -- because SVG does not support the html tag
% &minus; produced by tex4ht (and TikZ apparently does not know how to
% escape it somehow).
\def\pgfplots@sys@beforenode{%
	\pgfkeysifdefined{/tikz/tex4ht node/escape/.@cmd}{%
		\ifpgfplots@has@cell@picture
			\tikzset{tex4ht node/escape=true}%
			\pgfplots@warning{ATTENTION: you may want to use '\string\pgfplotsset{cell picture=false}' in your preamble. Otherwise, tex4ht will produce TWO SVG files per plot.^^J}%
		\fi
	}{}%
}%

% see compat/show suggested version
\newif\ifpgfplots@show@suggested@version
\pgfplots@show@suggested@versiontrue

\def\pgfplots@show@suggested@compat@value{%
	\ifpgfplots@show@suggested@version
		\begingroup
		\pgfkeysgetvalue{/pgfplots/compat/current}\current
		\pgfkeysgetvalue{/pgfplots/compat/mostrecent}\mostrecent
		%
		\def\b@isnewest{0}%
		\def\b@shouldupgrade{0}%
		\ifx\current\mostrecent
			\def\b@isnewest{1}%
		\else
			\def\pgfplots@loc@TMPa{newest}%
			\ifx\current\pgfplots@loc@TMPa
				\def\b@isnewest{1}%
			\else
				\expandafter\pgfplotsutilifstringequal\expandafter{\current}{pre 1.3}{%
					\def\b@shouldupgrade{1}%
				}{}%
				\expandafter\pgfplotsutilifstringequal\expandafter{\current}{default}{%
					\def\b@shouldupgrade{1}%
				}{}%
			\fi
		\fi
		\if1\b@isnewest
			\pgfplots@message{Package pgfplots notification 'compat/show suggested version=true': document has been generated with the most recent feature set (\string\pgfplotsset{compat=\mostrecent}).^^J}%
		\else
			\if1\b@shouldupgrade
				\pgfplots@warning{running in backwards compatibility mode (unsuitable tick labels; missing features). Consider writing \string\pgfplotsset{compat=\mostrecent} into your preamble.^^J}%
			\else
				\pgfplots@message{Package pgfplots notification 'compat/show suggested version=true': you might benefit from \string\pgfplotsset{compat=\mostrecent} (current compat level: \current).^^J}%
			\fi
		\fi
		\endgroup
	\fi
}

\pgfutil@IfUndefined{AtBeginDocument}{%
}{%
	\AtBeginDocument{%
		\pgfplots@show@suggested@compat@value
	}%
}%

pgfplotstableshared.code.tex
%--------------------------------------------
%
% Package pgfplotstable
%
% Provides support to read and work with abstact numeric tables of the
% form
%
% COLUMN1	COLUMN2 COLUMN3
% 1 		2		3
% 4			4		552
% 1e124		0.00001	1.2345e-12
% ...
%
% Copyright 2007-2010 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------

% This file provides a high-level table manipulation and typesetting
% package.
%
%
% ---------------------------------------------
%  Implementation notes for programmers:
% ---------------------------------------------
%
%  The table data structure consists of
%  1. A name which must be a valid TeX macro like '\table'
%  2. A column list in the \pgfplotslist format.
%   In fact, the column list is stored in the table's name:
%   	\pgfplotslistnewempty\table
%  3. A "file name" stored in
%     \csname\string<\namemacro>@@table@name\endcsname
%  4. A "scan line length" number stored in
%  		\csname\string<\namemacro>@@table@scanline\endcsname
%  		It contains the value of \pgfplotsscanlinelength which has
%  		been identified right after \pgfplotstableread.
%  5. foreach column, there is a list of row-values (a row-vector) in
%  the \pgfplotslist format named
%  		\csname\string<\namemacro>@<column name>\endcsname
%   

\newif\ifpgfplotstable@search@header
\newif\ifpgfplotstable@firstline@is@header
\newcount\c@pgfplotstable@counta
\newtoks\t@pgfplotstable@a
\newif\ifpgfplots@addplotimpl@readcompletely
% should always be false; use only in grouped internal macros
\newif\ifpgfplots@table@options@areset
\newif\ifpgfplots@tableread@to@listener
\newif\ifpgfplots@tableread@use@begingroup
\newif\ifpgfplotstable@trimcells

\pgfkeys{%
	/pgfplots/table/every table/.style={},
	/pgfplots/table/.unknown/.code={%
		\pgfplotstable@error@pkg{Sorry, I do not know the key `\pgfkeyscurrentkeyRAW' and I am going to ignore it. Perhaps you need \string\usepackage{pgfplotstable}? (The table typesetting parts are a separate package)}%
	},%
	/pgfplots/table/header/.is choice,
	/pgfplots/table/header/true/.code={\pgfplotstable@firstline@is@headerfalse\pgfplotstable@search@headertrue},
	/pgfplots/table/header/false/.code={\pgfplotstable@firstline@is@headerfalse\pgfplotstable@search@headerfalse},
	/pgfplots/table/header/has colnames/.code={\pgfplotstable@firstline@is@headertrue\pgfplotstable@search@headerfalse},
	/pgfplots/table/header=true,
	/pgfplots/table/x index/.initial=0,
	/pgfplots/table/x/.initial=,
	/pgfplots/table/x expr/.initial=,
	/pgfplots/table/y index/.initial=1,
	/pgfplots/table/y/.initial=,
	/pgfplots/table/y expr/.initial=,
	/pgfplots/table/z index/.initial=2,
	/pgfplots/table/z/.initial=,
	/pgfplots/table/z expr/.initial=,
	/pgfplots/table/meta index/.initial=,
	/pgfplots/table/meta/.initial=,
	/pgfplots/table/meta expr/.initial=,
	/pgfplots/table/x error index/.style={
		x error plus index={#1},%
		x error minus index={#1}%
	},
	/pgfplots/table/y error index/.style={
		y error plus index={#1},%
		y error minus index={#1}%
	},
	/pgfplots/table/z error index/.style={
		z error plus index={#1},%
		z error minus index={#1}%
	},
	/pgfplots/table/x error/.style={
		x error plus={#1},%
		x error minus={#1}%
	},
	/pgfplots/table/y error/.style={
		y error plus={#1},%
		y error minus={#1}%
	},
	/pgfplots/table/z error/.style={
		z error plus={#1},%
		z error minus={#1}%
	},
	/pgfplots/table/x error expr/.style={
		x error plus expr={#1},%
		x error minus expr={#1}%
	},
	/pgfplots/table/y error expr/.style={
		y error plus expr={#1},%
		y error minus expr={#1}%
	},
	/pgfplots/table/z error expr/.style={
		z error plus expr={#1},%
		z error minus expr={#1}%
	},
	/pgfplots/table/x error plus index/.initial=,
	/pgfplots/table/y error plus index/.initial=,
	/pgfplots/table/z error plus index/.initial=,
	/pgfplots/table/x error plus/.initial=,
	/pgfplots/table/y error plus/.initial=,
	/pgfplots/table/z error plus/.initial=,
	/pgfplots/table/x error plus expr/.initial=,
	/pgfplots/table/y error plus expr/.initial=,
	/pgfplots/table/z error plus expr/.initial=,
	/pgfplots/table/x error minus index/.initial=,
	/pgfplots/table/y error minus index/.initial=,
	/pgfplots/table/z error minus index/.initial=,
	/pgfplots/table/x error minus/.initial=,
	/pgfplots/table/y error minus/.initial=,
	/pgfplots/table/z error minus/.initial=,
	/pgfplots/table/x error minus expr/.initial=,
	/pgfplots/table/y error minus expr/.initial=,
	/pgfplots/table/z error minus expr/.initial=,
	/pgfplots/table/ignore chars/.initial=,
	/pgfplots/table/white space chars/.initial=,
	/pgfplots/table/comment chars/.initial=,
	/pgfplots/table/skip first n/.initial=0,
	/pgfplots/table/trim cells/.is if=pgfplotstable@trimcells,
	/pgfplots/table/trim cells/.default=true,
	/pgfplots/table/read completely/.is choice,
	/pgfplots/table/read completely/true/.code=	\pgfplots@addplotimpl@readcompletelytrue\def\pgfplots@addplotimpl@readcompletely@auto{0},
	/pgfplots/table/read completely/false/.code=\pgfplots@addplotimpl@readcompletelyfalse\def\pgfplots@addplotimpl@readcompletely@auto{0},
	/pgfplots/table/read completely/auto/.code=\pgfplots@addplotimpl@readcompletelyfalse\def\pgfplots@addplotimpl@readcompletely@auto{1},
	/pgfplots/table/read completely/.default=true,
	/pgfplots/table/read completely=auto,
	/pgfplots/table/col sep/.is choice,
	/pgfplots/table/col sep/space/.code		= {\def\pgfplotstableread@COLSEP@CASE{0}},
	/pgfplots/table/col sep/comma/.code		= {\def\pgfplotstableread@COLSEP@CASE{1}},
	/pgfplots/table/col sep/semicolon/.code	= {\def\pgfplotstableread@COLSEP@CASE{2}},
	/pgfplots/table/col sep/colon/.code		= {\def\pgfplotstableread@COLSEP@CASE{3}},
	/pgfplots/table/col sep/braces/.code	= {\def\pgfplotstableread@COLSEP@CASE{4}},
	/pgfplots/table/col sep/tab/.code		= {\def\pgfplotstableread@COLSEP@CASE{5}},
	/pgfplots/table/col sep/&/.code			= {\def\pgfplotstableread@COLSEP@CASE{6}\pgfplotstable@trimcellstrue},
	/pgfplots/table/col sep/ampersand/.code	= {\def\pgfplotstableread@COLSEP@CASE{6}\pgfplotstable@trimcellstrue},
	/pgfplots/table/col sep=space,
	/pgfplots/table/format/.is choice,
	/pgfplots/table/format/auto/.code		= {\def\pgfplotstableread@FORMAT@CASE{0}},
	/pgfplots/table/format/inline/.code		= {\def\pgfplotstableread@FORMAT@CASE{1}},
	/pgfplots/table/format/file/.code		= {\def\pgfplotstableread@FORMAT@CASE{2}},
	/pgfplots/table/format=auto,
	/pgfplots/table/row sep/.code={%
		\pgfplotsutilifstringequal{#1}{\\}{%
			\def\pgfplotstableread@ROWSEP@CASE{1}%
		}{%
			\pgfplotsutilifstringequal{#1}{crcr}{%
				\def\pgfplotstableread@ROWSEP@CASE{1}%
			}{%
				\pgfplotsutilifstringequal{#1}{newline}{%
					\def\pgfplotstableread@ROWSEP@CASE{0}%
				}{%
					{%
					\t@pgfplots@tokc={#1}%
					\pgfplotsthrow{invalid argument}{\pgfplots@loc@TMPa}{Sorry, the choice `row sep=\the\t@pgfplots@tokc' is not known. Maybe you misspelled it? Try `\string\\' or `newline'.}\pgfeov%
					}%
				}%
			}%
		}%
	},%
	/pgfplots/table/row sep=newline,
}

\pgfkeys{
	% #1: the argument which should have been assigned.
	% #2: an error message. 
	/pgfplots/exception/non unique colname/.code 2 args={%
		\ifx\pgfplotsexceptionmsg\relax
			\pgfplots@error{#2}%
		\else
			\pgfplots@error{\pgfplotsexceptionmsg}%
		\fi
		\let#1=\pgfutil@empty
	},%
	/pgfplots/exception/table columns unbalanced/.code={%
		\ifx\pgfplotsexceptionmsg\relax
			\pgfplots@error{#1}%
		\else
			\pgfplots@error{\pgfplotsexceptionmsg}%
		\fi
	},
}

% \pgfplotstableread[OPTIONS] {FILE} to \name
%
% This method reads a table from FILE to macro \name.
%
% FILE is something like
% G	Basis	dof	L2	A	Lmax	cgiter	maxlevel	eps
% 5	5	5	8.31160034e-02	0.00000000e+00	1.80007647e-01	2	2	-1
% 17	17	17	2.54685628e-02	0.00000000e+00	3.75580565e-02	5	3	-1
% ...
%
% A number format line is also understood:
% G	Basis	dof	L2	A	Lmax	cgiter	maxlevel	eps
% $flags int	int	int	sci:8	sci:8	sci:8	int	int	std:8
% 5	5	5	8.31160034e-02	0.00000000e+00	1.80007647e-01	2	2	-1
%
% or a three-column-gnuplot file with 2 comment headers like
% #Curve 0, 20 points
% #x y type
% 0.00000 0.00000 i
% 0.52632 0.50235 i
%
% The table data is stored columnwise in lists and can be accessed
% with the other methods of this package.
%
% \pgfplotstableread[<options>]{<file>}{<\macro>}
% \pgfplotstableread[<options>]{<file>} to listener{<\macro>}
% \pgfplotstableread* ...
%
% The '*' does not protect its local variables with TeX groups,
% everything is added to the current scope (useful to the 'to
% listener' thing.
%
% The 'to listener' variant does NOT assemble a table data structure.
% Instead, it processes the input table row-wise and invokes <\macro>
% after each complete row. During the evaluation of <\macro>, the
% following methods can be used to query values:
%   \pgfplotstablereadgetcolindex{<index>}{<\macro>}
%   \pgfplotstablereadgetcolname{<name>}{<\macro>}
%   \pgfplotstablereadvalueofcolname{<name>}
%   \pgfplotstablereadvalueofcolindex{<index>}
%   \thisrow{<name>} (equivalent to \pgfplotstablereadvalueofcolname)
%   \getthisrow{<name>}{<\macro>} (equivalent to \pgfplotstablereadgetcolname)
%   \thisrowno{<index>} (equivalent to \pgfplotstablereadvalueofcolindex)
%   \getthisrowno{<index>}{<\macro>}
%   \pgfplotstableforeachcolumn\as{<\iteratemacro>}{<loop body>}
%   	(the '\as' is required directly after
%   	\pgfplotstableforeachcolumn in this context)
% Attention: 'to listener' is scoped by TeX groups, so any assignments
% need to be done globally (or with aftergroup magic).
%
% More remarks about scoping:
% \pgfplotstableread to listener works as follows:
%     \begingroup
%     // load table
%     while file has more lines:
%     	load line, read every column;
%     	invoke listener;
%     repeat
%     \endgroup
%
%  In short: all invocations of listener have the same level of
%  scoping: they are inside of one TeX group. But single listener
%  invocations as such are not scoped. Make sure you don't
%  accidentally overwrite one of the internals in listener. And: make
%  sure you don't change temporary registers without scoping them!
%
% Note: this command also updates \pgfplotsscanlinelength.
\def\pgfplotstableread{%
	\pgfutil@ifnextchar*{%
		\pgfplots@tableread@use@begingroupfalse
		\pgfplotstableread@impl@star
	}{%
		\pgfplots@tableread@use@begingrouptrue
		\pgfplotstableread@impl@star*%
	}%
}%
\def\pgfplotstableread@impl@star*{%
	\pgfutil@ifnextchar[{%
		\pgfplotstableread@impl
	}{%
		\pgfplotstableread@impl[]%
	}%
}

% BACKWARDS COMPATIBILITY
\let\pgfnumtableread=\pgfplotstableread

% Invokes #2 if '#1' is an already loaded table and #3 if not.
\long\def\pgfplotstable@isloadedtable#1#2#3{%
	\pgfplotsutil@ifdefinedui@withsuffix{#1}{@@table@name}{#2}{#3}%
}%

% If the colum name `#1' is a `create on use' speicifcation, #2 is
% invoked, #3 otherwise.
\long\def\pgfplotstableifiscreateonuse#1#2#3{%
	\pgfkeysifdefined{/pgfplots/table/create on use/#1/.@cmd}{#2}{%
		\pgfutil@in@{create col/}{#1}%
		\ifpgfutil@in@
			#2%
		\else
			#3%
		\fi
	}%
}%

% Defines \pgfplotsretval to be a column name which does not already
% occur in the column names of table #1.
\def\pgfplotstablegenerateuniquecolnamefor#1{%
	\begingroup
	\c@pgf@countd=0
	\pgfplotstableforeachcolumn{#1}\as\pgfplots@loc@TMPa{%
		\def\pgfplots@loc@TMPa{\pgfplots@loc@TMPa}%
		\edef\pgfplots@loc@TMPb{autocol\the\c@pgf@countd}%
		\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPb
			\advance\c@pgf@countd by1
		\fi
	}%
	\edef\pgfplotsretval{autocol\the\c@pgf@countd}%
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}

% Returns a column vector in form of \pgfplotslist
% into #3.
%
% #1: the column name (not a macro)
% #2: the table structure
% #3: the output macro name.
%
% @throw `no such element' on error
\def\pgfplotstablegetcolumnbyname#1\of#2\to#3{%
	\let#3=\pgfutil@empty% just for sanity checking.
	\pgfplotstable@getcol{#1}\of{#2}\to{#3}\getcolmethod{STD}%
}

% Declares a new getcolmethod class #1.
% The argument '#1' can then be used as argument for 
% \pgfplotstable@getcol...\getcolmethod{#1}.
%
% #2: a set of keys which redefine the behavior.
% See below for available choices.
\def\pgfplotstable@definegetcolmethod#1#2{%
	\edef\pgfplotstable@definegetcolmethod@{#1}%
	\pgfqkeys{/pgfplots/table/@getcol}{%
		% Checks if column '#1' exists in table `#2' and invokes `#3' if that
		% is the case and `#4' if not.
		%
		% Note that the check is only for physically existent colums, no alias
		% or create on use is checked here.
		% #1: colname
		% #2: table struct
		% #3: true code
		% #4: false code
		% FIXME : THIS IS BUGGY: the macro may exist, but is it
		% (still) part of the table!? Currently, there is a workaround
		% such that \pgfplotstablenew cleans up and avoids that case..
		% and we have no "drop column" currently.
		ifexists	=\pgfutil@ifundefined{\string##2@##1}{##4}{##3},
		%
		% Low level method to return (the actual content) of column #1 of
		% table #2 to macro #3.
		% #1: colname
		% #2: table struct
		% #3: result macro
		getexisting	=\expandafter\let\expandafter##3\csname\string##2@##1\endcsname,
		%
		% no arguments, the value is a boolean (0 or 1)
		createonuse	=1,
		%
		% error handling.
		% #1: colname
		% #2: table struct
		% #3: result macro
		lazyforbidden=\pgfplotstablegetcolumnbyname@impl@createonuseforbidden{##1}\of{##2}\to{##3},
		noalias		=\pgfplotstablegetcolumnbyname@impl@nosuchalias{##1}\of{##2}\to{##3},
		nocol		=\pgfplotstablegetcolumnbyname@impl@nocolumn{##1}\of{##2}\to{##3},
		#2%
	}%
}%
\pgfqkeys{/pgfplots/table/@getcol}{%
	ifexists/.code		={\expandafter\def\csname pgfplotstable@getcol@ifexists@\pgfplotstable@definegetcolmethod@\endcsname##1\of##2##3##4{#1}},%
	getexisting/.code	={\expandafter\def\csname pgfplotstable@getcol@getexisting@\pgfplotstable@definegetcolmethod@\endcsname##1\of##2\to##3{#1}},%
	createonuse/.code	={\expandafter\def\csname pgfplotstable@getcol@createonuse@\pgfplotstable@definegetcolmethod@\endcsname{#1}},%
	lazyforbidden/.code	={\expandafter\def\csname pgfplotstable@getcol@lazyforbidden@\pgfplotstable@definegetcolmethod@\endcsname##1\of##2\to##3{#1}},%
	noalias/.code		={\expandafter\def\csname pgfplotstable@getcol@noalias@\pgfplotstable@definegetcolmethod@\endcsname##1\of##2\to##3{#1}},%
	nocol/.code			={\expandafter\def\csname pgfplotstable@getcol@nocol@\pgfplotstable@definegetcolmethod@\endcsname##1\of##2\to##3{#1}},%
}%

\pgfplotstable@definegetcolmethod{STD}{}%
\pgfplotstable@definegetcolmethod{getptr}{%
	ifexists	=\pgfutil@ifundefined{pgfplotstblread@colindex@for@name#1}{#4}{#3},%
	getexisting	=\edef#3{\csname pgfplotstblread@colindex@for@name#1\endcsname},%
}
\pgfplotstable@definegetcolmethod{resolvename}{%
	getexisting	=\edef#3{#1},%
}

% The low level implementation of \pgfplotstablegetcolumnbyname.
%
% #4: is a getcolmethod declared with \pgfplotstable@definegetcolmethod
%
% ATTENTION: this macro should be expandable! It is also used inside
% of \thisrow{}.
\def\pgfplotstable@getcol#1\of#2\to#3\getcolmethod#4{%
	\csname pgfplotstable@getcol@ifexists@#4\endcsname{#1}\of{#2}{%
		\csname pgfplotstable@getcol@getexisting@#4\endcsname{#1}\of{#2}\to#3%
	}{%
		% Oh, there is no column '#1' in table '#2'!
		%
		% Ok, then check for special features.
		%
		% 1. 'create col/...' 
		% 2. 'create on use'
		% 3. 'alias'
		%
		% WARNING : this code has been REPLICATED in
		% *** \pgfplotstablereadvalueofcolname ***
		\if1\csname pgfplotstable@getcol@createonuse@#4\endcsname%
			\pgfutil@in@{create col/}{#1}%
			\ifpgfutil@in@
				\pgfplotstablegenerateuniquecolnamefor{#2}%
				\def\pgfplotstable@loc@TMPa##1{%
					\pgfkeysdef{/pgfplots/table/create on use/##1}{\pgfkeysalso{#1}}%
					\pgfplotstablecreatecol[/pgfplots/table/create on use/##1]{##1}{#2}%
					% and return the newly generated col:
					\csname pgfplotstable@getcol@getexisting@#4\endcsname{##1}\of{#2}\to#3%
				}%
				\expandafter\pgfplotstable@loc@TMPa\expandafter{\pgfplotsretval}%
			\else
				\pgfplotstable@getcol@next{#1}\of{#2}\to{#3}\getcolmethod{#4}%
			\fi
		\else
			\pgfplotstable@getcol@next{#1}\of{#2}\to{#3}\getcolmethod{#4}%
		\fi
	}%
}%
\def\pgfplotstable@getcol@next#1\of#2\to#3\getcolmethod#4{%
	\pgfkeysifdefined{/pgfplots/table/create on use/#1/.@cmd}{%
		% aah - a 'create on use' style exists. Apply it!
		\if1\csname pgfplotstable@getcol@createonuse@#4\endcsname%
			\pgfplotstablecreatecol[/pgfplots/table/create on use/#1]{#1}{#2}%
			% and return the newly generated col:
			\csname pgfplotstable@getcol@getexisting@#4\endcsname{#1}\of{#2}\to#3%
		\else
			\csname pgfplotstable@getcol@lazyforbidden@#4\endcsname{#1}\of{#2}\to#3%
		\fi
	}{%
		% ok, then it is either an alias or it simply doesn't exist
		\pgfkeysifdefined{/pgfplots/table/alias/#1}{%
			\csname pgfplotstable@getcol@ifexists@#4\endcsname{\pgfkeysvalueof{/pgfplots/table/alias/#1}}\of{#2}{%
				\csname pgfplotstable@getcol@getexisting@#4\endcsname{\pgfkeysvalueof{/pgfplots/table/alias/#1}}\of{#2}\to#3%
			}{%
				\csname pgfplotstable@getcol@noalias@#4\endcsname{#1}\of{#2}\to{#3}%
			}%
		}{%
			\csname pgfplotstable@getcol@nocol@#4\endcsname{#1}\of{#2}\to{#3}%
		}%
	}%
}
\def\pgfplotstablegetcolumnbyname@impl@createonuseforbidden#1\of#2\to#3{%
	\pgfplotstablegetcolumnbyname@impl@nocolumn@{#1}\of{#2}\to{#3}\pgfplotstablegetcolumnbyname@impl@createonuseforbiddentext@
}

\def\pgfplotstablegetcolumnbyname@impl@createonuseforbiddentext@#1{%
	\space Note that I found a 'create on use/#1' style, but unfortunately, I can't evaluate it in this context. Please use the 'read completely' key such that it is processed earlier (see the manual for details)%
}%
\def\pgfplotstablegetcolumnbyname@impl@createonuseforbiddentext@disable#1{}%

\def\pgfplotstablegetcolumnbyname@impl@nosuchalias#1\of#2\to#3{
	\pgfplotstablegetcolumnbyname@impl@nosuchalias@{#1}\of{#2}\to{#3}\pgfplotstablegetcolumnbyname@impl@createonuseforbiddentext@disable
}%
	
\def\pgfplotstablegetcolumnbyname@impl@nosuchalias@#1\of#2\to#3#4{%
	\pgfplotsthrow{no such element}{#3}{Sorry, could not retrieve aliased column '\pgfkeysvalueof{/pgfplots/table/alias/#1}' from table '\pgfplotstablenameof{#2}'. The original request was for '#1', which does not exist either.#4{#1}}\pgfeov%
}%

\def\pgfplotstablegetcolumnbyname@impl@nocolumn#1\of#2\to#3{%
	\pgfplotstablegetcolumnbyname@impl@nocolumn@{#1}\of{#2}\to{#3}\pgfplotstablegetcolumnbyname@impl@createonuseforbiddentext@disable
}%
\def\pgfplotstablegetcolumnbyname@impl@nocolumn@#1\of#2\to#3#4{%
	\pgfplotsthrow{no such element}{#3}{Sorry, could not retrieve column '#1' from table '\pgfplotstablenameof{#2}'. Please check spelling (or introduce name aliases).#4{#1}}\pgfeov%
}%


% Retrieves the column *NAME* '#1' of table #2 and writes it into
% '#3'.
%
% If there is no such column, column aliases will be checked. Finally
% if there are no aliases, the command fails with an error.
%
% The 'create on use' statements can't be used in this context.
% @see \pgfplotstablegetcolumnbyname
%
% #1: a column name (not a macro)
% #2: the table structure
% #3: a macro name which will be filled with the (probably modified)
% column name into #2.
\def\pgfplotstableresolvecolname#1\of#2\to#3{%
	\let#3=\pgfutil@empty% just for sanity checking.
	\pgfplotstable@getcol{#1}\of{#2}\to{#3}\getcolmethod{resolvename}%
}

% Invokes either \pgfplotstablegetcolumnbyindex or
% \pgfplotstablegetcolumnbyname.
%
% #1: either a column name, alias or create on use specification, or
% [index]<integer> denoting a column index.
% #2: either a loaded table or a table macro.
% #3: a macro name which will be filled with the column, in the format
% accepted of \pgfplotslist...
\long\def\pgfplotstablegetcolumn#1\of#2\to#3{%
	\begingroup
	\pgfplotstable@isloadedtable{#2}{%
		\pgfplotstablegetcolumnfromstruct{#1}\of{#2}\to{#3}%
	}{%
		\pgfplotstableread{#2}\pgfplotstable@tmptbl
		\pgfplotstablegetcolumnfromstruct{#1}\of\pgfplotstable@tmptbl\to{#3}%
	}%
	\pgfmath@smuggleone#3%
	\endgroup
}%
\def\pgfplotstablegetcolumnfromstruct#1\of#2\to#3{%
	\def\pgfplotstable@loc@TMPc{#1}%
	\pgfplotstable@is@colname{\pgfplotstable@loc@TMPc}%%
	\ifpgfplotstableread@foundcolnames
	\else
		\expandafter\pgfplotstablegetcolumnnamebyindex\pgfplotstable@loc@TMPc\of{#2}\to\pgfplotstable@loc@TMPc
	\fi
	\expandafter\pgfplotstablegetcolumnbyname\pgfplotstable@loc@TMPc\of#2\to{#3}%
}%

% Defines #3 to be the column name of the column with index '#1'.
%
% #1: a column index (starting with 0)
% #2: a loaded table structure
% #3: an output macro name.
\def\pgfplotstablegetcolumnnamebyindex#1\of#2\to#3{%
	\pgfplotslistselect#1\of#2\to#3\relax
}%

% Defines #3 to be the column index of the column with name '#1'.
%
% #1: a column name
% #2: a loaded table structure
% #3: an output macro name which will be filled with the index (or -1
% if there is no such index)
\def\pgfplotstablegetcolumnindexforname#1\of#2\to#3{%
	\def#3{-1}%
	\edef\pgfplotstablegetcolumnindexforname@@{#1}%
	\pgfplotstableforeachcolumn{#2}\as\pgfplotstablegetcolumnindexforname@{%
	\relax
		\ifx\pgfplotstablegetcolumnindexforname@\pgfplotstablegetcolumnindexforname@@
			\edef#3{\pgfplotstablecol}%
		\fi
	}%
}%
\def\pgfplotstablegetcolumnbyindex#1\of#2\to#3{%
	\pgfplotslistselect#1\of#2\to#3\relax
	\expandafter\pgfplotstablegetcolumnbyname#3\of#2\to{#3}%
}

\def\pgfplotstablecopy#1\to#2{%
	\let#2=#1%
	\pgfplotstablegetname#1\pgfplotstable@loc@TMPa
	\expandafter\let\csname\string#2@@table@name\endcsname=\pgfplotstable@loc@TMPa
	\expandafter\edef\csname\string#2@@table@scanline\endcsname{\pgfplotstablescanlinelengthof{#1}}%
	\pgfplotslistforeachungrouped#1\as\pgfplotstable@loc@TMPa{%
		\def\pgfplotstable@loc@TMPb{%
			\expandafter\let\csname\string#2@\pgfplotstable@loc@TMPa\endcsname}%
		\expandafter\pgfplotstable@loc@TMPb\csname\string#1@\pgfplotstable@loc@TMPa\endcsname
	}%
}

% Returns the file name of table '#1' into macro #2.
\def\pgfplotstablegetname#1#2{%
	\expandafter\let\expandafter#2\csname\string#1@@table@name\endcsname
}
	
% expands to the table file name of table '#1'
\def\pgfplotstablenameof#1{%
	\csname\string#1@@table@name\endcsname
}

% Returns the value of \pgfplotsscanlinelength for table '#1' into
% macro #2.
\def\pgfplotstablegetscanlinelength#1#2{%
	\expandafter\let\expandafter#2\csname\string#1@@table@scanline\endcsname
}%

% Expands to the scan line length of table '#1'.
\def\pgfplotstablescanlinelengthof#1{\csname\string#1@@table@scanline\endcsname}%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IMPLEMENTATION
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newif\ifpgfplotstableread@curline@contains@colnames
\newif\ifpgfplotstableread@foundcolnames
\newif\ifpgfplotstableread@skipline

% A method which is necessary to work with inline table data.
%
% It does nothing if format=file.
%
% It needs to be invoked BEFORE the inline table data has been
% seen the first time. "Seen" means collected as argument!
%
% The macro changes \catcodes in order to implement the 'row sep=newline',
% some special 'col sep' choices and the 'ignore chars' features.
%
% ATTENTION: this changes the processing of ALL following newline
% characters.
% @see \pgfplotstablecollectoneargwithpreparecatcodes
\def\pgfplotstablereadpreparecatcodes{%
	\ifx\pgfplotstablereadrestorecatcodes\relax
		\edef\pgfplotstablereadrestorecatcodes{%
			\noexpand\pgfplotstableuninstallignorechars
			\noexpand\catcode`\noexpand\^^M=\the\catcode`\^^M\noexpand\space
			\noexpand\catcode`\noexpand\ =\the\catcode`\ \noexpand\space
			\noexpand\catcode`\noexpand\;=\the\catcode`\;\noexpand\space
			\noexpand\catcode`\noexpand\:=\the\catcode`\:\noexpand\space
			\noexpand\catcode`\noexpand\^^I=\the\catcode`\^^I\noexpand\space
			\noexpand\let\noexpand\pgfplotstablereadrestorecatcodes=\noexpand\relax
		}%
		\ifcase\pgfplotstableread@FORMAT@CASE\relax
			% format=auto
			\pgfplotstablereadpreparecatcodes@
		\or
			% format=inline
			\pgfplotstablereadpreparecatcodes@
		\fi
	\fi
}
\let\pgfplotstablereadrestorecatcodes=\relax
\def\pgfplotstablereadpreparecatcodes@{%
	\if0\pgfplotstableread@ROWSEP@CASE\relax
		% row sep = newline
		\catcode`\^^M=12
	\fi
	\ifcase\pgfplotstableread@COLSEP@CASE\relax
		% col sep=space:
		\catcode`\ =10
	\or
		% col sep=comma:
	\or
		% col sep=semicolon:
		\catcode`\;=12
	\or
		% col sep=colon:
		\catcode`\:=12
	\or
		% col sep=brace:
	\or
		% col sep=tab:
		\catcode`\^^I=12
	\fi
	\pgfplotstableinstallignorechars
}%

% Logically, this routine does
% \pgfplotstablereadpreparecatcodes
% #1
% and that's all. However, It makes sure that any white space
% characters (especially newlines) between '#1' and the following
% argument are gobbled!
%
% To show the problem, consider
% \pgfplotstabletypeset[<options>]
% 	\loadedtable
% 
% and we want to set the catcodes *before* \loadedtable is seen.
% Well, there is a newline character after ']'! If we change the
% catcodes, this newline will be considered as character and will make
% up the first argument, the \loadedtable will be ignored.
%
% \pgfplotstablecollectoneargwithpreparecatcodes avoids this problem
% by gobbling all space (newline) characters *before* collecting the
% directly following argument token. Furthermore, it restores the
% catcodes directly after the argument has been collected.
%
% @see \pgfplotstablecollectoneargwithpreparecatcodesnorestore
\long\def\pgfplotstablecollectoneargwithpreparecatcodes#1{%
	\begingroup
	\t@pgfplotstable@a{{#1}}% this allows '#' characters in '#1'
	\def\pgfplotstablecollectoneargwithpreparecatcodes@@{%
		\pgfplotstablereadpreparecatcodes
		\expandafter\pgfplotstablecollectoneargwithpreparecatcodes@end\the\t@pgfplotstable@a%
	}%
	% equivalent to
	%\let\pgfplotstable@loc@TMPa=<next token>\pgfplotstablecollectoneargwithpreparecatcodes@@<next token>
	\futurelet\pgfplotstable@loc@TMPa\pgfplotstablecollectoneargwithpreparecatcodes@@
	% this employs a side effect: \futurelet gobbles any spaces
	% (including newlines).
}%
\long\def\pgfplotstablecollectoneargwithpreparecatcodes@end#1#2{%
	\endgroup
	#1{#2}%
}%

% An overloaded method of
% \pgfplotstablecollectoneargwithpreparecatcodes which does not
% restore the catcodes after collecting one arg.
\long\def\pgfplotstablecollectoneargwithpreparecatcodesnorestore#1{%
	\t@pgfplotstable@a{{#1}}%
	\def\pgfplotstablecollectoneargwithpreparecatcodes@@{%
		\expandafter\pgfplotstablereadpreparecatcodes\t@pgfplotstable@a
	}%
	% equivalent to
	%\let\pgfplotstable@loc@TMPa=<next token>\pgfplotstablecollectoneargwithpreparecatcodes@@<next token>
	\futurelet\pgfplotstable@loc@TMPa\pgfplotstablecollectoneargwithpreparecatcodes@@
}%

% Accept one of
% \pgfplotstableread[#1]{<file>}{<\macro>}
% \pgfplotstableread[#1]{<file>} to listener{<\macro>}
% or
% \pgfplotstableread[#1]{<file>} to {<\macro>} (DEPRECATED)
\long\def\pgfplotstableread@impl[#1]{%
	\ifpgfplots@tableread@use@begingroup
		\begingroup
		\def\endgroup@@pgfplotstableread{\endgroup}%
	\else
		\let\endgroup@@pgfplotstableread=\relax%
	\fi
	% set options here, although we can't evaluate 'every table' yet
	% (the file name is not yet known).
	% But #1 may contain input format specifiers which are important
	% for \catcodes, BEFORE we have read the second argument:
	\pgfplotstableset{#1}%
	%
	\pgfplotstablecollectoneargwithpreparecatcodes{%
		\pgfplotstableread@impl@collectfirstarg{#1}%
	}%
}%
\long\def\pgfplotstableread@impl@collectfirstarg#1#2{%
	\pgfplotsutil@ifnextchar t{%
		\pgfplotstableread@impl@@{#1}{#2}%
	}{%
		\pgfplotstableread@impl@{#1}{#2}%
	}%
}%


% I don't know why; but I started with 
% >> \pgfplotstableread[]{file} to \macro
% That ' to ' is really ugly. This here is for backwards
% compatibility:
\long\def\pgfplotstableread@impl@@#1#2to {%
	\pgfutil@ifnextchar l{%
		\pgfplotstableread@impl@@listener{#1}{#2}%
	}{%
		\pgfplotstableread@impl@{#1}{#2}%
	}%
}%
\long\def\pgfplotstableread@impl@@listener#1#2listener#3{%
	\pgfplots@tableread@to@listenertrue
	\pgfplotstableread@impl@{#1}{#2}{#3}%
	\pgfplots@tableread@to@listenerfalse
}%

\newif\ifpgfplotstableread@inline
\long\def\pgfplotstableread@checkinlineformat@CRCR#1\\#2\pgfplotstable@EOI{%
	\def\pgfplotstable@loc@TMPa{#2}%
	\ifx\pgfplotstable@loc@TMPa\pgfutil@empty
		\pgfplotstableread@inlinefalse
	\else
		\pgfplotstableread@inlinetrue
		\let\pgfplotstableread@loop@next=\pgfplotstableread@loop@next@CRCR
	\fi
}%
\long\def\pgfplotstableread@loop@next@CRCR#1\\{%
	\long\def\pgfplotstable@LINE{#1}%
	\pgfplotstableread@loop@processnextline
	\pgfplotstableread@loop@over@lines
}%
\begingroup
\catcode`\^^M=12\relax%
\long\gdef\pgfplotstableread@checkinlineformat@NL@#1^^M#2\pgfplotstable@EOI{%
	\def\pgfplotstable@loc@TMPa{#2}%
	\ifx\pgfplotstable@loc@TMPa\pgfutil@empty%
		\pgfplotstableread@inlinefalse%
	\else%
		\pgfplotstableread@inlinetrue%
		\let\pgfplotstableread@loop@next=\pgfplotstableread@loop@next@NL%
	\fi%
}%
\long\gdef\pgfplotstableread@checkinlineformat@NL#1{%
	\pgfplotstableread@checkinlineformat@NL@ #1^^M\pgfplotstable@EOI%
}%
\long\gdef\pgfplotstableread@loop@next@NL#1^^M{%
	\long\def\pgfplotstable@LINE{#1}%
	\pgfplotstableread@loop@processnextline%
	\pgfplotstableread@loop@over@lines%
}%
\endgroup

% #1: options.
% #2: the table content (file name or inline data)
% #3: the result macro.
\long\def\pgfplotstableread@impl@#1#2#3{%
	\ifcase\pgfplotstableread@FORMAT@CASE\relax
		% format=auto
		\ifcase\pgfplotstableread@ROWSEP@CASE\relax
			% row sep=newline
			\pgfplotstableread@checkinlineformat@NL{#2}%
		\or
			% row sep=crcr
			\pgfplotstableread@checkinlineformat@CRCR #2\\\pgfplotstable@EOI
		\fi
	\or
		% format=inline
		\pgfplotstableread@inlinetrue
		\ifcase\pgfplotstableread@ROWSEP@CASE\relax
			% row sep=newline
			\let\pgfplotstableread@loop@next=\pgfplotstableread@loop@next@NL
		\or
			% row sep=crcr
			\let\pgfplotstableread@loop@next=\pgfplotstableread@loop@next@CRCR
		\fi
	\or
		\pgfplotstableread@inlinefalse
	\fi
	%
	% optimizations:
	\pgfkeysgetvalue{/pgfplots/table/comment chars}\pgfplots@loc@TMPd
	\ifx\pgfplots@loc@TMPd\pgfutil@empty
		\let\pgfplotstableread@checkspecial@line@default=\relax
	\fi
	\pgfkeysgetvalue{/pgfplots/table/skip first n}\pgfplots@loc@TMPd
	\ifx\pgfplots@loc@TMPd\pgfutil@empty \let\pgfplotstableread@check@skipfirstn=\relax \fi
	\ifnum\pgfplots@loc@TMPd=0           \let\pgfplotstableread@check@skipfirstn=\relax \fi
	%
	\ifpgfplotstableread@inline
		\def\pgfplotstableread@impl@fCLOSE{}%
		\let\pgfplotstableread@loop@over@lines=\pgfplotstableread@loop@over@lines@frominline%
		\long\def\pgfplotstableread@start@loop{%
			\pgfplotstableread@loop@over@lines #2\pgfplotstable@EOI
		}%
		\def\pgfplotstableread@ready{1}%
		\def\pgfplotstableread@filename{<inline_table>}%
	\else
		\def\pgfplotstableread@ready{1}%
		\def\pgfplotstableread@filename{#2}%
		\pgfplotstableread@openfile
		\def\pgfplotstableread@impl@fCLOSE{%
			\closein\r@pgfplots@reada
		}%
		\let\pgfplotstableread@loop@over@lines=\pgfplotstableread@loop@over@lines@fromfile%
		\def\pgfplotstableread@start@loop{\pgfplotstableread@loop@over@lines}%
		\pgfplotstableinstallignorechars
	\fi
	\edef\pgfplotstableread@oldendlinechar{\the\endlinechar}%
	\endlinechar=-1 % do not append a white space after each line for file input
%\pgfplots@message{ATTEMPTING TO READ \pgfplotstableread@filename}%
	%
	\def\pgfplots@loc@TMPa{\pgfplotstableread@impl@prepare{#1}}%
	\expandafter\pgfplots@loc@TMPa\expandafter{\pgfplotstableread@filename}{#3}%
	%
	\if1\pgfplotstableread@ready
		\pgfplotstableread@start@loop
		%
		\pgfplotstableread@impl@fCLOSE%
		%
		\pgfplotstableread@finish
		%
	\fi
	\endlinechar=\pgfplotstableread@oldendlinechar
	\pgfplotsscanlinelengthcleanup
	\expandafter\pgfplotstable@copy@to@globalbuffers@simple\expandafter{\pgfplotstableread@filename}%
	\endgroup@@pgfplotstableread
	\ifpgfplots@tableread@to@listener
		% there are no data structures in this case.
		\let\pgfplotsscanlinelength=\pgfplotstable@glob@buf@scanline
	\else
		% Now, we can access the global variables!
		% copy them to #3.
		\pgfplotstable@copy@globalbuffers@to#3%
	\fi
}

{\catcode`\"=12 \gdef\pgfplots@dquote{"}}

% Opens \pgfplotstableread@filename.
\def\pgfplotstableread@openfile{%
	\def\pgfplotstable@loc@TMPa{\pgfutil@in@{ }}%
	\expandafter\pgfplotstable@loc@TMPa\expandafter{\pgfplotstableread@filename}%
	\ifpgfutil@in@
		\t@pgfplots@toka=\expandafter{\pgfplotstableread@filename}%
		\edef\pgfplotstableread@filename{\pgfplots@dquote\the\t@pgfplots@toka\pgfplots@dquote}%
	\fi
	\let\pgfplotstableread@old@crcr=\\%
	\def\\{\string\\}% just to make sure we don't try to open inline table data...
	\openin\r@pgfplots@reada=\pgfplotstableread@filename.tex
	\ifeof\r@pgfplots@reada
		\openin\r@pgfplots@reada=\pgfplotstableread@filename\relax
	\else
		\pgfplots@warning{%
			You requested to open table '\pgfplotstableread@filename', but there is also a '\pgfplotstableread@filename.tex'. 
			TeX will automatically append the suffix '.tex', so I will now open '\pgfplotstableread@filename.tex'.
			Please make sure you don't accidentally load TeX files - this may produce unrecoverable errors.}%
		\closein\r@pgfplots@reada
		\openin\r@pgfplots@reada=\pgfplotstableread@filename\relax
	\fi
	%
	\ifeof\r@pgfplots@reada
		\pgfplotsthrow{no such table file}{\pgfplots@loc@TMPa}{\pgfplotstableread@filename}{Could not read table file '\pgfplotstableread@filename'. In case you intended to provide inline data: maybe TeX screwed up your end-of-lines? Try `row sep=crcr' and terminate your lines with `\string\\' (refer to the pgfplotstable manual for details)}\pgfeov%
		\global\let\pgfplotstable@colnames@glob=\pgfplots@loc@TMPa
		\def\pgfplotstableread@ready{0}%
	\fi
	\pgfplots@logfileopen{\pgfplotstableread@filename}%
	\let\\=\pgfplotstableread@old@crcr
}

\def\pgfplotstableinstallignorechars{%
	\ifx\pgfplotstableuninstallignorechars\pgfutil@empty
		\pgfkeysgetvalue{/pgfplots/table/ignore chars}\pgfplotstable@loc@TMPa
		\ifx\pgfplotstable@loc@TMPa\pgfutil@empty
		\else
			\pgfplotstableinstallignorechars@\pgfplotstable@loc@TMPa{9}%
		\fi
		\pgfkeysgetvalue{/pgfplots/table/white space chars}\pgfplotstable@loc@TMPa
		\ifx\pgfplotstable@loc@TMPa\pgfutil@empty
		\else
			\pgfplotstableinstallignorechars@\pgfplotstable@loc@TMPa{10}%
		\fi
		\ifx\pgfplotstableuninstallignorechars\pgfutil@empty
		\else
			\expandafter\def\expandafter\pgfplotstableuninstallignorechars\expandafter{%
				\pgfplotstableuninstallignorechars
				\let\pgfplotstableuninstallignorechars=\pgfutil@empty
			}%
		\fi
	\fi
}%		
\let\pgfplotstableuninstallignorechars\pgfutil@empty%
% #1 macro containing the characters as comma-separated list
% #2 the catcode to assign
\def\pgfplotstableinstallignorechars@#1#2{%
	\expandafter\pgfplotsutilforeachcommasep\expandafter{#1}\as\pgfplotstable@loc@TMPa{%
		\t@pgfplots@toka=\expandafter{\pgfplotstableuninstallignorechars}%
		\edef\pgfplotstableuninstallignorechars{%
			\the\t@pgfplots@toka
			\noexpand\catcode`\expandafter\noexpand\pgfplotstable@loc@TMPa=\expandafter\the\expandafter\catcode\expandafter`\pgfplotstable@loc@TMPa\noexpand\space
		}%
		\expandafter\catcode\expandafter`\pgfplotstable@loc@TMPa=#2\relax
	}%
}%

% #1: any options to set (respect \ifpgfplots@table@options@areset )
% #2: the file name (if any)
% #3: the output macro (or listener)
\def\pgfplotstableread@impl@prepare#1#2#3{%
	\ifpgfplots@table@options@areset
	\else
		\pgfplotstableset@every@table{#2}{#1}%
	\fi
	%
	\def\pgfplotstablename{\pgfplotstable@colnames@glob}% provide the name of the actual table struct (during \pgfplotstableread, only partial functionality is available!)
	%
	% local counter definitions:
	\ifpgfplots@tableread@use@begingroup
		\let\pgfplotstableread@lineno=\c@pgf@counta
		\let\pgfplotstableread@numcols=\c@pgf@countb
		\let\pgfplotstableread@curcol=\c@pgf@countc
		\let\pgfplotstableread@usablelineno=\c@pgf@countd
		\def\thepgfplotstableread@lineno{\the\pgfplotstableread@lineno}%
		\def\thepgfplotstableread@usablelineno{\the\pgfplotstableread@usablelineno}%
		\def\thepgfplotstableread@curcol{\the\pgfplotstableread@curcol}%
		\def\thepgfplotstableread@numcols{\the\pgfplotstableread@numcols}%
		\def\pgfplotstableread@countreset##1{##1=0 }%
		\def\pgfplotstableread@countset##1##2{##1=##2\relax}%
		\def\pgfplotstableread@countadvance##1{\advance##1 by1 }%
	\else
		% don't re-use integers! We have no protecting scopes!
		\def\thepgfplotstableread@lineno{\pgfplotstableread@lineno}%
		\def\thepgfplotstableread@usablelineno{\pgfplotstableread@usablelineno}%
		\def\thepgfplotstableread@curcol{\pgfplotstableread@curcol}%
		\def\thepgfplotstableread@numcols{\pgfplotstableread@numcols}%
		\def\pgfplotstableread@countreset##1{\def##1{0}}%
		\def\pgfplotstableread@countset##1##2{\def##1{##2}}%
		\def\pgfplotstableread@countadvance##1{\pgfplotsutil@advancestringcounter{##1}}%
	\fi
	\pgfplotstableread@countreset\pgfplotstableread@lineno
	\pgfplotstableread@countreset\pgfplotstableread@usablelineno
	\pgfplotstableread@countreset\pgfplotstableread@numcols
	\pgfplotstableread@countreset\pgfplotstableread@curcol
	%
	\pgfplotstableread@impl@prepare@DO
	\def\pgfplotstableread@isgnuplotformat{0}%
	\global\pgfplotslistnewempty\pgfplotstable@colnames@glob
	\pgfplotsscanlinelengthinitzero
	\ifpgfplots@tableread@to@listener
		\def\pgfplotstablerow{\thepgfplotstableread@usablelineno}%
		\def\pgfplotstablelineno{\thepgfplotstableread@lineno}%
		\let\pgfplotstable@listener=#3%
		\let\pgfplotstableread@impl@nextrow@NEXT=\pgfplotstableread@impl@nextrow@NEXT@listener
		\let\pgfplotstablereadgetcolindex=\pgfplotstablereadgetcolindex@
		\let\pgfplotstablereadgetcolname=\pgfplotstablereadgetcolname@
		\let\pgfplotstablereadgetptrtocolname=\pgfplotstablereadgetptrtocolname@
		\let\pgfplotstablereadgetptrtocolindex=\pgfplotstablereadgetptrtocolindex@
		\let\pgfplotstablereadevalptr=\pgfplotstablereadevalptr@
		\let\pgfplotstablereadvalueofptr=\pgfplotstablereadvalueofptr@
		\let\pgfplotstableforeachcolumn=\pgfplotstableforeachcolumn@listener
		\let\pgfplotstablereadvalueofcolname=\pgfplotstablereadvalueofcolname@
		\let\pgfplotstablereadvalueofcolindex=\pgfplotstablereadvalueofcolindex@
		\let\getthisrow=\pgfplotstablereadgetcolname
		\let\thisrow=\pgfplotstablereadvalueofcolname
		\let\thisrowno=\pgfplotstablereadvalueofcolindex
		\let\getthisrowno=\pgfplotstablereadgetcolindex
	\fi
}%

% Copies the table column list and the column vectors of #1 to global buffers. 
% @see \pgfplotstable@copy@globalbuffers@to
%
% Use these two methods to avoid scoping problems.
%
% #1: the <\macro> name of the table which is to be copied to global buffers.
% #2: the table file name.
\def\pgfplotstable@copy@to@globalbuffers#1#2{%
	\global\let\pgfplotstable@colnames@glob=#1\relax
	\c@pgfplotstable@counta=0\relax%
	\pgfplotslistforeachungrouped\pgfplotstable@colnames@glob\as\pgfplotstable@loc@TMPa{%
		\def\pgfplotstable@loc@TMPb{%
			\expandafter\global\expandafter\let\csname pgfp@numtable@glob@col@\the\c@pgfplotstable@counta\endcsname%
		}%
		\expandafter\pgfplotstable@loc@TMPb\csname\string#1@\pgfplotstable@loc@TMPa\endcsname
		\advance\c@pgfplotstable@counta by1\relax
	}%
	\pgfplotstable@copy@to@globalbuffers@simple{#2}%
}%
% A variant of \pgfplotstable@copy@to@globalbuffers which copies only
% the member variables of a loaded table (the name and scanline length) to
% global buffers.
%
% #1: the table's file name.
%
% @PRECONDITION: any other variables and cell data of the table are already stored
% in global buffers.
\def\pgfplotstable@copy@to@globalbuffers@simple#1{%
	\gdef\pgfplotstable@glob@buf@name{#1}%
	\global\let\pgfplotstable@glob@buf@scanline=\pgfplotsscanlinelength
}%

% copies the global column list and the global column vectors to #1
% (NOT the table file name).
% @see \pgfplotstable@copy@to@globalbuffers
%
% @PRECONDITION the global buffers contain all members of a table.
% 
% @POSTCONDITION The table '#1' is be initialised to these members.
% 		Furthermore, \pgfplotsscanlinelength is set.
\def\pgfplotstable@copy@globalbuffers@to#1{%
	\let#1=\pgfplotstable@colnames@glob
	\c@pgfplotstable@counta=0\relax%
	\pgfplotslistforeachungrouped\pgfplotstable@colnames@glob\as\pgfplotstable@loc@TMPa{%
		\def\pgfplotstable@loc@TMPb{%
			\expandafter\let\csname\string#1@\pgfplotstable@loc@TMPa\endcsname}%
		\expandafter\pgfplotstable@loc@TMPb\csname pgfp@numtable@glob@col@\the\c@pgfplotstable@counta\endcsname
%\message{Column '\pgfplotstable@loc@TMPa' has entries: \expandafter\meaning\csname pgfp@numtable@glob@col@\the\c@pgfplotstable@counta\endcsname}%
		\expandafter\global\expandafter\let\csname pgfp@numtable@glob@col@\the\c@pgfplotstable@counta\endcsname=\pgfutil@empty
		\advance\c@pgfplotstable@counta by1\relax
	}%
	\global\let\pgfplotstable@colnames@glob=\pgfutil@empty
	\expandafter\let\csname\string#1@@table@scanline\endcsname=\pgfplotstable@glob@buf@scanline
	\expandafter\let\csname\string#1@@table@name\endcsname=\pgfplotstable@glob@buf@name
	\let\pgfplotsscanlinelength=\pgfplotstable@glob@buf@scanline
}%

\def\pgfplotstableread@finish{%
	\pgfplotsscanlinecomplete
	\ifpgfplots@tableread@to@listener
	\else
		\ifpgfplotstableread@foundcolnames
		\else
			\pgfplotstableread@create@column@names@with@numbers
		\fi
		\pgfplotstableread@countreset\pgfplotstableread@curcol%
		\pgfutil@loop
		\ifnum\pgfplotstableread@curcol<\pgfplotstableread@numcols\relax
			\expandafter\pgfplotsapplistXflushbuffers\csname pgfp@numtable@glob@col@\thepgfplotstableread@curcol\endcsname
			\pgfplotstableread@countadvance\pgfplotstableread@curcol
		\pgfutil@repeat
	\fi
}

\def\pgfplotstableread@loop@over@lines@fromfile{%
	\ifeof\r@pgfplots@reada
%\pgfplots@message{EOF}%
	\else
		\read\r@pgfplots@reada to\pgfplotstable@LINE
		\ifeof\r@pgfplots@reada
		\else
			\pgfplotstableread@loop@processnextline
		\fi
		\expandafter\pgfplotstableread@loop@over@lines
	\fi
}%
\def\pgfplotstableread@loop@over@lines@frominline{%
	\pgfutil@ifnextchar\pgfplotstable@EOI{%
		\pgfutil@gobble
	}{%	
		\pgfplotstableread@loop@next
	}%
}%

\def\pgfplotstableread@check@skipfirstn{%
	\ifnum\pgfplotstableread@lineno<\pgfkeysvalueof{/pgfplots/table/skip first n} %
		\pgfplotstableread@skiplinetrue
	\fi
}%

% PRECONDITION: 
% 	\pgfplotstable@LINE contains the current input line.
\def\pgfplotstableread@loop@processnextline{%
	\expandafter\pgfplotstableread@checkspecial@line\pgfplotstable@LINE\pgfplotstable@EOI
	\pgfplotstableread@check@skipfirstn
	\ifpgfplotstableread@skipline
		\def\pgfplotstableread@gnuplotcheck{####x y type}%
		\ifx\pgfplotstableread@gnuplotcheck\pgfplotstable@LINE
			\def\pgfplotstableread@isgnuplotformat{1}%
		\fi
		\def\pgfplotstableread@gnuplotcheck{####x y z type}%
		\ifx\pgfplotstableread@gnuplotcheck\pgfplotstable@LINE
			\def\pgfplotstableread@isgnuplotformat{1}%
		\fi
	\else
		%--------------------------------------------------
		% \ifnum\pgfplotstableread@lineno=0
		% 	\let\pgfplotstable@firstline=\pgfplotstable@LINE
		% \fi
		%-------------------------------------------------- 
%\pgfplots@message{READING LINE \thepgfplotstableread@lineno: '\meaning\pgfplotstable@LINE'.}%
		\pgfplotstableread@curline@contains@colnamesfalse
		\ifnum\pgfplotstableread@numcols=0\relax
			% STEP 0: initialise
			% 	- count columns
			% 	- find header data
			\pgfplotstableread@countreset\pgfplotstableread@curcol
			\ifpgfplotstable@firstline@is@header
				\pgfplotstableread@curline@contains@colnamestrue
			\fi
			\pgfplotstableread@impl@DO\pgfplotstableread@impl@countcols@and@identifynames@NEXT\pgfplotstable@LINE
			\pgfplotstableread@countset\pgfplotstableread@numcols{\pgfplotstableread@curcol}%
			\edef\pgfplotstablecols{\thepgfplotstableread@numcols}%
			\pgfplotstableread@countreset\pgfplotstableread@curcol
			% Create empty column lists:
			\pgfplotstableread@create@column@lists
			%
			\ifnum\pgfplotstableread@usablelineno=0\relax
			\if1\pgfplotstableread@isgnuplotformat%
				% The file started with
				% #...
				% #x y type
				% X Y i
				% -> thats a gnuplot file!
				\pgfplotstableread@curline@contains@colnamesfalse
			\fi
			\fi
			% Now, read the first line.
			% It contains either
			% - column names,
			% - numerical data,
			% - nothing (comments).
			\ifpgfplotstableread@curline@contains@colnames
				\pgfplotstableread@foundcolnamestrue
				\pgfplotstableread@countreset\pgfplotstableread@curcol
				\pgfplotstableread@impl@DO\pgfplotstableread@impl@collectcolnames@NEXT\pgfplotstable@LINE
			\else
				\pgfplotsscanlinelengthincrease
				\pgfplotstableread@foundcolnamesfalse
				\pgfplotstableread@countreset\pgfplotstableread@curcol
				% Leave column name lists empty...
				\pgfplotstableread@impl@DO\pgfplotstableread@impl@nextrow@NEXT\pgfplotstable@LINE
			\fi
%\pgfplots@message{After reading first row: found '\thepgfplotstableread@numcols' columns; column name list='\meaning\pgfplotstable@colnames@glob'}%
		\else
			\pgfplotsscanlinelengthincrease
			\pgfplotstableread@countreset\pgfplotstableread@curcol
			\pgfplotstableread@impl@DO\pgfplotstableread@impl@nextrow@NEXT\pgfplotstable@LINE
		\fi
		\ifnum\pgfplotstableread@curcol=\pgfplotstableread@numcols\relax
		\else
			\pgfplotsthrow{table columns unbalanced}{input table '\pgfplotstableread@filename' has an unbalanced number  of columns in row '\thepgfplotstableread@lineno' (expected '\thepgfplotstableread@numcols' cols; got '\thepgfplotstableread@curcol'). Maybe the input table is corrupted? If you need unbalanced data, consider using 'nan' in empty cells (perhaps combined with 'unbounded coords=jump')}\pgfeov%
		\fi
		\ifpgfplots@tableread@to@listener
			\ifpgfplotstableread@curline@contains@colnames
			\else
				% report row!
				\pgfplotstable@listener
			\fi
		\fi
		\pgfplotstableread@countadvance\pgfplotstableread@usablelineno
	\fi
	\pgfplotstableread@countadvance\pgfplotstableread@lineno
}%

% WARNING: this routine is also used in pgfplots.code.tex ...
\def\pgfplotstableread@checkspecial@line{%
	\futurelet\pgfplotstableread@tmp\pgfplotstableread@checkspecial@line@
}%
\def\pgfplotstableread@checkspecial@line@{%
	\pgfplotstableread@skiplinefalse
	\let\pgfplotstableread@checkspecial@line@@\pgfplotstableread@impl@gobble%
	%
	\let\pgfplotstableread@tmpb=##%
	\ifx\pgfplotstableread@tmp\pgfplotstableread@tmpb
		\pgfplotstableread@skiplinetrue
	\else
		\let\pgfplotstableread@tmpb=$%
		\ifx\pgfplotstableread@tmp\pgfplotstableread@tmpb
			\let\pgfplotstableread@checkspecial@line@@=\pgfplotstableread@process@flags@line
		\else
			\let\pgfplotstableread@tmpb=\pgfplotstable@EOI%
			\ifx\pgfplotstableread@tmp\pgfplotstableread@tmpb
				\pgfplotstableread@skiplinetrue
				\pgfplotsscanlinecomplete% the line is empty; same as \par!
			\else
				\let\pgfplotstableread@tmpb=\par%
				\ifx\pgfplotstableread@tmp\pgfplotstableread@tmpb
					\pgfplotstableread@skiplinetrue
					\pgfplotsscanlinecomplete% the line is empty;
				\else
					\pgfplotstableread@checkspecial@line@default%
				\fi
			\fi
		\fi
	\fi
	\pgfplotstableread@checkspecial@line@@
}%
\def\pgfplotstableread@checkspecial@line@default{%
	% this routine can be optimized away
	\pgfkeysgetvalue{/pgfplots/table/comment chars}\pgfplots@loc@TMPd
	\ifx\pgfplots@loc@TMPd\pgfutil@empty
	\else
		\expandafter\pgfplotsutilforeachcommasep\expandafter{\pgfplots@loc@TMPd}\as\pgfplots@loc@TMPd{%
			\expandafter\let\expandafter\pgfplotstableread@tmpb\pgfplots@loc@TMPd
			\ifx\pgfplotstableread@tmp\pgfplotstableread@tmpb
				\pgfplotstableread@skiplinetrue
			\fi
		}%
	\fi
}%

%--------------------------------------------------
% \def\pgfplotstableread@checkspecial@line{%
% 	\pgfutil@ifnextchar##{%
% 		\pgfplotstableread@skiplinetrue
% 		\pgfplotstableread@impl@gobble
% 	}{%
% 		\pgfutil@ifnextchar${%
% 			\pgfplotstableread@process@flags@line
% 		}{%
% 			\pgfutil@ifnextchar\pgfplotstable@EOI{%
% 				\pgfplotstableread@skiplinetrue
% 				\pgfplotsscanlinecomplete% the line is empty; same as \par!
% 				\pgfplotstableread@impl@gobble
% 			}{%
% 				\pgfutil@ifnextchar\par{%
% 					\pgfplotstableread@skiplinetrue
% 					\pgfplotsscanlinecomplete
% 					\pgfplotstableread@impl@gobble
% 				}{%
% 					\pgfplotstableread@skiplinefalse
% 					\pgfplotstableread@impl@gobble
% 				}%
% 			}%
% 		}%
% 	}%
% }
%-------------------------------------------------- 

\long\def\pgfplotstableread@process@flags@line$flags {%
%\pgfplots@message{Ignoring flags line ...}%
	\pgfplotstableread@skiplinetrue
	\pgfplotstableread@impl@gobble
}

\def\pgfplotstableread@create@column@lists{%
	\pgfutil@loop
	\ifnum\pgfplotstableread@curcol<\pgfplotstableread@numcols\relax
		\def\pgfplots@loc@TMPa{\pgfplotsapplistXnewempty[to global]}%
		\expandafter\pgfplots@loc@TMPa\csname pgfp@numtable@glob@col@\thepgfplotstableread@curcol\endcsname
		\pgfplotstableread@countadvance\pgfplotstableread@curcol
	\pgfutil@repeat
}

\def\pgfplotstableread@create@column@names@with@numbers{%
	\pgfplotstableread@countreset\pgfplotstableread@curcol
	\pgfutil@loop
	\ifnum\pgfplotstableread@curcol<\pgfplotstableread@numcols\relax
		\edef\pgfplotstable@loc@TMPb{\thepgfplotstableread@curcol}%
		\expandafter\pgfplotslistpushbackglobal\pgfplotstable@loc@TMPb\to\pgfplotstable@colnames@glob
		\pgfplotstableread@countadvance\pgfplotstableread@curcol
	\pgfutil@repeat
}

\long\def\pgfplotstableread@impl@gobble#1\pgfplotstable@EOI{}%

\def\pgfplotstable@EOI{\pgfplotstable@EOI}%

% A loop command which processes every single entry in a raw data row #2 
% and invokes the macro #1{<arg>}  for each found column entry.
%
% Columns are separated by the /pgfplots/table/col sep character.
%
% #1: a command which takes precisely one argument. It will be called
% for each found column entry
%
% #2: a macro containing a raw data line with <col sep> separated
% entries.
\long\def\pgfplotstableread@impl@DO#1#2{%
	\ifpgfplotstable@trimcells
		\long\def\pgfplotstableread@impl@ITERATE@NEXT@##1{%
			\pgfkeys@spdef\pgfplotstableread@impl@ITERATE@NEXT@@@{##1}%
			\expandafter#1\expandafter{\pgfplotstableread@impl@ITERATE@NEXT@@@}%
		}%
	\else
		\let\pgfplotstableread@impl@ITERATE@NEXT@=#1\relax
	\fi
	\expandafter\pgfplotstableread@impl@DO@\expandafter{#2}%
}
{%
	\catcode`\ =10
	\catcode`\;=12
	\catcode`\:=12
	\gdef\pgfplotstableread@impl@prepare@DO{%
		\ifcase\pgfplotstableread@COLSEP@CASE\relax
			% col sep=space:
			\catcode`\ =10
			\long\def\pgfplotstableread@impl@DO@##1{\pgfplotstableread@impl@ITERATE##1 \pgfplotstable@EOI}%
		\or
			% col sep=comma:
			\let\pgfplotstableread@impl@ITERATE@NEXT=\pgfplotstableread@impl@ITERATE@NEXT@COMMA
			\long\def\pgfplotstableread@impl@DO@##1{\pgfplotstableread@impl@ITERATE##1,\pgfplotstable@EOI}%
		\or
			% col sep=semicolon:
			\catcode`\;=12
			\let\pgfplotstableread@impl@ITERATE@NEXT=\pgfplotstableread@impl@ITERATE@NEXT@SEMICOLON
			\long\def\pgfplotstableread@impl@DO@##1{\pgfplotstableread@impl@ITERATE##1;\pgfplotstable@EOI}%
		\or
			% col sep=colon:
			\catcode`\:=12
			\let\pgfplotstableread@impl@ITERATE@NEXT=\pgfplotstableread@impl@ITERATE@NEXT@COLON
			\long\def\pgfplotstableread@impl@DO@##1{\pgfplotstableread@impl@ITERATE##1:\pgfplotstable@EOI}%
		\or
			% col sep=brace:
			% allow multi line cells:
			\endlinechar=\pgfplotstableread@oldendlinechar\relax
			\let\pgfplotstableread@impl@ITERATE@NEXT=\pgfplotstableread@impl@ITERATE@NEXT@BRACE
			\long\def\pgfplotstableread@impl@DO@##1{\pgfplotstableread@impl@ITERATE##1\pgfplotstable@EOI}%
		\or
			% col sep=tab:
			\catcode`\^^I=12
			\let\pgfplotstableread@impl@ITERATE@NEXT=\pgfplotstableread@impl@ITERATE@NEXT@TAB
			\long\edef\pgfplotstableread@impl@DO@##1{\noexpand\pgfplotstableread@impl@ITERATE##1\pgfplotstableread@tab\noexpand\pgfplotstable@EOI}%
		\or
			% col sep=&:
			\let\pgfplotstableread@impl@ITERATE@NEXT=\pgfplotstableread@impl@ITERATE@NEXT@AMPERSAND
			\long\def\pgfplotstableread@impl@DO@##1{\pgfplotstableread@impl@ITERATE##1&\pgfplotstable@EOI}%
		\fi
	}%
}%
\long\def\pgfplotstableread@impl@ITERATE{%
	\pgfutil@ifnextchar\pgfplotstable@EOI{%
		\pgfplotstableread@impl@gobble
	}{%
		\pgfplotstableread@impl@ITERATE@NEXT
	}%
}%
\long\def\pgfplotstableread@impl@ITERATE@NEXT#1 {%
	\pgfplotstableread@impl@ITERATE@NEXT@{#1}%
	\pgfplotstableread@impl@ITERATE
}%
\long\def\pgfplotstableread@impl@ITERATE@NEXT@COMMA#1,{%
	\pgfplotstableread@impl@ITERATE@NEXT@{#1}%
	\pgfplotstableread@impl@ITERATE
}%
\long\def\pgfplotstableread@impl@ITERATE@NEXT@SEMICOLON#1;{%
	\pgfplotstableread@impl@ITERATE@NEXT@{#1}%
	\pgfplotstableread@impl@ITERATE
}%
\long\def\pgfplotstableread@impl@ITERATE@NEXT@COLON#1:{%
	\pgfplotstableread@impl@ITERATE@NEXT@{#1}%
	\pgfplotstableread@impl@ITERATE
}%
\long\def\pgfplotstableread@impl@ITERATE@NEXT@BRACE#1{%
	\pgfplotstableread@impl@ITERATE@NEXT@{#1}%
	\pgfplotstableread@impl@ITERATE
}%
\long\def\pgfplotstableread@impl@ITERATE@NEXT@AMPERSAND#1&{%
	\pgfplotstableread@impl@ITERATE@NEXT@{#1}%
	\pgfplotstableread@impl@ITERATE
}%
\begingroup
\catcode`\^^I=12
\gdef\pgfplotstableread@tab{^^I}%
\long\gdef\pgfplotstableread@impl@ITERATE@NEXT@TAB#1^^I{% the following white spaces are SPACES, not tabs:
    \pgfplotstableread@impl@ITERATE@NEXT@{#1}%
    \pgfplotstableread@impl@ITERATE
}%
\endgroup
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% these values are only usable for a read-listener, that means:
% when using
%
% \pgfplotstableread{<file>} to listener<\macro>
%
% -> <\macro> can than use the methods
%
% \pgfplotstablereadgetcolindex{<index>}{<\content>}
% performs \let\content=<content of column no <index> >
\def\pgfplotstablereadgetcolindex@#1#2{%
	\pgfutil@ifundefined{pgfplotstblread@colcontent@no#1}{%
		\pgfplotsthrow{no such element}{#2}{Sorry, the requested column number '#1' in table '\pgfplotstableread@filename' does not exist!? Please verify you used the correct index 0 <= i < N.}\pgfeov%
	}{%
		\expandafter\let\expandafter#2\csname pgfplotstblread@colcontent@no#1\endcsname
	}%
}%

\pgfkeysdef{/pgfplots/table/@undefined column text}{#1__column_not_found.}%
\def\pgfplotstable@undefinedtext#1{\pgfkeysvalueof{/pgfplots/table/@undefined column text/.@cmd}#1\pgfeov}%

% As \pgfplotstablereadgetcolindex, but
% \pgfplotstablereadvalueofcolindex{<index>}
% directly expands to the value stored in the desired column.
%
% Example:
% \pgfplotstablereadvalueofcolindex{3}  -> expands to '42' if '42' is
% written in column no 3.
%
% Column indexing starts at 0.
%
% @ATTENTION: since such a command may occur within an \edef or an
% \csname, it can't perform sanity checking. Proving an invalid index
% expands to \pgfkeysvalueof{/pgfplots/table/@undefined column text}.
\def\pgfplotstablereadvalueofcolindex@#1{%
	\pgfutil@ifundefined{pgfplotstblread@colcontent@no#1}{%
		\pgfplotstable@undefinedtext{colindex#1}%
	}{%
		\csname pgfplotstblread@colcontent@no#1\endcsname
	}%
}

% \pgfplotstablereadgetcolname{<name>}{<\content>}
% performs \let\content=<content of column named <name> >
\def\pgfplotstablereadgetcolname@#1#2{%
	\pgfplotstablereadgetptrtocolname{#1}{\pgfplots@loc@TMPa}%
	\pgfplotstablereadevalptr\pgfplots@loc@TMPa{#2}%
}%

% This here is the implementation of \pgfplotstablereadvalueofcolname
% (and \thisrow{<colname>}) for use inside of the 'read to listener'
% framework.
%
% Like \pgfplotstablereadgetcolname, but this one expands directly to
% the value of the desired column.
%
% #1: a column name or a column alias.
%
% @ATTENTION: since such a command may occur within an \edef or an
% \csname, it can't perform sanity checking. Proving an invalid index
% expands to \pgfkeysvalueof{/pgfplots/table/@undefined column text}.
\def\pgfplotstablereadvalueofcolname@#1{%
	\pgfplotstable@thisrow@impl{#1}{pgfplotstblread@colindex@for@name}{\pgfplotstable@thisrow@impl@read}%
}%
\def\pgfplotstable@thisrow@impl@read#1{\csname pgfplotstblread@colcontent@no#1\endcsname}%

% This implements \thisrow in different contexts.
%
% Usage:
% \def\thisrow#1{\pgfplotstable@thisrow@impl{#1}{macroprefix@}{\pgfplotstable@thisrow@impl@}}
%
% Then, \thisrow{existingcol}
% will expand to 
% -> \pgfplotstable@thisrow@impl@{\csname macroprefix@existingcol\endcsname}
% -> \csname macroprefix@existingcol\endcsname
%
% Furthermore, if '#1' is no existing col and there exists /pgfplots/table/alias/#1,
% \thisrow{aliased}
% will expand to
% -> \pgfplotstable@thisrow@impl@{\csname macroprefix@\pgfkeysvalueof{/pgfplots/table/alias/aliased}\endcsname}
% -> \csname macroprefix@\pgfkeysvalueof{/pgfplots/table/alias/aliased}\endcsname
%
% #1: the argument for \thisrow{#1}
% #2: a macro prefix such that \csname #2<colname>\endcsname contains
% the value of the current row for (physical) column <colname>
% #3: the name of a one-argument-macro which will get \csname #2<colname>\endcsname
% as argument. This is the last step of \thisrow. It allows indirect
% access by translating colnames to col indices in '\pgfplotstableread to listener'
\def\pgfplotstable@thisrow@impl#1#2#3{%
	\pgfutil@ifundefined{#2#1}%
	{%
		% WARNING : this code has been REPLICATED in
		% *** \pgfplotstablereadgetptrtocolname ***
		% *** \pgfplotstablegetcolumnbyname ***
		% *** \pgfplotstableresolvecolname ***
		% *** \pgfplotstablereadvalueofcolname ***
		\pgfkeysifdefined{/pgfplots/table/alias/#1}{%
			\pgfutil@ifundefined{#2\pgfkeysvalueof{/pgfplots/table/alias/#1}}{%
				\pgfplotstable@undefinedtext{\pgfkeysvalueof{/pgfplots/table/alias/#1}}%
			}{%
				#3{\csname #2\pgfkeysvalueof{/pgfplots/table/alias/#1}\endcsname}%
			}%
		}{%
			\pgfplotstable@undefinedtext{#1}%
		}%
	}%
	{%
		#3{\csname #2#1\endcsname}%
	}%
}%
\def\pgfplotstable@thisrow@impl@#1{#1}%

% \pgfplotstablereadgetptrtocolname{<name>}{\ptr}
% Creates some sort of "pointer" to the column named <name>. This
% pointer can than be used every time a new line has been reported to
% the listener. It works like this:
%
% \let\ptr=\pgfutil@empty
% \def\macro{%
% 	\ifx\ptr\empty
% 		\pgfplotstablereadgetptrtocolname{<my col>}{\ptr}%
% 	\fi
% 	\pgfplotstablereadevalptr{\ptr}{\content}%
% 	-> do something with \content!
% }
% 	
% \pgfplotstableread{<file>} to listener<\macro>
%
% -> will evaluate \macro foreach row.
%
% The advantage of such a prepared pointer over \thisrow{#1} or
% \getthisrow{#1} is simply efficiency and sanity checking: the checks
% are done at the time of pointer creation, dereferencing the pointer
% is fast.
\def\pgfplotstablereadgetptrtocolname@#1#2{%
	\def#2{0}%
	\pgfplotstable@getcol{#1}\of{\pgfplotstableread@filename}\to{#2}\getcolmethod{getptr}%
}%

% As \pgfplotstablereadgetptrtocolname, but this here accesses columns
% by index.
\def\pgfplotstablereadgetptrtocolindex@#1#2{\edef#2{#1}}%

% \pgfplotstablereadevalptr{<\ptr>}{<\content}
% writes the current value of <\ptr> to <\content>. The pointer <\ptr>
% must be initialised with \pgfplotstablereadgetptrtocolname
\let\pgfplotstablereadevalptr@=\pgfplotstablereadgetcolindex@

% \pgfplotstablereadvalueofptr{<\ptr>} -> expands to the pointers value.
%
% The pointer \ptr must be initialised with
% \pgfplotstablereadgetptrtocolname.
\let\pgfplotstablereadvalueofptr@=\pgfplotstablereadvalueofcolindex@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\long\def\pgfplotstableread@impl@nextrow@NEXT@listener#1{%
	\expandafter\def\csname pgfplotstblread@colcontent@no\thepgfplotstableread@curcol\endcsname{#1}%
	\pgfplotstableread@countadvance\pgfplotstableread@curcol
}

\long\def\pgfplotstableread@impl@nextrow@NEXT#1{%
%\pgfplots@message{Inserting '#1' at (\thepgfplotstableread@lineno, \thepgfplotstableread@curcol).}%
	\ifnum\pgfplotstableread@curcol<\pgfplotstableread@numcols\relax
		\pgfplotslist@assembleentry{#1}\into\t@pgfplots@tokc
		\def\pgfplotstableread@TMP{\expandafter\pgfplotsapplistXpushback\expandafter{\the\t@pgfplots@tokc}\to}%
		\expandafter\pgfplotstableread@TMP\csname pgfp@numtable@glob@col@\thepgfplotstableread@curcol\endcsname
		\pgfplotstableread@countadvance\pgfplotstableread@curcol
	\else
		\begingroup
		\t@pgfplots@tokc={#1}%
		\pgfplotsthrow{table columns unbalanced}{Table '\pgfplotstableread@filename' appears to have too many columns in line \thepgfplotstableread@lineno: Ignoring '\the\t@pgfplots@tokc'. PGFPlots found that the number of columns is larger than the previously determined number of columns. Please verify that every cell entry is separated correctly (use braces {<cell entry>} if necessary. Also verify that column names are plain ASCII.). This error is not critical}\pgfeov%
		\endgroup
	\fi
}



\long\def\pgfplotstableread@impl@collectcolnames@NEXT#1{%
	\edef\pgfplotstable@loc@TMPa{#1}%
	\ifx\pgfplotstable@loc@TMPa\pgfutil@empty
		\edef\pgfplotstable@loc@TMPa{\thepgfplotstableread@curcol}%
		\pgfplotswarning{empty column name}{\pgfplotstableread@filename}{\pgfplotstable@loc@TMPa'}\pgfeov%
	\fi
	\expandafter\pgfplotstableread@impl@collectcolnames@NEXT@\expandafter{\pgfplotstable@loc@TMPa}%
}
\long\def\pgfplotstableread@impl@collectcolnames@NEXT@#1{%
%\pgfplots@message{Got column name no \thepgfplotstableread@curcol\ as '#1'}%
	\pgfutil@ifundefined{pgfplotstableread@impl@COLNAME@#1}{%
		\def\pgfplotstable@loc@TMPa{#1}%
	}{% generate unique column names warning:
		\pgfplots@warning{Table '\pgfplotstableread@filename' has non-unique column name '#1'. Only the first occurence can be accessed via column names.}%
		\edef\pgfplotstable@loc@TMPa{#1--index\thepgfplotstableread@curcol}%
	}%
	\expandafter\def\csname pgfplotstableread@impl@COLNAME@#1\endcsname{foo}% remember this name.
	\expandafter\pgfplotslistpushbackglobal\expandafter{\pgfplotstable@loc@TMPa}\to\pgfplotstable@colnames@glob
	\ifpgfplots@tableread@to@listener
		% create an associative container colindex -> colname
		% for use in a listener.
		\expandafter\edef\csname pgfplotstblread@colindex@for@name#1\endcsname{\thepgfplotstableread@curcol}%
	\fi
	\pgfplotstableread@countadvance\pgfplotstableread@curcol
}




\long\def\pgfplotstableread@impl@countcols@and@identifynames@NEXT#1{%
	\pgfplotstableread@countadvance\pgfplotstableread@curcol
	\ifpgfplotstable@search@header
		\ifpgfplotstableread@curline@contains@colnames
		\else
			\pgfplotstableread@isnumber@ITERATE#1\pgfplotstable@EOI
%\ifpgfplotstableread@curline@contains@colnames\pgfplots@message{'#1' is a column name!}\else\pgfplots@message{'#1' is NO column name!}\fi
		\fi
	\fi
}
\def\pgfplotstableread@isnumber@plus{+}
\def\pgfplotstableread@isnumber@minus{-}
\def\pgfplotstableread@isnumber@zero{0}
\def\pgfplotstableread@isnumber@one{1}
\def\pgfplotstableread@isnumber@two{2}
\def\pgfplotstableread@isnumber@three{3}
\def\pgfplotstableread@isnumber@four{4}
\def\pgfplotstableread@isnumber@five{5}
\def\pgfplotstableread@isnumber@six{6}
\def\pgfplotstableread@isnumber@seven{7}
\def\pgfplotstableread@isnumber@eight{8}
\def\pgfplotstableread@isnumber@nine{9}
\def\pgfplotstableread@isnumber@e{e}
\def\pgfplotstableread@isnumber@E{E}
\def\pgfplotstableread@isnumber@period{.}

\def\pgfplotstableread@isnumber@ITERATE#1{%
	\def\pgfplotstableread@CURTOK{#1}%
	\ifx\pgfplotstableread@CURTOK\pgfplotstable@EOI
		\def\pgfplotstableread@NEXT{}%
	\else
		\def\pgfplotstableread@NEXT{\pgfplotstableread@isnumber@ITERATE}%
		\ifx\pgfplotstableread@CURTOK\pgfplotstableread@isnumber@plus
		\else
		\ifx\pgfplotstableread@CURTOK\pgfplotstableread@isnumber@minus
		\else
		\ifx\pgfplotstableread@CURTOK\pgfplotstableread@isnumber@zero
		\else
		\ifx\pgfplotstableread@CURTOK\pgfplotstableread@isnumber@one
		\else
		\ifx\pgfplotstableread@CURTOK\pgfplotstableread@isnumber@two
		\else
		\ifx\pgfplotstableread@CURTOK\pgfplotstableread@isnumber@three
		\else
		\ifx\pgfplotstableread@CURTOK\pgfplotstableread@isnumber@four
		\else
		\ifx\pgfplotstableread@CURTOK\pgfplotstableread@isnumber@five
		\else
		\ifx\pgfplotstableread@CURTOK\pgfplotstableread@isnumber@six
		\else
		\ifx\pgfplotstableread@CURTOK\pgfplotstableread@isnumber@seven
		\else
		\ifx\pgfplotstableread@CURTOK\pgfplotstableread@isnumber@eight
		\else
		\ifx\pgfplotstableread@CURTOK\pgfplotstableread@isnumber@nine
		\else
		\ifx\pgfplotstableread@CURTOK\pgfplotstableread@isnumber@e
		\else
		\ifx\pgfplotstableread@CURTOK\pgfplotstableread@isnumber@E
		\else
		\ifx\pgfplotstableread@CURTOK\pgfplotstableread@isnumber@period
		\else
%\message{NO ITS NOT!  Token: '\meaning\pgfplotstableread@CURTOK'}%
			% it's no number, so it is a column name.
			\pgfplotstableread@curline@contains@colnamestrue
			\def\pgfplotstableread@NEXT{\pgfplotstableread@impl@gobble}%
		\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi
	\fi
	\pgfplotstableread@NEXT
}

\def\pgfplotstable@error#1{\pgfplotsthrow{unsupported operation}{#1}\pgfeov}%


\def\pgfplotstableset{%
	\pgfqkeys{/pgfplots/table}%
}%

% Accepts a macro #1 which contains an argument denoting a column
% name.
%
% It checks whether #1 starts with '[index]', indicating that it is actually
% a column INDEX. If that is the case,
% \ifpgfplotstableread@foundcolnames is set to false and the index is
% returned into #1.
%
% Otherwise, \ifpgfplotstableread@foundcolnames is set to true.
\def\pgfplotstable@is@colname#1{%
	\expandafter\pgfplotstabletypeset@is@colname@#1\pgfplotstable@EOI
	\ifpgfplotstableread@foundcolnames
	\else
		\let#1=\pgfplotstable@loc@TMPa
	\fi
}%
\def\pgfplotstabletypeset@is@colname@{%
	\pgfutil@ifnextchar[{%
		\pgfplotstabletypeset@is@colname@index
	}{%
		\pgfplotstableread@foundcolnamestrue
		\pgfplotstabletypeset@is@colname@name
	}%
}
\def\pgfplotstabletypeset@is@colname@index@@{index}%
\def\pgfplotstabletypeset@is@colname@index[#1]#2\pgfplotstable@EOI{%
	\def\pgfplotstable@loc@TMPa{#1}%
	\ifx\pgfplotstable@loc@TMPa\pgfplotstabletypeset@is@colname@index@@
		\pgfplotstableread@foundcolnamesfalse
		\edef\pgfplotstable@loc@TMPa{#2}%
	\else
		\pgfplotstableread@foundcolnamestrue
	\fi
}%
\def\pgfplotstabletypeset@is@colname@name#1\pgfplotstable@EOI{}%

% calls \pgfplotstableset{every table={#1}} where '#1' is the table
% file name.
%
% Note that 'every table' is usually set *AFTER* any other option. In
% other words: settings in 'every table' have higher precedence than
% those provided, for example, at
% \pgfplotstabletypeset[<options>]{...}.
%
% Why? Well, the <options> need to be set *before* the file name
% argument is read. After all, it might contain an inline table for
% which \catcodes need to be adjusted -- and <options> might explain
% how.
%
% REMARK: An early attempt to change the precendence for 'every table'
% was to set <options> again after 'every table'. But that is
% incompatible with, for example '/.add={}{}' key handlers.
%
% This macro does nothing if 'every table' is empty.
%
% #1: the table name (argument to 'every table')
% #2: The <options> which have already been set.
\long\def\pgfplotstableset@every@table#1#2{%
	\pgfkeysgetvalue{/pgfplots/table/every table/.@cmd}\pgfplotstable@loc@TMPa
	\ifx\pgfplotstable@loc@TMPa\pgfplots@empty@style@key
	\else
		\pgfplotstableset{/pgfplots/table/every table={#1}}%,#2}%
	\fi
}%

\def\pgfplotstabletypeset{%
	\pgfutil@ifnextchar[{%	
		\pgfplotstabletypeset@opt
	}{%
		\pgfplotstabletypeset@opt[]%
	}%
}
\long\def\pgfplotstabletypeset@opt[#1]#2{%
	\pgfplotstable@error@pkg{Please load \string\usepackage{pgfplotstable} before using \string\pgfplotstabletypeset}%
}
\let\pgfplotstabletypesetfile=\pgfplotstabletypeset

\def\pgfplotstablecreatecol{%
	\pgfutil@ifnextchar[{%
		\pgfplotstablecreatecol@opt
	}{%
		\pgfplotstablecreatecol@opt[]%
	}%
}%
\def\pgfplotstablecreatecol@opt[#1]#2#3{%
	\pgfplotstable@error@pkg{Please load \string\usepackage{pgfplotstable} before using \string\pgfplotstablecreatecol}%
}%

% Iterates through every column of table '#1' and invokes the code
% '#3' for each column. The current column name will be available as
% '#2' and the current column index as |\pgfplotstablecol| (starting
% with 0).
%
% Example:
% \pgfplotstableforeachcolumn{\table}\as\colname{%
% 	The column name is `\colname'; its index \pgfplotstablecol.\par
% }%
%
% REMARK: this routine does NOT introduce TeX groups.
\long\def\pgfplotstableforeachcolumn#1\as#2#3{%
	\def\pgfplotstablecol{0}%
	\pgfplotslistforeachungrouped#1\as#2{%
		#3\relax%
		\pgfplotsutil@advancestringcounter\pgfplotstablecol
	}%
	\let\pgfplotstablecol=\relax
}%
\let\pgfplotstableforeachcolumn@orig=\pgfplotstableforeachcolumn

% A variant of \pgfplotstableforeachcolumn which is used inside of
% \pgfplotstableread to listener.
%
% It is used as \pgfplotstableforeachcolumn\as\cur{<do something with \cur>}
\long\def\pgfplotstableforeachcolumn@listener#1\as#2#3{%
	\pgfplotstableforeachcolumn@orig\pgfplotstable@colnames@glob\as{#2}{#3}%
}%

% Reports every element t_{ij} for a fixed column j (in read-only
% mode).
%
% For every cell, the code '#4' will be executed where '#3' will
% contain the cell's value. During code '#4', the macro
% \pgfplotstablerow will contain the current row index.
%
% #1: either a column name or the string '[index]' followed by a
% number denoting a column index Access by column name is much faster..
% #2: the table (macro or file name)
% #3: the macro in which the cell values shall be written
% #4: the code to execute.
%
% Example:
% \pgfplotstableforeachcolumnelement{colname}\of\table\as\cellelem{%
% 	I have now cell element `\cellelem' at row index
% 	`\pgfplotstablerow'.
% 	\par
% }
%
% REMARK: this routine does NOT introduce TeX groups.
\long\def\pgfplotstableforeachcolumnelement#1\of#2\as#3#4{%
	\def\pgfplotstablerow{0}%
	\pgfplotstablegetcolumn{#1}\of{#2}\to\pgfplotstableforeachcolumnelement@list
	\pgfplotslistforeachungrouped\pgfplotstableforeachcolumnelement@list\as#3{%
		% allow nesting by copying the old value of \pgfplotstablerow:
		\expandafter\pgfplotstableforeachcolumnelement@\expandafter{\pgfplotstablerow}{#4}%
	}%
	\let\pgfplotstablerow=\relax
}%
% helper method to allow nesting. It copies \pgfplotstablerow.
% #1: the expanded value of \pgfplotstablerow. 
\long\def\pgfplotstableforeachcolumnelement@#1#2{%
	#2\relax
	\def\pgfplotstablerow{#1}% restore to old value.
	% advance.
	\pgfplotsutil@advancestringcounter\pgfplotstablerow
}%

% A routine which is similar to \pgfplotstableforeachcolumnelement,
% but this here checks for changes in \pgfplotsretval and writes them
% back into the respected cell.
%
% The runtime is quadratic in the number of rows.
\long\def\pgfplotstablemodifyeachcolumnelement#1\of#2\as#3#4{%
	\def\pgfplotstablerow{0}%
	%
	% Step 0: get the REAL column name for '#1'.
	% This needs modifications if '#1' is [index]<integer>.
	% -> store the colname to \pgfplotstable@loc@TMPc:
	\def\pgfplotstable@loc@TMPc{#1}%
	\pgfplotstable@is@colname{\pgfplotstable@loc@TMPc}%%
	\ifpgfplotstableread@foundcolnames
	\else
		\expandafter\pgfplotstablegetcolumnnamebyindex\pgfplotstable@loc@TMPc\of{#2}\to\pgfplotstable@loc@TMPc
	\fi
	% Step 0.1: prepare a command which re-assembles column '#1'
	% (using the real column name).
	% The re-assemblation command will be invoked at the end of each
	% iteration. This complicated macro preparation allows nested
	% calls to \pgfplotstablemodifyeachcolumnelement.
	\t@pgfplots@toka={\expandafter\pgfplotslistpushback\expandafter{#3}\to}%
	\edef\pgfplotstable@loc@TMPd{%
		\the\t@pgfplots@toka{\expandafter\noexpand\csname\string#2@\pgfplotstable@loc@TMPc\endcsname}}%
	% Step 1: copy the column data to \pgfplotstable@loc@TMPb
	\expandafter\pgfplotstablegetcolumnbyname\pgfplotstable@loc@TMPc\of#2\to\pgfplotstable@loc@TMPb%
	%
	% clear the original column:
	\expandafter\pgfplotslistnewempty\csname\string#2@\pgfplotstable@loc@TMPc\endcsname
	%
	% Call loop. The prepared re-assemble macro will be provided as macro argument
	% to allow nested calls:
	\expandafter\pgfplotstablemodifyeachcolumnelement@\expandafter{\pgfplotstable@loc@TMPd}
		{\pgfplotstable@loc@TMPb}{#3}{#4}%
	\let\pgfplotstablerow=\relax
}%
% #1: post-iteration code
% #2: the row list
% #3: the loop macro to assign
% #4: the loop body
\long\def\pgfplotstablemodifyeachcolumnelement@#1#2#3#4{%
	\pgfplotslistforeachungrouped{#2}\as#3{%
		% allow nesting by copying the old value of \pgfplotstablerow:
		\expandafter\pgfplotstableforeachcolumnelement@\expandafter{\pgfplotstablerow}{#4}%
		#1%
	}%
}

% Selects a single table element at row #1 and column #2 from table
% #3.
%
% #1: a row index.
% #2: a column name or the string '[index]' followed by a number
% denoting a column index. Access by column name is much faster.
% #3: the table (macro or file name).
%
% The cell value will be written into the macro \pgfplotsretval.
%
% REMARK:
% this routine is supposed to be very slow: it needs time O(N) where N
% is the number of rows. This may change in future versions.
%
% Example:
% \pgfplotstablegetelem{0}{[index]2}\of\table
% The elem is `\pgfplotsretval'.
\def\pgfplotstablegetelem#1#2\of#3{%
	\begingroup
	\pgfplotstablegetcolumn{#2}\of{#3}\to\pgfplotstable@loc@TMPa
	\def\pgfplotsexceptionmsg{Sorry, row `#1' does not exist in table \pgfplotstablenameof{#3}}%
	\pgfplotslistselect#1\of\pgfplotstable@loc@TMPa\to\pgfplotsretval
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%

\def\pgfplotstablegetcolumnlist#1\to#2{\let#2=#1}

% Defines \pgfmathresult (and now also \pgfplotsretval) to be the number of rows in table #1.
%
% #1 may be either a loaded table structure (a macro name) or a table
% file name. In the latter case, the file will be loaded temporarily.
\long\def\pgfplotstablegetrowsof#1{%
	\pgfplotstable@isloadedtable{#1}{%
		% ah - it is an already loaded table!
		\begingroup
		\pgfplotslistfront#1\to\pgfplotstablegetrows@@
		\expandafter\pgfplotslistsize\csname\string#1@\pgfplotstablegetrows@@\endcsname\to\c@pgfplotstable@counta
		\edef\pgfmathresult{\the\c@pgfplotstable@counta}%
		\pgfmath@smuggleone\pgfmathresult
		\endgroup
	}{%
		% ah - it is a file name.
		\begingroup
			\pgfplotstableread{#1}\pgfplotstablegetrows@
			\pgfplotstablegetrowsof{\pgfplotstablegetrows@}%
			\pgfmath@smuggleone\pgfmathresult
		\endgroup
	}%
	\let\pgfplotsretval=\pgfmathresult
}%

% Defines \pgfplotsretval to contain the number of columns in table
% #1.
%
% #1 may be either a loaded table structure (a macro name) or a table
% file name. In the latter case, the file will be loaded temporarily.
\long\def\pgfplotstablegetcolsof#1{%
	\pgfplotstable@isloadedtable{#1}{%
		% ah - it is an already loaded table!
		\begingroup
		\pgfplotslistsize#1\to\c@pgfplotstable@counta
		\edef\pgfplotsretval{\the\c@pgfplotstable@counta}%
		\pgfmath@smuggleone\pgfplotsretval
		\endgroup
	}{%
		% ah - it is a file name.
		\begingroup
			\pgfplotstableread{#1}\pgfplots@table
			\pgfplotstablegetcolsof{\pgfplots@table}%
			\pgfmath@smuggleone\pgfplotsretval
		\endgroup
	}%
	\let\pgfmathresult=\pgfplotsretval
}

pgfplotsticks.code.tex
%--------------------------------------------
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2007/2008 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------

\newif\ifpgfplots@log@tick@isminor@tick@pos
% Checks whether the tick position given as #1.#2=log10(T) belongs to
% T=i*10^j with an integer i>1.
%
% If T=i*10^j,  \ifpgfplots@log@tick@isminor@tick@pos will be set to true and
% \pgfmathresult will contain T.
%
% Otherwise, \ifpgfplots@log@tick@isminor@tick@pos will be set to false and
% pgfmathresult to #1.#2
%
% Arguments:
% #1.#2  the value log10(T)
%
% Implementation:  
% if T = i*10^j,  log10(T) = log10(i) + j.
% That means if log10(T) in \Z,  we have T = 10^j. If not, we need to
% check wether i is an integer. Please note that log10(i) < 1.
%
% Further note: log(T) < 0 <=>  j<0.
% In case j<0, we have 
%   #1.#2 = j + log(i) 
%         = - ( -j - log(i) ) 
%         = - ( -j - 1  + (1-log(i)) )
%         = #1 '.' #2 [ up to the '0.'
% that means #1 = j-1  and #2 = 1-log(i).
\def\pgfplots@is@log@tick@a@minor@tick@pos#1.#2\relax{%
	\pgfmathapproxequalto@{#1.#2}{#1.0}%
	\ifpgfmathcomparison
		% in MOST cases, this here will be true:
		\pgfplots@log@tick@isminor@tick@posfalse
		\def\pgfmathresult{#1.#2}%
	\else
		% I guess this won't happen too often. In fact, it's a very
		% special case.
		\begingroup
		\c@pgf@counta=#1\relax
		\ifdim#1.#2pt<0pt %
			\advance\c@pgf@counta by-1
			\pgfmathsubtract@{1}{0.#2}%
			\expandafter\pgfplots@is@log@tick@a@minor@tick@pos@IDENTIFY@LOGi\pgfmathresult\relax
			\ifpgfplots@log@tick@isminor@tick@pos
				\aftergroup\pgfplots@log@tick@isminor@tick@postrue
				\edef\pgfmathresult{\pgfmathresult e\the\c@pgf@counta}%
			\else
			\aftergroup\pgfplots@log@tick@isminor@tick@posfalse
				\def\pgfmathresult{#1.#2}%
			\fi
		\else
			\pgfplots@is@log@tick@a@minor@tick@pos@IDENTIFY@LOGi0.#2\relax
			\ifpgfplots@log@tick@isminor@tick@pos
				\aftergroup\pgfplots@log@tick@isminor@tick@postrue
				\edef\pgfmathresult{\pgfmathresult e\the\c@pgf@counta}%
			\else
				\aftergroup\pgfplots@log@tick@isminor@tick@posfalse
				\def\pgfmathresult{#1.#2}%
			\fi
		\fi
		\pgfmath@smuggleone\pgfmathresult
		\endgroup
	\fi
}

% expects a positive number.
\def\pgfplots@is@log@tick@a@minor@tick@pos@IDENTIFY@LOGi0.#1\relax{%
	\pgfplots@log@tick@isminor@tick@postrue
	\pgfmathapproxequalto@{0.#1}{0.3010299956639}%
	\ifpgfmathcomparison
		\def\pgfmathresult{2}%
	\else
		\pgfmathapproxequalto@{0.#1}{0.4771212547196}%
		\ifpgfmathcomparison
			\def\pgfmathresult{3}%
		\else
			\pgfmathapproxequalto@{0.#1}{0.6020599913279}%
			\ifpgfmathcomparison
				\def\pgfmathresult{4}%
			\else
				\pgfmathapproxequalto@{0.#1}{0.698970004}%
				\ifpgfmathcomparison
					\def\pgfmathresult{5}%
				\else
					\pgfmathapproxequalto@{0.#1}{0.7781512503}%
					\ifpgfmathcomparison
						\def\pgfmathresult{6}%
					\else
						\pgfmathapproxequalto@{0.#1}{0.8450980400}%
						\ifpgfmathcomparison
							\def\pgfmathresult{7}%
						\else
							\pgfmathapproxequalto@{0.#1}{0.9030899869}%
							\ifpgfmathcomparison
								\def\pgfmathresult{8}%
							\else
								\pgfmathapproxequalto@{0.#1}{0.954242509439}%
								\ifpgfmathcomparison
									\def\pgfmathresult{9}%
								\else
									\pgfplots@log@tick@isminor@tick@posfalse
								\fi
							\fi
						\fi
					\fi
				\fi
			\fi
		\fi
	\fi
}

% Checks whether we need to create a separate 'tick scale label',
% a node with ' * 10^3' on the side of the axis:
%
% PRECONDITION:
%    Axis limits for #1 are given. I need their values before any data
%    scale transformation has been applied.
%    If  
%    	\pgfplots@#1min@unscaled@as@float 
%    and
%    	\pgfplots@#1max@unscaled@as@float 
%    exist; I will use these macros.
%    Otherwise, I will use \pgfplots@#1min and \pgfplots@#1max;
%    assuming that no data scale transformation is active.
%    FIXME : does that need further attention?
\def\pgfplots@init@scaled@tick@for#1{%
	\global\def\pgfplots@glob@TMPa{0}%
	\expandafter\pgfplotslistcheckempty\csname pgfplots@prepared@tick@positions@major@#1\endcsname
	\ifpgfplotslistempty
		% we have no tick labels. Omit the tick scale label as well!
	\else
	\begingroup
	\ifcase\csname pgfplots@scaled@ticks@#1@choice\endcsname\relax
	% CASE 0 : scaled #1 ticks=false: do nothing here.
	\or
		% CASE 1 : scaled #1 ticks=true:
		%--------------------------------
		% the \pgfplots@xmin@unscaled@as@float  is set just before the data
		% scale transformation is initialised.
		%
		% The variables are empty if there is no datascale transformation.
		\expandafter\let\expandafter\pgfplots@cur@min@unscaled\csname pgfplots@#1min@unscaled@as@float\endcsname
		\expandafter\let\expandafter\pgfplots@cur@max@unscaled\csname pgfplots@#1max@unscaled@as@float\endcsname
		%
		\ifx\pgfplots@cur@min@unscaled\pgfutil@empty
			\edef\pgfplots@loc@TMPa{\csname pgfplots@#1min\endcsname}%
			\expandafter\pgfmathfloatparsenumber\expandafter{\pgfplots@loc@TMPa}%
			\let\pgfplots@cur@min@unscaled=\pgfmathresult
			\edef\pgfplots@loc@TMPa{\csname pgfplots@#1max\endcsname}%
			\expandafter\pgfmathfloatparsenumber\expandafter{\pgfplots@loc@TMPa}%
			\let\pgfplots@cur@max@unscaled=\pgfmathresult
		\fi
		%
		\expandafter\pgfmathfloat@decompose@E\pgfplots@cur@min@unscaled\relax\pgfmathfloat@a@E
		\expandafter\pgfmathfloat@decompose@E\pgfplots@cur@max@unscaled\relax\pgfmathfloat@b@E
		\pgfplots@init@scaled@tick@normalize@exponents
		\ifnum\pgfmathfloat@b@E<\pgfmathfloat@a@E
			\pgfmathfloat@b@E=\pgfmathfloat@a@E
		\fi
		\xdef\pgfplots@glob@TMPa{\pgfplots@scale@ticks@above@exponent}%
		\ifnum\pgfplots@glob@TMPa<\pgfmathfloat@b@E
			% ok, scale it:
			\multiply\pgfmathfloat@b@E by-1
			\xdef\pgfplots@glob@TMPa{\the\pgfmathfloat@b@E}%
		\else
			\xdef\pgfplots@glob@TMPa{\pgfplots@scale@ticks@below@exponent}%
			\ifnum\pgfplots@glob@TMPa>\pgfmathfloat@b@E
				% ok, scale it:
				\multiply\pgfmathfloat@b@E by-1
				\xdef\pgfplots@glob@TMPa{\the\pgfmathfloat@b@E}%
			\else
				% no scaling necessary:
				\xdef\pgfplots@glob@TMPa{0}%
			\fi
		\fi
	\or
		% CASE 2 : scaled #1 ticks=base 10:
		%--------------------------------
		\c@pgf@counta=\csname pgfplots@scaled@ticks@#1@arg\endcsname\relax
		%\multiply\c@pgf@counta by-1
		\xdef\pgfplots@glob@TMPa{\the\c@pgf@counta}%
	\or
		% CASE 3 : scaled #1 ticks=real:
		%--------------------------------
		\pgfmathfloatparsenumber{\csname pgfplots@scaled@ticks@#1@arg\endcsname}%
		\global\let\pgfplots@glob@TMPa=\pgfmathresult
	\or
		% CASE 4 : scaled #1 ticks=manual:
		\expandafter\global\expandafter\let\expandafter\pgfplots@glob@TMPa\csname pgfplots@scaled@ticks@#1@arg\endcsname
	\fi
	\endgroup
	\fi
	\expandafter\let\csname pgfplots@tick@scale@#1\endcsname=\pgfplots@glob@TMPa%
}

% Handles the case that one of the limits is 0 (or unbounded, although
% that might not be a use-case at all).
%
% Note that 0 = 0*10^A (naturally). In this case, A can be undefined,
% and we want to use B's exponent (only) for the decision here.
%
% INPUT:
%  - \pgfplots@cur@min@unscaled, 
%  - \pgfplots@cur@max@unscaled,
%  - \pgfmathfloat@a@E
%  - \pgfmathfloat@b@E
%
% Output:
%  normalized values of \pgfmathfloat@a@E and \pgfmathfloat@b@E
\def\pgfplots@init@scaled@tick@normalize@exponents{%
	\pgfmathfloatgetflags\pgfplots@cur@min@unscaled\pgfmathfloat@a@S
	\pgfmathfloatgetflags\pgfplots@cur@max@unscaled\pgfmathfloat@b@S
	\ifcase\pgfmathfloat@a@S%
		% min = 0. 
		\ifcase\pgfmathfloat@b@S
			% max =0
			% normalize to 0 * 10^0 !
			\pgfmathfloat@a@E=0 %
			\pgfmathfloat@b@E=0 %
		\or
			% max > 0
			% since 0 = 0 * 10^A for any A, tick scaling is based on
			% B only.
			\pgfmathfloat@a@E=\pgfmathfloat@b@E
		\or
			% max < 0
			\pgfmathfloat@a@E=\pgfmathfloat@b@E
		\else
			% max is unbounded. normalize exponent to something
			% useful:
			\pgfmathfloat@a@E=0 %
			\pgfmathfloat@b@E=0 %
		\fi
	\or
		% min>0
		\ifcase\pgfmathfloat@b@S
			% max =0
			% since 0 = 0 * 10^B for any B, tick scaling is based on
			% A only.
			\pgfmathfloat@b@E=\pgfmathfloat@a@E
		\or
			% max > 0
		\or
			% max < 0
		\else
			% max is unbounded. normalize exponent to something
			% useful:
			\pgfmathfloat@b@E=\pgfmathfloat@a@E
		\fi
	\or
		% min<0
		\ifcase\pgfmathfloat@b@S
			% max =0
			% since 0 = 0 * 10^B for any B, tick scaling is based on
			% A only.
			\pgfmathfloat@b@E=\pgfmathfloat@a@E
		\or
			% max > 0
		\or
			% max < 0
		\else
			% max is unbounded. normalize exponent to something
			% useful:
			\pgfmathfloat@b@E=\pgfmathfloat@a@E
		\fi
	\else
		% min is unbounded:
		% normalize somehow.
		\pgfmathfloat@a@E=0 %
		\pgfmathfloat@b@E=0 %
	\fi
}

% x-axis tick labels for #1th tick
% #1: the axis (x,y or z)
% #2: the value
% #3,#4+#5: arguments for \pgfplotspointonorientedsurfaceabwithbshift
% #5: ticknumber
\def\pgfplots@show@ticklabel#1#2(#3,#4+#5)#6{%
	\begingroup%
	\csname ifpgfplots@#1ticklabel@interval\endcsname
		% Special case for the INTERVAL feature:
		% we have to do additional work here.
		\pgfmathparse{#3}%
		\edef\pgfplots@show@ticklabel@coord@x@new{\pgfmathresult}%
		\pgfmathparse{#4}%
		\edef\pgfplots@show@ticklabel@coord@y@new{\pgfmathresult}%
		%
		\pgfplots@show@ticklabel@{#1}{#2}%
		\let\nexttick=\tick
		\ifx\pgfplots@show@ticklabel@LASTTICK\pgfutil@empty
			% its the first call. Simply remember arguments and wait
			% for interval boundary before proceeding.
		\else
			% acquire options of first interval boundary:
			\pgfplots@show@ticklabel@LASTTICK
			% compute new node position:
			\pgfmathparse{0.5*(\pgfplots@show@ticklabel@coord@x + \pgfplots@show@ticklabel@coord@x@new)}%
			\let\pgfplots@show@ticklabel@coord@x=\pgfmathresult%
			\pgfmathparse{0.5*(\pgfplots@show@ticklabel@coord@y + \pgfplots@show@ticklabel@coord@y@new)}%
			\let\pgfplots@show@ticklabel@coord@y=\pgfmathresult%
			\let\ticknum=\pgfplots@show@ticklabel@num\relax%
			\let\tick=\pgfplots@show@ticklabel@tick%
			\pgfplots@show@ticklabel@@{#1}
				{\pgfplotspointonorientedsurfaceabwithbshift{\pgfplots@show@ticklabel@coord@x}{\pgfplots@show@ticklabel@coord@y}{#5}}%
		\fi
		\xdef\pgfplots@show@ticklabel@LASTTICK{%
			\noexpand\def\noexpand\pgfplots@show@ticklabel@tick{\nexttick}%
			\noexpand\def\noexpand\pgfplots@show@ticklabel@coord@x{\pgfplots@show@ticklabel@coord@x@new}%
			\noexpand\def\noexpand\pgfplots@show@ticklabel@coord@y{\pgfplots@show@ticklabel@coord@y@new}%
			\noexpand\edef\noexpand\pgfplots@show@ticklabel@num{#6}%
		}%
	\else
		\let\ticknum=#6\relax%
		\pgfplots@show@ticklabel@{#1}{#2}%
		\pgfplots@show@ticklabel@@{#1}{\pgfplotspointonorientedsurfaceabwithbshift{#3}{#4}{#5}}%
	\fi
	\endgroup
}

% #1: the axis (x,y or z)
% #2: the location where to place it.
\def\pgfplots@show@ticklabel@@#1#2{%
	% Typeset the label!
	\pgfinterruptboundingbox
		% What makes this complicated is the 'ticklabel cs' feature.
		% What we need is to compute the MAXIMUM LENGTH over each tick
		% label IN DIRECTION OF THE OUTER NORMAL.
		%
		% This needs to
		% 1. enable bounding box computation even in case of
		% 'overlay',
		% 2. projection of the bounding box in direction of the outer
		% normal,
		% 3. update of the bounding box if 'overlay' is not active.
		\begingroup
		%
		% prepare step (1.):
		\pgfkeysalso{%
			/tikz/every node/.append code={%
				\ifpgf@relevantforpicturesize
					\gdef\pgfplots@show@ticklabel@@update@BB{1}%
				\else
					\gdef\pgfplots@show@ticklabel@@update@BB{0}%
				\fi
				\pgf@relevantforpicturesizetrue
			}%
		}%
		%
		% Compute and remember the position '#2':
		\pgf@process{#2}%
		\edef\pgfplots@ticklabel@at@x{\the\pgf@x}%
		\edef\pgfplots@ticklabel@at@y{\the\pgf@y}%
		%
		% ok, generate the label!
		\node at (\pgfplots@ticklabel@at@x,\pgfplots@ticklabel@at@y) {\csname pgfplots@#1ticklabel\endcsname};%
		%
		% compute the label's dimensions, step (2.):
		\pgfplots@ticklabel@maxtickdimen@updateforcurrentpath
			{#1}
			{\pgf@x=\pgfplots@ticklabel@at@x\space\pgf@y=\pgfplots@ticklabel@at@y\space}%%
		%
		% prepare step (3.): update of bounding box:
		\if\pgfplots@show@ticklabel@@update@BB1%
			\xdef\pgfplots@glob@TMPa{%
				\pgf@xa=\the\pgf@picminx\space
				\pgf@xb=\the\pgf@picminy\space
				\pgf@ya=\the\pgf@picmaxx\space
				\pgf@yb=\the\pgf@picmaxy\space
				\noexpand\pgf@protocolsizes{\pgf@xa}{\pgf@xb}%
				\noexpand\pgf@protocolsizes{\pgf@ya}{\pgf@yb}%
				\noexpand\pgf@resetpathsizes
			}%
		\else
			\global\let\pgfplots@glob@TMPa=\relax
		\fi
		\endgroup
	\endpgfinterruptboundingbox
	\begingroup
		\pgfplots@glob@TMPa
	\endgroup
}%

% TICK LABEL DIMENSION CONTROL
%
% The following framework is supposed to accumulate the value for
% \pgfplotsvalueoflargesttickdimen.
%
% It works like this:
%
% \pgfplots@ticklabel@maxtickdimen@reset{#1}
% \pgfplots@ticklabel@maxtickdimen@prepare@for@normalvec{#1}{<normal vector>}
% ...
% \pgfplots@ticklabel@maxtickdimen@updateforcurrentpath{#1}
% \pgfplots@ticklabel@maxtickdimen@updateforcurrentpath{#1}
% \pgfplots@ticklabel@maxtickdimen@updateforcurrentpath{#1}
% ...
% \pgfplots@ticklabel@maxtickdimen@finish{#1}
%
% -> then, \pgfplotsvalueoflargesttickdimen expands to the largest
%  distance from a tick's coordinate to its tick label bounding box in
%  direction of the outer normal vector.
\def\pgfplots@ticklabel@maxtickdimen@reset#1{%
	\expandafter\gdef\csname pgfplots@maxtickdimen@#1\endcsname{0pt}%
	\expandafter\gdef\csname pgfplots@maxtickdimen@extrashift@#1\endcsname{0pt}%
}%

% Adds the extra shift '#2' along the normal vector for axis '#1'.
\def\pgfplots@ticklabel@maxtickdimen@extrashift#1#2{%
	\begingroup
	\afterassignment\pgfplots@gobble@until@relax
	\pgf@xa=#2pt\relax
	\advance\pgf@xa by\csname pgfplots@maxtickdimen@extrashift@#1\endcsname\relax
	\expandafter\xdef\csname pgfplots@maxtickdimen@extrashift@#1\endcsname{\the\pgf@xa}%
	\endgroup
}

% Finalizes the maxtickdimen computation.
%
% This applies any extra shifts (including '#1ticklabel shift').
\def\pgfplots@ticklabel@maxtickdimen@finish#1{%
	\pgfkeysgetvalue{/pgfplots/#1ticklabel shift}\pgfmathresult
	\ifx\pgfmathresult\pgfutil@empty
	\else
		\pgfplots@ticklabel@maxtickdimen@extrashift{#1}{\pgfkeysvalueof{/pgfplots/#1ticklabel shift}}%
	\fi
	\begingroup
	\pgf@xa=\csname pgfplots@maxtickdimen@extrashift@#1\endcsname\relax
	\advance\pgf@xa by \csname pgfplots@maxtickdimen@#1\endcsname\relax
	\expandafter\xdef\csname pgfplots@maxtickdimen@#1\endcsname{\the\pgf@xa}%
	\endgroup
}%
% 
% #1: the axis (x,y or z)
% #2: the normal vector
\def\pgfplots@ticklabel@maxtickdimen@prepare@for@normalvec#1#2{%
	\pgf@process{#2}%
	\edef\pgfplots@loc@vector@to@outside{\pgf@x=\the\pgf@x\space\pgf@y=\the\pgf@y\space}%
	% Identify the corner point of the ticklabel bounding box which
	% shall be used: 
	\ifdim\pgf@x>0sp
		\ifdim\pgf@y>0sp
			% NORTH EAST
			\def\pgfplots@loc@ticklabel@bb@corner{\pgf@x=\pgf@picmaxx\pgf@y=\pgf@picmaxy}%
		\else
			% SOUTH EAST
			\def\pgfplots@loc@ticklabel@bb@corner{\pgf@x=\pgf@picmaxx\pgf@y=\pgf@picminy}%
		\fi
	\else
		\ifdim\pgf@y>0sp
			% NORTH WEST
			\def\pgfplots@loc@ticklabel@bb@corner{\pgf@x=\pgf@picminx\pgf@y=\pgf@picmaxy}%
		\else
			% SOUTH WEST
			\def\pgfplots@loc@ticklabel@bb@corner{\pgf@x=\pgf@picminx\pgf@y=\pgf@picminy}%
		\fi
	\fi
}%

% #1: the axis (x,y or z)
% #2: the point from where dimension shall be computed (the 'at'
% argument of the tick label)
\def\pgfplots@ticklabel@maxtickdimen@updateforcurrentpath#1#2{%
	\pgfplotsscalarproductofvectors
		{\pgfplots@loc@vector@to@outside}%
		{\pgfpointdiff
			{#2\pgf@pos@transform\pgf@x\pgf@y}%
			{\pgfplots@loc@ticklabel@bb@corner}}%
	\ifdim\pgf@x>\csname pgfplots@maxtickdimen@#1\endcsname\relax
		\expandafter\xdef\csname pgfplots@maxtickdimen@#1\endcsname{\the\pgf@x}%
	\fi
}%

% Expands to the largest distance of a tick position to its tick label
% bounding box in direction of the outer unit normal vector.
%
% It does also include the value of the 'ticklabel shift' key.
%
% This function assumes that
% \pgfplots@ticklabel@maxtickdimen@reset{#1}
% \pgfplots@ticklabel@maxtickdimen@prepare@for@normalvec{#1}{<normal vector>}
% ...
% \pgfplots@ticklabel@maxtickdimen@updateforcurrentpath{#1}
% \pgfplots@ticklabel@maxtickdimen@updateforcurrentpath{#1}
% \pgfplots@ticklabel@maxtickdimen@updateforcurrentpath{#1}
% ...
% \pgfplots@ticklabel@maxtickdimen@finish{#1}
% has been invoked completely.
%
% #1: either x,y or z. It denotes the axis for which the ticks are
% requested.
\def\pgfplotsvalueoflargesttickdimen#1{%
	\csname pgfplots@maxtickdimen@#1\endcsname
}%

% Just like \pgfplotsqpointoutsideofaxis, but this one here uses the
% axis on which tick labels will be drawn.
%
% #1: one of x, y or z.
% #2: the coordinate on the tick axis designated by '#1'.
% #3: a scale (a dimen) in which the point is moved in direction of
% the outward normal vector of the axis.
%
% @see \pgfplotsqpointoutsideofaxis
\def\pgfplotsqpointoutsideofticklabelaxis#1#2#3{%
	\pgfplotsqpointoutsideofaxis{\csname pgfplots@#1ticklabelaxisspec\endcsname}{#2}{#3}%
}%
\def\pgfplotsqpointoutsideofticklabelaxisrel#1#2#3{%
%\message{using \string\pgfplotsqpointoutsideofaxisrel{\csname pgfplots@#1ticklabelaxisspec\endcsname}{#2}{#3}^^J}%
	\pgfplotsqpointoutsideofaxisrel{\csname pgfplots@#1ticklabelaxisspec\endcsname}{#2}{#3}%
}%
\def\pgfplotsqpointoutsideofticklabelaxistransformed#1#2#3{%
	\pgfplotsqpointoutsideofaxistransformed{\csname pgfplots@#1ticklabelaxisspec\endcsname}{#2}{#3}%
}%

% Expands to the three-character-identification for the axis
% containing tick labels for axis #1.
%
% #1: either x, y or z.
\def\pgfplotsticklabelaxisspec#1{\csname pgfplots@#1ticklabelaxisspec\endcsname}%

% The unit outer normal vector for axis #1.
% #1: one of x, y or z.
\def\pgfplotspointouternormalvectorofticklabelaxis#1{%
	\pgfplotspointouternormalvectorofaxis{\csname pgfplots@#1ticklabelaxisspec\endcsname}%
}

% Defines \tick by applying any necessary math to the (possibly
% transformed) tick value #2.
%
% #1: axis (x or y)
% #2: tick value.
\def\pgfplots@show@ticklabel@#1#2{%
	\csname ifpgfplots@apply@datatrafo@#1\endcsname
		\pgfplotscoordmath{#1}{datascaletrafo inverse}{#2}%
		\ifcase\csname pgfplots@scaled@ticks@#1@choice\endcsname
		\or
			\expandafter\pgfmathfloatshift@\expandafter{\pgfmathresult}{\csname pgfplots@tick@scale@#1\endcsname}%
		\or
			\expandafter\pgfmathfloatshift@\expandafter{\pgfmathresult}{\csname pgfplots@tick@scale@#1\endcsname}%
		\or
			\expandafter\pgfmathfloatdivide@\expandafter{\pgfmathresult}{\csname pgfplots@tick@scale@#1\endcsname}%
		\or
			% scaled #1 ticks=manual. Invoke manual tick scaling code:
			\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplots@tick@scale@#1\endcsname
			\begingroup
			\pgfkeys{/pgf/fpu=true}%
			\expandafter\pgfplots@loc@TMPa\expandafter{\pgfmathresult}%
			\pgfmath@smuggleone\pgfmathresult
			\endgroup
			\pgfmathfloatparsenumber\pgfmathresult%
		\fi
		% .. and this here provides \tick as fixed point repr:
		\expandafter\pgfmathfloattofixed\expandafter{\pgfmathresult}%
		\let\tick=\pgfmathresult
	\else
		\edef\tick{#2}%
		\pgfplots@if{pgfplots@#1islinear}{%
			\ifnum\csname pgfplots@scaled@ticks@#1@choice\endcsname=0
			\else
				\pgfmathfloatparsenumber{#2}%
				\ifnum\csname pgfplots@scaled@ticks@#1@choice\endcsname=3
					\expandafter\pgfmathfloatdivide@\expandafter{\pgfmathresult}{\csname pgfplots@tick@scale@#1\endcsname}%
				\else
					\expandafter\pgfmathfloatshift@\expandafter{\pgfmathresult}{\csname pgfplots@tick@scale@#1\endcsname}%
				\fi
				\expandafter\pgfmathfloattofixed\expandafter{\pgfmathresult}%
				\let\tick=\pgfmathresult
			\fi
		}{}%
	\fi
	\pgfplots@coord@inv@trafo@apply{#1}{\tick}%
	\let\tick=\pgfmathresult
}%

\def\pgfplots@user@ticklabel@list@x{%
	\pgfplotslistselectorempty\ticknum\of\pgfplots@xticklabels\to\tick
	\pgfplots@ticklabel@typeset@arg\tick
}
\def\pgfplots@user@ticklabel@list@y{%
	\pgfplotslistselectorempty\ticknum\of\pgfplots@yticklabels\to\tick
	\pgfplots@ticklabel@typeset@arg\tick
}
\def\pgfplots@user@ticklabel@list@z{%
	\pgfplotslistselectorempty\ticknum\of\pgfplots@zticklabels\to\tick
	\pgfplots@ticklabel@typeset@arg\tick
}
\def\pgfplots@user@extra@ticklabel@list@x{%
	\pgfplotslistselectorempty\ticknum\of\pgfplots@extra@xticklabels\to\tick
	\pgfplots@ticklabel@typeset@arg\tick
}
\def\pgfplots@user@extra@ticklabel@list@y{%
	\pgfplotslistselectorempty\ticknum\of\pgfplots@extra@yticklabels\to\tick
	\pgfplots@ticklabel@typeset@arg\tick
}
\def\pgfplots@user@extra@ticklabel@list@z{%
	\pgfplotslistselectorempty\ticknum\of\pgfplots@extra@zticklabels\to\tick
	\pgfplots@ticklabel@typeset@arg\tick
}

\def\pgfplots@limit@max@reg#1{%
	\if\pgfkeysvalueof{/pgfplots/#1 dir/value}n%
		\csname pgfplots@#1max@reg\endcsname
	\else
		\csname pgfplots@#1min@reg\endcsname
	\fi
}%
\def\pgfplots@limit@min@reg#1{%
	\if\pgfkeysvalueof{/pgfplots/#1 dir/value}n%
		\csname pgfplots@#1min@reg\endcsname
	\else
		\csname pgfplots@#1max@reg\endcsname
	\fi
}%

% Check if a label does not cross the x-axis
\def\pgfplots@ytick@check@tickshow{%
	\pgfplots@tickshowtrue
	\ifpgfplots@hide@obscured@ytick
		\if\pgfplots@yaxislinesnum2% center
			\ifcase\pgfplots@xaxislinesnum\relax
				\pgfplotsmath@ifapproxequal@dim
					{\pgfplots@tmpa}{\pgfplots@limit@min@reg{y}}
					{\pgfplots@loc@tick@placement@tolerance}
					{%
						\pgfplots@tickshowfalse
					}{}%
				\pgfplotsmath@ifapproxequal@dim
					{\pgfplots@tmpa}{\pgfplots@limit@max@reg{y}}
					{\pgfplots@loc@tick@placement@tolerance}
					{%
						\pgfplots@tickshowfalse
					}{}%
			\or
				\pgfplotsmath@ifapproxequal@dim
					{\pgfplots@tmpa}{\pgfplots@limit@min@reg{y}}
					{\pgfplots@loc@tick@placement@tolerance}
					{%
						\pgfplots@tickshowfalse
					}{%
					}%
			\or
				\pgfplotsmath@ifapproxequal@dim
					{\pgfplots@tmpa}{\pgfplots@logical@ZERO@y pt}
					{\pgfplots@loc@tick@placement@tolerance}
					{%
						\pgfplots@tickshowfalse
					}{}%
			\or
				\pgfplotsmath@ifapproxequal@dim
					{\pgfplots@tmpa}{\pgfplots@limit@max@reg{y}}
					{\pgfplots@loc@tick@placement@tolerance}
					{%
						\pgfplots@tickshowfalse
					}{}%
			\fi
		\fi
	\fi
}
\def\pgfplots@ztick@check@tickshow{%
	\pgfplots@tickshowtrue
	\ifpgfplots@hide@obscured@ztick
		\if\pgfplots@zaxislinesnum2% center
			\pgfplotsmath@ifapproxequal@dim
				{\pgfplots@tmpa}{\pgfplots@logical@ZERO@z pt}
				{\pgfplots@loc@tick@placement@tolerance}
				{%
					\pgfplots@tickshowfalse
				}{}%
		\fi
	\fi
}%

% Fills the macros
%   \pgfplots@tick@LOWER@b \pgfplots@tick@end@a
%   \pgfplots@tick@UPPER@b \pgfplots@tick@end@b
% with coordinates such that 
%   (\pgfplots@tick@LOWER@b,\pgfplots@tmpa) -- (\pgfplots@tick@end@a,\pgfplots@tmpa)
% produces a correct tick line. 
%
% The '@b' variant is only used in case of \pgfplots@ytickposnum = 0
%
% #1 : the current axis (x or y).
% #2 : the current tick width
%
\def\pgfplots@prepare@tick@offsets@for@#1#2{%
	%
	% FIXME : this stuff was ok for 2D.
	% For 3D, it works only for the cases of boxed axes or centered
	% axis lines.
	\ifcase\csname pgfplots@#1tickposnum\endcsname\relax
		% both
		%(\pgfplots@xcoordminTEX-\pgfplots@tick@offset, \pgfplots@tmpa) -- ++( #2, 0pt)
		\edef\pgfplots@tick@LOWER@b{\csname pgfplots@\pgfplotspointonorientedsurfaceB min\endcsname}%
		%
		%(\pgfplots@xcoordmaxTEX+\pgfplots@tick@offset, \pgfplots@tmpa)	-- ++(-#2, 0pt)
		\edef\pgfplots@tick@UPPER@b{\csname pgfplots@\pgfplotspointonorientedsurfaceB max\endcsname}%
	\or
		% left
		% (\pgfplots@xcoordminTEX-\pgfplots@tick@offset, \pgfplots@tmpa) -- ++( #2, 0pt);
		\edef\pgfplots@tick@LOWER@b{\csname pgfplots@\pgfplotspointonorientedsurfaceB min\endcsname}%
	\or
		% center
		% (\pgfplots@ZERO@x      -\pgfplots@tick@offset, \pgfplots@tmpa) -- ++( #2, 0pt);
		\edef\pgfplots@tick@LOWER@b{\csname pgfplots@logical@ZERO@\pgfplotspointonorientedsurfaceB \endcsname}%
	\or
		% right
		% (\pgfplots@xcoordmaxTEX+\pgfplots@tick@offset, \pgfplots@tmpa)	-- ++(-#2, 0pt);
		\edef\pgfplots@tick@UPPER@b{\csname pgfplots@\pgfplotspointonorientedsurfaceB max\endcsname}%
	\else
		% FALL BACK. never used, I guess?
		% (\pgfplots@xcoordminTEX-\pgfplots@tick@offset, \pgfplots@tmpa) -- ++( #2, 0pt);
		\edef\pgfplots@tick@LOWER@b{\csname pgfplots@\pgfplotspointonorientedsurfaceB min\endcsname}%
	\fi
	%
	\ifcase\csname pgfplots@#1tickalignnum\endcsname\relax
		\def\pgfplots@tick@offset{0}%
	\or
		\edef\pgfplots@tick@offset{#2}%
	\or
		\pgfmathmultiply@{0.5}{#2}%
		\let\pgfplots@tick@offset=\pgfmathresult%
	\fi
	%
	\edef\pgfplots@tick@LOWER@shiftbeg{-\pgfplots@tick@offset}%
	\pgfmathadd@{\pgfplots@tick@LOWER@shiftbeg}{#2}%
	\let\pgfplots@tick@LOWER@shiftend=\pgfmathresult
	%
	\edef\pgfplots@tick@UPPER@shiftbeg{\pgfplots@tick@offset}%
	\pgfmathsubtract@{\pgfplots@tick@UPPER@shiftbeg}{#2}%
	\let\pgfplots@tick@UPPER@shiftend=\pgfmathresult
	%
	% Assemble the \pgfplots@drawticklines@for@placecomputedtick
	% command.
	\def\pgfplots@drawticklines@for@placecomputedtick{%
		\if\pgfplots@drawticklines@for@placecomputedtick@LOWEROK1%
			\pgfpathmoveto{\pgfplotspointonorientedsurfaceabwithbshift{\pgfplots@curtickpos}{\pgfplots@tick@LOWER@b}{\pgfplots@tick@LOWER@shiftbeg pt}}%
			\pgfpathlineto{\pgfplotspointonorientedsurfaceabwithbshift{\pgfplots@curtickpos}{\pgfplots@tick@LOWER@b}{\pgfplots@tick@LOWER@shiftend pt}}%
		\fi
		\if\pgfplots@drawticklines@for@placecomputedtick@UPPEROK1%
			\pgfpathmoveto{\pgfplotspointonorientedsurfaceabwithbshift{\pgfplots@curtickpos}{\pgfplots@tick@UPPER@b}{\pgfplots@tick@UPPER@shiftbeg pt}}%
			\pgfpathlineto{\pgfplotspointonorientedsurfaceabwithbshift{\pgfplots@curtickpos}{\pgfplots@tick@UPPER@b}{\pgfplots@tick@UPPER@shiftend pt}}%
		\fi
	}%
%\message{place computed tick: LOWEROK=\pgfplots@drawticklines@for@placecomputedtick@LOWEROK; UPPEROK=\pgfplots@drawticklines@for@placecomputedtick@UPPEROK.}%
}%


\newif\ifpgfplots@needsminorloop

\def\pgfplots@draw@tick@scale@label@for#1{%
	\csname ifpgfplots@#1islinear\endcsname
		\begingroup
			\def\pgfplots@temp@isbaseten{0}%
			\ifcase\csname pgfplots@scaled@ticks@#1@choice\endcsname
				\global\let\pgfplots@glob@TMPa=\pgfutil@empty
			\or
				\xdef\pgfplots@glob@TMPa{\csname pgfplots@tick@scale@#1\endcsname}%
				\def\pgfplots@temp@isbaseten{1}%
			\or
				\xdef\pgfplots@glob@TMPa{\csname pgfplots@tick@scale@#1\endcsname}%
				\def\pgfplots@temp@isbaseten{1}%
			\or
				\xdef\pgfplots@glob@TMPa{\csname pgfplots@tick@scale@#1\endcsname}%
				% real:
			\or
				% manual:
				\global\def\pgfplots@glob@TMPa{dummyargument}%
			\fi
			\if1\pgfplots@temp@isbaseten
				\expandafter\c@pgf@counta\pgfplots@glob@TMPa\relax
				\multiply\c@pgf@counta by-1
				\ifnum\c@pgf@counta=0\relax
					\global\let\pgfplots@glob@TMPa=\pgfutil@empty
				\else
					\xdef\pgfplots@glob@TMPa{\the\c@pgf@counta}%
				\fi
			\fi
		\endgroup
		\ifx\pgfplots@glob@TMPa\pgfutil@empty
		\else
			\begingroup
			\pgfkeysgetvalue{/pgfplots/#1tick scale label code/.@cmd}\pgfplots@loc@TMPa
			\ifx\pgfplots@loc@TMPa\pgfplots@empty@command@key
			\else
				\edef\pgfplots@tick@scale@labels{\noexpand\pgfplots@invoke@pgfkeyscode{/pgfplots/#1tick scale label code/.@cmd}{\pgfplots@glob@TMPa}}%
				%
				\pgfplots@change@pgfpoints@to@descriptioncs
				%
				\node[%
					/pgfplots/every tick label,%
					/pgfplots/every #1 tick label,%
					/pgfplots/every #1 tick scale label]
				{\pgfplots@tick@scale@labels};
			\fi
			\endgroup
		\fi
	\fi
}

% Check if the current tick position, stored in \pgfplots@tmpa, 
% does not cross the y-axis.
%
% This is just a special case for centered axis lines.
\def\pgfplots@xtick@check@tickshow{%
	\pgfplots@tickshowtrue
	\ifpgfplots@hide@obscured@xtick
		\if\pgfplots@xaxislinesnum2% center
			\ifcase\pgfplots@yaxislinesnum\relax
				\pgfplotsmath@ifapproxequal@dim
					{\pgfplots@tmpa}{\pgfplots@limit@min@reg{x}}
					{\pgfplots@loc@tick@placement@tolerance}
					{%
						\pgfplots@tickshowfalse
					}{}%
				\pgfplotsmath@ifapproxequal@dim
					{\pgfplots@tmpa}{\pgfplots@limit@max@reg{x}}
					{\pgfplots@loc@tick@placement@tolerance}
					{%
						\pgfplots@tickshowfalse
					}{}%
			\or
				\pgfplotsmath@ifapproxequal@dim
					{\pgfplots@tmpa}{\pgfplots@limit@min@reg{x}}
					{\pgfplots@loc@tick@placement@tolerance}
					{%
						\pgfplots@tickshowfalse
					}{}%
			\or
				\pgfplotsmath@ifapproxequal@dim
					{\pgfplots@tmpa}{\pgfplots@logical@ZERO@x pt}
					{\pgfplots@loc@tick@placement@tolerance}
					{%
						\pgfplots@tickshowfalse
					}{}%
			\or
				\pgfplotsmath@ifapproxequal@dim
					{\pgfplots@tmpa}{\pgfplots@limit@max@reg{x}}
					{\pgfplots@loc@tick@placement@tolerance}
					{%
						\pgfplots@tickshowfalse
					}{}%
			\fi
		\fi
	\fi
}

% Draws extra ticks including grid lines, tick lines and tick labels
% along the current oriented surface.
%
% See \pgfplots@drawticklines@onorientedsurf@ for a description of the
% oriented surface.
%
% #1 : tick position list
\def\pgfplots@draw@extra@ticks@onorientedsurf{%
	\expandafter\pgfplots@draw@extra@ticks@onorientedsurf@\pgfplotspointonorientedsurfaceA
}%
% #1: axis (x or y)
% #2: tick position list
\def\pgfplots@draw@extra@ticks@onorientedsurf@#1#2{%
	\begingroup
	\def\pgfplots@scaled@ticks@x@choice{0}%
	\def\pgfplots@scaled@ticks@y@choice{0}%
	\def\pgfplots@scaled@ticks@z@choice{0}%
	\csname pgfplots@#1minorticksfalse\endcsname
	\csname pgfplots@#1minorgridsfalse\endcsname
	\expandafter\let\expandafter\pgfplots@ticklabel@pos@orig\csname pgfplots@#1ticklabel@pos\endcsname%
	\expandafter\let\expandafter\axis@TMP\csname pgfplots@extra@#1ticklabel\endcsname
	\expandafter\let\csname pgfplots@#1ticklabel\endcsname=\axis@TMP
%	\pgfplotsset{/pgfplots/every extra #1 tick}%
	% use a scope here such that line width and draw color can be set.
	\scope[/pgfplots/.cd,/pgfplots/every extra #1 tick]
	\expandafter\let\expandafter\pgfplots@ticklabel@pos@\csname pgfplots@#1ticklabel@pos\endcsname
	\ifx\pgfplots@ticklabel@pos@\pgfplots@ticklabel@pos@orig
	\else
		\pgfplots@init@ticklabelaxisspec
	\fi
	\pgfplots@prepare@tick@coordlists@for{#1}{#2}%
	\pgfplots@drawgridlines@onorientedsurf%
	\pgfplots@drawticklines@onorientedsurf%
	\pgfplots@drawticklabels@onorientedsurf%
	\endscope
	\endgroup
}

% Computes final major and minor tick positions into global lists
% \pgfplots@prepared@tick@positions@major@x
% and
% \pgfplots@prepared@tick@positions@minor@x.
%
% Both lists contain entries of the form {<index>}{<logical position>}
% @see \pgfplots@prepared@tick@pos@unpack
%
% #1: the axis
% #2: the tick list.
%
% PRECONDITION:  
% 	- \pgfplots@determinedefaultvalues has been executed.
% 		That means particularly that \pgfplots@[xy][min,max] are available in TeX point
% 		range (after datascaling and logs).
% POSTCONDITION:
% 	- the lists
% 		\pgfplots@prepared@tick@positions@major@x
% 		\pgfplots@prepared@tick@positions@major@tickindices@x
% 		\pgfplots@prepared@tick@positions@minor@x
% 	  are ready.
\def\pgfplots@prepare@tick@coordlists@for#1#2{%
	\begingroup
	\expandafter\let\expandafter\ifpgfplots@islinear\csname ifpgfplots@#1islinear\endcsname
	\expandafter\let\expandafter\ifpgfplots@minorticks\csname ifpgfplots@#1minorticks\endcsname
	\expandafter\let\expandafter\ifpgfplots@minorgrids\csname ifpgfplots@#1minorgrids\endcsname
	% these lists need to be global such that I can fill them inside
	% of \foreach statements. And, yes: I have also added a TeX group
	% on my own (but that's not the problem).
	\global\pgfplotslistnewempty\pgfplots@prepared@tick@positions@major
	%\global\pgfplotslistnewempty\pgfplots@prepared@tick@positions@major@tickindices
	\global\pgfplotslistnewempty\pgfplots@prepared@tick@positions@minor
	%
	\pgfplots@prepare@tick@coordlists@for@handletolerance#1%
	%
	\edef\pgfplots@loc@TMPa{#2}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
	\else
		\ifpgfplots@minorticks
			\pgfplots@needsminorlooptrue
		\else
			\ifpgfplots@minorgrids
				\pgfplots@needsminorlooptrue
			\else
				\pgfplots@needsminorloopfalse
			\fi
		\fi
		\pgfkeysgetvalue{/pgfplots/minor #1tick}\pgfplots@minor@tick@list
		\ifx\pgfplots@minor@tick@list\pgfutil@empty
		\else
			\pgfplots@needsminorloopfalse
		\fi
		%
		\ifpgfplots@needsminorloop
			\ifpgfplots@islinear
				\pgfkeysgetvalue{/pgfplots/minor #1 tick num}\pgfplots@minor@tick@num
				\begingroup
				\c@pgf@counta=\pgfplots@minor@tick@num\relax
				\advance\c@pgf@counta by1\relax
				\pgfplots@tmpa=\csname pgfplots@tick@distance@#1\endcsname pt %
				\divide\pgfplots@tmpa by\c@pgf@counta
				\edef\pgfmathresult{\pgf@sys@tonumber{\pgfplots@tmpa}}%
				\pgfmath@smuggleone\pgfmathresult
				\endgroup
				\let\pgfplots@minor@tick@dist=\pgfmathresult
			\else
				\def\pgfplots@minor@tick@num{9}%
			\fi
		\fi
		%
		% Prepare the [xy]tick[min|max] key processing:
		\let\pgfplots@checktickminmax=\pgfutil@empty
		\expandafter\ifx\csname pgfplots@#1tickmin\endcsname\pgfutil@empty
		\else
			\expandafter\def\expandafter\pgfplots@checktickminmax\expandafter{%
				\pgfplots@checktickminmax
				\pgfplots@prepare@tick@coordlists@for@checktickmin#1%
			}%
		\fi
		\expandafter\ifx\csname pgfplots@#1tickmax\endcsname\pgfutil@empty
		\else
			\expandafter\def\expandafter\pgfplots@checktickminmax\expandafter{%
				\pgfplots@checktickminmax
				\pgfplots@prepare@tick@coordlists@for@checktickmax#1%
			}%
		\fi
		%
		%
		\gdef\pgfplots@glob@TMPa{0}%
		\foreach \x in {#2} {%
			\let\pgfplots@ticknum=\pgfplots@glob@TMPa
			%
			\pgfplots@prepare@tick@coordlists@for@assign\pgfplots@tmpa=\x
			\csname pgfplots@#1tick@check@tickshow\endcsname
			\pgfplots@prepare@tick@coordlists@for@checkdatalimits#1%
			\pgfplots@checktickminmax
			%
			\ifpgfplots@tickshow
				\edef\x{{\pgfplots@ticknum}{\x}}%
				\expandafter\pgfplotslistpushbackglobal\x\to\pgfplots@prepared@tick@positions@major
				%\expandafter\pgfplotslistpushbackglobal\pgfplots@ticknum\to\pgfplots@prepared@tick@positions@major@tickindices
			\fi
			% X-Axis ticks bottom and top
			\ifpgfplots@needsminorloop
				% SEE BELOW for the 'minor #1tick' feature -- it has a
				% separate loop.
				\foreach \pgfplots@i in {1,...,\pgfplots@minor@tick@num} {%
					\ifpgfplots@islinear
						\pgfmathmultiply@{\pgfplots@i}{\pgfplots@minor@tick@dist}%
					\else
						% in log:
						%  log( i*10^k ) = log\pgfplots@i + k\log10 -> draw ticks for i=1..9
						\pgfplotscoordmath{#1}{log unsigned int}{\pgfplots@i}%
						\pgfplotscoordmath{#1}{tofixed}{\pgfmathresult}%
					\fi
					\pgfplots@prepare@tick@coordlists@for@advance\pgfplots@tmpa by\pgfmathresult
					\pgfplots@tickshowtrue
					\pgfplots@prepare@tick@coordlists@for@checkdatalimits#1%
					\pgfplots@checktickminmax
					\ifpgfplots@tickshow
						\pgfplots@prepare@tick@coordlists@for@tofixed\pgfplots@tmpa
						\c@pgf@counta=\pgfplots@ticknum\relax
						\advance\c@pgf@counta by\pgfplots@i\relax
						\edef\x{{\the\c@pgf@counta}{\pgfmathresult}}%
						\expandafter\pgfplotslistpushbackglobal\x\to\pgfplots@prepared@tick@positions@minor
					\fi
				}%
			\fi
			\pgfplotsutil@advancestringcounter\pgfplots@ticknum
			% carry \ticknum outside of this scope:
			\global\let\pgfplots@glob@TMPa=\pgfplots@ticknum
		}%
		%
		\ifx\pgfplots@minor@tick@list\pgfutil@empty
		\else
			% handle the 'minor #1tick' feature:
			\def\pgfplots@loc@TMPa{\foreach \x in }%
			\expandafter\pgfplots@loc@TMPa\expandafter{\pgfplots@minor@tick@list} {%
				\let\pgfplots@ticknum=\pgfplots@glob@TMPa
				%
				\pgfplots@prepare@tick@coordlists@for@assign\pgfplots@tmpa=\x
				\pgfplots@tickshowtrue
				\pgfplots@prepare@tick@coordlists@for@checkdatalimits#1%
				\pgfplots@checktickminmax
				\ifpgfplots@tickshow
					\edef\x{{\pgfplots@ticknum}{\x}}%
					\expandafter\pgfplotslistpushbackglobal\x\to\pgfplots@prepared@tick@positions@minor
				\fi
				\pgfplotsutil@advancestringcounter\pgfplots@ticknum
				% carry \ticknum outside of this scope:
				\global\let\pgfplots@glob@TMPa=\pgfplots@ticknum
			}%
		\fi
	\fi
	\endgroup
	\expandafter\let\csname pgfplots@prepared@tick@positions@minor@#1\endcsname=\pgfplots@prepared@tick@positions@minor
	\expandafter\let\csname pgfplots@prepared@tick@positions@major@#1\endcsname=\pgfplots@prepared@tick@positions@major
	%\expandafter\let\csname pgfplots@prepared@tick@positions@major@tickindices@#1\endcsname=\pgfplots@prepared@tick@positions@major@tickindices
	\global\let\pgfplots@prepared@tick@positions@major=\relax
	%\global\let\pgfplots@prepared@tick@positions@major@tickindices=\relax
	\global\let\pgfplots@prepared@tick@positions@minor=\relax
}%

% The following set of macros can be used to replace the TeX register
% arithmetics used to speed up the computations inside of
% \pgfplots@prepare@tick@coordlists@for by something different.
%
% FIXME : that is no clean programming! Perhaps a new math class
% should be used here, and implemented during the complete tick
% preparation!?
%
% Keep in mind that these tick positions are in "transformed
% range", i.e. they are expected to be in the range -16000...16000. At
% the time of this modification, only the smithchart lib needs special
% handling here... does this justify a re-design?
\def\pgfplots@prepare@tick@coordlists@for@assign#1=#2{%
	#1=#2pt
}%
\def\pgfplots@prepare@tick@coordlists@for@advance#1by#2{%
	\advance#1 by#2 pt %
}%
\def\pgfplots@prepare@tick@coordlists@for@tofixed#1{%
	\edef\pgfmathresult{\pgf@sys@tonumber{#1}}%
}%
\def\pgfplots@prepare@tick@coordlists@for@handletolerance#1{%
	\afterassignment\pgfplots@gobble@until@relax
	\pgfplots@tmpa=\pgfkeysvalueof{/pgfplots/#1tick placement tolerance}pt\relax
	\pgfplots@tmpa=\csname pgfplots@#1@inverseveclength\endcsname\pgfplots@tmpa
	\edef\pgfplots@loc@tick@placement@tolerance{\the\pgfplots@tmpa}%
	%
	\advance\csname pgfplots@#1min@reg\endcsname by-\pgfplots@tmpa
	\advance\csname pgfplots@#1max@reg\endcsname by\pgfplots@tmpa
}%
\def\pgfplots@prepare@tick@coordlists@for@checktickmin#1{%
	\ifdim\pgfplots@tmpa<\csname pgfplots@#1tickmin\endcsname pt
		\pgfplots@tickshowfalse
	\fi
}%
\def\pgfplots@prepare@tick@coordlists@for@checktickmax#1{%
	\ifdim\pgfplots@tmpa>\csname pgfplots@#1tickmax\endcsname pt
		\pgfplots@tickshowfalse
	\fi
}%
\def\pgfplots@prepare@tick@coordlists@for@checkdatalimits#1{%
	\ifdim\pgfplots@tmpa<\csname pgfplots@#1min@reg\endcsname
		\pgfplots@tickshowfalse
	\else
		\ifdim\pgfplots@tmpa>\csname pgfplots@#1max@reg\endcsname
			\pgfplots@tickshowfalse
		\fi
	\fi
}%

% Unpacks entries of the \pgfplots@prepared@tick@positions@* lists.
%
% Defines \pgfplots@tick to be the actual tick position and
% \pgfplots@ticknum to be its index.
%
% Usage:
% \expandafter\pgfplots@prepared@tick@pos@unpack\entry
\def\pgfplots@prepared@tick@pos@unpack#1#2{%
	\def\pgfplots@tick{#2}%
	\def\pgfplots@ticknum{#1}%
}

% Draws grid lines at the a-positions of the currently set oriented
% surface.
%
% Tick positions are taken out of the already precomputed list
% \pgfplots@prepared@tick@positions@major@...
%
% See \pgfplots@drawticklines@onorientedsurf@ for a description of the
% oriented surface.
%
% #1 : the verbatim axis name (either 'x' or 'y')
% #2 : the index of the axis  (either 0 or 1)
\def\pgfplots@drawgridlines@onorientedsurf{%
	\expandafter\pgfplots@drawgridlines@onorientedsurf@\pgfplotspointonorientedsurfaceA
}%
\def\pgfplots@drawgridlines@onorientedsurf@#1{%
	\pgfplots@if{pgfplots@shownothingof@\pgfplotspointonorientedsurfaceB}{%
		\relax
	}{%
		\begingroup
		\pgfplots@ifgridlines@onorientedsurf@should@be@drawn{%
			\expandafter\let\expandafter\pgfplots@prepared@tick@positions@major@\csname pgfplots@prepared@tick@positions@major@#1\endcsname
			\expandafter\let\expandafter\pgfplots@prepared@tick@positions@minor@\csname pgfplots@prepared@tick@positions@minor@#1\endcsname
			\pgfplots@loop@CONTINUEfalse
			\pgfplots@if{pgfplots@#1majorgrids}{\pgfplots@loop@CONTINUEtrue}{}%
			\pgfplots@if{pgfplots@#1minorgrids}{\pgfplots@loop@CONTINUEtrue}{}%
			\ifpgfplots@loop@CONTINUE
				% I support only ONE layer for both, minor and major
				% grid lines -- no distinction! I am lazy... FIXME
				\pgfplotsgetlayerforstyle{%
					every axis grid,%
					every minor grid,%
					every axis #1 grid,%
					every major grid,%
					every minor #1 grid,%
					every major #1 grid%
				}%
				\pgfplotsonlayer{\pgfplotsretval}{#1 grid style}%
				\scope
				\pgfplots@drawgridlines@INSTALLCLIP@onorientedsurf#1%
				%
				\pgfplots@if{pgfplots@#1minorgrids}{%
					\draw[%
						/pgfplots/every axis grid,
						/pgfplots/every minor grid,
						/pgfplots/every axis #1 grid,
						/pgfplots/every minor #1 grid]%
					\pgfextra
					\pgfplotslistforeach\pgfplots@prepared@tick@positions@minor@\as\pgfplots@curgridpos{%
						\expandafter\pgfplots@prepared@tick@pos@unpack\pgfplots@curgridpos
						\pgfplots@drawgridlines@onorientedsurf@fromto\pgfplots@tick
					}%
					\endpgfextra;
				}{}%
				%
				\pgfplots@if{pgfplots@#1majorgrids}{%
					\draw[%
						/pgfplots/every axis grid,
						/pgfplots/every major grid,
						/pgfplots/every axis #1 grid,
						/pgfplots/every major #1 grid]%
					\pgfextra
					\pgfplotslistforeach\pgfplots@prepared@tick@positions@major@\as\pgfplots@curgridpos{%
						\expandafter\pgfplots@prepared@tick@pos@unpack\pgfplots@curgridpos
						\pgfplots@drawgridlines@onorientedsurf@fromto\pgfplots@tick
					}%
					\endpgfextra;
				}{}%
				%
				\endscope
				\endpgfplotsonlayer
			\fi
		}{}%
		\endgroup
	}%
}

% Should draw a single grid line on the actual oriented surface.
% #1 the value of the grid line.
%
% PRECONDITION
% 	\pgfplots@ticknum contains the index of the current tick.
\def\pgfplots@drawgridlines@onorientedsurf@fromto#1{%
	\pgfpathmoveto{\pgfplotspointonorientedsurfaceab{#1}{\csname pgfplots@\pgfplotspointonorientedsurfaceB min\endcsname}}%
	\pgfpathlineto{\pgfplotspointonorientedsurfaceab{#1}{\csname pgfplots@\pgfplotspointonorientedsurfaceB max\endcsname}}%
}%

% Draws ticks on the currently active "oriented surface".
%
% The oriented surface is two dimensional and has been initialised
% with \pgfplotspointonorientedsurfaceabsetupfor*** somehow.
%
% The idea is now the following: 
% - the tick positions change along the FIRST coordinate of this
%   surface:
%
%   x ---- x ---- x ---- x
%   --> FIRST -->
%
% - the tick lines are drawn along the SECOND coordinate of this
%   surface:
%
%   | ---- | ---- | ---- |   | SECOND
%   |      |      |      |   v
%
% for example, 
% \pgfplotspointonorientedsurfaceab@setupfor@xyZ{1}
% \pgfplots@drawticklines@onorientedsurf
% will draw ticks at x-positions designated by \pgfplots@xtick. The
% small tick lines will be drawn along the y axis.  For each processed
% point, the z coordinate will be fixed to '1'.
%
% Another example:
% \pgfplotspointonorientedsurfaceab@setupfor@yxZ{-1}
% \pgfplots@drawticklines@onorientedsurf
% will draw ticks at y-positions designated by \pgfplots@ytick. The
% small tick lines will be drawn along the x axis.  For each processed
% point, the z coordinate will be fixed to '-1'.
% 
% Tick positions are taken out of the already precomputed list
% \pgfplots@prepared@tick@positions@major@...
\def\pgfplots@drawticklines@onorientedsurf{%
	\expandafter\pgfplots@drawticklines@onorientedsurf@\pgfplotspointonorientedsurfaceA
}%

\def\pgfplots@drawticklines@INSTALLCLIP@onorientedsurf#1{%
	\pgfplots@drawtickgridlines@INSTALLCLIP@onorientedsurf{#1}%
}%
\def\pgfplots@drawgridlines@INSTALLCLIP@onorientedsurf#1{%
	\pgfplots@drawtickgridlines@INSTALLCLIP@onorientedsurf{#1}%
}%
% Avoids tick lines which are too thick by introducing a clipping
% region. Tick lines (and grid lines) won't extend to the left or
% right of axis #1.
\def\pgfplots@drawtickgridlines@INSTALLCLIP@onorientedsurf#1{%
	\ifpgfplots@enable@tick@line@clipping
		% this is LEGACY SUPPORT only. I did not want to change
		% existing bounding boxes.
		% Starting with 'compat=1.11', this is OFF.
		\pgfplots@drawtickgridlines@INSTALLCLIP@onorientedsurf@{#1}%
	\fi
}
\def\pgfplots@drawtickgridlines@INSTALLCLIP@onorientedsurf@#1{%
	\pgfinterruptboundingbox%
	\begingroup
		% the case ||e_b|| == 0 should never happen here! Should be
		% caught before entering this routine.
		\let\pgfplots@loc@LENGTH=\pgfmathresult
		\expandafter\let\expandafter\pgfplots@loc@MIN\csname pgfplots@\pgfplotspointonorientedsurfaceB min\endcsname
		\expandafter\let\expandafter\pgfplots@loc@MAX\csname pgfplots@\pgfplotspointonorientedsurfaceB max\endcsname
		\pgfpathmoveto{\pgfplotspointonorientedsurfaceabwithbshift{\csname pgfplots@#1min\endcsname}{\pgfplots@loc@MIN}{-5cm}}%
		\pgfpathlineto{\pgfplotspointonorientedsurfaceabwithbshift{\csname pgfplots@#1max\endcsname}{\pgfplots@loc@MIN}{-5cm}}%
		\pgfpathlineto{\pgfplotspointonorientedsurfaceabwithbshift{\csname pgfplots@#1max\endcsname}{\pgfplots@loc@MAX}{5cm}}%
		\pgfpathlineto{\pgfplotspointonorientedsurfaceabwithbshift{\csname pgfplots@#1min\endcsname}{\pgfplots@loc@MAX}{5cm}}%
		\pgfusepath{clip}%
	\endgroup
	\endpgfinterruptboundingbox%
}%

\def\pgfplots@drawticklines@onorientedsurf@#1{%
	\pgfplots@if{pgfplots@shownothingof@\pgfplotspointonorientedsurfaceB}{%
		\relax
	}{%
		\begingroup
		% FIXME : the case of centered axis lines is missing here.
		% 0 = lower limit,
		% 1 = upper limit
		% 2 = centered...
		% Currently, "0" is also used for centered axis lines.
		\if 2\csname pgfplots@\pgfplotspointonorientedsurfaceA axislinesnum\endcsname
			% centered axis lines need no complicated visibility
			% checks. They need tick lines in *any* case.
			% So, enabled them here!
			\def\pgfplots@drawticklines@for@placecomputedtick@LOWEROK{1}%
			%
			% UPPEROK is unnecessary in this context - for centered
			% axis lines, it will be disabled anyway because the
			% styles like 'axis x line*' set \pgfplots@xticknum to
			% center - and that means that no tick lines will be drawn
			% (see below).
			\def\pgfplots@drawticklines@for@placecomputedtick@UPPEROK{0}%
		\else
			\pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn{0}{%
				\def\pgfplots@drawticklines@for@placecomputedtick@LOWEROK{1}%
			}{%
				\def\pgfplots@drawticklines@for@placecomputedtick@LOWEROK{0}%
			}%
			\pgfplots@ifaxisline@B@onorientedsurf@should@be@drawn{1}{%
				\def\pgfplots@drawticklines@for@placecomputedtick@UPPEROK{1}%
			}{%
				\def\pgfplots@drawticklines@for@placecomputedtick@UPPEROK{0}%
			}%
		\fi
		\if\pgfkeysvalueof{/pgfplots/\pgfplotspointonorientedsurfaceB\space dir/value}r%
			% local special handling for reversed axes: exchange
			% meaning of 'left' and 'right' here.
			%
			% the rest of the pgfplots code does that automatically because
			% there, tickposnum is relevant to determine the axes
			% which contains tick labels. And this algorithm checks
			% for reversed axes implicitly.
			%
			\if1\csname pgfplots@\pgfplotspointonorientedsurfaceA tickposnum\endcsname
				\expandafter\def\csname pgfplots@\pgfplotspointonorientedsurfaceA tickposnum\endcsname{3}%
			\else
				\if3\csname pgfplots@\pgfplotspointonorientedsurfaceA tickposnum\endcsname
					\expandafter\def\csname pgfplots@\pgfplotspointonorientedsurfaceA tickposnum\endcsname{1}%
				\fi
			\fi
		\fi
		\ifcase\csname pgfplots@\pgfplotspointonorientedsurfaceA tickposnum\endcsname\relax
			% both
		\or
			% lower
			\def\pgfplots@drawticklines@for@placecomputedtick@UPPEROK{0}%
		\or
			% center
			\def\pgfplots@drawticklines@for@placecomputedtick@UPPEROK{0}%
		\or
			% upper
			\def\pgfplots@drawticklines@for@placecomputedtick@LOWEROK{0}%
		\else
			% never used?
			\def\pgfplots@drawticklines@for@placecomputedtick@UPPEROK{0}%
		\fi
		\expandafter\let\expandafter\pgfplots@prepared@tick@positions@major@\csname pgfplots@prepared@tick@positions@major@#1\endcsname
		\expandafter\let\expandafter\pgfplots@prepared@tick@positions@minor@\csname pgfplots@prepared@tick@positions@minor@#1\endcsname
		%
		% There is only ONE layer for both, minor and major
		% tick lines -- no distinction!
		\pgfplotsgetlayerforstyle{%
			every tick,%
			every minor tick,%
			every #1 tick,%
			every major tick,%
			every minor #1 tick,%
			every major #1 tick%
		}%
		\pgfplotsonlayer{\pgfplotsretval}{#1tick style}%
		\scope
		\pgfplots@drawticklines@INSTALLCLIP@onorientedsurf#1
		%
		\pgfplots@if{pgfplots@#1minorticks}{%
			\draw[%
				/pgfplots/every tick,
				/pgfplots/every minor tick,
				/pgfplots/every #1 tick,
				/pgfplots/every minor #1 tick]%
			\pgfextra
			\pgfmathparse{\pgfplots@subtickwidth}%
			\let\pgfplots@subtickwidth@=\pgfmathresult
			\let\pgfplots@subtickwidth@=\pgfmathresult
			\let\pgfplots@subtickwidth=\pgfmathresult
			\pgfplots@prepare@tick@offsets@for@{#1}{\pgfplots@subtickwidth@}%
			\pgfplotslistforeach\pgfplots@prepared@tick@positions@minor@\as\pgfplots@curtickpos{%
				\expandafter\pgfplots@prepared@tick@pos@unpack\pgfplots@curtickpos
				\let\pgfplots@curtickpos=\pgfplots@tick
				\pgfplotspointouternormalvectorofaxissetv{}{\pgfplots@curtickpos}%
				\pgfplots@drawticklines@for@placecomputedtick
			}%
			\endpgfextra;
		}{}%
		%
		\pgfplots@if{pgfplots@#1majorticks}{%
			\draw[%
				/pgfplots/every tick,
				/pgfplots/every major tick,
				/pgfplots/every #1 tick,
				/pgfplots/every major #1 tick]%
			\pgfextra
			\pgfmathparse{\pgfplots@tickwidth}%
			\let\pgfplots@tickwidth@=\pgfmathresult
			\let\pgfplots@tickwidth@=\pgfmathresult
			\let\pgfplots@tickwidth=\pgfmathresult
			\pgfplots@prepare@tick@offsets@for@{#1}{\pgfplots@tickwidth@}%
			\pgfplotslistforeach\pgfplots@prepared@tick@positions@major@\as\pgfplots@curtickpos{%
				\expandafter\pgfplots@prepared@tick@pos@unpack\pgfplots@curtickpos
				\let\pgfplots@curtickpos=\pgfplots@tick
				\pgfplotspointouternormalvectorofaxissetv{}{\pgfplots@curtickpos}%
				\pgfplots@drawticklines@for@placecomputedtick
			}%
			\endpgfextra;
		}{}%
		%
		\endscope
		\endpgfplotsonlayer
		\endgroup
	}%
}

% Draws tick labels at the positions of the currently set oriented
% surface.
%
% Tick positions are taken out of the already precomputed list
% \pgfplots@prepared@tick@positions@major@...
%
% For 2D axes, this task is relatively simple:
% we iterate through every prepared major tick position and place a
% tick label. Open points, however, are the question whether to use
% the RIGHT or the LEFT axis line on the current oriented surface:
%
%        direction 'b' (second oriented)
% |-------------------------|
% |                         |
% |                         |
% |                         |direction 'a' (first oriented)
% |                         |
% |                         |
% |                         |
% |-------------------------|
% Left                  Right
%
% Given the axis line which shall contain the labels, we have to
% decide how to align the tick label nodes: on the left or on the
% right? Of course, we want to align them such that they are "outside"
% of the figure! That's simple as well: "Left axis line => outside
% means left", "Right axis line => outside means right".
%
% That's all, basically.
%
% For 3D axes, all these points are basically ... the same! 
% Now it can happen that the current oriented surface shall
% not contain ANY tick label. In that case, we do nothing.
% Furthermore, the "outside" direction (i.e. the anchoring of the
% label nodes) is a little bit more difficult.
% 
%
% See \pgfplots@drawticklines@onorientedsurf@ for a description of the
% oriented surface.
\def\pgfplots@drawticklabels@onorientedsurf{%
	\expandafter\pgfplots@drawticklabels@onorientedsurf@\pgfplotspointonorientedsurfaceA
}
\def\pgfplots@drawticklabels@onorientedsurf@#1{%
	\begingroup
	\expandafter\let\expandafter\pgfplots@prepared@tick@positions@major@\csname pgfplots@prepared@tick@positions@major@#1\endcsname
	% check whether
	% - we need to place tick labels on the LEFT side,
	% - we need to place tick labels on the RIGHT side,
	% - we don't need tick labels for the current surface at all:
	\pgfplotspointonorientedsurfaceabmatchaxisline{\csname pgfplots@#1ticklabelaxisspec\endcsname}{\pgfplots@ticklabelside}%
	\ifx\pgfplots@ticklabelside\pgfutil@empty
		% SKIP. The current oriented surface shall not get tick labels
		% for #1.
	\else
		\pgfplots@if{pgfplots@#1majorticks}{%
			\pgfplots@if{pgfplots@#1islinear}{%
				\pgfplots@init@scaled@tick@for{#1}%
			}{\relax}%
			\begingroup
			\pgfplotsgetlayerforstyle{every tick label,every #1 tick label}%
			\pgfplotsonlayer\pgfplotsretval{#1tick label style}%
			\pgfkeysalso{/tikz/every node/.append style={/pgfplots/every tick label,/pgfplots/every #1 tick label}}%
			\pgfplots@drawticklabels@onorientedsurf@prepareanchor#1%
			%
			\pgfplotsmath@ifzero{\csname pgfplots@\pgfplotspointonorientedsurfaceB @veclength\endcsname}{%
				\def\pgfplots@tick@offset{0}%
			}{%
				\ifcase\csname pgfplots@#1tickalignnum\endcsname\relax
					\def\pgfmathresult{0}%
				\or
					\pgfmathparse{\pgfplots@tickwidth}%
				\or
					\pgfmathmultiply{0.5}{\pgfplots@tickwidth}%
				\fi
				\let\pgfplots@tick@offset=\pgfmathresult
				\pgfplots@ticklabel@maxtickdimen@extrashift{#1}{\pgfplots@tick@offset}%
				%\pgfmathmultiply@{\pgfplots@tick@offset}{\csname pgfplots@\pgfplotspointonorientedsurfaceB @inverseveclength\endcsname}%
				\let\pgfplots@tick@offset=\pgfmathresult
			}%
			%				
			\if2\csname pgfplots@#1axislinesnum\endcsname % Centered axis lines?
				\expandafter\let\expandafter\pgfplots@tick@origin\csname pgfplots@logical@ZERO@\pgfplotspointonorientedsurfaceB\endcsname%
				% FIXME : that stuff here does not respect
				% '[xyz]tickpos num' keys!
				\pgfplots@tickposchoiceb%<-- backw. compat, is usually empty.
				\if r\pgfkeysvalueof{/pgfplots/\pgfplotspointonorientedsurfaceB\space dir/value}%
					% special handling for reversed axes.
					\pgfmathmultiply{-1}{\pgfplots@tick@offset}%
					\let\pgfplots@tick@offset=\pgfmathresult
				\fi
				\edef\pgfplots@tick@offset{-\pgfplots@tick@offset}%
				%\pgfmathsubtract@{\pgfplots@tick@origin}{\pgfplots@tick@offset}%
			\else
				\if0\pgfplots@ticklabelside
				 	\expandafter\let\expandafter\pgfplots@tick@origin\csname pgfplots@\pgfplotspointonorientedsurfaceB min\endcsname%
					\pgfplots@tickposchoiceb%<-- backw. compat, is usually empty.
					%\pgfmathsubtract@{\pgfplots@tick@origin}{\pgfplots@tick@offset}%
					\edef\pgfplots@tick@offset{-\pgfplots@tick@offset}%
				\else
					\if1\pgfplots@ticklabelside
						\expandafter\let\expandafter\pgfplots@tick@origin\csname pgfplots@\pgfplotspointonorientedsurfaceB max\endcsname%
						\pgfplots@tickposchoicea%<-- backw. compat, is usually empty.
						%\pgfmathadd@{\pgfplots@tick@origin}{\pgfplots@tick@offset}%
					\else
						% FIXME : ticklabelside == 2 is, in principle,
						% a valid choice. It is the case handled with
						% "if 2 == pgfplots@#1axislinesnum" above,
						% isn't it!?
						\expandafter\let\expandafter\pgfplots@tick@origin\csname pgfplots@logical@ZERO@\pgfplotspointonorientedsurfaceB\endcsname%
						% FIXME : is that correct!?
						\pgfplots@tickposchoiceb%<-- backw. compat, is usually empty.
						%\pgfmathsubtract@{\pgfplots@tick@origin}{\pgfplots@tick@offset}%
						%\edef\pgfplots@tick@offset{-\pgfplots@tick@offset}%
						%
						\if2\pgfplots@ticklabelside
						\else
							% Should never happen.
							\pgfplots@error{Internal logic error during tick label placement (got placement character '\pgfplots@ticklabelside'). 
									Please report this as a bug or verify your input arguments to #1ticklabel pos.}%
						\fi
					\fi
				\fi
			\fi
			%\let\pgfplots@tick@origin=\pgfmathresult%
			\edef\pgfplots@tick@offset{\pgfplots@tick@offset pt}%
			%
			% make sure the \pgfmathlogtologten method works even for
			% non-standard 'log basis #1':
			\def\pgfmathlogtologten@{\pgfplotscoordmath{#1}{log to log 10}}%
			%
			\xdef\pgfplots@show@ticklabel@LASTTICK{}%
			\pgfplotslistforeachungrouped\pgfplots@prepared@tick@positions@major@\as\pgfplots@curtickpos{%
				\expandafter\pgfplots@prepared@tick@pos@unpack\pgfplots@curtickpos
				\let\pgfplots@curtickpos=\pgfplots@tick
				%\expandafter\pgfplotslistpopfront\csname pgfplots@prepared@tick@positions@major@tickindices@#1\endcsname\to\pgfplots@ticknum
				\pgfplotspointouternormalvectorofaxissetv{}{\pgfplots@curtickpos}%
				\pgfplots@show@ticklabel
					{#1}{\pgfplots@curtickpos}(\pgfplots@curtickpos,\pgfplots@tick@origin+\pgfplots@tick@offset)%
					{\pgfplots@ticknum}%
			}%
			\pgfplots@ticklabel@maxtickdimen@finish{#1}%
			\endpgfplotsonlayer
			\endgroup
			\pgfplots@draw@tick@scale@label@for #1%
		}%
		{\relax}% if...@major==false
	\fi
	\endgroup
}

% This here does the main work for any tick label ANCHORING.
%
% FIXME : the new 'near ticklabel' anchors are now the default method
% to place tick labels.
%
% This feature here can be used to disable this anchoring, i.e. set
% 'ticklabel anchor=tikz' to use a stupid heuristics.
%
% There are actually two choices:
% Choice 1: near ticklabel
% 	This choice places tick labels fully automatic outside of the
% 	figure, all on a line which is parallel to the axis which
% 	contains the corresponding tick labels.
%
% 	Since we are currently working on a restricted surface, we have
% 	three direction related to that surface:
% 		'a': this is the direction in which tick positions are known.
% 		'b': the 'orthogonal' axis to 'a' which is also in the surface.
% 		'n': the surface normal.
% 	Now, the idea for tick labels is to place them at 
% 		SCALE_b * b + SCALE_n * n,
% 	where the SCALE_[bn] numbers are choosen such that the label is
% 	outside of the axis.
%
% 	The offset is simply added to the transformation matrix (as a
% 	shift).
%
% Choice 2: tikz.
%   This is more or less a backwards compatibility feature. It does
%   not change the transformation matrix. It simply sets the 'at' key
%   of each node to the tick position and prepares the correct anchors
%   for the TikZ '\node' commands.
%   That's all here.
%
% PRECONDITION:
%   - called inside of  \pgfplots@drawticklabels@onorientedsurf@
% POSTCONDITION:
% 	- defines 
% 		- \pgfplots@tickposchoicea
% 			if called, sets keys such that tick labels are RIGHT (TOP) of
% 			the axis,
%
% 		- \pgfplots@tickposchoiceb
% 			if called, sets keys such that tick labels are LEFT
% 			(BOTTOM) of the axis,
\def\pgfplots@drawticklabels@onorientedsurf@prepareanchor#1{%
	\if\csname pgfplots@ticklabel@anchor@#1\endcsname0%
		% auto is the same as 'near ticklabel':
		\expandafter\def\csname pgfplots@ticklabel@anchor@#1\endcsname{1}%
	\fi
	\ifcase\csname pgfplots@ticklabel@anchor@#1\endcsname%
		% 0: doesn't happen, see above.
	\or
		% 1: near ticklabel.
		% The following code contains automatically
		% aligned tick labels (especially for 3D axes). 
		% see the manual for the |near ticklabel| anchors.
		\pgfkeys{/tikz/anchor=near #1ticklabel}%
		%
		% process the (optional) ticklabel distance:
		\begingroup
			\pgfkeysgetvalue{/pgfplots/#1ticklabel shift}\pgfmathresult
			\ifx\pgfmathresult\pgfutil@empty
			\else
				\afterassignment\pgfplots@gobble@until@relax
				\pgf@xa=\pgfkeysvalueof{/pgfplots/#1ticklabel shift}pt\relax
				\multiply\pgf@xa by-1 % the direction vector points to the INSIDE. the shift should have opposite sign.
				\edef\pgfmathresult{\pgf@sys@tonumber\pgf@xa}%
			\fi
			\pgfmath@smuggleone\pgfmathresult
		\endgroup
		\let\pgfplots@loc@TMPc=\pgfmathresult
		\ifx\pgfplots@loc@TMPc\pgfutil@empty
		\else
			\pgfplotspointouternormalvectorofaxis@ifdependson@v{\pgfplotsticklabelaxisspec{#1}}{%
				\tikzset{every node/.append code={%
						\tikz@addtransform{%
							\pgftransformshift{%
								\pgfplotspointouternormalvectorofticklabelaxis{#1}%
								\pgfqpointscale{-\pgfplots@loc@TMPc}{}%
							}%
						}%
					}%
				}%
			}{%
				\pgftransformshift{%
					\pgfplotspointouternormalvectorofticklabelaxis{#1}%
					\pgfqpointscale{-\pgfplots@loc@TMPc}{}%
				}%
			}%
		\fi
		%
		% these things are irrelevant here:
		\let\pgfplots@tickposchoicea=\pgfutil@empty
		\let\pgfplots@tickposchoiceb=\pgfutil@empty
	\or
		% 2: tikz.
		% We simply prepare the default anchor.
		% Actually, this code is just for backwards compatibility -
		% there may be people who prefer to set anchors. The
		% 'near ticklabel' implementation is much more general, however.
		\if\pgfplotspointonorientedsurfaceB x
			\def\pgfplots@tickposchoicea{\tikzset{right}}%
			\def\pgfplots@tickposchoiceb{\tikzset{left}}%
		\else
			\if\pgfplotspointonorientedsurfaceB y
				\def\pgfplots@tickposchoicea{\tikzset{above}}%
				\def\pgfplots@tickposchoiceb{\tikzset{below}}%
			\else
				\def\pgfplots@tickposchoicea{\tikzset{anchor=north east}}%
				\def\pgfplots@tickposchoiceb{\tikzset{anchor=south east}}%
			\fi
		\fi
	\fi
	\pgfplots@ticklabel@maxtickdimen@prepare@for@normalvec
		{#1}%
		{\pgfplotspointouternormalvectorofticklabelaxis{#1}}%
}%

\newif\ifpgfplots@checkuniform@isfirst
% Checks whether the argument to xtick or ytick is a UNIFORM tick
% sequence.
%
% A uniform tick sequence is 0,...,10 and 3,4,5 and -5,-4,-2 but 
% NOT 0,2,4 or 4,10.
%
% Furthermore, any NON-integer tick arguments are also assumed to be
% NOT uniform.
%
% INPUT:
% #1: a tick argument (i.e. something which can be put to 
%     \foreach \x in {#1})
%
% OUTPUT:
%    \pgfplots@isuniformticktrue
%    or
%    \pgfplots@isuniformtickfalse
% depending on the check.
% This variable will be set globally.
\def\pgfplots@checkisuniformLOGtick#1{%
	\begingroup
	\global\pgfplots@isuniformticktrue
	\pgfplots@checkuniform@isfirsttrue
	\foreach \x in {#1}{%
		\pgfmathmultiply@\x\reciproclogten
		\let\cur=\pgfmathresult
		% check whether
		%  \cur - last == 1 (last = \pgfplots@glob@TMPb)
		\ifpgfplots@checkuniform@isfirst
			\global\pgfplots@checkuniform@isfirstfalse
		\else
			\pgfmathsubtract@\cur\pgfplots@glob@TMPb%
			\pgfmathapproxequalto@\pgfmathresult{1.0}%
			\ifpgfmathcomparison
			\else
				\global\pgfplots@isuniformtickfalse
				\breakforeach
			\fi
		\fi
		\global\let\pgfplots@glob@TMPb=\cur
	}%
	\endgroup
}

% Checks whether the linear tick sequence #1 is a uniform tick.
%
% It also assigns pgfplots@tick@distance@#1  as the distance.
%
% see \pgfplots@checkisuniformLOGtick for details.
%
% #1: a tick sequence (expanded)
% #2: a macro which will be filled with the tick distance. This is
% only valid if \pgfplots@isuniformticktrue.
\def\pgfplots@checkisuniformLINEARtick#1#2{%
	\begingroup
	\global\pgfplots@isuniformticktrue
	\pgfplots@checkuniform@isfirsttrue
	\global\let\pgfplots@glob@TMPb=\pgfutil@empty
	\global\def\pgfplots@glob@TMPa{1}%
	\foreach \x in {#1}{%
		\ifx\pgfplots@glob@TMPb\pgfutil@empty
		\else
			\pgfmathsubtract@\x\pgfplots@glob@TMPb
			\ifpgfplots@checkuniform@isfirst
				% remember first distance h = x_1 - x_0
				\global\let\pgfplots@glob@TMPa=\pgfmathresult
				\global\pgfplots@checkuniform@isfirstfalse
			\else
				% check whether x_i - x_{i-1} = h
				\pgfmathapproxequalto@\pgfmathresult\pgfplots@glob@TMPa%
				\ifpgfmathcomparison
				\else
					\global\pgfplots@isuniformtickfalse
					\breakforeach
				\fi
			\fi
		\fi
		\global\let\pgfplots@glob@TMPb=\x%
	}%
	\endgroup
	\let#2=\pgfplots@glob@TMPa
}

% helper method which computes log10*\x foreach \x in {#1}.
% The result will be \xdef'ed into #2.
%
% #1: the ticks
% #2: the output macro
% #3: the axis
\def\pgfplots@compute@tick@times@logten#1\to#2#3{%
	\global\let#2=\pgfutil@empty
	\foreach \pgfplots@loc@TMPb in {#1} {%
		\pgfplotscoordmath{#3}{log to display log}{\pgfplots@loc@TMPb}%
		\pgfplotscoordmath{#3}{tofixed}{\pgfmathresult}%
		\ifx#2\pgfutil@empty
			\xdef#2{\pgfmathresult}%
		\else
			\xdef#2{#2,\pgfmathresult}%
		\fi
	}%
}

% Computes tick positions using the current axis limits.
%
% Parameters:
% /pgfplots/max space between ticks
%    Determines the maximum space which is not filled by at least one
%    tick label (approximate, there is some rounding internally)
% /pgfplots/try min ticks
%    see manual
%
% Idea:
% We want ticks at each 
%    { i*H, i in \Z }.
% Of course, there shouldn't be TOO MUCH ticks. 
%
% Our heuristics is to set
%    desirednumticks = round(ACTUAL WIDTH / (max space between ticks) )
% and generate H = (axis range) / (desirednumticks).
%
% Since not all step sizes H look well, restrict H to a set of allowed 
% step sizes such as 
%   { 1, 1/2, 1/5, 1/10 },
% or, to be more precise:
%   { 1*10^e, 2*10^e, 5*10^e }
% -> round to the nearest matching number!
% This yields H (for example as 2*10^e). Then, compute i*H, i \in \Z
%
% The data scaling transformation T(x) makes things more complicated.
% Now, T(x) = q * x - p  and we need to check for problems with large
% numbers:
%   - q* H = ( T(Max) - T(Min) ) / desirednumticks = q * (Max - Min) / desirednumticks.
%   - Using floating point arithmetics, (Max-Min)/desirednumticks (unscaled!)
%   is analysed to restrict H to {1*10^e, 2*10^e, 5*10^e}.
%   - So, we get  q * H  (we can't use the 'p' shift of the affine trafo here).
%   - The next problem is to compute { I*H, I in \Z } because
%   	I = trunc( Min / H )  = trunc(  ( T(Min) + p ) / (q*H) ).
%     This can be seen by Min = I*H + rest   and thus T(Min) = I*q*H + q*rest -p.
%     The Problem: (T(min)+p ) / (q*H) can be TOO BIG for pgfmath.
%   -> for the data scaling case, I will use floating point
%   arithmetics to compute that last step.
%   I will acquire \pgfplots@[xy]min@unscaled@as@float here.
%     
%
%
%
%
% For log-plots, 
% 	H in { j*log(10), j=1,2,3,... }
% where the usual case should be j = 1.
%
% Then, the resulting tick is
% TICK={MIN,MIN+H,...,MAX}
% where
%    MIN = I*H
% is chosen such that 
%    axis minimum limit = I*H + rest; |rest| < H.
%
% Again, log plots follow a slightly different approach: here,
%   MIN = I * log(10)
% is chosen such that
%    axis minimum limit = I*log(10) + rest; |rest| < log(10)
% while H = j*log(10), j>=1.
%
%
% PRECONDITION:
% - limits are correct
% - axis width/height is set correctly
%
% POSTCONDITION:
% - Tick for axis #1 is assigned
% - \ifpgfplots@determinedefaultvalues@needs@check@uniformtick is set
%
% REMARKS:
% - this algorithms works also if the data range has been transformed
%   with a LINEAR transformation.
%   ATTENTION: as of 2008-05-15, the scaling trafo is AFFINE LINEAR.
%   That means we have to eliminate the 'affine' shifting before the
%   algorithms works correctly.
\def\pgfplots@assign@default@tick@foraxis#1{%
	\begingroup
	% Shortcut-names:
	\expandafter\let\expandafter\ifpgfplots@is@datascaled\csname ifpgfplots@apply@datatrafo@#1\endcsname
	% Attention here: use UNSHIFTET scalings, see remark above
	\expandafter\let\expandafter\ifpgfplots@cur@is@linear\csname ifpgfplots@#1islinear\endcsname
	%
	\let\desirednumticks=\c@pgf@countd
	\let\Wr=\pgf@xc
	\Wr=\csname pgfplotspoint#1axislength\endcsname\relax
	% r = max place without ticks in pt -> choose desirednumticks >= W/r
	\divide\Wr by\axisdefaulttickwidth\relax
	\afterassignment\pgfplots@gobble@until@relax
	\desirednumticks=\the\Wr\relax
	\advance\desirednumticks by1
	\csname ifpgfplots@#1islinear\endcsname
		\ifnum\axisdefaulttryminticks>\desirednumticks\relax
			\desirednumticks=\axisdefaulttryminticks\relax
		\fi
	\else
		\ifnum\pgfplots@default@try@minticks@log>\desirednumticks\relax
			\desirednumticks=\pgfplots@default@try@minticks@log\relax
		\fi
		\expandafter\ifx\csname pgfplots@#1tickten\endcsname\pgfutil@empty
		\else
			% log plot and tickten-option: provide special processing.
			\edef\pgfplots@loc@TMPa{\csname pgfplots@#1tickten\endcsname}%
			\expandafter\pgfplots@compute@tick@times@logten\pgfplots@loc@TMPa\to\pgfplots@glob@TMPa{#1}%
			\expandafter\let\csname pgfplots@#1tick\endcsname=\pgfplots@glob@TMPa
		\fi
	\fi
	\ifpgfplots@cur@is@linear
	\else
		\pgfplotscoordmath{#1}{parsenumber}{1}%
		\let\pgfplots@loc@TMPa=\pgfmathresult
		\pgfplotscoordmath{#1}{log from display log}{\pgfplots@loc@TMPa}%
		\pgfplotscoordmath{#1}{tofixed}{\pgfmathresult}%
		\let\pgfplots@loc@log@from@display@log@scale=\pgfmathresult
		%
		\pgfplotscoordmath{#1}{log to display log}{\pgfplots@loc@TMPa}%
		\pgfplotscoordmath{#1}{tofixed}{\pgfmathresult}%
		\let\pgfplots@loc@log@to@display@log@scale=\pgfmathresult
	\fi
	%
	\expandafter\ifx\csname pgfplots@#1tick\endcsname\pgfutil@empty
		% Ok, we have either log or linear axis and need default
		% ticks MIN,MIN+H,...,MAX.
		\let\MINH=\pgf@xa
		\let\H=\pgf@xb
		\let\MAX=\pgf@ya
		\let\MIN=\pgf@yb
		% compute step size 'H':
		\MAX=\csname pgfplots@#1max\endcsname pt %
		\advance\MAX by0.001pt % avoid round errors
		%\expandafter\MIN\the\c@pgf@counta pt
		\MIN=\csname pgfplots@#1min\endcsname pt %
		\H=\MAX
		\advance\H by-\MIN
		\ifdim\H<0pt \H=-1\H \fi
%\message{Axis limit #1: [\the\MIN:\the\MAX], diff = \the\H.^^J}%
		\c@pgf@counta=\desirednumticks
		\advance\c@pgf@counta by-1 %
		\divide\H by\c@pgf@counta
%\message{determining ticks for #1-axis: Wr := (width/max space between ticks) = \the\Wr, desirednumticks=max(\axisdefaulttryminticks, trunc(Wr)) = \the\desirednumticks, H#1=(axis range/(desirednumticks-1)) = \the\H^^J}%
		%
		% SEARCH for the NEXT FEASABLE H.
		\edef\Hmacro{\pgf@sys@tonumber\H}%
		\ifpgfplots@cur@is@linear
			% CASE LINEAR AXIS
			\ifpgfplots@is@datascaled
				% This here works if the scaling trafo is linear.
				\pgfplotscoordmath{#1}{datascaletrafo noshift inverse}{\Hmacro}%
				\let\Hmacro=\pgfmathresult
			\else
				\pgfmathfloatparsenumber{\Hmacro}%
				\let\Hmacro=\pgfmathresult
			\fi
%\message{Got T^{-1}(H#1) = \Hmacro^^J}%
			%
			\pgfplots@assign@default@tick@foraxis@normalizetickdist#1\Hmacro
			\let\Hmacro=\pgfmathresult
			%
%\message{snapped-to-nicest = \Hmacro^^J}%
			\aftergroup\pgfplots@isuniformticktrue
			% The following code is carried out in floating point
			% arithmetics because it requires large data ranges.
			%
			% I want to compute MIN@new := I*H  where I is chosen
			% such that MIN = I*H + rest with rest < H.
			% The problem is the possibly large range of MIN. I
			% can't work completely in the transformed datarange,
			% so numbers get too large.
			%
			% So, compute I := int( MIN / H )  (integer truncation)
			% in float arithmetics and then MIN@new := I*H
			\pgfmathfloatdivide@{\csname pgfplots@#1min@unscaled@as@float\endcsname}{\Hmacro}%
			\pgfmathfloatint@{\pgfmathresult}%
			\pgfmathfloatmultiply@{\pgfmathresult}{\Hmacro}%
			\let\MIN@new=\pgfmathresult
			% Ok, we are ready.
			% Now, convert everything into the fixed point data
			% range:
			\ifpgfplots@is@datascaled
				\pgfplotscoordmath{#1}{datascaletrafo}{\MIN@new}%
				\MIN=\pgfmathresult pt
				\pgfplotscoordmath{#1}{datascaletrafo noshift}{\Hmacro}%
				\H=\pgfmathresult pt
			\else
				\pgfmathfloattofixed\MIN@new
				\MIN=\pgfmathresult pt
				\pgfmathfloattofixed\Hmacro
				\H=\pgfmathresult pt
			\fi
			%
			% And, since we have used finite precision, I is most
			% likely to be large. So: subtract one H. In the worst
			% case, this produces one tick position too much (but
			% it won't be printed).
			\advance\MIN by-\H\relax
		\else
			% CASE LOG AXIS
			%
			% search for the "best" H= j* log(10),  j an integer.
			%
			% And prefer j=1 if that is possible (otherwise minor
			% ticks are not useful).
			\pgfmath@basic@multiply@{\Hmacro}{\pgfplots@loc@log@from@display@log@scale}%
			\let\Hmacrobaseten=\pgfmathresult
			\expandafter\H\pgfmathresult pt
%\message{ [ H / log(10) = \pgfmathresult ]}%
			\ifdim\H<2pt
				\H=1pt
			\else
				\ifnum\H<1pt
					\H=1pt
				\else
					\expandafter\pgfmathfloor\expandafter{\pgfmathresult}%
					\expandafter\H\pgfmathresult pt
				\fi
			\fi
			\ifdim\H=1pt
				\aftergroup\pgfplots@isuniformticktrue
				\pgfplots@isuniformticktrue
			\else
				\aftergroup\pgfplots@isuniformtickfalse
				\pgfplots@isuniformtickfalse
			\fi
%\message{final H=\pgf@sys@tonumber{\H} * log(10)}%
			\H=\pgfplots@loc@log@to@display@log@scale\H
			% Now, we want to activate the Tick set 
			%   {lowest, lowest+H, ..., highest}
			%
			% Where 
			% 	lowest =  I * log(10) + rest, |rest| < log(10).
			% this is conceptionally different from the approach for
			% linear axes, because H = j*log(10).
			%
			% remember the original xmin in MINH:
			\MINH=\MIN
			%
			% and compute I and I*log(10) here:
			\MIN=\pgfplots@loc@log@from@display@log@scale \MIN
			\edef\pgfmathresult{\pgf@sys@tonumber{\MIN}}%
			\pgfmathsetcount{\c@pgf@counta}{\pgfmathresult}%
			\ifdim\MIN<0pt
				% the truncation rounds TOWARDS 0 which is not what I want.
				\advance\c@pgf@counta by-1
			\fi
			\MIN=\pgfplots@loc@log@to@display@log@scale pt
			\multiply\MIN by\c@pgf@counta
			\ifpgfplots@isuniformtick
			\else
				% This here is a special case to move the first tick
				% near the lower axis limit.
				%
				% "Near" means either directly above or directly below ymin.
				% 
				% My application example is as follows:
				% Let H = 2*log(10).
				% Furthermore, ymin = 3e-6, ymax= 8e-2. That means we can choose either
				%    10^{-5}, 10^{-3}, 10^{-1}
				% or
				%    10^{-4}, 10^{-2}
				% as ticks. Well, I prefer the first one.
				%
				% HEURISTICS: start as near to ymin as possible!
				%
				% We check here if we can come nearer to ymin if we
				% shift the current tick by log(10):
				%  if( ymin - I * log(10) < 0.5*H ->  use I+1, that means add log(10).
				%
				% that's equivalent to 
				%  2*(ymin - I * log(10)) - H < 0.
				\advance\MINH by-\MIN
				\multiply\MINH by2
				\advance\MINH by-\H
				% 
				\ifdim\MINH<0pt
					\advance\MIN \pgfplots@loc@log@to@display@log@scale pt
				\fi
			\fi
		\fi
		\MINH=\MIN
		\advance\MINH by\H
		% Ok, now it can happen that only ONE tick label is placed in
		% this range.
		% That's useless, so check for it.
		%
		% That's the case if
		%    MIN < ORIGMIN && MAX < MIN+2 H 
		% MIN < ORIGMIN by construction (ok, MIN <= ORIGMIN by
		% construction, but I don't care about this case). 
		% So: check only the second condition.
%\message{Got MIN=\pgf@sys@tonumber\MIN; H=\pgf@sys@tonumber\H; MAX=\pgf@sys@tonumber\MAX.^^J}%
		\def\pgfplots@tick@returnval@ready{0}%
		\pgfplots@tmpa=\MINH
		\advance\pgfplots@tmpa by\H
		\ifdim\MAX<\pgfplots@tmpa
			\pgfplots@if{pgfplots@#1islinear}{%
				\begingroup
					\def\pgfplots@tick@returnval@ready{1}%
					\pgfutil@ifundefined{pgfplots@assign@default@tick@foraxis@recurselevel}{%
						\def\pgfplots@assign@default@tick@foraxis@recurselevel{1}%
					}{%
						\pgfplotsutil@advancestringcounter\pgfplots@assign@default@tick@foraxis@recurselevel
					}%
					\ifnum\pgfplots@assign@default@tick@foraxis@recurselevel<15
						\c@pgf@counta=\axisdefaulttryminticks\relax
						\advance\c@pgf@counta by1
						\edef\axisdefaulttryminticks{\the\c@pgf@counta}%
%\message{**TOO FEW TICK LABELS FOR #1. RECURSION with try min ticks=\axisdefaulttryminticks.**^^J}%
						% recurse.
						\pgfplots@assign@default@tick@foraxis{#1}%
						\expandafter\global\expandafter\let\expandafter\pgfplots@glob@TMPa\csname pgfplots@#1tick\endcsname
						\expandafter\global\expandafter\let\expandafter\pgfplots@glob@TMPb\csname pgfplots@tick@distance@#1\endcsname
					\else
						\pgfplotswarning{tick computation failed}{#1}{\axisdefaulttryminticks}\pgfeov%
						\def\pgfplots@tick@returnval@ready{0}%
					\fi
					\pgfmath@smuggleone\pgfplots@tick@returnval@ready
				\endgroup
			}{%
				% Case logarithmic axes and too few ticks.
				\aftergroup\pgfplots@isuniformtickfalse
				% ok, do something special.
				%
				% The idea is now to place ticks at
				% 10^{i*h} with properly choosen 'h'.
				%
				% So: apply basically the SAME code as above for linear
				% axis, just everything log 10!  And keep in mind that all
				% coordinates are actually given as natural logarithms.
				\MIN\csname pgfplots@#1min\endcsname pt
				\H=\MAX
				\advance\H by-\MIN
				\ifdim\H<0pt \H=-1\H \fi
				\H=\pgfplots@loc@log@from@display@log@scale \H
%\message{Axis limit #1: [\the\MIN:\the\MAX], diff/log(10) = \the\H.}%
				\c@pgf@counta=\desirednumticks\relax
				\advance\c@pgf@counta by-1
				\ifnum\c@pgf@counta>2
					% subtract one more. This algorithm here produces more
					% ticks than the normal one which is designed for 10^i
					\advance\c@pgf@counta by-1
				\fi
				\divide\H by\c@pgf@counta\relax
%\message{determining ticks for #1-axis: Wr := (width/max space between ticks) = \the\Wr, desirednumticks=max(\axisdefaulttryminticks, trunc(Wr)) = \the\desirednumticks, H#1=(axis range/(desirednumticks-1)) = \the\H}%
				%
				% SEARCH for the NEXT FEASABLE H.
				\edef\Hmacro{\pgf@sys@tonumber\H}%
				\pgfmathfloatparsenumber{\Hmacro}%
				\pgfplots@assign@default@tick@foraxis@normalizetickdist#1\pgfmathresult
				%
				\expandafter\pgfmathfloattofixed\expandafter{\pgfmathresult}%
				\let\Hmacro=\pgfmathresult
				\H=\Hmacro pt %
				% Ok, our step size h for 10^{i*h} is ready!
%\message{determined step size 10^{\Hmacro}}%
				% Now, we want to activate the Tick set {10^{i*H}, i in \Z}
				% compute I such that
				%   10^{min} = 10^{I * H + rest};  |rest| < H
				% -> I = round(xmin/H)
				% -> MIN = I * H
				% BUT EVERYTHING to log(10) basis!
				\MIN=\pgfplots@loc@log@from@display@log@scale \MIN
				\pgfmathlog@invoke@expanded\pgfmathdivide@{%
					{\pgf@sys@tonumber\MIN}%
					{\Hmacro}%
				}%
				\pgfmathsetcount{\c@pgf@counta}{\pgfmathresult}%
				\ifdim\MIN<0pt
					% the truncation rounds TOWARDS 0 which is not what I want.
					\advance\c@pgf@counta by-1
				\fi
				\MIN=\H\relax
				\multiply\MIN by\c@pgf@counta\relax
				%
				% convert back to basis 'e':
				\MIN=\pgfplots@loc@log@to@display@log@scale\MIN\relax
				\H=\pgfplots@loc@log@to@display@log@scale\H\relax
				\MINH=\MIN\relax
				\advance\MINH by\H\relax
			}%
		\fi
%\message{final H=\the\H.}%
		\if0\pgfplots@tick@returnval@ready
			\xdef\pgfplots@glob@TMPb{\pgf@sys@tonumber{\H}}%
			\advance\MAX by0.5\H % avoid rounding inaccuracies:
			\xdef\pgfplots@glob@TMPa{\pgf@sys@tonumber{\MIN},\pgf@sys@tonumber{\MINH},...,\pgf@sys@tonumber{\MAX}}%
		\fi
		\aftergroup\pgfplots@determinedefaultvalues@needs@check@uniformtickfalse
	\else
		\expandafter\global\expandafter\let\expandafter\pgfplots@glob@TMPa\csname pgfplots@#1tick\endcsname
		\gdef\pgfplots@glob@TMPb{}% will be computed later, in 'check uniform tick'
		\aftergroup\pgfplots@determinedefaultvalues@needs@check@uniformticktrue
	\fi
	\endgroup
	\expandafter\let\csname pgfplots@#1tick\endcsname=\pgfplots@glob@TMPa
	\expandafter\let\csname pgfplots@tick@distance@#1\endcsname=\pgfplots@glob@TMPb
%\message{pgfplots.sty: #1tick set to \csname pgfplots@#1tick\endcsname [#1min=\csname pgfplots@#1min\endcsname, #1max=\csname pgfplots@#1max\endcsname].}%
}

% Takes the distance between adjacent ticks as floating point number
% and returns a normalized tick distance.
% 
%
% The idea is to get "nice" (human readable) distances instead of
% strange fractions or real numbers.
%
% The result will be assigned to \pgfmathresult (in float).
% 
% #1 the axis (x or y or z)
% #2 the unnormalized tick distance computed so far
%
% Example:
% \pgfmathfloatparsenumber{x}{1234}
% \pgfplots@assign@default@tick@foraxis@normalizetickdist{x}{\pgfmathresult}
% \pgfmathfloatotfixed\pgfmathresult
% -->
%
%  \pgfmathresult={1200}
% or something like that. 
\def\pgfplots@assign@default@tick@foraxis@normalizetickdist#1#2{%
	\begingroup
	\let\H=\pgf@xb
	\expandafter\pgfmathfloat@decompose#2\relax\pgfmathfloat@a@S\H\pgfmathfloat@a@E
	% modify the mantisse:
	\ifdim\H<2pt
		\ifdim\H<1.5pt
			\H=1.0pt
		\else
			\H=2.0pt
		\fi
	\else
		\ifdim\H<4.9999pt
			\ifdim\H<3.5pt
				\H=2.0pt\relax
			\else
				\H=5.0pt\relax
			\fi
		\else
			\ifdim\H<7.5pt
				\H=5.0pt\relax
			\else
				\H=1.0pt\relax
				\advance\pgfmathfloat@a@E by1
			\fi
		\fi
	\fi
	\pgfmathfloatcreate{\the\pgfmathfloat@a@S}{\pgf@sys@tonumber{\H}}{\the\pgfmathfloat@a@E}%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%

% Helper method for 
%  \pgfplots@apply@data@scale@trafo@to@options@for
% #1: the ticks
% #2: the trafo routine (not necessarily a single macro, but should
% take one arg) 
% #3: the output macro name
\long\def\pgfplots@apply@data@scale@trafo@to@user@ticks#1#2\to#3{%
	\let#3=\pgfutil@empty
	\foreach \pgfplots@loc@TMPb in {#1} {%
		\pgfmathfloatparsenumber{\pgfplots@loc@TMPb}%
		#2{\pgfmathresult}%
		\ifx#3\pgfutil@empty
			\xdef#3{\pgfmathresult}%
		\else
			\xdef#3{#3,\pgfmathresult}%
		\fi
	}%
	%
}%

% Helper method for 
%  \pgfplots@apply@data@scale@trafo@to@options@for
% #1: the ticks ALREADY IN FLOAT FORMAT
% #2: the trafo macro name 
% #3: the output macro name
\long\def\pgfplots@apply@data@scale@trafo@to@user@ticks@isfloat#1#2\to#3{%
	\let#3=\pgfutil@empty
	\foreach \pgfplots@loc@TMPb in {#1} {%
		#2{\pgfplots@loc@TMPb}%
		\ifx#3\pgfutil@empty
			\xdef#3{\pgfmathresult}%
		\else
			\xdef#3{#3,\pgfmathresult}%
		\fi
	}%
	%
}%

% Adds a further, temporary anchor to every node which will be
% processed. The anchor will be named '#2'. It is placed such that
% 1. the node's center is on a line in direction of the inwards normal
% vector of the #1 ticklabel axis and the 'at' position of the node,
% 2. the node does not intrude the axis.
%
% In effect, one of the node's standard anchors (north, east, ... )
% will be placed on the line
%    \draw[blue,thick,->] (xticklabel cs:0,0) -- (xticklabel cs:1,0);
%
% This command is identical to calling
% \pgfplotsdeclareborderanchorforaxis{#1}{<three-char-string-of-#1-ticklabel-axis>}{#2}
%
% @REMARKS:
% 	- it is -by no means- necessary that any ticks or tick labels are
% 	drawn or defined for this method.
% 	- in fact, tick labels use such an anchor (the 'near #1ticklabel'
% 	anchor is defined in this way)
\def\pgfplotsdeclareborderanchorforticklabelaxis#1#2{%
	\pgfplotsdeclareborderanchorforaxis{#1}{\pgfplotsticklabelaxisspec{#1}}{#2}%
}


pgfplotsutil.code.tex
%--------------------------------------------
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2007/2008 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------

\newif\ifpgfplots@usefpu
\pgfkeys{%
	/pgfplots/use fpu/.is if=pgfplots@usefpu,
	/pgfplots/use fpu=true,
}

% only useful inside of \ifx (equals only itsself)
\def\pgfplots@EOI{\pgfplots@EOI}%

% Produces an \aftergroup statement for each single token in #1.
%
% ATTENTION: you *can't* use braces inside of '#1'!
\def\pgfplotsqaftergroupeach#1{%
	\pgfplotsqaftergroupeach@#1\pgfplots@EOI
}
\def\pgfplotsqaftergroupeach@#1{%
	\gdef\pgfplots@TMP{#1}%
	\ifx\pgfplots@TMP\pgfplots@EOI
	\else
		\aftergroup#1%
		\expandafter\pgfplotsqaftergroupeach@
	\fi
}

\def\pgfplotsaftergroupcollectinto#1#2\pgfplots@EOI{%
	\def#1{#2}%
}%

% Assigns list contents #2 to a list macro #1.
%
% The list contents may be provided in one of two formats:
% a) in the  list format 'first\\second\\thirst\\'
% or
% b) in the PGF foreach list format 'first,second,third'.
\def\pgfplots@assign@list#1#2{%
	\pgfplotslistnew#1{#2}%
}%

% Sets the boolean \ifpgfplots@is@old@list@format  to true if and only
% if the input is a list in the format '{first\\second\\}'.
%
%
% Usage:
% \pgfplots@check@backwards@compatible@list@format <argument>'\\'\pgfplots@EOI
% you NEED to append '\\\pgfplots@EOI' at the end.
\def\pgfplots@check@backwards@compatible@list@format#1\pgfplots@EOI{%
	\pgfplotslist@check@backslash@list#1\pgfplotslist@EOI
	\ifpgfplotslist@is@backslash@terminated
		\pgfplots@is@old@list@formattrue
	\else
		\pgfplots@is@old@list@formatfalse
	\fi
}%

% Issues an error message if the **LaTeX** package '#1' is not loaded
% (An error is also raised if the document is not a LaTeX document).
% #1: the required LaTeX package
% #2: the feature which requires this package
\def\pgfplots@assert@LaTeX@package@loaded#1#2{%
	\pgfutil@IfUndefined{@ifpackageloaded}{%
		\pgfplots@error{Sorry, #2 only works with LaTeX (it relies on the LaTeX package #1)}%
	}{%
		\pgfutil@IfUndefined{ver@#1.sty}% this here has been extracted from ltclass.dtx. \@ifpackageloaded is only usable in preamble.
			{\pgfplots@error{Sorry, use need \string\usepackage{#1} in your preamble for '#2'}}%
			{\relax}%
	}%
}%
\def\pgfplots@assert@tikzinternal@exists#1{%
	\pgfutil@IfUndefined{#1}{%
		\pgfplots@error{Sorry, pgfplots relies on the existance of the tikz internal macro '#1'.
		 Unfortunately, this does no longer exist ... you will need to get an updated version of pgfplots to fix this problem.}%
		\expandafter\let\csname #1\endcsname=\pgfutil@empty
	}{}%
}%


% A future-version compatibility method which checks whether the
% macro '#2' exists.
%
% We assume that '#2' usually contains the value of the tikz key '#1'.
% Example:
% /tikz/variable is usually stored into '\tikz@plot@var'.
%
% However, this may change in future versions.
%
% So, we do the following:
% 1. check whether '#2' exists, if yet: ok.
% 2. if not, check whether the value is stored directly into '/tikz/#1'.
% 3. if not, check whether the value is stored directly into '/pgf/#1'.
% 4. If everything fails, provide an error message.
%
% #1: a tikz key without key prefix (/tikz/ and /pgf/ will be prepended).
% #2: a macro name WITHOUT backslash.
% #3: the default value if everything fails.
\def\pgfplots@gettikzinternal@keyval#1#2#3{%
	\pgfutil@IfUndefined{#2}{%
		\pgfkeysifdefined{/tikz/#1}{%
			\pgfkeysgetvalue{/tikz/#1}\pgfplots@TMP
			\expandafter\let\csname #1\endcsname=\pgfplots@TMP
		}{%
			\pgfkeysifdefined{/pgf/#1}{%
				\pgfkeysgetvalue{/pgf/#1}\pgfplots@TMP
				\expandafter\let\csname #1\endcsname=\pgfplots@TMP
			}{%
				\expandafter\def\csname #1\endcsname{#3}%
				{\t@pgfplots@tokc={#3}%
				\pgfplots@warning{Sorry, could not find value of '/tikz/#1'. Assuming '\the\t@pgfplots@tokc'.}%
				}%
			}%
		}%
	}{}%
}%

\def\pgfplots@getcurrent@plothandler#1{%
	\pgfutil@IfUndefined{tikz@plot@handler}{%
		\pgfplots@error{Sorry, can't get the current plot handler. It appears that tikz and pgfplots is no longer compatible!? You will need to get a newer version of pgfplots.}%
		\let#1=\pgfplothandlerlineto
	}{%
		\let#1=\tikz@plot@handler
	}%
}



% Converts an arbitrary command (without arguments) to a string in which all characters
% have category 12.
%
% #1: a macro name (which takes no arguments)
% #2: a macro name which will be assigned to '#1' converted to string.
%
% This uses '\meaning#1' hackery.
\def\pgfplots@command@to@string#1#2{%
	\expandafter\pgfplots@command@to@string@@\meaning#1\pgfplots@EOI{#2}%
}%
\xdef\pgfplots@glob@TMPa{\meaning\pgfutil@empty}%
\expandafter\def\expandafter\pgfplots@command@to@string@@\pgfplots@glob@TMPa#1\pgfplots@EOI#2{%
	\def#2{#1}%
}%
\def\pgfplotscommandtostring#1#2{\pgfplots@command@to@string{#1}{#2}}%

% As \pgfplots@command@to@string, but it works for commands accepting
% arguments. More precisely, #2 will be a string (!) of the form
% <argument pattern>{ <body> }
% such that you can write
% \def\test #2
% into a file to restore the original macro. This IGNORES \long
% (sorry)
\def\pgfplots@command@with@args@to@string#1#2{%
	\expandafter\PGFPLOTS@CS@WITH@ARGS@TO@STRING\meaning#1\EOI{#2}%
}%
{
\let\CATCODE=\catcode
\let\LONG=\long
\CATCODE`\m=12
\CATCODE`\a=12
\CATCODE`\c=12
\CATCODE`\r=12
\CATCODE`\o=12
\CATCODE`\:=12
\CATCODE`\-=12
\CATCODE`\>=12
\LONG\gdef\PGFPLOTS@CS@WITH@ARGS@TO@STRING #1macro:#2->#3\EOI#4{\def#4{#2{#3}}}%
}%

% Defines \pgfplotsretval to be '#1' but without leading and trailing
% spaces.
\def\pgfplotsutil@trim#1{%
	\pgfkeys@spdef\pgfplotsretval{#1}%
}%

% Invokes '#2' if the token(s) '#1' are actually are defined control
% sequence and '#3' if not.
%
% This method accepts different values '#1' than \pgfutil@ifundefined.
% It is indended to autodetect values provided in the user interface
% (ui),
% that means '#1' can be anything. But I still like to know whether it
% is a control sequence.
%
% \pgfplotsutil@ifdefinedui{\table} -> yes if \table is defined.
% \pgfplotsutil@ifdefinedui{\csname abc\endcsname} -> no
% \pgfplotsutil@ifdefinedui{a_file_name} -> no
\def\pgfplotsutil@ifdefinedui#1#2#3{%
	{\toks0={#1}% this construction is necessary to handle '#' characters in '#1'
	\xdef\pgfplotsutil@@arg@ifdefined{\the\toks0}%
	}%
	\pgfplots@command@to@string\pgfplotsutil@@arg@ifdefined\pgfplotsutil@@arg@ifdefined
	\expandafter\pgfplotsutil@trim\expandafter{\pgfplotsutil@@arg@ifdefined}%
	\pgfutil@IfUndefined{\pgfplotsretval}{#3}{#2}%
}%
% The same as \pgfplotsutil@ifdefinedui but appends the suffix '#2' to
% '#1' after '#1' has been normalized.
% It invokes '#3' if '#1#2' is defined and '#4' if not.
\def\pgfplotsutil@ifdefinedui@withsuffix#1#2#3#4{%
	{\toks0={#1}%
	\xdef\pgfplotsutil@@arg@ifdefined{\the\toks0}%
	}%
	\pgfplots@command@to@string\pgfplotsutil@@arg@ifdefined\pgfplotsutil@@arg@ifdefined
	\expandafter\pgfplotsutil@trim\expandafter{\pgfplotsutil@@arg@ifdefined}%
	\pgfutil@IfUndefined{\pgfplotsretval #2}{#4}{#3}%
}%

% Writes the command name of '#1' without the leading backslash to
% macro #2.
\def\pgfplotsutil@getcommandname#1#2{%
	\begingroup
		\escapechar=-1
		\xdef\pgfplots@glob@TMPa{\string#1}%
	\endgroup
	\let#2=\pgfplots@glob@TMPa
}

{
\catcode`\%=12
\gdef\pgfplots@PERCENT@TEXT{%}
\catcode`\^^I=12
\gdef\pgfplots@SPACE{ }
\gdef\pgfplots@TAB{^^I}
\catcode`\#=12 \gdef\pgfplots@ROUTE{#}}

% Usage:
% \pgfplots@if{pgfplots@scaled@ticks}{true-code}{false-code}
%
% it is to be used if the tex boolean is only known as string, not as
% macro.
\def\pgfplots@if#1#2#3{%
	\csname if#1\endcsname
		#2%
	\else
		#3%
	\fi
}%

% Executes '#2' if the number '#1' is zero and '#3' if not.
% Example:
% \pgfplotsmath@ifzero{0}{It's zero!}{It's not zero}
% \pgfplotsmath@ifzero{0.0}{It's zero!}{It's not zero}
%
% The argument must be assignable to a TeX dimension as 'pt', but
% without units.
\def\pgfplotsmath@ifzero#1#2#3{%
	\begingroup
	\pgf@xa=#1pt
	\ifdim\pgf@xa=0pt
		\gdef\pgfplots@glob@TMPa{#2}%
	\else
		\gdef\pgfplots@glob@TMPa{#3}%
	\fi
	\endgroup
	\pgfplots@glob@TMPa
}%

% Invokes code `#4' if |#1 - #2| <= #3 and `#5' if not.
%
% #1,#2 are dimension (registers or numbers) with unit.
% #3: absolute thresold (dimen)
\def\pgfplotsmath@ifapproxequal@dim#1#2#3#4#5{%
	\begingroup
	\pgf@xa=#1\relax
	\pgf@xb=#2\relax
	\advance\pgf@xa by-\pgf@xb
	\ifdim\pgf@xa<0pt
		\multiply\pgf@xa by-1
	\fi
	\ifdim\pgf@xa>#3\relax
		\gdef\pgfplots@glob@TMPa{#5}%
	\else
		\gdef\pgfplots@glob@TMPa{#4}%
	\fi
	\endgroup
	\pgfplots@glob@TMPa
}

\def\pgfplotsmathmin#1#2{%
	\ifdim#1 pt<#2 pt
		\edef\pgfmathresult{#1}%
	\else
		\edef\pgfmathresult{#2}%
	\fi
}%
\def\pgfplotsmathmax#1#2{%
	\ifdim#1 pt>#2 pt
		\edef\pgfmathresult{#1}%
	\else
		\edef\pgfmathresult{#2}%
	\fi
}%
\def\pgfplotsmathlessthan#1#2{\ifdim#1pt<#2pt \pgfmathfloatcomparisontrue\else\pgfmathfloatcomparisonfalse\fi}

% Re-define two-argument function for min and max.
% The pgfmath engine now uses a variable number of arguments.
\def\pgfplotsmathfloatmax#1#2{%
	\pgfmathfloatlessthan{#1}{#2}%
	\ifpgfmathfloatcomparison
		\edef\pgfmathresult{#2}%
	\else
		\edef\pgfmathresult{#1}%
	\fi
}
\def\pgfplotsmathfloatmin#1#2{%
	\pgfmathfloatlessthan{#1}{#2}%
	\ifpgfmathfloatcomparison
		\edef\pgfmathresult{#1}%
	\else
		\edef\pgfmathresult{#2}%
	\fi
}

% Defines \pgfmathresult to be #1 * 10^{#2}.
%
% #1 a macro without unit suffix.
% #2 an integer number (may be a register)
\def\pgfplotsmathmultiplypowten@#1#2{%
	\begingroup
	\pgf@xa=#1pt
	\ifnum#2<0
		\ifcase-#2
		\or\divide\pgf@xa by10
		\or\divide\pgf@xa by100
		\or\divide\pgf@xa by1000
		\or\divide\pgf@xa by10000
		\or\divide\pgf@xa by100000
		\fi
	\else
		\ifcase#2
		\or\multiply\pgf@xa by10
		\or\multiply\pgf@xa by100
		\or\multiply\pgf@xa by1000
		\or\multiply\pgf@xa by10000
		\or\multiply\pgf@xa by100000
		\fi
	\fi
	\edef\pgfmathresult{\pgf@sys@tonumber{\pgf@xa}}%
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%

% defines \pgf@x to be the scalar product between points #1 and #2
% #1, #2 are pgfpoint commands
\def\pgfplotsscalarproductofvectors#1#2{%
	\begingroup
	\pgf@process{#1}%
	\edef\pgfplots@scalarprod@a{\pgf@sys@tonumber\pgf@x}%
	\edef\pgfplots@scalarprod@b{\pgf@sys@tonumber\pgf@y}%
	\pgf@process{#2}%
	\pgf@x=\pgfplots@scalarprod@a\pgf@x
	\advance\pgf@x by\pgfplots@scalarprod@b\pgf@y
	\global\pgf@x=\pgf@x
	\endgroup
}%

% converts a comma-separated list (PGF foreach)  to my internal list
% structure.
\long\def\pgfplots@foreach@to@list#1\to#2{%
	\global\pgfplotslistnewempty\pgfplots@glob@TMPa
	\begingroup
	\foreach \pgfplots@i in {#1} {%
		\expandafter\pgfplotslistpushbackglobal\pgfplots@i\to\pgfplots@glob@TMPa
	}%
	\endgroup
	\pgfplotslistcopy\pgfplots@glob@TMPa\to#2\relax
}


% Removes duplicates in a comma separated list and creates a new list
% into the macro \pgfplotsretval. The list doesn't need to be sorted,
% but it should not contain too much elements as the runtime for this
% simple method is quadratic.
%
% #1: a CSV list.
% Assigns \pgfplotsretval
\def\pgfplotsutil@unify@short@csv@list#1{%
	\begingroup
		\def\pgfplotsretval{}%
		\pgfplotsutilforeachcommasep{#1}\as\pgfplots@unify@cur{%
			\pgfutil@ifundefined{pgfp@unify@\pgfplots@unify@cur @@@}{%
				\expandafter\def\csname pgfp@unify@\pgfplots@unify@cur @@@\endcsname{1}%
				\ifx\pgfplotsretval\pgfutil@empty
					\let\pgfplotsretval=\pgfplots@unify@cur%
				\else
					\t@pgfplots@toka=\expandafter{\pgfplotsretval}%
					\t@pgfplots@tokb=\expandafter{\pgfplots@unify@cur}%
					\edef\pgfplotsretval{\the\t@pgfplots@toka,\the\t@pgfplots@tokb}%
				\fi
			}{}%
		}%
		\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%

% Simply invokes the code of PGF key #1 with value #2, that means
% #1#2\pgfeov
\def\pgfplots@invoke@pgfkeyscode#1#2{%
	\pgfkeysvalueof{#1}#2\pgfeov
}

% Usage:
% \pgfplots@letcsname pgfplots@xtick={pgfplots@kram@x}
% -> invokes \csname ... \endcsname for both args.
\def\pgfplots@letcsname#1=#2{%
	\expandafter\let\expandafter\pgfplots@loc@TMPc\csname #2\endcsname
	\expandafter\let\csname #1\endcsname=\pgfplots@loc@TMPc
}%

% Inside of a pgfplots axis, this method (together with
% \pgfplotsqpointxyz for 3d axes) is THE
% point method. If you override the mapping to PGF coordinates here,
% all other \pgfplotspoint* commands should inherit the changes as well.
\def\pgfplotsqpointxy#1#2{%
  \global\pgf@x=#1\pgf@xx%
  \global\advance\pgf@x by #2\pgf@yx%
  \global\pgf@y=#1\pgf@xy%
  \global\advance\pgf@y by #2\pgf@yy}

% Inside of a pgfplots axis, this method (together with
% \pgfplotsqpointxy for 2d axes) is THE
% point method. If you override the mapping to PGF coordinates here,
% all other \pgfplotspoint* commands should inherit the changes as well.
\def\pgfplotsqpointxyz#1#2#3{%
  \global\pgf@x=#1\pgf@xx%
  \global\advance\pgf@x by #2\pgf@yx%
  \global\advance\pgf@x by #3\pgf@zx%
  \global\pgf@y=#1\pgf@xy%
  \global\advance\pgf@y by #2\pgf@yy%
  \global\advance\pgf@y by #3\pgf@zy}

% A "quick" quick variant of \pgfqpointxy which assumes that 
% the X unit vector is ( e_xx,0 )^T  and the Y unit vector is ( 0,
% e_yy)^T.
%
% In words, the unit vectors are orthogonal. This is the usual case
% for two-dimensional plots and shall be optimized.
\def\pgfplotsqpointxy@orthogonal#1#2{%
	\global\pgf@x=#1\pgf@xx%
	\global\pgf@y=#2\pgf@yy
}


% Takes a domain as input and generates a foreach argument which
% samples from the domain.
% Writes the result to \pgfplotsretval
% INPUT:
% 	#1:#2 the domain
% 	#3: the number of samples
% OUTPUT:
% 	\pgfplotsretval a foreach specification.
\def\pgfplots@domain@to@foreach#1:#2\relax#3{%
	\pgfmathparse{#1}%
	\let\pgfplots@loc@TMPa=\pgfmathresult%
	\pgfmathparse{#2}%
	\let\pgfplots@loc@TMPb=\pgfmathresult%
	\pgfmathparse{\pgfplots@loc@TMPa+(\pgfplots@loc@TMPb-\pgfplots@loc@TMPa)/(#3-1)}%
	\edef\pgfplotsretval{\pgfplots@loc@TMPa,\pgfmathresult,...,\pgfplots@loc@TMPb}%
}

{
	\catcode`\;=\active
	\catcode`\:=\active
	\gdef\pgfplots@activesemicolon{;}%
	\gdef\pgfplots@activecolon{:}%
}

% checks whether ';' is active and replaces a sequence of commands
% accordingly.
%
% @see \pgfplots@appendto@activesemicolon@switcher
\def\pgfplots@checkandpreparefor@active@semicolon{%
	\ifnum\the\catcode`\;=\active\relax
		\pgfplots@checkandpreparefor@active@semicolon@
	\fi
}%
\def\pgfplots@checkandpreparefor@active@semicolon@{}%

% Adds all commands '#1' to the sequence of commands which will be
% issued in case ';' is active.
\def\pgfplots@appendto@activesemicolon@switcher#1{%
	\expandafter\def\expandafter\pgfplots@checkandpreparefor@active@semicolon@\expandafter{%
		\pgfplots@checkandpreparefor@active@semicolon@
		#1%
	}%
}%

% Invokes '#3' for every element in the comma separated list '#1'.
% during '#3', the macro '#2' will be set to the current list element.
%
% In contrast to \foreach of tikz, this processing is NOT scoped by
% TeX groups. However, it can be nested.
%
% Please note that no trimming of white spaces is performed.
%
% This is the (accidentally) the same as \pgfplotsforeachentryinCSV.
\long\def\pgfplotsutilforeachcommasep#1\as#2#3{%
	\pgfplotsforeachentryinCSVisterminated@loop{#2}{#3}#1,\pgfplots@EOI
}%

% Usage:
% \pgfplotsforeachentryinCSV{\value}{1,2,3,4.5,6.7,10}{The value is \value\par}
%
% The loop is ungrouped.
%
% This is the same as \pgfplotsutilforeachcommasep, I must have been
% sleeping somehow.
%
% @see \pgfplotsutilforeachcommasep
% @see \pgfplotsforeachentryinCSVisterminated
% @see \pgfplotsforeachungrouped
% This loop can be nested.
\long\def\pgfplotsforeachentryinCSV#1#2#3{%
	\pgfplotsforeachentryinCSVisterminated@loop{#1}{#3}#2,\pgfplots@EOI
}%
% A variant of \pgfplotsforeachentryinCSV where a trailing comma
% indicates the end of input.
% Example:
%
% \pgfplotsforeachentryinCSV{\value}{1,2,3,4.5,6.7,10,}{The value is \value\par}
%                                                    ^
%
% It is permissable to provide an empty list (without trailing comma)
%
% This loop can be nested.
\long\def\pgfplotsforeachentryinCSVisterminated#1#2#3{%
	\pgfplotsforeachentryinCSVisterminated@loop{#1}{#3}#2\pgfplots@EOI
}%
% #1 : the loop macro
% #2 : the loop BODY
% #3 : the loop LIST
% (note the different sequence)
\long\def\pgfplotsforeachentryinCSVisterminated@loop#1#2{%
	\pgfutil@ifnextchar\pgfplots@EOI{%
		\pgfutil@gobble
	}{%
		\pgfplotsforeachentryinCSV@next{#1}{#2}%
	}%
}%
\long\def\pgfplotsforeachentryinCSV@next#1#2#3,{%
	\def#1{#3}%
	#2\relax
	\pgfplotsforeachentryinCSVisterminated@loop{#1}{#2}%
}%


% Discards any token up to (and including) \relax.
\def\pgfplots@gobble@until@relax#1\relax{}%
\def\pgfplots@gobble@until@EOI#1\pgfplots@EOI{}%

% A (simple) replacement for \foreach which 
% 1. does NOT scope the argument
% 2. allows to use PGF Math routines for loops ( '...' notation)
% instead of TeX registers.
%
% Usage:
% \pgfplotsforeachungrouped \x in {1,2,3,4,5} {<code>}
% 
% Some details:
% 1. If #2 is a UNIFORM SAMPLING RANGE, the algorithm is supposed to be
%   most effective. This is considered to be the case for the syntax
%   \pgfplotsforeachungrouped \x in {1,2,...,8}.
% 2. If case (1.) is not used, \foreach \x in {#2} {} is invoked to
% generate a temporary list. Afterwards, this list is invoked without
% scopes.
%
% This loop *can* be nested.
\def\pgfplotsforeachungrouped#1{%
	\pgfutil@ifnextchar/{\pgfplotsforeachungrouped@{#1}}{\pgfplotsforeachungrouped@{#1}/{}}%
}%
\long\def\pgfplotsforeachungrouped@#1/#2in #3#4{%
	\def\pgfplots@foreach@loc@TMPa{#2}%
	\ifx\pgfplots@foreach@loc@TMPa\pgfutil@empty
		\pgfplotsforeachungrouped@isuniform{#3}%
		\ifpgfplots@loc@tmp
			% special handling:
			% \foreach #1 in {a,b,...,c} can be improved:
			\pgfplotsforeachungroupeduniform@{#1}#3\relax{#4}%
		\else
			% invoke  \foreach #1 in {#3} and transport results:
			\pgfplotsforeachungroupednonuniform@#1{#3}{#4}%
		\fi
	\else
		% invoke  \foreach #1/#2 in {#3} and transport results:
		\pgfplotsforeachungroupedslashed@#1/#2{#3}{#4}%
	\fi
}
\let\pgfplots@original@pgfmathadd@=\pgfmathadd@

\long\def\pgfplotsforeachungroupeduniform@#1#2,#3,...,#4\relax#5{%
	% Compute mesh width!
	\pgfmathparse{#2}%
	\let\pgfplots@foreach@loc@TMPa=\pgfmathresult
	\pgfmathparse{#3}%
	\let\pgfplots@foreach@loc@TMPb=\pgfmathresult
	\pgfmathsubtract@{\pgfplots@foreach@loc@TMPb}{\pgfplots@foreach@loc@TMPa}%
	% Use \pgfmath engine for the loop:
	% mesh width:
	\let\pgfplots@foreach@loc@meshwidth=\pgfmathresult
	\pgfmathparse{0}% invoke the parser - in case the fpu is active.
	\pgfmathlessthan@{\pgfplots@foreach@loc@meshwidth}{\pgfmathresult}%
	% the loop will run while ( NOT \pgfplots@foreach@loc@cmp{<cur>}{<last>} )
	\ifdim\pgfmathresult pt=1pt
		\def\pgfplots@foreach@loc@cmp{\pgfmathlessthan@}%
	\else
		\def\pgfplots@foreach@loc@cmp{\pgfmathgreaterthan@}%
	\fi
	%
	\pgfmathparse{#4 + 0.5*\pgfplots@foreach@loc@meshwidth}%
	\let\pgfplots@foreach@loc@TMPb=\pgfmathresult
	%
	\t@pgfplots@toka={#5}%
	% to allow nesting without additional TeX groups of
	% \pgfplotsforeachungroupeduniform, I introduce this loop
	% structure here which does not need ANY state macro:
	\edef\pgfplots@foreach@loc@TMPc{%
		\noexpand\pgfplotsforeachungroupeduniform@loop@mathengine
			{\expandafter\noexpand\pgfplots@foreach@loc@cmp}% #1= comparison fct
			{\pgfplots@foreach@loc@TMPa}% #2 =lower limit (ITERATES)
			{\pgfplots@foreach@loc@TMPb}% #3 = upper limit
			{\noexpand#1}% #4 = the loop macro name
			{\pgfplots@foreach@loc@meshwidth}% #5 =  h
			{\the\t@pgfplots@toka}% #6 = the code to invoke
	}%
	\pgfplots@foreach@loc@TMPc
}%
\long\def\pgfplotsforeachungroupeduniform@loop@mathengine#1#2#3#4#5#6{%
	#1{#2}{#3}%
	\ifdim\pgfmathresult pt=0pt
		\pgfutil@in@{.0\relax}{#2\relax}%
		\ifpgfutil@in@
			\def\pgfplotsforeach@loc@TMP##1.0\relax{%
				\def#4{##1}%
			}%
			\pgfplotsforeach@loc@TMP#2\relax
		\else
			\def#4{#2}%
		\fi
		#6\relax
		\pgfmathadd@{#2}{#5}%
		\t@pgfplots@toka={{#1}}%
		\t@pgfplots@tokb=\expandafter{\pgfmathresult}%
		\t@pgfplots@tokc={{#3}{#4}{#5}{#6}}%
		% loop!
		\edef\pgfplots@loc@TMPa{\noexpand\pgfplotsforeachungroupeduniform@loop@mathengine
			\the\t@pgfplots@toka
			{\the\t@pgfplots@tokb}%
			\the\t@pgfplots@tokc}%
		\expandafter\pgfplots@loc@TMPa
	\fi
}%

\long\def\pgfplotsforeachungroupednonuniform@#1#2#3{%
	\pgfplotsapplistXXglobalnewempty
	\foreach\pgfplots@foreach@loc@TMPa in {#2} {%
		\expandafter\pgfplotsapplistXXglobalpushback\expandafter{\pgfplots@foreach@loc@TMPa,}%
	}%
	\pgfplotsapplistXXgloballet\pgfplots@foreach@loc@TMPa
	\pgfplotsapplistXXglobalclear
	\expandafter\pgfplotsforeachentryinCSVisterminated\expandafter\pgfplots@foreach@loc@TMPa\expandafter{\pgfplots@foreach@loc@TMPa}{%
		\let#1=\pgfplots@foreach@loc@TMPa
		#3%
	}%
}
\long\def\pgfplotsforeachungroupedslashed@#1/#2#3#4{%
	\pgfplotsapplistXXglobalnewempty
	\foreach\pgfplots@foreach@loc@TMPa/\pgfplots@foreach@loc@TMPb in {#3} {%
		\edef\pgfplots@foreach@loc@TMPa{\pgfplots@foreach@loc@TMPa/\pgfplots@foreach@loc@TMPb}%
		\expandafter\pgfplotsapplistXXglobalpushback\expandafter{\pgfplots@foreach@loc@TMPa,}%
	}%
	\pgfplotsapplistXXgloballet\pgfplots@foreach@loc@TMPa
	\pgfplotsapplistXXglobalclear
	\expandafter\pgfplotsforeachentryinCSVisterminated\expandafter\pgfplots@foreach@loc@TMPa\expandafter{\pgfplots@foreach@loc@TMPa}{%
		\expandafter\pgfplotsforeachungroupedslashed@@\pgfplots@foreach@loc@TMPa\pgfplots@EOI
		\let#1=\pgfplots@foreach@loc@TMPa
		\let#2=\pgfplots@foreach@loc@TMPb
		#4%
	}%
}
\def\pgfplotsforeachungroupedslashed@@#1/#2\pgfplots@EOI{%
	\def\pgfplots@foreach@loc@TMPa{#1}%
	\def\pgfplots@foreach@loc@TMPb{#2}%
}%

% Sets \ifpgfplots@loc@tmp to true if and only if '#1' is of the form
% #1 = <number1>,<number2>,...,<number3>.
\def\pgfplotsforeachungrouped@isuniform#1{%
	\edef\pgfplots@foreach@loc@TMPa{#1}%
	\expandafter\pgfplotsforeachungrouped@isuniform@\pgfplots@foreach@loc@TMPa,,,,\relax
}%
\def\pgfplotsforeachungrouped@isuniform@#1,#2,#3,#4,#5\relax{%
	\def\pgfplots@foreach@loc@TMPa{#5}%
	\def\pgfplots@foreach@loc@TMPb{,,,}%
	\pgfplots@loc@tmpfalse
	\ifx\pgfplots@foreach@loc@TMPa\pgfplots@foreach@loc@TMPb
		\def\pgfplots@foreach@loc@TMPa{#3}%
		\def\pgfplots@foreach@loc@TMPb{...}%
		\ifx\pgfplots@foreach@loc@TMPa\pgfplots@foreach@loc@TMPb
			\pgfutil@in@,{#4}%
			\ifpgfutil@in@
			\else
				% ok, we REALLY have a uniform range!
				\pgfplots@loc@tmptrue
			\fi
		\fi
	\fi
}%

% A variant of \pgfplotsforeachungrouped ( or \foreach ) which
% *invokes* with #1 set to the current iterate.
%
% Example:
% 	\pgfplotsinvokeforeach{a,b,c,d} 
% 		{\pgfkeys{key #1/.style={otherstyle #1}}}
% -> will invoke
%  \pgfkeys{key a/.style={otherstyle a}}
%  \pgfkeys{key b/.style={otherstyle b}}
%  \pgfkeys{key c/.style={otherstyle c}}
%  \pgfkeys{key d/.style={otherstyle d}}
% Note that \pgfplotsforeachungrouped \d in {a,b,c,d} 
% 		{\pgfkeys{key \d/.style={}}}
% would not work:
%  \pgfkeys{key a/.style={otherstyle \d}}
%  \pgfkeys{key b/.style={otherstyle \d}}
%  \pgfkeys{key c/.style={otherstyle \d}}
%  \pgfkeys{key d/.style={otherstyle \d}}
% such an application would need expansion control.
%
% #1: the iterates. Can be any argument as you would supply it to
% \foreach, for example \foreach \x in {1,2,...,10}
% 	-> #1 = {1,2,...,10}
% #2: the loop body. It can contain the parameter string '#1' which
% will be set to each element in the iterates list in turn.
%
% This method is actually just a light-weight adapter around
% \pgfplotsforeachungrouped.
\long\def\pgfplotsinvokeforeach#1#2{%
	\long\def\pgfplotsinvokeforeach@@##1{#2}%
	\pgfplotsforeachungrouped \pgfplotsinvokeforeach@ in {#1} {%
		\expandafter\pgfplotsinvokeforeach@@\expandafter{\pgfplotsinvokeforeach@}%
	}%
}

% Allows to provide an output routine for
% \pgfplotsforeachlogarithmicungrouped which changes the number format
% of \pgfmathresult.
%
% Example:
% \pgfplotsforeachlogarithmicformatresultwith{\pgfmathfloattofixed{\pgfmathresult}}
%
% #1: is code which modifies \pgfmathresult.
\def\pgfplotsforeachlogarithmicformatresultwith#1{%
	\def\pgfplotsforeachlogarithmicungrouped@finalizeresult{#1}%
}

% \pgfplotsforeachlogarithmicungrouped[<samples>] \x/\logx in {a:b} {#3}
%
% samples \x between a and b using a logarithmic scale.
%
% During '#3', \x will contain the sample and \logx the logarithm of
% \x.
%
% Both, #1 and #2 will be provided as floating point numbers unless
% configured otherwise with \pgfplotsforeachlogarithmicsetoutput,
% see above.
%
% Arithmethics will be carried out with the math class
% '\pgfplotsforeachlogarithmicmathid'.
% This macro should expand to something which is usable inside of
% \pgfplotscoordmath{\pgfplotsforeachlogarithmicmathid}{....}
% the default is 'float'
% 
% FIXME : THIS CAN'T BE NESTED YET!
\def\pgfplotsforeachlogarithmicungrouped[#1]#2/#3{\pgfplotsforeachlogarithmicungrouped@[#1]{#2}{#3}}%
\long\def\pgfplotsforeachlogarithmicungrouped@[#1]#2#3in #4#5{%
	% define
	% 	\pgfplots@foreach@loc@TMPd = N in fixed point
	% 	\pgfplots@foreach@loc@TMPc = N-1 in float :
	\edef\pgfplots@plot@samples@@{#1}%
	\pgfplotscoordmath{\pgfplotsforeachlogarithmicmathid}{one}%
	\let\pgfplots@foreach@loc@TMPa=\pgfmathresult
	\pgfplotscoordmath{\pgfplotsforeachlogarithmicmathid}{parsenumber}{\pgfplots@plot@samples@@}%
	\pgfplotscoordmath{\pgfplotsforeachlogarithmicmathid}{op}{subtract}{{\pgfmathresult}{\pgfplots@foreach@loc@TMPa}}%
	\let\pgfplots@foreach@loc@TMPc=\pgfmathresult
	%
	\edef\pgfplots@loc@TMPb{#4}%
	\expandafter\pgfplotsforeachlogarithmicungrouped@readdomain\pgfplots@loc@TMPb\relax
	\pgfplotscoordmath{\pgfplotsforeachlogarithmicmathid}{if is bounded}{\pgfplots@foreach@loc@TMPb}{%
	}{%
		\pgfplotsforeachlogarithmicmath@unbounded@domain{#4}%
		\pgfplotscoordmath{\pgfplotsforeachlogarithmicmathid}{parsenumber}{-10000}%
		\let\pgfplots@foreach@loc@TMPb=\pgfmathresult
	}%
	\pgfplotscoordmath{\pgfplotsforeachlogarithmicmathid}{if is bounded}{\pgfplots@foreach@loc@TMPa}{%
	}{%
		\pgfplotsforeachlogarithmicmath@unbounded@domain{#4}%
		\pgfplotscoordmath{\pgfplotsforeachlogarithmicmathid}{parsenumber}{-10000}%
		\let\pgfplots@foreach@loc@TMPa=\pgfmathresult
	}%
	% compute mesh width into \pgfplots@foreach@loc@TMPc:
	%  \pgfplots@foreach@loc@TMPc := h := ( log(xmax) - log(xmin) ) / (N-1)
	\pgfplotscoordmath{\pgfplotsforeachlogarithmicmathid}{op}{subtract}{{\pgfplots@foreach@loc@TMPb}{\pgfplots@foreach@loc@TMPa}}%
	\pgfplotscoordmath{\pgfplotsforeachlogarithmicmathid}{op}{divide}{{\pgfmathresult}{\pgfplots@foreach@loc@TMPc}}%
	\let\pgfplots@foreach@loc@TMPc=\pgfmathresult
	%
	% apply local scoping here:
	\edef\pgfplots@foreach@loc@TMPd{%
		\noexpand\c@pgf@counta=\the\c@pgf@counta\noexpand\relax
	}%
	\long\def\pgfplots@foreach@loc@TMPf{#5}%
	\c@pgf@counta=0
	\pgfutil@loop
	\ifnum\c@pgf@counta<\pgfplots@plot@samples@@
		% compute exp(log(min) + i * h)
		\edef\pgfplots@loc@TMPa{\the\c@pgf@counta}%
		\pgfplotscoordmath{\pgfplotsforeachlogarithmicmathid}{parsenumber}{\pgfplots@loc@TMPa}%
		\pgfplotscoordmath{\pgfplotsforeachlogarithmicmathid}{op}{multiply}{{\pgfmathresult}{\pgfplots@foreach@loc@TMPc}}%
		\pgfplotscoordmath{\pgfplotsforeachlogarithmicmathid}{op}{add}{{\pgfmathresult}{\pgfplots@foreach@loc@TMPa}}%
		\let\pgfplots@loc@TMPa=\pgfmathresult
		\pgfplotsforeachlogarithmicungrouped@finalizeresult%
		\let#3=\pgfmathresult
		\pgfplotscoordmath{\pgfplotsforeachlogarithmicmathid}{exp}{\pgfplots@loc@TMPa}%
		\pgfplotsforeachlogarithmicungrouped@finalizeresult%
		\let#2=\pgfmathresult
		%
		% ok, invoke it!
		% -> store \c@pgf@counta before doing so. We need to scope
		%  manually here.
		\edef\pgfplots@foreach@loc@TMPe{\the\c@pgf@counta}%
		\pgfplots@foreach@loc@TMPf\relax
		\c@pgf@counta=\pgfplots@foreach@loc@TMPe\relax
		\advance\c@pgf@counta by 1
	\pgfutil@repeat
	% restore scoped variables:
	\pgfplots@foreach@loc@TMPd
}

\def\pgfplotsforeachlogarithmicmath@unbounded@domain#1{%
	\pgfplots@error{Sorry, the provided domain #1 is unsuitable for logarithmic sampling (applying the log results in unbounded values)}%
}%

% can be used to convert the number format from float to something
% else.
\def\pgfplotsforeachlogarithmicungrouped@finalizeresult{}%


\def\pgfplotsforeachlogarithmicmathid{float}

% defines 
%  \pgfplots@foreach@loc@TMPa := log(firstintervalpt)
% and
%  \pgfplots@foreach@loc@TMPb := log(secondintervalpt)
\def\pgfplotsforeachlogarithmicungrouped@readdomain#1:#2\relax{%
	\pgfplotscoordmath{default}{parse}{#1}%
	\pgfplotscoordmath{\pgfplotsforeachlogarithmicmathid}{log}{\pgfmathresult}%
	\let\pgfplots@foreach@loc@TMPa=\pgfmathresult
	\pgfplotscoordmath{default}{parse}{#2}%
	\pgfplotscoordmath{\pgfplotsforeachlogarithmicmathid}{log}{\pgfmathresult}%
	\let\pgfplots@foreach@loc@TMPb=\pgfmathresult
}

% invokes '#2' if #1 expands (\edef) to the empty string or '#3' if not.
\def\pgfplots@ifempty#1#2#3{%
	\edef\pgfplots@loc@TMPa{#1}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty #2\else #3\fi
}%

{
	\catcode`\#=12
	\catcode`\1=12
	\gdef\pgfplotsutil@add@to@macro@@one{#1}%
	\gdef\pgfplotsutil@add@to@macro@@two{#1#2}%
}

\def\pgfplotsutil@ifmacrodependsononearg#1#2#3{%
	\edef\pgfplots@loc@TMPa{\noexpand\pgfutil@in@{\pgfplotsutil@add@to@macro@@one}{\meaning#1}}%
	\pgfplots@loc@TMPa
	\ifpgfutil@in@
		#2%
	\else
		#3%
	\fi
}%

\def\pgfplotsutil@ifmacrodependsontwoargs#1#2#3{%
	\edef\pgfplots@util@add@to@macro@@{\noexpand\pgfutil@in@{\pgfplotsutil@add@to@macro@@two}{\meaning#1}}%
	\pgfplots@util@add@to@macro@@
	\ifpgfutil@in@
		#2%
	\else
		#3%
	\fi
}%

% Appends '#2' to macro '#1'.
%
% #1: a macro which takes either no arguments or exactly one.
% #2: some token text. May depend on '#1' if #1 is a macro which
% depends on one arg.
\def\pgfplotsutil@add@to@macro#1#2{%
	\pgfplotsutil@ifmacrodependsononearg#1{%
		\pgfplotsutil@ifmacrodependsontwoargs#1{%
			\pgfplotsutil@add@to@macro@twoargs{#1}{#2}%
		}{%
			\pgfplotsutil@add@to@macro@onearg{#1}{#2}%
		}%
	}{%
		\pgfplotsutil@add@to@macro@noargs{#1}{#2}%
	}%
}%

\def\pgfplotsutil@add@to@macro@twoargs#1#2{%
	\t@pgfplots@tokc=\expandafter{#1{##1}{##2}}%
	\t@pgfplots@tokb={#2}%
	\edef\pgfplots@util@add@to@macro@@{\the\t@pgfplots@tokc\the\t@pgfplots@tokb}%
	\expandafter\def\expandafter#1\expandafter##\expandafter1\expandafter##\expandafter2\expandafter{\pgfplots@util@add@to@macro@@}%
}

\def\pgfplotsutil@add@to@macro@onearg#1#2{%
	\t@pgfplots@tokc=\expandafter{#1{##1}}%
	\t@pgfplots@tokb={#2}%
	\edef\pgfplots@util@add@to@macro@@{\the\t@pgfplots@tokc\the\t@pgfplots@tokb}%
	\expandafter\def\expandafter#1\expandafter##\expandafter1\expandafter{\pgfplots@util@add@to@macro@@}%
}

\def\pgfplotsutil@add@to@macro@noargs#1#2{%
	\t@pgfplots@tokc=\expandafter{#1}%
	\t@pgfplots@tokb=\expandafter{#2}%
	\edef#1{\the\t@pgfplots@tokc\the\t@pgfplots@tokb}%
}
\def\pgfplots@logfileopen#1{%
	\immediate\write-1{PGFPlots: reading {#1}}%
	\pgfutil@IfUndefined{tikzifexternalizingcurrent}{%
		% version not up-to-date or external lib not loaded?
	}{%
		% adjust the .dep file only if we are externalizing.
		% Otherwise, it may be overwritten by \pgfplotstableread
		% commands which are *before* the tikzpicture (and the picture
		% will be replaced by its graphics)
		\tikzifexternalizingcurrent{\tikzpicturedependsonfile{#1}}{}%
	}%
}%

% Expands #2 using \edef and invokes #1 with the resulting string.
%
% DEPRECATED
% Example:
%   \pgf@xa=7.9pt
%   \pgfplotsutil@edef@invoke\pgfmathexp@{{\pgf@sys@tonumber{\pgf@xa}}}%
% will invoke
%   \pgfmathexp@{7.9}
\def\pgfplotsutil@edef@invoke#1#2{%
	\edef\pgfutil@edef@invoke@{#2}%
	\expandafter#1\pgfutil@edef@invoke@
}

% defines \pgfmathresult to be the INTEGER result of (#1 mod #2).
%
% \pgfplotsmathmod{2}{4} -> 2
% \pgfplotsmathmod{9}{5} -> 4
\def\pgfplotsmathmodint#1#2{%
	\begingroup
	\c@pgf@counta=#2\relax
	\c@pgf@countb=#1\relax
	\ifnum\c@pgf@counta=2
		\ifodd\c@pgf@countb
			\def\pgfmathresult{1}%
		\else
			\def\pgfmathresult{0}%
		\fi
	\else
		\c@pgf@countc=\c@pgf@countb
		\ifnum\c@pgf@counta=0
			\pgfplots@error{Can't compute \the\c@pgf@countb\space mod \the\c@pgf@counta\space -- this yields division by zero (second argument is zero)!}%
			\edef\pgfmathresult{#1}%
		\else
			\divide\c@pgf@countc by\c@pgf@counta
			\multiply\c@pgf@countc by\c@pgf@counta
			\advance\c@pgf@countb by-\c@pgf@countc
			\edef\pgfmathresult{\the\c@pgf@countb}%
		\fi
	\fi
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%

% Advances a number stored in a macro and writes the result back into
% the macro.
% #1 is a macro containing a number. 
\def\pgfplotsutil@advancestringcounter#1{%
	\begingroup
		\c@pgf@counta=#1\relax
		\advance\c@pgf@counta by1
		\edef#1{\the\c@pgf@counta}%
		\pgfmath@smuggleone#1%
	\endgroup
}%
\def\pgfplotsutil@advancestringcounter@global#1{%
	\begingroup
		\c@pgf@counta=#1\relax
		\advance\c@pgf@counta by1
		\xdef#1{\the\c@pgf@counta}%
	\endgroup
}%

\newif\ifpgfplotsloopcontinue

% A loop construct which invokes '#1' and continues the loop if the
% boolean \ifpgfplotsloopcontinue is true and stops if it is false.
%
% #1: a statement which is expected to set \ifpgfplotsloopcontinue
% #2: the loop body.
\def\pgfplotsloop#1#2{%
	#1\relax
	\ifpgfplotsloopcontinue
		#2\relax
		\def\pgfplotsloop@{\pgfplotsloop{#1}{#2}}%
		\expandafter\pgfplotsloop@
	\fi
}%

% String comparison of '#1' and '#2'.
% Defines 
% \pgfplotsretval=0  if #1 == #2 
% \pgfplotsretval=1  if #1 < #2
% \pgfplotsretval=2  if #1 > #2
\def\pgfplotsutilstrcmp#1#2{%
	\begingroup
	\def\pgfplots@strcmp@arga{#1}%
	\pgfplots@command@to@string\pgfplots@strcmp@arga\pgfplots@strcmp@arga
	\def\pgfplots@strcmp@argb{#2}%
	\pgfplots@command@to@string\pgfplots@strcmp@argb\pgfplots@strcmp@argb
	%
	%
	\def\pgfplotsretval{0}%
	%
	\pgfplotsloop{%
		\if0\pgfplotsretval
			% get next token of arga:
			\expandafter\pgfplotsutilstrcmp@popfront\pgfplots@strcmp@arga\relax\relax
			\let\pgfplots@strcmp@arga=\pgfplots@strcmp@rest
			\let\pgfplots@strcmp@arga@=\pgfplots@strcmp@cur
			%
			% get next token of argb:
			\expandafter\pgfplotsutilstrcmp@popfront\pgfplots@strcmp@argb\relax\relax
			\let\pgfplots@strcmp@argb=\pgfplots@strcmp@rest
			\let\pgfplots@strcmp@argb@=\pgfplots@strcmp@cur
			%
			% if one of them is empty: set retval and break loop.
			\ifx\pgfplots@strcmp@arga@\pgfplotsutilstrcmp@relaxtext
				\ifx\pgfplots@strcmp@argb@\pgfplotsutilstrcmp@relaxtext
				\else
					\def\pgfplotsretval{1}%
				\fi
				\pgfplotsloopcontinuefalse
			\else
				\ifx\pgfplots@strcmp@argb@\pgfplotsutilstrcmp@relaxtext
					\def\pgfplotsretval{2}%
					\pgfplotsloopcontinuefalse
				\else
					\pgfplotsloopcontinuetrue
				\fi
			\fi
		\else
			\pgfplotsloopcontinuefalse
		\fi
	}{%
		%
		\ifnum\expandafter`\pgfplots@strcmp@arga@<\expandafter`\pgfplots@strcmp@argb@
			\def\pgfplotsretval{1}%
			\let\pgfplots@strcmp@arga=\pgfutil@empty
		\else
			\ifnum\expandafter`\pgfplots@strcmp@arga@>\expandafter`\pgfplots@strcmp@argb@
				\def\pgfplotsretval{2}%
				\let\pgfplots@strcmp@arga=\pgfutil@empty
			\fi
		\fi
	}%
	%
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%
\def\pgfplotsutilstrcmp@relaxtext{\relax}%
\def\pgfplotsutilstrcmp@popfront#1#2\relax{%
	\def\pgfplots@strcmp@cur{#1}%
	\def\pgfplots@strcmp@rest{#2}%
}%

% Takes two dimensional cartesian coordinates #1,#2 and 
% defines the macros #3 and #4 to contain the associated polar
% coordinates.
%
% #1: x
% #2: y
% #3: a macro which will be filled with the angle (in degrees)
% #4: a macro which will be filled with the radius
\def\pgfplotsmathcarttopol#1#2#3#4{%
	\pgfplotsmathcarttopol@{#1}{#2}{#3}{#4}{default}%
}%
\def\pgfplotsmathcarttopolbasic#1#2#3#4{%
	\pgfplotsmathcarttopol@{#1}{#2}{#3}{#4}{pgfbasic}%
}%
% #5: the math engine to use (\pgfplotscoordmath argument)
\def\pgfplotsmathcarttopol@#1#2#3#4#5{%
	\begingroup
	\pgfplotscoordmath{#5}{parsenumber}{#1}%
	\let\pgfplots@x=\pgfmathresult
	\pgfplotscoordmath{#5}{parsenumber}{#2}%
	\let\pgfplots@y=\pgfmathresult
	\pgfplotscoordmath{#5}{op}{veclen}{{\pgfplots@x}{\pgfplots@y}}%
	\let\pgfplots@r=\pgfmathresult
	\pgfplotscoordmath{#5}{if is}{\pgfplots@r}{0}{%
		\pgfplotscoordmath{#5}{parsenumber}{0}%
	}{%
		\pgfplotscoordmath{#5}{op}{divide}{{\pgfplots@x}{\pgfplots@r}}%
		\let\pgfplots@quot=\pgfmathresult
		%
		\pgfplotscoordmath{#5}{one}%
		\let\pgfplots@loc@TMPc=\pgfmathresult
		\pgfplotscoordmath{#5}{min}{\pgfplots@quot}{\pgfplots@loc@TMPc}%
		\let\pgfplots@quot=\pgfmathresult
		\pgfplotscoordmath{#5}{-one}%
		\let\pgfplots@loc@TMPc=\pgfmathresult
		\pgfplotscoordmath{#5}{max}{\pgfplots@quot}{\pgfplots@loc@TMPc}%
		\let\pgfplots@quot=\pgfmathresult
		%
		\pgfplotscoordmath{#5}{op}{acos}{{\pgfplots@quot}}%
		%
		\pgfplotscoordmath{#5}{if is}{\pgfplots@y}{-}{%
			\let\pgfplots@acos=\pgfmathresult
			\pgfplotscoordmath{#5}{-one}%
			\pgfplotscoordmath{#5}{op}{multiply}{{\pgfmathresult}{\pgfplots@acos}}%
		}{}%
	}%
	\let\pgfplots@deg=\pgfmathresult
	\xdef\pgfplots@glob@TMPa{\noexpand\def\noexpand#3{\pgfplots@deg}\noexpand\def\noexpand#4{\pgfplots@r}}%
	\endgroup
	\pgfplots@glob@TMPa
}%

% Takes two dimensional polar coordinates #1,#2 and 
% defines the macros #3 and #4 to contain the associated cartesian
% coordinates.
%
% #1: angle (in degrees)
% #2: radius
% #3: a macro which will be filled with the x value
% #4: a macro which will be filled with the y value
\def\pgfplotsmathpoltocart#1#2#3#4{%
	\pgfplotsmathpoltocart@{#1}{#2}{#3}{#4}{default}%
}%
\def\pgfplotsmathpoltocartbasic#1#2#3#4{%
	\pgfplotsmathpoltocart@{#1}{#2}{#3}{#4}{pgfbasic}%
}%
% #5: the math engine to use (\pgfplotscoordmath argument)
\def\pgfplotsmathpoltocart@#1#2#3#4#5{%
	\begingroup
	\pgfplotscoordmath{#5}{parsenumber}{#1}%
	\let\pgfplots@deg=\pgfmathresult
	\pgfplotscoordmath{#5}{parsenumber}{#2}%
	\let\pgfplots@r=\pgfmathresult
	\pgfplotscoordmath{#5}{op}{sin}{{\pgfplots@deg}}%
	\pgfplotscoordmath{#5}{op}{multiply}{{\pgfplots@r}{\pgfmathresult}}%
	\let\pgfplots@y=\pgfmathresult
	\pgfplotscoordmath{#5}{op}{cos}{{\pgfplots@deg}}%
	\pgfplotscoordmath{#5}{op}{multiply}{{\pgfplots@r}{\pgfmathresult}}%
	\let\pgfplots@x=\pgfmathresult
	\xdef\pgfplots@glob@TMPa{\noexpand\def\noexpand#3{\pgfplots@x}\noexpand\def\noexpand#4{\pgfplots@y}}%
	\endgroup
	\pgfplots@glob@TMPa
}%



\pgfutil@IfUndefined{pgfmathdeclarefunction}{%
	% BACKWARDS COMPATIBILITY: We have PGF 2.00 :
	\def\pgfplotsmathdeclarepseudoconstant#1#2{%
		\t@pgfplots@toka=\expandafter{\csname pgfmath#1@\endcsname}%
		\t@pgfplots@tokb={\pgfmath@postfunction}%
		\expandafter\edef\csname pgfmath@parsefunction@#1\endcsname{\the\t@pgfplots@toka\the\t@pgfplots@tokb}%
		\expandafter\edef\csname pgfmath#1\endcsname{\the\t@pgfplots@toka}%
		\expandafter\def\csname pgfmath#1@\endcsname{#2}%
	}%
	\let\pgfplotsmathredeclarepseudoconstant=\pgfplotsmathdeclarepseudoconstant
}{%
	\def\pgfplotsmathdeclarepseudoconstant#1#2{%
		\pgfmathdeclarefunction*{#1}{0}{#2}%
	}%
	\def\pgfplotsmathredeclarepseudoconstant#1#2{%
		\pgfmathredeclarefunction{#1}{#2}%
	}%
}%

\def\pgfplotsmathfloatln@#1{%
	\pgfmathfloatln@{#1}%
}

% Defines a macro which computes ln(x)/ln(#2) in float.
%
% #1: a macro name without backslash
% #2: the log base as fixed point number. Maybe the empty string in
% which case the natural log is used.
%
% It will define the macros:
% <macro>##1    -> calls \pgfmathfloatparsenumber and then the '@' variant:
% <macro>@##1   -> expects and returns result in float
% <macro>@tofixed##1 -> expects result in float, returns it in fixed (or an empty string)
% <macro>inv@##1   -> the inverse (exponential) function, expects float, returns float
% %
% <macro>logbase   -> the basis as number
% <macro>logofbasefixed -> log(#2)
% <macro>invlogofbasefixed -> 1/log(#2)
% <macro>logofbasefloat -> log(#2) in float
% <macro>invlogofbasefloat -> 1/log(#2) in float
\def\pgfplotsmathdefinemacrolnbase#1#2{%
	\expandafter\edef\csname #1logbase\endcsname{#2}%
	\expandafter\ifx\csname #1logbase\endcsname\pgfutil@empty
		\expandafter\edef\csname #1logbase\endcsname{2.718281828459}%
		\expandafter\def\csname #1logofbasefixed\endcsname{1}%
		\expandafter\def\csname #1invlogofbasefixed\endcsname{1}%
	\else
		\pgfmathlog@{\csname #1logbase\endcsname}%
		\expandafter\let\csname #1logofbasefixed\endcsname\pgfmathresult%
		\expandafter\pgfmath@basic@reciprocal@\expandafter{\pgfmathresult}%
		\expandafter\let\csname #1invlogofbasefixed\endcsname\pgfmathresult%
	\fi
	%
	\pgfmathfloatparsenumber{\csname #1logofbasefixed\endcsname}%
	\expandafter\let\csname #1logofbasefloat\endcsname\pgfmathresult%
	\pgfmathfloatparsenumber{\csname #1invlogofbasefixed\endcsname}%
	\expandafter\let\csname #1invlogofbasefloat\endcsname\pgfmathresult%
	%
	\expandafter\def\csname #1@tofixed\endcsname##1{%
		\pgfmathlog@float{##1}%
		\ifx\pgfmathresult\pgfutil@empty
		\else
			\expandafter\pgfmath@basic@multiply@\expandafter
				{\pgfmathresult}%
				{\csname #1invlogofbasefixed\endcsname}%
		\fi
	}%
	\expandafter\def\csname #1@\endcsname##1{%
		\expandafter\csname #1@tofixed\endcsname{##1}%
		\ifx\pgfmathresult\pgfutil@empty
			\pgfmathfloatcreate{3}{0.0}{0}%
		\else
			\pgfmathfloatparsenumber{\pgfmathresult}%
		\fi
	}%
	\expandafter\def\csname #1\endcsname##1{%
		\pgfmathfloatparsenumber{##1}%
		\csname #1@\endcsname{\pgfmathresult}%
	}%
	%
	\expandafter\def\csname #1inv@\endcsname##1{%
		\expandafter\pgfmathfloatmultiply@\expandafter{##1}{\csname #1logofbasefloat\endcsname}%
		\pgfmathfloatexp@{\pgfmathresult}%
	}%
}%

% Tests if string '#2' starts with pattern '#1'. 
%
% If so, it executes #3 and defines \pgfplotsretval to contain the
% suffix which is not equal to #1. Otherwise it executes #4.
\def\pgfplotsutilifstartswith#1#2#3#4{%
	\def\pgfplotsutilifstartswith@ ##1#1##2\pgfplots@EOI{%
		\def\pgfplotsutil@tmp{##1}%
		\ifx\pgfplotsutil@tmp\pgfutil@empty
			% Ah - a hit!
			%
			% define \pgfplotsretval to be the suffix...
			\def\pgfplotsutil@tmp#1####1\pgfplots@EOI{%
				\def\pgfplotsretval{####1}%
			}%
			\pgfplotsutil@tmp#2\pgfplots@EOI
			% 
			% ... and execute the <true> code:
			#3\relax
		\else
			% hm. No such prefix.
			#4\relax
		\fi
	}%
	\pgfplotsutilifstartswith@#2--#1\pgfplots@EOI
}%

% Usage:
% \pgfplotsutilstrreplace{<token>}{<replacement>}{<string>}
%
% -> will assign the modified string into \pgfplotsretval.
%
% #1: the string to search (one or more tokens)
% #2: zero, one or more tokens which will be inserted instead of '#1'.
% #3: the string to search in
\long\def\pgfplotsutilstrreplace#1#2#3{%
	\def\pgfplotsretval{}%
	\long\def\pgfplotsutil@search@and@replace@@##1#1##2\pgfplots@EOI{%
		\expandafter\def\expandafter\pgfplotsretval\expandafter{\pgfplotsretval ##1#2}%
		\pgfplotsutil@search@and@replace@loop{#1}{##2}%
	}%
	\pgfplotsutil@search@and@replace@loop{#1}{#3}%
}
\long\def\pgfplotsutil@search@and@replace@loop#1#2{%
	\pgfutil@in@{#1}{#2}%
	\ifpgfutil@in@
		\def\pgfplots@loc@TMPa{\pgfplotsutil@search@and@replace@@ #2\pgfplots@EOI}%
	\else
		\expandafter\def\expandafter\pgfplotsretval\expandafter{\pgfplotsretval #2}%
		\let\pgfplots@loc@TMPa=\relax
	\fi
	\pgfplots@loc@TMPa
}%

% strcmp: invokes #3 if #1=#2 (top level expansion only) and it
% invokes #4 if #1!=#2.
\long\def\pgfplotsutilifstringequal#1#2#3#4{%
	\def\pgfplotsifstringequal@{#1}%
	\def\pgfplotsifstringequal@@{#2}%
	\ifx\pgfplotsifstringequal@\pgfplotsifstringequal@@ #3\else #4\fi
}%

% this command is in pgfplotscore.code.tex:
% \pgfplotsiffileexists

% EXPERIMENTAL OPTIMIZATION:
\let\pgfmathparsex@orig=\pgfmathparse
\def\pgfmathparsex#1{%
	\begingroup
	\message{WORKING ON #1...}%
	\tracingmacros=2 \tracingcommands=2
	\let\pgfmath@parse@@@operator\relax
	\let\pgfmath@parse@@operator\relax
	\let\pgfmath@parse@operator\relax
	\let\pgfmath@stack@push@operand\pgfutil@gobble
	\let\pgfmath@base=\pgfmath@empty
	\let\pgfmath@number=\pgfmath@empty
	\let\pgfmath@parse@number@failed=\relax
    \edef\pgfmath@expression{#1}%
	\expandafter\pgfmathparsex@first\pgfmath@expression\pgfmathparsex@EOI%
	\if1\pgfmathparsex@recover@
		\xdef\pgfmathparsex@@{\noexpand\pgfmathparsex@orig{\pgfmath@expression}}%
	\else
		\xdef\pgfmathparsex@@{\noexpand\def\noexpand\pgfmathresult{\pgfmathresult}}%
	\fi
	\endgroup
	\pgfmathparsex@@
}%
\def\pgfmathparsex@first#1#2\pgfmathparsex@EOI{%
	\def\pgfmath@token@next{#1}%
	\pgfmath@parse@number{#2}%
}%
\def\pgfmathparsex@recover{\def\pgfmathparsex@recover@{1}}%
\def\pgfmathparsex@recover@{0}%


% compares YYYY-MM-DD < YYYY-MM-DD
%
% \pgfplotsutilifdatelessthan 2010-01-01\cmp 2011-01-01\relax{<true>}{<false>}
\long\def\pgfplotsutilifdatelessthan#1-#2-#3\cmp #4-#5-#6\relax#7#8{%
	\long\def\pgfplotsutilifdatelessthan@true{#7}%
	\long\def\pgfplotsutilifdatelessthan@false{#8}%
	\ifnum#1<#4\relax
		\pgfplotsutilifdatelessthan@true
	\else
		\ifnum#1>#4\relax
			\pgfplotsutilifdatelessthan@false
		\else
			\ifnum#2<#5\relax
				\pgfplotsutilifdatelessthan@true
			\else
				\ifnum#2>#5\relax
					\pgfplotsutilifdatelessthan@false
				\else
					\ifnum#3<#6\relax
						\pgfplotsutilifdatelessthan@true
					\else
						\pgfplotsutilifdatelessthan@false
					\fi
				\fi
			\fi
		\fi
	\fi
}%
\long\def\pgfplotsutilifdategreaterthan#1-#2-#3\cmp #4-#5-#6\relax#7#8{%
	\long\def\pgfplotsutilifdatelessthan@true{#7}%
	\long\def\pgfplotsutilifdatelessthan@false{#8}%
	\ifnum#1>#4\relax
		\pgfplotsutilifdatelessthan@true
	\else
		\ifnum#1<#4\relax
			\pgfplotsutilifdatelessthan@false
		\else
			\ifnum#2>#5\relax
				\pgfplotsutilifdatelessthan@true
			\else
				\ifnum#2<#5\relax
					\pgfplotsutilifdatelessthan@false
				\else
					\ifnum#3>#6\relax
						\pgfplotsutilifdatelessthan@true
					\else
						\pgfplotsutilifdatelessthan@false
					\fi
				\fi
			\fi
		\fi
	\fi
}%
\pgfkeys{%
	% /pgfplots/iflessthan{#1}{#2}{#3}{#4}:
	% #1: arg1 (a macro containing the first argument)
	% #2: arg2 (a macro containing the second argument)
	% #3: code to invoke in case arg1<arg2
	% #4: code to invoke in case arg1>=arg2
	% the iflessthan method will be invoked within local scopes.
	/pgfplots/fixed </.style={%
		/pgfplots/iflessthan/.code args={##1##2##3##4}{\ifdim##1pt<##2pt\relax##3\else ##4\fi},%
	},
	/pgfplots/fixed <,
	/pgfplots/fixed >/.style={%
		/pgfplots/iflessthan/.code args={##1##2##3##4}{\ifdim##1pt>##2pt\relax##3\else ##4\fi},%
	},
	/pgfplots/int </.style={%
		/pgfplots/iflessthan/.code args={##1##2##3##4}{\ifnum##1<##2\relax##3\else ##4\fi},%
	},
	/pgfplots/int >/.style={%
		/pgfplots/iflessthan/.code args={##1##2##3##4}{\ifnum##1>##2\relax##3\else ##4\fi},%
	},
	/pgfplots/float </.style={%
		/pgfplots/iflessthan/.code args={##1##2##3##4}{%
			\pgfmathfloatparsenumber{##1}%
			\let\pgfplots@iflt@arga=\pgfmathresult
			%
			\pgfmathfloatparsenumber{##2}%
			\let\pgfplots@iflt@argb=\pgfmathresult
			%
			\pgfmathfloatlessthan@{\pgfplots@iflt@arga}{\pgfplots@iflt@argb}%
			\ifpgfmathfloatcomparison
				##3%
			\else
				##4%
			\fi
		}%
	},%
	/pgfplots/float >/.style={%
		/pgfplots/iflessthan/.code args={##1##2##3##4}{%
			\pgfmathfloatparsenumber{##1}%
			\let\pgfplots@iflt@arga=\pgfmathresult
			%
			\pgfmathfloatparsenumber{##2}%
			\let\pgfplots@iflt@argb=\pgfmathresult
			%
			\pgfmathfloatgreaterthan@{\pgfplots@iflt@arga}{\pgfplots@iflt@argb}%
			\ifpgfmathfloatcomparison
				##3%
			\else
				##4%
			\fi
		}%
	},%
	% 
	% compares YYYY-MM-DD < YYYY-MM-DD
	/pgfplots/date </.style={%
		/pgfplots/iflessthan/.code args={##1##2##3##4}{%
			\edef\pgfplotsarray@ltdate{##1\noexpand\cmp ##2}%
			\expandafter\pgfplotsutilifdatelessthan\pgfplotsarray@ltdate\relax{##3}{##4}%
		}%
	},%
	/pgfplots/date >/.style={%
		/pgfplots/iflessthan/.code args={##1##2##3##4}{%
			\edef\pgfplotsarray@ltdate{##1\noexpand\cmp ##2}%
			\expandafter\pgfplotsutilifdategreaterthan\pgfplotsarray@ltdate\relax{##3}{##4}%
		}%
	},%
	%
	/pgfplots/string </.style={%
		/pgfplots/iflessthan/.code args={##1##2##3##4}{%
			\t@pgfplots@toka=\expandafter{##1}%
			\t@pgfplots@tokb=\expandafter{##2}%
			\edef\pgfplots@loc@TMPa{{\the\t@pgfplots@toka}{\the\t@pgfplots@tokb}}%
			\expandafter\pgfplotsutilstrcmp\pgfplots@loc@TMPa
			\if1\pgfplotsretval ##3\else ##4\fi
		}%
	},%
	/pgfplots/string >/.style={%
		/pgfplots/iflessthan/.code args={##1##2##3##4}{%
			\t@pgfplots@toka=\expandafter{##1}%
			\t@pgfplots@tokb=\expandafter{##2}%
			\edef\pgfplots@loc@TMPa{{\the\t@pgfplots@toka}{\the\t@pgfplots@tokb}}%
			\expandafter\pgfplotsutilstrcmp\pgfplots@loc@TMPa
			\if2\pgfplotsretval ##3\else ##4\fi
		}%
	},%
}

% defines \pgfplotsretval to be
%
% \ifpgfpicture #1\else #2\fi
%
% and handles the '/pgfplots/invoke before crossref tikzpicture' key.
% 
% #1 first argument to \ifpgfpicture
% #2 second argument to \ifpgfpicture
\def\pgfplots@assemble@ref@picture#1#2{%
	\begingroup
	\pgfkeysgetvalue{/pgfplots/invoke before crossref tikzpicture}\pgfplots@loc@TMPa
	\pgfkeysgetvalue{/pgfplots/invoke after crossref tikzpicture}\pgfplots@loc@TMPb
	\toks0={#1}%
	\toks1=\expandafter{\pgfplots@loc@TMPa}%
	\toks2={#2}%
	\toks3=\expandafter{\pgfplots@loc@TMPb}%
	\xdef\pgfplots@glob@TMPa{%
		\noexpand\ifpgfpicture
			\the\toks0 %
		\noexpand\else
			\the\toks1
			\the\toks2
			\the\toks3
		\noexpand\fi
	}%
	\endgroup
	\let\pgfplotsretval=\pgfplots@glob@TMPa
}%

\def\pgfplots@auxwrite@latex#1{%
	\if@filesw
		\immediate\write\@auxout{#1}%
	\fi
}%
\pgfutil@IfUndefined{if@filesw}{%
	\def\pgfplots@auxwrite#1{}%
}{%
	\let\pgfplots@auxwrite=\pgfplots@auxwrite@latex
}%

% sorts three elements.
%
% #1,#2,#3 are three macros containing the input.
% On output, these macros are redefined to represent the sorted range.
% The values of these macros must be a <dimen>, followed by anything
% else (but no \relax please)
%
% Example:
% \def\A{10pt furthervalues}
% \def\B{4pt value of b}
% \def\C{1pt value of c}
% \pgfplotsutilsortthree\A\B\C
% ->
% \A={1pt value of c}
% \B={4pt value of b}
% \C={10pt furthervalues}
%
% It uses insertion sort.
\def\pgfplotsutilsortthree#1#2#3{%
	\afterassignment\pgfplots@gobble@until@relax \pgf@xa=#1\relax
	\afterassignment\pgfplots@gobble@until@relax \pgf@xb=#2\relax
	\ifdim\pgf@xa>\pgf@xb
		\let\pgfplots@loc@TMPa=#2%
		\let#2=#1%
		\let#1=\pgfplots@loc@TMPa%
	\fi
	% first two are sorted.
	%
	\afterassignment\pgfplots@gobble@until@relax \pgf@xa=#2\relax
	\afterassignment\pgfplots@gobble@until@relax \pgf@xb=#3\relax
	\let\pgfplots@loc@TMPa=#3%
	\ifdim\pgf@xa>\pgf@xb
		\let#3=#2%
		\afterassignment\pgfplots@gobble@until@relax \pgf@xa=#1\relax
		\ifdim\pgf@xa>\pgf@xb
			\let#2=#1%
			\let#1=\pgfplots@loc@TMPa%
		\else
			\let#2=\pgfplots@loc@TMPa%
		\fi
	\fi
	% ok.
}%

% Like \pgfplotsutilsortthree, but for four elements (of the same
% form, see \pgfplotsutilsortthree).
%
% It uses insertion sort.
\def\pgfplotsutilsortfour#1#2#3#4{%
	\afterassignment\pgfplots@gobble@until@relax \pgf@xa=#1\relax
	\afterassignment\pgfplots@gobble@until@relax \pgf@xb=#2\relax
	\ifdim\pgf@xa>\pgf@xb
		\let\pgfplots@loc@TMPa=#2%
		\let#2=#1%
		\let#1=\pgfplots@loc@TMPa%
	\fi
	% first two are sorted.
	%
	\afterassignment\pgfplots@gobble@until@relax \pgf@xa=#2\relax
	\afterassignment\pgfplots@gobble@until@relax \pgf@xb=#3\relax
	\let\pgfplots@loc@TMPa=#3%
	\ifdim\pgf@xa>\pgf@xb
		\let#3=#2%
		\afterassignment\pgfplots@gobble@until@relax \pgf@xa=#1\relax
		\ifdim\pgf@xa>\pgf@xb
			\let#2=#1%
			\let#1=\pgfplots@loc@TMPa%
		\else
			\let#2=\pgfplots@loc@TMPa%
		\fi
	\fi
	% ok, first three are sorted.
	%
	\afterassignment\pgfplots@gobble@until@relax \pgf@xa=#3\relax
	\afterassignment\pgfplots@gobble@until@relax \pgf@xb=#4\relax
	\let\pgfplots@loc@TMPa=#4%
	\ifdim\pgf@xa>\pgf@xb
		\let#4=#3%
		\afterassignment\pgfplots@gobble@until@relax \pgf@xa=#2\relax
		\ifdim\pgf@xa>\pgf@xb
			\let#3=#2%
			\afterassignment\pgfplots@gobble@until@relax \pgf@xa=#1\relax
			\ifdim\pgf@xa>\pgf@xb
				\let#2=#1%
				\let#1=\pgfplots@loc@TMPa%
			\else
				\let#2=\pgfplots@loc@TMPa%
			\fi
		\else
			\let#3=\pgfplots@loc@TMPa%
		\fi
	\fi
	% ok, first four are sorted.
}%

% A variant of \pgfutil@ifnextchar which allows the '#' character
% inside of either '#2' or '#3'.
%
% It is slightly more expensive and relies on \t@pgfplots@tokc
\long\def\pgfplotsutil@ifnextchar#1#2#3{%
  \let\pgfplotsutil@reserved@d=#1%
  \t@pgfplots@tokc={#2}%
  \edef\pgfplotsutil@reserved@a{\the\t@pgfplots@tokc}%
  \t@pgfplots@tokc={#3}%
  \def\pgfplotsutil@reserved@b{\the\t@pgfplots@tokc}%
  \futurelet\pgfplotsutil@let@token\pgfplotsutil@ifnch}
\def\pgfplotsutil@ifnch{%
  \ifx\pgfplotsutil@let@token\pgfplotsutil@sptoken
    \let\pgfplotsutil@reserved@c\pgfplotsutil@xifnch
  \else
    \ifx\pgfplotsutil@let@token\pgfplotsutil@reserved@d
      \let\pgfplotsutil@reserved@c\pgfplotsutil@reserved@a
    \else
      \let\pgfplotsutil@reserved@c\pgfplotsutil@reserved@b
    \fi
  \fi
  \pgfplotsutil@reserved@c}
{%
  \def\:{\global\let\pgfplotsutil@sptoken= } \:
  \def\:{\pgfplotsutil@xifnch} \expandafter\gdef\: {\futurelet\pgfplotsutil@let@token\pgfplotsutil@ifnch}
}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% basic 3d linear algebra utils.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Converts a 3d vectors to string.
% #1: a vector which expands to the form 'x,y,z'
% on output, \pgfplotsretval will contain the result vector.
% #3: the argument for \pgfplotscoordmath (such as 'default')
% 
\def\pgfplotsmathvectortostring#1#2{%
	\begingroup
	\edef\pgfplots@loc@TMPa{#1}%
	\expandafter\pgfplotsmathvectorcompwiseop@unary\pgfplots@loc@TMPa\pgfplots@EOI{#2}{{tostring}}%
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%

% Reads a 3d vector's coordinates.
% #1: a vector which expands to the form 'x,y,z'
% on output, \pgfplotsretval will contain the result vector.
% #2: the argument for \pgfplotscoordmath (such as 'default')
% 
% Example:
% \pgfplotsmathvectorfromstring{1,4,5}{default}
% will parse each component
\def\pgfplotsmathvectorfromstring#1#2{%
	\begingroup
	\edef\pgfplots@loc@TMPa{#1}%
	\expandafter\pgfplotsmathvectorcompwiseop@unary\pgfplots@loc@TMPa\pgfplots@EOI{#2}{{parsenumber}}%
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%

% Takes two 3d vectors and subtracts them.
% #1: a vector which expands to the form 'x,y,z'
% #2: a vector which expands to the form 'x,y,z'
% on output, \pgfplotsretval will contain the difference vector.
% #3: the argument for \pgfplotscoordmath (such as 'default')
% 
\def\pgfplotsmathvectorsubtract#1#2#3{%
	\begingroup
	\edef\pgfplots@loc@TMPa{#1:#2}%
	\expandafter\pgfplotsmathvectorcompwiseop@binary\pgfplots@loc@TMPa\pgfplots@EOI{#3}{subtract}%
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%
\def\pgfplotsmathvectorcompwiseop@binary#1,#2,#3:#4,#5,#6\pgfplots@EOI#7#8{%
	\def\Ax{#1}%
	\def\Ay{#2}%
	\def\Az{#3}%
	\def\Bx{#4}%
	\def\By{#5}%
	\def\Bz{#6}%
	\pgfplotscoordmath{#7}{op}{#8}{{\Ax}{\Bx}}%
	\let\pgfplots@loc@TMPa=\pgfmathresult
	\pgfplotscoordmath{#7}{op}{#8}{{\Ay}{\By}}%
	\let\pgfplots@loc@TMPb=\pgfmathresult
	\pgfplotscoordmath{#7}{op}{#8}{{\Az}{\Bz}}%
	\let\pgfplots@loc@TMPc=\pgfmathresult
	\edef\pgfplotsretval{\pgfplots@loc@TMPa,\pgfplots@loc@TMPb,\pgfplots@loc@TMPc}%
}%

% #5: an operation ENCLOSED IN BRACES!
% like '{tostring}' or '{op}{<someunaryop>}'
\def\pgfplotsmathvectorcompwiseop@unary#1,#2,#3\pgfplots@EOI#4#5{%
	\def\Ax{#1}%
	\def\Ay{#2}%
	\def\Az{#3}%
	\pgfplotscoordmath{#4}#5{\Ax}%
	\let\pgfplots@loc@TMPa=\pgfmathresult
	\pgfplotscoordmath{#4}#5{\Ay}%
	\let\pgfplots@loc@TMPb=\pgfmathresult
	\pgfplotscoordmath{#4}#5{\Az}%
	\let\pgfplots@loc@TMPc=\pgfmathresult
	\edef\pgfplotsretval{\pgfplots@loc@TMPa,\pgfplots@loc@TMPb,\pgfplots@loc@TMPc}%
}%

% Takes two 3d vectors and adds them.
% #1: a vector which expands to the form 'x,y,z'
% #2: a vector which expands to the form 'x,y,z'
% on output, \pgfplotsretval will contain the added vector.
% #3: the argument for \pgfplotscoordmath (such as 'default')
% 
\def\pgfplotsmathvectoradd#1#2#3{%
	\begingroup
	\edef\pgfplots@loc@TMPa{#1:#2}%
	\expandafter\pgfplotsmathvectorcompwiseop@binary\pgfplots@loc@TMPa\pgfplots@EOI{#3}{add}%
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%

% Takes two 3d vectors and applies a component-wise operation.
% #1: a vector which expands to the form 'x,y,z'
% #2: a vector which expands to the form 'x,y,z'
% on output, \pgfplotsretval will contain a boolean vector with three
% entries.
% #3: a scalar operation which takes two arguments (such as "add", "subtract", "equal")
% #4 the argument for \pgfplotscoordmath (such as 'default')
% 
% Example: \pgfplotsmathvectorcompwise{1,1,1}{0,1,0}{add}{pgfbasic}
% -> \pgfplotsretval={1.0,2.0,1.0}
\def\pgfplotsmathvectorcompwise#1#2#3#4{%
	\begingroup
	\edef\pgfplots@loc@TMPa{#1:#2}%
	\expandafter\pgfplotsmathvectorcompwiseop@binary\pgfplots@loc@TMPa\pgfplots@EOI{#4}{#3}%
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%

% Defines \pgfplotsretval to x+y+z
% #1: a vector which expands to the form 'x,y,z'
% on output, \pgfplotsretval will contain the result scalar.
% #2: the argument for \pgfplotscoordmath (such as 'default')
% 
% Example:
% \pgfplotsmathvectorsum{1,4,5}{default}
% \pgfplotsretval = 10 (in that format)
\def\pgfplotsmathvectorsum#1#2{%
	\begingroup
	\edef\pgfplots@loc@TMPa{#1}%
	\expandafter\pgfplotsmathvectorsum@\pgfplots@loc@TMPa\pgfplots@EOI{#2}%
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%

\def\pgfplotsmathvectorsum@#1,#2,#3\pgfplots@EOI#4{%
	\def\Ax{#1}%
	\def\Ay{#2}%
	\def\Az{#3}%
	\pgfplotscoordmath{#4}{op}{add}{{\Ax}{\Ay}}%
	\let\pgfplotsretval=\pgfmathresult
	\pgfplotscoordmath{#4}{op}{add}{{\pgfplotsretval}{\Az}}%
	\let\pgfplotsretval=\pgfmathresult
}%

% Computes the euclidean scalar product of two 3d vectors #1 and #2 in math
% format #3.
\def\pgfplotsmathvectorscalarproduct#1#2#3{%
	\pgfplotsmathvectorscaleindividually{#1}{#2}{#3}%
	\pgfplotsmathvectorsum{\pgfplotsretval}{#3}%
}%

% takes a vector #1 and defines three new macros 
% \csname #2x\endcsname, 
% \csname #2y\endcsname, 
% \csname #2z\endcsname, 
% with the components.
% #3: the math format
\def\pgfplotsmathvectortocomponents#1#2#3{%
	\edef\pgfplots@loc@TMPa{#1}%
	\expandafter\pgfplotsmathvectortocomponents@\pgfplots@loc@TMPa\pgfplots@EOI{#3}{#2}%
}%
\def\pgfplotsmathvectortocomponents@#1,#2,#3\pgfplots@EOI#4#5{%
	\expandafter\def\csname #5x\endcsname{#1}%
	\expandafter\def\csname #5y\endcsname{#2}%
	\expandafter\def\csname #5z\endcsname{#3}%
}%


% Takes two 3d vectors and computes their cross product.
% #1: a vector which expands to the form 'x,y,z'
% #2: a vector which expands to the form 'x,y,z'
% on output, \pgfplotsretval will contain the result vector.
% #3: the argument for \pgfplotscoordmath (such as 'default')
%
\def\pgfplotsmathvectorcrossprod#1#2#3{%
	\begingroup
	\edef\pgfplots@loc@TMPa{#1:#2}%
	\expandafter\pgfplotsmathvectorcrossprod@\pgfplots@loc@TMPa\pgfplots@EOI{#3}%
%\message{\string\pgfplotsmathvectorcrossprod{#1}{#2} = \pgfplotsretval^^J}%
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%
\def\pgfplotsmathvectorcrossprod@#1,#2,#3:#4,#5,#6\pgfplots@EOI#7{%
	\def\Ax{#1}%
	\def\Ay{#2}%
	\def\Az{#3}%
	\def\Bx{#4}%
	\def\By{#5}%
	\def\Bz{#6}%
	%
	\pgfplotscoordmath{#7}{op}{multiply}{{\Ay}{\Bz}}\let\AyBz=\pgfmathresult
	\pgfplotscoordmath{#7}{op}{multiply}{{\Az}{\By}}\let\AzBy=\pgfmathresult
	\pgfplotscoordmath{#7}{op}{multiply}{{\Az}{\Bx}}\let\AzBx=\pgfmathresult
	\pgfplotscoordmath{#7}{op}{multiply}{{\Ax}{\Bz}}\let\AxBz=\pgfmathresult
	\pgfplotscoordmath{#7}{op}{multiply}{{\Ax}{\By}}\let\AxBy=\pgfmathresult
	\pgfplotscoordmath{#7}{op}{multiply}{{\Ay}{\Bx}}\let\AyBx=\pgfmathresult
	%
	\pgfplotscoordmath{#7}{op}{subtract}{{\AyBz}{\AzBy}}\let\pgfplots@loc@TMPa=\pgfmathresult%
	\pgfplotscoordmath{#7}{op}{subtract}{{\AzBx}{\AxBz}}\let\pgfplots@loc@TMPb=\pgfmathresult%
	\pgfplotscoordmath{#7}{op}{subtract}{{\AxBy}{\AyBx}}\let\pgfplots@loc@TMPc=\pgfmathresult%
	\edef\pgfplotsretval{\pgfplots@loc@TMPa,\pgfplots@loc@TMPb,\pgfplots@loc@TMPc}%
}%

% Takes two 3d vectors and defines a new vector (Ax*Bx,Ay*By,Az*Bz)
% #1: a vector which expands to the form 'x,y,z'
% #2: a vector which expands to the form 'x,y,z'
% on output, \pgfplotsretval will contain the result vector.
% #3: the argument for \pgfplotscoordmath (such as 'default')
%
\def\pgfplotsmathvectorscaleindividually#1#2#3{%
	\begingroup
	\edef\pgfplots@loc@TMPa{#1:#2}%
	\expandafter\pgfplotsmathvectorscaleindividually@\pgfplots@loc@TMPa\pgfplots@EOI{#3}%
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%
\def\pgfplotsmathvectorscaleindividually@#1,#2,#3:#4,#5,#6\pgfplots@EOI#7{%
	\def\Ax{#1}%
	\def\Ay{#2}%
	\def\Az{#3}%
	\def\Bx{#4}%
	\def\By{#5}%
	\def\Bz{#6}%
	%
	\pgfplotscoordmath{#7}{op}{multiply}{{\Ax}{\Bx}}\let\Cx=\pgfmathresult
	\pgfplotscoordmath{#7}{op}{multiply}{{\Ay}{\By}}\let\Cy=\pgfmathresult
	\pgfplotscoordmath{#7}{op}{multiply}{{\Az}{\Bz}}\let\Cz=\pgfmathresult
	%
	\edef\pgfplotsretval{\Cx,\Cy,\Cz}%
}%

% #1 a vector as x,y,z
% #2 the math format of its components
\def\pgfplotspointfromcsvvector#1#2{%
	\begingroup
	\edef\pgfplots@loc@TMPa{#1}%
	\expandafter\pgfplotspointfromcsvvector@\pgfplots@loc@TMPa\pgfplots@EOI{#2}
	\endgroup
}%
\def\pgfplotspointfromcsvvector@#1,#2,#3\pgfplots@EOI#4{%
	\pgfplotscoordmath{#4}{tofixed}{#1}\let\Ax=\pgfmathresult
	\pgfplotscoordmath{#4}{tofixed}{#2}\let\Ay=\pgfmathresult
	\pgfplotscoordmath{#4}{tofixed}{#3}\let\Az=\pgfmathresult
	\pgfplotsqpointxyz\Ax\Ay\Az
	\pgf@process{}%
}%

% #1 a vector as (x,y,z)
% #2 a coordmath value
% defines \pgfplotsretval to contain the vector length
\def\pgfplotsmathvectorlength#1#2{%
	\begingroup
	\edef\pgfplots@loc@TMPa{#1}%
	\expandafter\pgfplotsmathvectorlength@\pgfplots@loc@TMPa\pgfplots@EOI{#2}%
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%
\def\pgfplotsmathvectorlength@#1,#2,#3\pgfplots@EOI#4{%
	\begingroup
	\def\Ax{#1}%
	\def\Ay{#2}%
	\def\Az{#3}%
	%
	\pgfplotscoordmath{#4}{op}{multiply}{{\Ax}{\Ax}}\let\Axx=\pgfmathresult
	\pgfplotscoordmath{#4}{op}{multiply}{{\Ay}{\Ay}}\let\Ayy=\pgfmathresult
	\pgfplotscoordmath{#4}{op}{multiply}{{\Az}{\Az}}\let\Azz=\pgfmathresult
	%
	\pgfplotscoordmath{#4}{op}{add}{{\Axx}{\Ayy}}%
	\pgfplotscoordmath{#4}{op}{add}{{\Azz}{\pgfmathresult}}%
	\pgfplotscoordmath{#4}{op}{sqrt}{{\pgfmathresult}}%
	\let\pgfplotsretval=\pgfmathresult
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%

% #1 a vector as (x,y,z)
% #2 a scale
% #3 a coordmath value
% defines \pgfplotsretval to contain the scaled vector
\def\pgfplotsmathvectorscale#1#2#3{%
	\begingroup
	\edef\pgfplots@loc@TMPa{#1:#2}%
	\expandafter\pgfplotsmathvectorscale@\pgfplots@loc@TMPa\pgfplots@EOI{#3}%
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%
\def\pgfplotsmathvectorscale@#1,#2,#3:#4\pgfplots@EOI#5{%
	\begingroup
	\def\Ax{#1}%
	\def\Ay{#2}%
	\def\Az{#3}%
	\pgfplotscoordmath{#5}{parsenumber}{#4}\let\S\pgfmathresult
	%
	\pgfplotscoordmath{#5}{op}{multiply}{{\Ax}{\S}}\let\Ax=\pgfmathresult
	\pgfplotscoordmath{#5}{op}{multiply}{{\Ay}{\S}}\let\Ay=\pgfmathresult
	\pgfplotscoordmath{#5}{op}{multiply}{{\Az}{\S}}\let\Az=\pgfmathresult
	%
	\edef\pgfplotsretval{\Ax,\Ay,\Az}%
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%

% Takes an input vector #1 = x,y,z and applies the inverse data scale
% trafo.
%
% The result is \pgfplotsretval; it will be in '#2' coordmath for
% every component.
\def\pgfplotsmathvectordatascaletrafoinverse#1#2{%
	\begingroup
	\edef\pgfplots@loc@TMPa{#1}%
	\expandafter\pgfplotsmathvectordatascaletrafoinverse@\pgfplots@loc@TMPa\pgfplots@EOI{#2}%
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}
\def\pgfplotsmathvectordatascaletrafoinverse@#1,#2,#3\pgfplots@EOI#4{%
	\begingroup
	\def\Ax{#1}%
	\def\Ay{#2}%
	\def\Az{#3}%
	\ifpgfplots@apply@datatrafo@x
		\pgfplotscoordmath{x}{datascaletrafo inverse}{\Ax}\let\Ax=\pgfmathresult
	\fi
	\ifpgfplots@apply@datatrafo@y
		\pgfplotscoordmath{y}{datascaletrafo inverse}{\Ay}\let\Ay=\pgfmathresult
	\fi
	\ifpgfplots@curplot@threedim
		\ifpgfplots@apply@datatrafo@z
			\pgfplotscoordmath{z}{datascaletrafo inverse}{\Az}\let\Az=\pgfmathresult
		\fi
	\fi
	\pgfplotsmathvectorfromstring{\Ax,\Ay,\Az}{#4}%
	\pgfmath@smuggleone\pgfplotsretval
	\endgroup
}%


{
\catcode`\"=12
\gdef\pgfplotsDQ{"}%
\catcode`\|=12
\gdef\pgfplotsVERTBAR{|}%
\catcode`\#=12
\gdef\pgfplotsHASH{#}%
\catcode`\%=12 \gdef\pgfplotsPERCENT{%}}

\pgfutil@IfUndefined{directlua}{}{%
	\directlua{require(\pgfplotsDQ pgfplots\pgfplotsDQ)}%
}%

% swaps the content of two macros
\def\pgfplotsutil@swap#1#2{%
	\let\pgfplotsutil@swap@=#1%
	\let#1=#2%
	\let#2=\pgfplotsutil@swap@
}%

\input pgfplotsliststructure.code.tex
\input pgfplotsliststructureext.code.tex
\input pgfplotsarray.code.tex
\input pgfplotsmatrix.code.tex
\input pgfplotstableshared.code.tex
\input pgfplotsdeque.code.tex
\input pgfplotsbinary.code.tex
\input pgfplotsutil.verb.code.tex

\usepgfplotslibrary{surfshading}

\endinput

pgfplotsutil.verb.code.tex
%--------------------------------------------
%
% Package pgfplots
%
% Copyright 2007-2011 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------
%
% This source file contains helper utilities for verbatim character
% processing.


%
% USAGE: 
% \beginpgfplotsverbatim[result/.code={\message{I read #1}}]
% <verbatim code>
% \endpgfplotsverbatim
%
% The verbatim code MUST start at the line after the ']' (or after
% \beginpgfplotsverbatim if there is no ']')
\def\beginpgfplotsverbatim{\pgfutil@ifnextchar[{\beginpgfplotsverbatim@}{\beginpgfplotsverbatim@[]}}
\def\beginpgfplotsverbatim@[#1]{%
	\begingroup
	\pgfqkeys{/pgfplots/verb}{#1}%
	\pgfplots@verbatim@prepare@collect
	\beginpgfplotsverbatim@gobbleuntileol
}

\begingroup
\catcode`\|=0
\catcode`\\=12
|gdef|endpgfplotsverbatim{\endpgfplotsverbatim}%
|endgroup

\expandafter\long\expandafter\def\expandafter\pgfplots@verbatim@collect@until\expandafter#\expandafter1\endpgfplotsverbatim{%
	\begingroup
	\pgfplots@verbatim@newline@handler
	\xdef\pgfplots@glob@TMPa{#1}%
	\endgroup
	\pgfkeysgetvalue{/pgfplots/verb/result/.@cmd}\pgfplots@loc@TMPb
	\global\let\pgfplots@glob@TMPb=\pgfplots@loc@TMPb
	\endgroup% restore old catcodes etc.
	\expandafter\pgfplots@glob@TMPb\expandafter{\pgfplots@glob@TMPa}\pgfeov%
}%

\begingroup
\long\def\pgfplots@loc@TMPa{
}%^^M}%
\catcode`\^^M=13 %
\gdef\beginpgfplotsverbatim@gobbleuntileol^^M{\pgfplots@verbatim@collect@until}%
\gdef\pgfplots@verbatim@newline@toHATHATJ{\def^^M{^^J}}%
\xdef\pgfplots@verbatim@newline@IDENTITY{\noexpand\long\noexpand\def\noexpand^^M{\pgfplots@loc@TMPa}}%
\endgroup

\pgfkeys{
	/pgfplots/verb/result/.code={%
		\pgfplots@error{Please use \string\beginpgfplotsverbatim[result/.code=....] to configure what to do with the content of \string\beginpgfplotsverbatim...\endpgfplotsverbatim\space (or use \string\pgfplotsset{verb/.cd,result/.code=....} in your preamble)}%
	},
	/pgfplots/verb/newline handler/.is choice,
	/pgfplots/verb/newline handler/to outfile/.code=
		{\let\pgfplots@verbatim@newline@handler=\pgfplots@verbatim@newline@toHATHATJ},
	/pgfplots/verb/newline handler/identity/.code=
		{\let\pgfplots@verbatim@newline@handler=\pgfplots@verbatim@newline@IDENTITY},
	/pgfplots/verb/newline handler/identity,
}

\def\pgfplots@verbatim@prepare@collect{%
	\def\do##1{\catcode`##1=12 }\dospecials
	\catcode`\^^M=13
	\catcode`\^^J=12
	\catcode`\^^I=12
}%

\def\pgfplots@verbatim@restore@catcodes{%
	\catcode`\^^M=5
	\catcode`\^^J=10
	\catcode`\^^I=10
	% this is important to get \scantokens to work: otherwise, it will
	% eat up the ^^M chars:
	\endlinechar=`\^^M
	\newlinechar=\endlinechar
}%

\endinput

pgfrcs.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.



% The purpose of this file is to define the command
% \ProvidesPackageRCS, which should be followed by an RCS id
% string. This command will also be available in plain TeX, where it
% prints out a message to the log.


\def\pgfversion{3.0.0}
\def\pgftypesetversion{\oldstylenums{3}.\oldstylenums{0}.\oldstylenums{0}}


\ifx\pgfrcsloaded\undefined
\def\pgfrcsloaded{}

\edef\pgfrcsatcode{\the\catcode`\@}
\catcode`\@=11

% Get date and version from RCS Ids
\def\pgf@parseid $#1: #2.#3,v #4 #5/#6/#7 #8${%
  \pgf@parsercsfile$#2/$
  \def\pgf@rcssuffix{#3}
  \def\pgf@rcsrevision{#4}
  \def\pgf@rcsdate{#5/#6/#7}
}
\def\pgf@parsercsfile$#1/#2${
  \def\pgf@temp{#2}
  \ifx\pgf@temp\pgfutil@empty
    \def\pgf@rcsfile{#1}
  \else
    \pgf@parsercsfile$#2$
  \fi}

\def\ProvidesFileRCS{%
  \def\pgfrcs@marshal{\ProvidesFile{\pgf@rcsfile.\pgf@rcssuffix}}%
  \pgfrcs@parserest%
}

\def\ProvidesPackageRCS{%
  \def\pgfrcs@marshal{\ProvidesPackage{\pgf@rcsfile}}%
  \pgfrcs@parserest%
}

\def\pgfrcs@parserest{%
  \def\pgf@rcsadditional{}%
  \afterassignment\pgfrcs@checkforoptional\let\next=}

\def\pgfrcs@checkforoptional{%
  \ifx\next[%
    \let\next=\pgfrcs@getoptional%
  \else
    \let\next=\pgfrcs@package%
  \fi%
  \next}%}

\def\pgfrcs@getoptional#1] ${%
  \def\pgf@rcsadditional{#1}%
  \pgfrcs@package%
}

\def\pgfrcs@package#1${
  \pgf@parseid $#1$
  \pgfrcs@marshal[\pgf@rcsdate\space\pgf@rcsadditional\space(rcs-revision \pgf@rcsrevision)]
}

\def\ProvidesClassRCS $#1$ [#2]{%
  \pgf@parseid $#1$
  \ProvidesClass{\pgf@rcsfile}[\pgf@rcsdate\space#2\space (rcs-revision \pgf@rcsrevision)]
}

\ifx\ProvidesPackage\@undefined
  % plain tex
  \def\ProvidesPackage#1[#2]{\wlog{Loading package #1 version #2.}}
\fi

\ifx\ProvidesFile\@undefined
  % plain tex
  \def\ProvidesFile#1[#2]{\wlog{Loading file #1 version #2.}}
\fi

\ProvidesPackageRCS[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/utilities/pgfrcs.code.tex,v 1.28 2013/12/20 14:44:47 tantau Exp $

\catcode`\@=\pgfrcsatcode

\fi


% Local Variables:
% coding: undecided-unix
% End:

pgfsys.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesPackageRCS[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/systemlayer/pgfsys.code.tex,v 1.47 2013/11/30 11:35:10 ludewich Exp $


% Load key mechanism
\input pgfkeys.code.tex

% "pgf" is a family
\pgfkeys{/pgf/.is family}
\def\pgfset{\pgfqkeys{/pgf}}

% This is if is needed *very* early
\newif\ifpgfpicture


%
% The following conversion functions are used to convert from TeX
% dimensions to postscript/pdf points.
% 
{\catcode`\p=12\catcode`\t=12\gdef\Pgf@geT#1pt{#1}}

\def\pgf@sys@tonumber#1{\expandafter\Pgf@geT\the#1}

\def\pgf@sys@bp@correct#1{#1=0.99627#1}

\def\pgf@sys@bp#1{%
  {%
    \pgf@x=#1\relax%
    \pgf@x=0.99627\pgf@x%
    \edef\temp{\expandafter\Pgf@geT\the\pgf@x\space}%
    \pgfutil@toks@\expandafter\expandafter\expandafter{\expandafter\pgfsysprotocol@currentprotocol\temp}%
    \xdef\pgfsysprotocol@currentprotocol{\the\pgfutil@toks@}%
  }%
}
\def\pgf@sys@pt#1{%
  {%
    \pgf@x=#1\relax%
    \edef\temp{\expandafter\Pgf@geT\the\pgf@x\space}%
    \pgfutil@toks@\expandafter\expandafter\expandafter{\expandafter\pgfsysprotocol@currentprotocol\temp}%
    \xdef\pgfsysprotocol@currentprotocol{\the\pgfutil@toks@}%
  }%
}


% internal dimensions that are always present when pgsys is loaded.
\newdimen\pgf@x
\newdimen\pgf@y
\newdimen\pgf@xa
\newdimen\pgf@ya
\newdimen\pgf@xb
\newdimen\pgf@yb
\newdimen\pgf@xc
\newdimen\pgf@yc

\newwrite\w@pgf@writea
\newread\r@pgf@reada
\let\pgfutil@inputcheck=\r@pgf@reada

% internal counters that are alwyas present when pgfsys is loaded
\newcount\c@pgf@counta
\newcount\c@pgf@countb
\newcount\c@pgf@countc
\newcount\c@pgf@countd

\newtoks\t@pgf@toka
\newtoks\t@pgf@tokb
\newtoks\t@pgf@tokc

% Ensure that math registers are the same (math is broken in case it
% is loaded first)
\let\pgfmath@x\pgf@x
\let\pgfmath@xa\pgf@xa
\let\pgfmath@xb\pgf@xb
\let\pgfmath@xc\pgf@xc

\let\pgfmath@y\pgf@y
\let\pgfmath@ya\pgf@ya
\let\pgfmath@yb\pgf@yb
\let\pgfmath@yc\pgf@yc

\let\c@pgfmath@counta\c@pgf@counta
\let\c@pgfmath@countb\c@pgf@countb
\let\c@pgfmath@countc\c@pgf@countc
\let\c@pgfmath@countd\c@pgf@countd



% The following \if decides, whether even-odd filling and clipping is
% to be used or normal the non-zero winding number rule. See the
% pdf-documentation for details on what these rules are.

\newif\ifpgfsys@eorule



% In the following dummy definitions of the pgf system commands are
% given. The individual drivers must overwrite these definitions,
% preferably all of them. If some system command is used that has not
% been overwritten, the command fails with a warning.
%
% In some cases, some pgf system commands are just shorthands for a
% series of more complicated commands. In this case, a default
% implementation is given in this file, but a driver may choose to
% overwrite this default implementation with a more effecient
% version. For example, a closestroke is the same as a closepath
% followed by a stroking, but in pdf there is a special shorthand for
% this. So, the pdf driver overwrites \pgfsys@closestroke, while the
% postscript driver does not.
%
% The commands for which default implementations are available are
% given at the end.

\def\pgf@sys@fail#1{%
  \expandafter\ifx\csname pgf@sys@fail@#1\endcsname\pgfutil@empty%
  \else%
    \expandafter\global\expandafter\let\csname pgf@sys@fail@#1\endcsname=\pgfutil@empty%
    \pgfwarning{Your graphic driver \pgfsysdriver\space does not support #1. This warning is given only once}%
  \fi%
}



\def\pgfsys@invoke{\pgf@sys@fail{invoking specials}}
% This command is used whenever some literal text needs to be inserted
% into the resulting .pdf, .ps, or .dvi file. Note that most
% \pgfsys@xxxx commands will not directly call this command, but,
% rather, use the protocolling mechanism to record their literal
% text. It is then left to the discretion of the protocolling
% mechansim to insert the literal text at some appropriate, later
% time. 
%
% This command should only be called when \pgfsys@beginpicture has
% been called previously and when the picture has not been suspended
% using \pgfsys@beginhbox.


\def\pgfsys@outerinvoke{\pgfsys@invoke}
% This command can be used to insert protocolled graphic commands
% outside any picture. This is extremely dangerous, but sometimes
% useful. By default, this command does the same as inside pictures. 



%
%
% Path construction commands
%
%

\def\pgfsys@moveto#1#2{\pgf@sys@fail{path constructions}}
% This command is used to start a path at a specific point (#1,#2)
% or to move the current point of the current path to (#1,#2)
% without drawing anything upon stroking (the current path is
% `interrupted'). 
%
% The arguments must be dimensions (like |10pt|).
%
% Example:
%
% \pgfsys@moveto{10pt}{10pt}
% \pgfsys@lineto{0pt}{0pt}
% \pgfsys@stroke
%
% This will draw a line from (10pt,10pt) to the origin of the picture.

\def\pgfsys@lineto#1#2{\pgf@sys@fail{path constructions}}
% Continue the current path to (#1,#2) with a line.

\def\pgfsys@curveto#1#2#3#4#5#6{\pgf@sys@fail{path constructions}}
% Continue the current path with a bezier curver to (#5,#6). The
% control points of the curve are at (#1,#2) and (#3,#4).

\def\pgfsys@rect#1#2#3#4{\pgf@sys@fail{path constructions}}
% Append a rectangle to the current path whose lower left corner is at
% (#1,#2) and whose width/height is given by (#3,#4).
%
% This command can be `mapped back' to moveto and lineto commands, but
% it is included since pdf has a special, quick version of this command.

\def\pgfsys@closepath{\pgf@sys@fail{path constructions}}
% Close the current path. This results in joining the current point of
% the path with the point specified by the last moveto
% operation. Typically, this is preferable over using lineto to the
% last point specified by a moveto, since the line starting at this
% point and the line ending at this point will be smoothly joined by
% closepath. 
%
% Example:
%
% \pgfsys@moveto{0}{0}
% \pgfsys@lineto{10}{10}
% \pgfsys@lineto{0}{10}
% \pgfsys@closepath
% \pgfsys@stroke
%
% versus
%
% \pgfsys@moveto{0}{0}
% \pgfsys@lineto{10}{10}
% \pgfsys@lineto{0}{10}
% \pgfsys@lineto{0}{0}
% \pgfsys@stroke
% 
% The difference between the above will be that in the second triangle
% the corner at the origin will be wrong; it will just be the overlay
% of two lines going in different directions, not a sharp pointed
% corner.






%
%
% Stroking and filling commands
%
%

\def\pgfsys@stroke{\pgf@sys@fail{path usage}}
% Stroke the current path (as if it were drawn with a pen). A number
% of so-called graphic state parameters influence this, which can be
% set in different ways:
%
% - linewidth
%   The `thickness' of the line. A width of 0 is the thinnest width
%   renderable on the device. On a high-resolution printer this may
%   become invisible and should be avoided. A good choice is 0.4pt,
%   which is the default.
%
% - stroke color
%   This special color is used for stroking. If it is not set, the
%   current color is used.
%
% - cap
%   The cap describes how the endings of lines a drawn. A round cap
%   adds a little half circle to these endings. A butt cap ends the
%   lines exactly at the end (or start) point without anything
%   added. A rectangular cap ends the lines like the butt cap, but the
%   lines protrude over the endpoint by the line thickness. (See also
%   the pdf or postscript manual). If the path has been closed, no cap
%   is drawn.
%
% - join
%   This describes how a bend (a join) in a path is rendered. A round
%   join draws bends using small arcs. A bevel join just draws the two
%   lines and then fills the join minimally so that it becomes
%   convex. A miter join extends the lines so that they form a single
%   sharp corner, but only up to a certain miter limit. (See the pdf
%   or postscript manual once more).
%
% - dash
%   The line may be dashed according to a dashing pattern.
%
% - clipping area
%   If a clipping area is established, only those parts of the path
%   that are inside the clipping area will be drawn.
%
% In addition to stroking a path, the path may also be used for
% clipping after it has been stroked. This will happen if the
% \pgfsys@clipnext is used prior to this command, see there for
% details.

\def\pgfsys@fill{\pgf@sys@fail{path usage}}
% This command fills the area surrounded by the current path. If the
% path has not yet been closed, it is closed prior to filling. The
% path itself is not stroked. For self-intersecting paths or paths
% consisting of multiple parts, the nonzero winding number rule is
% used to determine whether a point is inside or outside the
% path, except if \ifpgfsys@eorule holds -- in which case the even-odd
% rule should be used. (See the pdf or postscript manual for details.) 
%
% The following graphic state parameters influence the filling:
%
% - fill color
%   If the fill color is not especially set, the current color is
%   used. 
%
% - clipping area
%   If a clipping area is established, only those parts of the filling
%   area that are inside the clipping area will be drawn.
%
% In addition to filling the path, the path will also be used for
% clipping if \pgfsys@clipnext is used prior to this command.

\def\pgfsys@fillstroke{\pgf@sys@fail{path usage}}
% First, the path is filled, then the path is stroked. If the fill and
% stroke colors are the same (or if they are not specified and the
% current color is used), this yields almost the same as a
% \pgfsys@fill. However, due to the line thickness of the stroked
% path, the fillstroked area will be slightly larger.
%
% In addition to stroking and filling the path, the path will also be
% used for clipping if \pgfsys@clipnext is used prior to this command.

\def\pgfsys@clipnext{\pgf@sys@fail{path usage}}
% This command should be issued after a path has been constructed, but
% before it has been stroked and/or filled or discarded. When the
% command is used, the next stroking/filling/discarding command will
% first be executed normally. Then, afterwards, the just-used path
% will be used for subsequent clipping. If there has already been a
% clipping region, this region is intersected with the new clipping
% path (the clipping cannot get bigger). The nonzero winding number
% rule is used to determine whether a point is inside or outside the
% clipping area or the even-odd rule, depending on whether
% \ifpgfsys@eorule holds.

\def\pgfsys@discardpath{\pgf@sys@fail{path usage}}
% Normally, this command should `throw away' the current path.
% However, after \pgfsys@clipnext has been called, the current path
% should subsequently be used for clipping. See \pgfsys@clipnext for
% details. 





%
%
% Stroking options
%
%
\def\pgfsys@setlinewidth#1{\pgf@sys@fail{setting the line width}}
% Sets the width of lines, when stroked, to #1.

\def\pgfsys@buttcap{\pgf@sys@fail{setting the line cap}}
% Sets the cap to a butt cap. See \pgfsys@stroke.

\def\pgfsys@roundcap{\pgf@sys@fail{setting the line cap}}
% Sets the cap to a round cap. See \pgfsys@stroke.

\def\pgfsys@rectcap{\pgf@sys@fail{setting the line cap}}
% Sets the cap to a rectangular cap. See \pgfsys@stroke.

\def\pgfsys@miterjoin{\pgf@sys@fail{setting the line join}}
% Sets the join to a miter join. See \pgfsys@stroke.

\def\pgfsys@setmiterlimit#1{\pgf@sys@fail{setting the line cap}}
% Sets the miter limit of lines to #1. See the pdf or postscript
% documentation.

\def\pgfsys@roundjoin{\pgf@sys@fail{setting the line cap}}
% Sets the join to a round join. See \pgfsys@stroke.

\def\pgfsys@beveljoin{\pgf@sys@fail{setting the line cap}}
% Sets the join to a bevel join. See \pgfsys@stroke.

\def\pgfsys@setdash#1#2{\pgf@sys@fail{setting the dashing pattern}}
% Sets the dashing patter. #1 should be a list of lengths separated by
% spaces. #2 should be a single dimension.
%
% The list of values in #1 is used to determine the lengths of the
% `on' phases of the dashing and of the `off' phases. For example, if
% #1 is `3pt 4pt', then the dashing pattern is `3pt on followed by 4pt
% off, followed by 3pt on, followed by 4pt off, and so on'. A pattern
% of `.5pt 4pt 3pt 1.5pt' means `.5pt on, 4pt off, 3pt on, 1.5pt off, .5pt on,
% ...'. If the number of entries is odd, the last one is used twice,
% so `3pt' means `3pt on, 3pt off, 3pt on, 3pt off,...'. An empty list
% means `always on'.
%
% The second argument determines the `phase' of the pattern. For
% example, for a pattern of `3pt 4pt' and a phase of `1pt', the pattern
% would start: `2pt on, 4pt off, 3pt on, 4pt off, 3pt on, 4pt off...'.





%
%
% Color stuff
%
%

\def\pgfsys@color@rgb@stroke#1#2#3{\pgf@sys@fail{color}}
% Sets the color used for stroking operations to the given rgb tuple
% (numbers between 0 and 1). 
%
% Example: Make stroked text dark red: \pgfsys@color@rgb@stroke{0.5}{0}{0}
%
% The special stroking color is only used if the stroking color has
% been set since the last \pgfutil@color command. Thus, each \pgfutil@color command
% should reset both the stroking and filling colors.

\def\pgfsys@color@rgb@fill#1#2#3{\pgf@sys@fail{color}}
% Sets the color used for filling operations to the given rgb tuple
% (numbers between 0 and 1). This color may be different from the
% stroking color.

\def\pgfsys@color@rgb#1#2#3{\pgfsys@color@rgb@stroke{#1}{#2}{#3}\pgfsys@color@rgb@fill{#1}{#2}{#3}}
% Sets the color used for filling and stroking operations. This is a
% ``low-level'' version of the \pgfutil@color command. It is currently only
% used by the plain tex version to support colors.

\def\pgfsys@color@cmyk@stroke#1#2#3#4{\pgf@sys@fail{color}}
% Sets the color used for stroking operations to the given cymk tuple
% (numbers between 0 and 1). 

\def\pgfsys@color@cmyk@fill#1#2#3#4{\pgf@sys@fail{color}}
% Sets the color used for filling operations to the given cymk tuple
% (numbers between 0 and 1). 

\def\pgfsys@color@cmyk#1#2#3#4{\pgfsys@color@cmyk@stroke{#1}{#2}{#3}{#4}\pgfsys@color@cmyk@fill{#1}{#2}{#3}{#4}}
% Sets the color used for filling and stroking operations.

\def\pgfsys@color@cmy@stroke#1#2#3{\pgf@sys@fail{color}}
% Sets the color used for stroking operations to the given cym tuple
% (numbers between 0 and 1). 

\def\pgfsys@color@cmy@fill#1#2#3{\pgf@sys@fail{color}}
% Sets the color used for filling operations to the given cym tuple
% (numbers between 0 and 1). 

\def\pgfsys@color@cmy#1#2#3{\pgfsys@color@cmy@stroke{#1}{#2}{#3}\pgfsys@color@cmy@fill{#1}{#2}{#3}}
% Sets the color used for filling and stroking operations.

\def\pgfsys@color@gray@stroke#1{\pgf@sys@fail{color}}
% Sets the color used for stroking operations to the given gray level 
% (number between 0 and 1). 

\def\pgfsys@color@gray@fill#1{\pgf@sys@fail{color}}
% Sets the color used for filling operations to the given gray level 
% (number between 0 and 1). 

\def\pgfsys@color@gray#1{\pgfsys@color@gray@stroke{#1}\pgfsys@color@gray@fill{#1}}
% Sets the color used for filling and stroking operations.

\newif\ifpgfsys@color@reset@inorder
% This if decides whether the color resetting of the
% \pgfsys@color@reset command may assume that all color commands are
% given ``in order.'' This means that this command will not be called,
% say, at the beginning of a box that is later inserted at a point
% where a fill color was actively set. This may allow the command to
% produce more compact code when it ``knows'' that no special fill or
% stroke color has been set.
\pgfsys@color@reset@inordertrue


\def\pgfsys@color@reset{}
% This command will be called when the \pgfutil@color command is used. It
% should purge any internal settings of stroking and filling
% color. After this call, till the next use of a command like
% \pgfsys@color@rgb@fill, the current color installed by the \pgfutil@color
% command should be used.

\def\pgfsys@color@unstacked#1{}
% This slightly obscure command causes the color stack to be
% tricked. When called, this command should set the current color to
% #1 without causing any change in the color stack. 



%
%
% Coordinate system transformations
%
%

\def\pgfsys@transformcm#1#2#3#4#5#6{\pgf@sys@fail{transformations}}
% Perform a concatenation of the low-level current transformation
% matrix with the matrix given by the values #1 to #6. The
% transformation matrix is a transformation on a homogeneous
% 2D-coordinate system. See the pdf or postscript manual for details. 




%
%
% Graphic state saving and restoring.
%
%

\def\pgfsys@beginscope{\pgf@sys@fail{scoping}}
% Saves the current graphic state on a graphic state stack. All
% changes to the graphic state parameters mentioned for \pgfsys@stroke
% and \pgfsys@fill will be local to the current graphic state and will
% the old values will be restored after endscope is used.
%
% WARNING: pdf and postscript differ with respect to the question of
% whether the current path is part of the graphic state or not. For
% this reason, you should never use this command unless the path is
% currently empty. For example, it might be a good idea to use
% discardpath prior to calling this command. 

\def\pgfsys@endscope{\pgf@sys@fail{scoping}}
% Restores the last saved graphic state.




%
%
% Special commands
%
%

\def\pgfsys@imagesuffixlist{}
% A list of suffixes, separated by `:', that will be tried when
% searching for an image.



%
%
% Transparency
%
%

\def\pgfsys@stroke@opacity#1{\pgf@sys@fail{opacity}}
% Sets the opacity of stroking operations. 1 means fully opaque, 0
% means fully transparent.

\def\pgfsys@fill@opacity#1{\pgf@sys@fail{opacity}}
% Sets the opacity of filling operations. 1 means fully opaque, 0
% means fully transparent.

\def\pgfsys@transparencygroupfrombox#1{\pgf@sys@fail{transparency groups}}
% This takes a TeX box and converts it into a transparency
% group. This means that any transparency settings apply to the box as
% a whole. For instance, if a box contains two overlapping black
% circles and you draw them normally with 50% transparency, then the
% overlap will be darker than the rest. By comparison, if the circles
% are part of a transparency group, the overlap will get the same
% color as the rest.
%
% The following settings modify the bevahiour of a transparency group:

\newif\ifpgfsys@transparency@group@isolated
\newif\ifpgfsys@transparency@group@knockout


\def\pgfsys@blend@mode#1{\pgf@sys@fail{blend mode}}
% Sets the current blend mode. See the PDF specification for details
% on blend modes.


\def\pgfsys@definemask{\pgf@sys@fail{image masks}}
% This command declares a mask for usage with images. It works similar
% to \pgfsys@defineimage: Certain macros are set when the command is
% called. The result should be to set the macro \pgf@mask to a pdf
% object count that can subsequently be used as a soft mask. The
% following macros will be set when this command is invoked:
%
% - \pgf@filename
%   File name of the mask to be defined.
%
% - \pgf@maskmatte
%   The so-called matte of the mask (see the pdf documentation for
%   details). The matte is a color specification consisting of 1, 3 or
%   4 numbers between 0 and 1. The number of numbers depends on the
%   number of color channels in the image (not in the mask!). It will
%   be assumed that the image has been preblended with this color.

\def\pgfsys@fadingfrombox#1#2{\pgf@sys@fail{fadings}}
% Declares an fading named #1. The parameter #2 must be a
% box. Its contents luminosity determines the opacity of the resulting
% mask. 

\def\pgfsys@usefading#1#2#3#4#5#6#7{\pgf@sys@fail{fadings}}
% Installs a previously declared fading #1 in the current graphics
% state. Parameters #2 to #7 specify a transformation cm that should
% be applied to the mask before it is used.



%
%
% Shading commands
%
%

\def\pgfsys@horishading#1#2#3{\pgf@sys@fail{shadings}\pgf@sys@noshading{#1}}
% Declares a horizontal shading for later use. The effect of this
% command should be the definition of a macro called `@pgfshading#1!'
% (or \csname @pdfshading#1!\endcsname, to be precise). When invoked,
% this new macro should insert a shading at the current position.
%
% #1 is the name of the shading, which is also used in the output
% macro name. #2 is the height of the shading and must be given as a
% TeX dimension like `2cm' or `10pt'. #3 is a shading color
% specification as specified in the pgfuserguide. The shading
% specification implicitly fixes the width of the shading. 
%
% When `@pgfshading#1!' is invoked, it should insert a box of height
% #2 and the width implicit in the shading declaration.

\def\pgfsys@vertshading#1#2#3{\pgf@sys@fail{shadings}\pgf@sys@noshading{#1}}
% Like horishading, only for vertical shadings. This time, the height
% of the shading is implicit in #3 and the width is given as #2.

\def\pgfsys@radialshading#1#2#3{\pgf@sys@fail{shadings}\pgf@sys@noshading{#1}}
% Declares a radial shading. Like the previous macros, this command
% should setup the macro `@pgfshading#1!', which upon invocation
% should insert a radial shading whose size is implicit in #3. 
%
% The parameter #2 is a pgf point specification if the starting point
% of the shading. See the pgfuserguide for details.

\def\pgfsys@functionalshading#1#2#3#4{\pgf@sys@fail{shadings (functional)}\pgf@sys@noshading{#1}}
% Declares a shading using a PostScript-like function that provides a
% color for each point. Like the previous macros, this command
% should setup the macro `@pgfshading#1!' so that it will produce a
% box containing the desired shading.
%
% Parameter #1 is the name of the shading. Parameter #4 is a
% Postscript-like function (type 4 function of the PDF specification)
% as described in Section 3.9.4 of the PDF Specification version 1.7.
% Parameter #2 and #3 are pgf point specifications that specifies the
% lower left and upper right coordinate.
%
% When function #4 is evaluated, the coordinate of the current
% point will be on the (virtual) PostScript stack in bp units. After
% the function has been evaluated, the stack should consist of three
% numbers (not integers! - the Apple PDF renderer is broken in this
% regard, so add cvr's at the end if needed) that represent the red,
% green, and blue components of the color.
%
% A buggy #4 will result is *totally unpredictable chaos* during
% rendering. 

\def\pgf@sys@noshading#1{\expandafter\global\expandafter\let\csname @pgfshading#1!\endcsname=\pgfutil@empty}




%
%
% Pattern stuff
%
%

\def\pgfsys@declarepattern#1#2#3#4#5#6#7#8#9{\pgf@sys@fail{patterns}}
% This command declares a new colored or uncolored pattern. Uncolored
% patterns have no inherent color, the color is provided when they are
% set. Colored patters have an inherent color.
% #1       = name of the pattern (must be a plain suffix for use in
%            postscript/pdf/etc.) 
% #2 to #5 = four coordinates describing the corners of a bounding box
%            of pattern cells
% #6       = x-step
% #7       = y-step
% #8       = pattern code
% #9       = 0 if uncolored patter, 1 if colored pattern.

\def\pgfsys@setpatternuncolored#1#2#3#4{\pgf@sys@fail{patterns}}
% Sets an uncolored pattern #1 as filling color. The numbers #2, #3,
% #4 must be an rgb-value to be used as the color of the pattern.

\def\pgfsys@setpatterncolored#1{\pgf@sys@fail{patterns}}
% Sets an colored pattern #1 as filling color.


%
%
% Page size stuff
%
%

\def\pgfsys@papersize#1#2{\pgf@sys@fail{papersize}}
% This command sets the paper size in a portable way. It tries to do
% so "locally" for the current page, but what really happens depends
% strongly on the driver. For instance, dvips will use whatever is
% used with the first call to this command that is part of the
% shipped-out document and will ignore all other uses. In contrast,
% pdftex will use the current value of the papersize for each page
% and, additionally, setting the papersize is local to the current TeX
% group. 
% #1 = width
% #2 = height

\def\pgfsys@global@papersize#1#2{\pgfsys@papersize{#1}{#2}}
% This command does the same as the papersize command, only for
% drivers that support this, \global is used to set the papersize. 
% #1 = width
% #2 = height


\ifx\paperheight\@undefined
  \def\pgfsys@thepageheight{\the\vsize} % this is wrong, but I do not
                                % know how to compute the page height
                                % in plain tex.
  \def\pgfsys@thepagewidth{\the\hsize}
\else
  \def\pgfsys@thepageheight{\paperheight}
  \def\pgfsys@thepagewidth{\paperwidth}
\fi


%
%
% Position tracking commands
%
%

% Marks the current position on the page. This position can later be
% referenced using \pgfsys@getposition
\def\pgfsys@markposition#1{\pgf@sys@fail{marking the current position}}

% Sets #2 to a pgfpoint macro that returns the position #1 is
% returned in a coordinate system where the x-axis goes right and the
% y-axis goes up. The origin of this coordinate system may or may not
% lie in the lower left corner; you should shift the coordinate system
% to the position "pgfpageorigin" to make sure that the origin is at
% the lower left corner. Typically, getting this position
% requires two runs of TeX. On the first run, the macro will be set to
% \relax, indicating that the position is not available. 
%
% If #1 is set to the special position "pgfpageorigin", the position
% of the the lower left page corner is returned. 

\def\pgfsys@getposition#1#2{\let#2=\relax}



%
%
% Commands having a default implementation. These commands only need
% not be implemented by drivers if this results in a better
% preformance. 
%
%


\def\pgfsys@shadingoutsidepgfpicture#1{%
  #1%
}
% This command gets the definition of a shading (@pgfshadingxxxx!) as
% an argument and should insert this shading into the normal text.
%
% This command has a default implementation.


\def\pgfsys@shadinginsidepgfpicture#1{%
  \pgf@makehbox{#1}%
  \setbox\pgf@hbox=\hbox{\hskip-.5\wd\pgf@hbox\lower.5\ht\pgf@hbox\hbox{\box\pgf@hbox}}%
  \pgfqbox{\pgf@hbox}%
}
% This command works like \pgfsys@shadingoutsidepgfpicture, only it is
% called when a shading should be inserted inside a picture. This
% command should insert the shading centered on the origin (which will
% typically have been low-level translated somewhere else.)
%
% This command has a default implementation.





\def\pgfsys@closestroke{\pgfsys@closepath\pgfsys@stroke}
% This command should have the same effect as first closing the path
% and then stroking it.


\def\pgfsys@transformshift#1#2{\pgfsys@transformcm{1}{0}{0}{1}{#1}{#2}}
% This command will change the origin of the low-level coordinate
% system to (#1,#2).

\def\pgfsys@transformxyscale#1#2{\pgfsys@transformcm{#1}{0}{0}{#2}{0bp}{0bp}}
% This command will scale the low-level coordinate system (and
% everything that is drawn) by a factor of #1 in x-directed and #2 in
% y-direction. Note that this applies to everything, including
% lines. So a scaled line will have a different width and may even
% have a different width when going along the x-axis and when going
% along the y-axis, if the scaling is different in these directions.

\def\pgfsys@hbox#1{%
  \pgfsys@beginscope%
    \setbox#1=\hbox{\box#1}%
    \wd#1=0pt%
    \ht#1=0pt%
    \dp#1=0pt%
    \box#1%
  \pgfsys@endscope%
}
% Called to insert a TeX hbox into a pgfpicture. 

\def\pgfsys@hboxsynced#1{%
  {\pgfsys@beginscope\pgflowlevelsynccm\pgfsys@hbox#1\pgfsys@endscope}%
}
% Called to insert a TeX hbox into a pgfpicture, but with the current
% coordinate transformation matrix synced with the canvas
% transformation matrix. 
%
% In essence, this command does the same as if you first said
% \pgflowlevelsynccm and then \pgfsys@hbox. However, a driver may
% choose to use a ``TeX-translation'' for the translation part of the
% transformation cm. This will ensure that hyperlinks ``survive'' at
% least translations. 

\def\pgfsys@pictureboxsynced#1{%
  {%
    \setbox0=\hbox{\pgfsys@beginpicture\box#1\pgfsys@endpicture}%
    \pgfsys@hboxsynced0%
  }%
}
% Basically, this should do the same as doing a (scoped) low level sync
% followed by inserting the box #1 directly into the output
% stream. However, the default implementation uses \pgfsys@hboxsynced
% in conjunction with \pgfsys@beginpicture to ensure that, if
% possible, hyperlinks survive in pdfs. Drivers that are sensitive to
% picture-in-picture scopes shuold replace this implementation by
% \pgfsys@beginscope\pgflowlevelsynccm\box#1\pgfsys@endscope

\def\pgfsys@beginpicture{}
% Called at the beginning of a pgfpicture. Used to setup things.

\def\pgfsys@endpicture{}
% Called at the end of a pgfpicture. 

\def\pgfsys@typesetpicturebox#1{%
  \pgf@ya=\pgf@shift@baseline\relax%
  \advance\pgf@ya by-\pgf@picminy\relax%
  %
  %
  \advance\pgf@picmaxy by-\pgf@picminy\relax% maxy is now the height
  \advance\pgf@picmaxx by-\pgf@picminx\relax% maxx is now the width
  \setbox#1=\hbox{\hskip-\pgf@picminx\lower\pgf@picminy\box#1}%
  \ht#1=\pgf@picmaxy%
  \wd#1=\pgf@picmaxx%
  \dp#1=0pt%
  \leavevmode%
  \pgf@xa=\pgf@trimleft@final\relax  \ifdim\pgf@xa=0pt \else\kern\pgf@xa\fi
  \raise-\pgf@ya\box#1%
  \pgf@xa=\pgf@trimright@final\relax \ifdim\pgf@xa=0pt \else\kern\pgf@xa\fi
}
% Called after a picture has been typeset in box #1. This
% command should insert the box into the normal TeX code. The box #1
% will still be a ``raw'' box that contains only the \special's. The
% job of this command is to resize and shift this box according to the
% baseline shift and the size of the box.
%
% This command has a default implementation.

\def\pgfsys@beginpurepicture{\pgfsys@beginpicture}
% This version of the beginpicture command can be used for pictures
% that are guaranteed not to contain any hboxes. In this case, a
% driver might provide a more compact version of the command.

\def\pgfsys@endpurepicture{\pgfsys@endpicture}
% Called at the end of a ``pure'' pgfpicture.

\def\pgfsys@defineimage{%
  \ifx\pgf@imagewidth\pgfutil@empty\else\edef\pgf@imagewidth{width=\pgf@imagewidth,}\fi%
  \ifx\pgf@imageheight\pgfutil@empty\else\edef\pgf@imageheight{height=\pgf@imageheight,}\fi%
  \ifx\pgf@imagepage\pgfutil@empty\else\edef\pgf@imagepage{page=\pgf@imagepage,}\fi%
  \edef\pgf@image{\noexpand\includegraphics[\pgf@imageheight\pgf@imagewidth]{\pgf@filename}}%
}
% Called, when an image should be defined. 
%
% This command does not take any parameters. Instead, certain macros
% will be preinstalled with appropriate values when this command is
% invoked. These are:
%
% - \pgf@filename
%   File name of the image to be defined.
%
% - \pgf@imagewidth
%   Will be set to the desired (scaled) width of the image.
%
% - \pgf@imageheight
%   Will be set to the desired (scaled) height of the image.
%
%   If this macro and also the height macro are empty, the image
%   should have its `natural' size.
%
%   If exactly only of them is specified, the undefined value the
%   image is scaled so that the aspect ratio is kept.
%
%   If both are set, the image is scaled in both directions
%   independently, possibly changing the aspect ratio.
%
%
% The following macros presumable mostly make sense for drivers that
% can handle pdf: 
%
% - \pgf@imagepage
%   The desired page number to be extracted from a multi-page
%   `image'. 
%
% - \pgf@imagemask
%   If set, it will be set to `/SMask x 0 R', where x is the pdf
%   object number of a soft mask to be applied to the image.
%
% - \pgf@imageinterpolate
%   If set, it will be set to `/Interpolate true' or  `/Interpolate
%   false', indicating whether the image should be interpolated in
%   pdf. 
%
%
% The command should now setup the macro \pgf@image such that calling
% this macro will result in typesetting the image. Thus, \pgf@image is
% the `return value' of the command.


\def\pgfsys@defobject#1#2#3#4{%
  \pgfsysprotocol@getcurrentprotocol\pgfsys@temp%
  {%
    \pgfsysprotocol@setcurrentprotocol\pgfutil@empty%
    \pgfsysprotocol@bufferedtrue%
    \pgfsys@beginscope%
    #4%
    \pgfsys@endscope%
    \pgfsysprotocol@getcurrentprotocol\pgfsys@@temp%
    \expandafter\global\expandafter\let\csname #1\endcsname=\pgfsys@@temp%
  }%
  \pgfsysprotocol@setcurrentprotocol\pgfsys@temp%
}
% Declares an object for later use. The idea is that the object can be
% precached in some way and then be rendered more quickly when used
% several times. For example, an arrow head might be defined and
% prerendered in this way.
%
% The parameter #1 is the name for later use. #2 and #3 are pgf points
% specifying a bounding box for the object. #4 is the code for the
% object. The code may only contain protocollable code.


\def\pgfsys@useobject#1#2{%
  \pgfsysprotocol@getcurrentprotocol\pgfsys@temp%
  {%
    \pgfsysprotocol@setcurrentprotocol\pgfutil@empty%
    \pgfsysprotocol@bufferedfalse%
    #2%
    \expandafter\pgfsysprotocol@setcurrentprotocol\csname #1\endcsname%
    \pgfsysprotocol@invokecurrentprotocol%
  }%
  \pgfsysprotocol@setcurrentprotocol\pgfsys@temp%
}
% Renders a previously declared object. The first parameter is the
% name of the the object. The second parameter is extra code that
% should be executed right *before* the object is rendered. Typically,
% this will be some transformation code. 


\def\pgfsys@begininvisible{\pgfsys@transformcm{1}{0}{0}{1}{2000bp}{2000bp}}
% Between this command and the closing endinvisible, all output should
% be suppressed. Nothing should be drawn at all, which includes all
% paths, images and shadings.

\def\pgfsys@endinvisible{\pgfsys@transformcm{1}{0}{0}{1}{-2000bp}{-2000bp}}
% Ends the invisibilty section, unless invisibility blocks have been
% nested. In this case, only the `last' one restores visibility.


\def\pgfsys@atbegindocument{}
% This command will be executed at the begin of the document. If for
% whatever reason this is not done, you may wish to execute this
% command yourself. It will setup certain specials that need to be
% inserted into the resulting .pdf/.ps/.xxx file.





% Discern the driver:

% Default driver:
\ifx\pgfsysdriver\@undefined
  \pgfutil@guessdriver
\fi

\input pgf.cfg

\immediate\write-1{Driver file for pgf: \pgfsysdriver}
\pgfutil@InputIfFileExists{\pgfsysdriver}{}{%
  \pgferror{Driver file ``\pgfsysdriver'' not found.}}



% This will insert always-present-specials at the beginning of the
% code. 
\AtBeginDocument{
  \pgfsys@atbegindocument
  \let\pgfsys@atbegindocument=\pgfutil@empty
}



% Read aux file in plain and context mode:

\pgfutil@aux@read@hook


\endinput

pgfsysprotocol.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/systemlayer/pgfsysprotocol.code.tex,v 1.4 2006/10/16 22:32:59 tantau Exp $



% This package provides the pgf system protcol layer. Protocolling is
% used to record a bunch of graphic operations so that they can be
% reused quickly at a later point.
%
% Basically, all ``recordable'' \pgfsys@xxxx commands call
% \pgfsysprotocol@protocol for their protocolable literal
% specials. The literal text will either be stored in the current
% protocol. At a later point (actually, normally this happens
% immediately afterwards), the accumulated protocolled text is invoked
% using pgfsys@invokeprotocol.



\let\pgfsysprotocol@currentprotocol=\pgfutil@empty
\newif\ifpgfsysprotocol@buffered


% Add to the protocol buffered
\def\pgfsysprotocol@literalbuffered#1{%
  \edef\pgfsysprotocol@temp{{#1\space}}%
  \expandafter\pgfutil@g@addto@macro\expandafter\pgfsysprotocol@currentprotocol\pgfsysprotocol@temp%
}

% Add to the protocol
\def\pgfsysprotocol@literal#1{%
  \pgfsysprotocol@literalbuffered{#1}%
  \ifpgfsysprotocol@buffered%
  \else%
    \pgfsysprotocol@flushcurrentprotocol%
  \fi%
}

% Getting and setting the current protocol
\def\pgfsysprotocol@getcurrentprotocol#1{%
  \let#1=\pgfsysprotocol@currentprotocol%
}

\def\pgfsysprotocol@setcurrentprotocol#1{%
  \global\let\pgfsysprotocol@currentprotocol=#1%
}


% Invoking the current protocol
\def\pgfsysprotocol@invokecurrentprotocol{%
  \ifx\pgfsysprotocol@currentprotocol\pgfutil@empty%
  \else%
    \expandafter\pgfsys@invoke\expandafter{\pgfsysprotocol@currentprotocol}%
  \fi%
}

\def\pgfsysprotocol@flushcurrentprotocol{%
  \pgfsysprotocol@invokecurrentprotocol%
  \pgfsysprotocol@setcurrentprotocol\pgfutil@empty%
}


\endinput

pgfsyssoftpath.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS $Header: /cvsroot/pgf/pgf/generic/pgf/systemlayer/pgfsyssoftpath.code.tex,v 1.9 2013/09/09 10:05:41 tantau Exp $


% This package provides the pgf system path abstraction layer. This
% layer is used to construct paths first ``abstractly.'' These
% abstract paths can still be modified, before they are ``made
% concrete.'' 
%
% An abstract path consists of a sequence of basic building blocks,
% each of which is a tuple consisting of two numbers (specifying a
% coordinate) and a token. Possible tokens are:
%
% 1. moveto
% 2. lineto
% 3. rectcorner
% 4. rectsize
% 5. curvetosupporta
% 6. curvetosupportb
% 7. curveto
% 8. closepath
% 9. specialround
%
% A curveto must always be preceeded by a curvetosupporta and a
% curvetosupportb. A non-empty path must always begin with a
% moveto. The coordinates of a closepath are non-specified, currently, 
% but they might be set to the coordinate of the path segment start,
% in the future.


% Access to the current path:
%
% Lots of stuff is added to the current path and it can get very long
% (containing literally tens of thousands of tokens). For such macros,
% adding things using a simple "g@addtomacro" takes more and more
% time, resulting in quadratic runtime. To avoid this, ideally, one
% would collect things in an array and then use a divide and conquer
% merger. A simple intermediate solution is the following, implemented
% here: We have the path and two buffers. New tokens are added to the
% first buffer, which is quite small. When it overflow, its contents
% is added to the second buffer, which is large. If that buffer
% overflow, the contents is finally added to the main path (which can
% have arbitrary length). Whenever the main path is set or read, the
% buffers are flushed.
%
% Because of this buffering, it is imperative that the main path is
% accessed only via appropriate interface macros.



% The current path
\let\pgfsyssoftpath@thepath=\pgfutil@empty
\let\pgfsyssoftpath@bigbuffer=\pgfutil@empty
\let\pgfsyssoftpath@smallbuffer=\pgfutil@empty
\newcount\pgfsyssoftpath@smallbuffer@items
\newcount\pgfsyssoftpath@bigbuffer@items

\def\pgfsyssoftpath@flushbuffers{%
  \expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\gdef%
  \expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\pgfsyssoftpath@thepath%
  \expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter{%
    \expandafter\expandafter\expandafter\pgfsyssoftpath@thepath%
    \expandafter\pgfsyssoftpath@bigbuffer\pgfsyssoftpath@smallbuffer}%
  \global\let\pgfsyssoftpath@smallbuffer=\pgfutil@empty
  \global\let\pgfsyssoftpath@bigbuffer=\pgfutil@empty
  \global\pgfsyssoftpath@bigbuffer@items0\relax%
  \global\pgfsyssoftpath@smallbuffer@items0\relax%
}

% Getting and setting the current path
\def\pgfsyssoftpath@getcurrentpath#1{%
  \pgfsyssoftpath@flushbuffers%
  \let#1=\pgfsyssoftpath@thepath%
}

\def\pgfsyssoftpath@setcurrentpath#1{%
  \global\let\pgfsyssoftpath@thepath=#1%
  \global\let\pgfsyssoftpath@smallbuffer=\pgfutil@empty
  \global\let\pgfsyssoftpath@bigbuffer=\pgfutil@empty
  \global\pgfsyssoftpath@bigbuffer@items0\relax%
  \global\pgfsyssoftpath@smallbuffer@items0\relax%
}


% Invoking the current path (slightly optimized)
\def\pgfsyssoftpath@invokecurrentpath{%
  \pgfsyssoftpath@thepath%
  \pgfsyssoftpath@bigbuffer%
  \pgfsyssoftpath@smallbuffer%
}

\def\pgfsyssoftpath@flushcurrentpath{%
  \pgfsyssoftpath@invokecurrentpath%
  \pgfsyssoftpath@setcurrentpath\pgfutil@empty%
}

% Add an item at the end
\def\pgfsyssoftpath@addtocurrentpath#1{%
  \global\advance\pgfsyssoftpath@smallbuffer@items by1\relax%
  \ifnum\pgfsyssoftpath@smallbuffer@items<40\relax% good number?
    \expandafter\gdef\expandafter\pgfsyssoftpath@smallbuffer\expandafter{\pgfsyssoftpath@smallbuffer#1}%
  \else%
    \pgfsyssoftpath@smalloverflow{#1}%
  \fi%
}
\def\pgfsyssoftpath@smalloverflow#1{%
  \global\advance\pgfsyssoftpath@bigbuffer@items by1\relax%
  \ifnum\pgfsyssoftpath@bigbuffer@items<30\relax% good number?
    \expandafter\expandafter\expandafter\gdef%
    \expandafter\expandafter\expandafter\pgfsyssoftpath@bigbuffer%
    \expandafter\expandafter\expandafter{\expandafter\pgfsyssoftpath@bigbuffer\pgfsyssoftpath@smallbuffer#1}%
    \global\let\pgfsyssoftpath@smallbuffer=\pgfutil@empty%
    \global\pgfsyssoftpath@smallbuffer@items0\relax%
  \else%
    \expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\gdef%
    \expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\pgfsyssoftpath@thepath%
    \expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter{%
      \expandafter\expandafter\expandafter\pgfsyssoftpath@thepath
      \expandafter\pgfsyssoftpath@bigbuffer\pgfsyssoftpath@smallbuffer#1}%
    \global\let\pgfsyssoftpath@smallbuffer=\pgfutil@empty
    \global\let\pgfsyssoftpath@bigbuffer=\pgfutil@empty
    \global\pgfsyssoftpath@bigbuffer@items0\relax%
    \global\pgfsyssoftpath@smallbuffer@items0\relax%
  \fi%
}



\def\pgfsyssoftpath@lastmoveto{{0pt}{0pt}}

\newif\ifpgfsyssoftpathmovetorelevant
\pgfsyssoftpathmovetorelevanttrue

% Add a moveto element to the current path
\def\pgfsyssoftpath@moveto#1#2{%
  \edef\pgfsyssoftpath@coord{{#1}{#2}}%
  \expandafter\pgfsyssoftpath@addtocurrentpath\expandafter{\expandafter\pgfsyssoftpath@movetotoken\pgfsyssoftpath@coord}%
  \ifpgfsyssoftpathmovetorelevant%
    \global\let\pgfsyssoftpath@lastmoveto\pgfsyssoftpath@coord%
  \fi%
}

% Add a lineto element to the current path
\def\pgfsyssoftpath@lineto#1#2{%
  \edef\pgfsyssoftpath@coord{{#1}{#2}}%
  \expandafter\pgfsyssoftpath@addtocurrentpath\expandafter{\expandafter\pgfsyssoftpath@linetotoken\pgfsyssoftpath@coord}%
}


% Add curveto elements to the current path
\def\pgfsyssoftpath@curveto#1#2#3#4#5#6{%
  \edef\pgfsyssoftpath@temp{{%
      \noexpand\pgfsyssoftpath@curvetosupportatoken{#1}{#2}%
      \noexpand\pgfsyssoftpath@curvetosupportbtoken{#3}{#4}%
      \noexpand\pgfsyssoftpath@curvetotoken{#5}{#6}%
    }}%
  \expandafter\pgfsyssoftpath@addtocurrentpath\pgfsyssoftpath@temp%
}


% Add rectanlge elements to the current path
\def\pgfsyssoftpath@rect#1#2#3#4{%
  \edef\pgfsyssoftpath@temp{{%
    \noexpand\pgfsyssoftpath@rectcornertoken{#1}{#2}%
    \noexpand\pgfsyssoftpath@rectsizetoken{#3}{#4}%
  }}%
  \expandafter\pgfsyssoftpath@addtocurrentpath\pgfsyssoftpath@temp%
}

% Add closepath element to the current path
\def\pgfsyssoftpath@closepath{%
  \expandafter\pgfsyssoftpath@addtocurrentpath\expandafter{\expandafter\pgfsyssoftpath@closepathtoken\pgfsyssoftpath@lastmoveto}%
}

% Add special element to the current path
\def\pgfsyssoftpath@specialround#1#2{%
  \edef\pgfsyssoftpath@temp{{#1}{#2}}%
  \expandafter\pgfsyssoftpath@addtocurrentpath\expandafter{\expandafter\pgfsyssoftpath@specialroundtoken\pgfsyssoftpath@temp}%
}

% Marshallers
\def\pgfsyssoftpath@movetotoken#1#2{\pgfsys@moveto{#1}{#2}}
\def\pgfsyssoftpath@linetotoken#1#2{\pgfsys@lineto{#1}{#2}}
\def\pgfsyssoftpath@rectcornertoken#1#2#3#4#5{\pgfsys@rect{#1}{#2}{#4}{#5}} % #3 = \pgfsyssoftpath@rectsizetoken
\def\pgfsyssoftpath@curvetosupportatoken#1#2#3#4#5#6#7#8{\pgfsys@curveto{#1}{#2}{#4}{#5}{#7}{#8}}
\def\pgfsyssoftpath@closepathtoken#1#2{\pgfsys@closepath}
\let\pgfsyssoftpath@specialroundtoken=\pgfutil@gobbletwo
\def\pgfsyssoftpath@curvetosupportbtoken#1#2{curvetotokenb} % make sure this this \ifx-equal only to itself
\def\pgfsyssoftpath@curvetotoken#1#2{curvetotoken}% make sure this this \ifx-equal only to itself


\endinput

%%% Local Variables: 
%%% mode: latex
%%% End: 

pgfutil-common-lists.tex
% Copyright 2013 by Christian Feuersaenger
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
%
% This list here is a general re-implementation of the list used in
% the PGF system layer.
% It employs two collect-buffers to reduce the runtime.
%
% - It has preasymptotical runtime O(N), but is O(N^2) asymptotically.
% - It requires only 5 macros per list.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Usage: 
% \pgfapplistnewempty\macro
\def\pgfapplistnewempty#1{%
	\expandafter\let\csname pgfapp@#1\endcsname=\pgfutil@empty
	\expandafter\let\csname pgfapp@#1@smallbuf\endcsname=\pgfutil@empty
	\expandafter\let\csname pgfapp@#1@bigbuf\endcsname=\pgfutil@empty
	\expandafter\def\csname pgfapp@#1@smallbuf@c\endcsname{0}%
	\expandafter\def\csname pgfapp@#1@bigbuf@c\endcsname{0}%
}%

% #1: the item to append
% #2: the list as macro name
\long\def\pgfapplistpushback#1\to#2{%
	\begingroup
		\c@pgf@counta=\csname pgfapp@#2@smallbuf@c\endcsname\relax
		\advance\c@pgf@counta by1
		\xdef\pgf@glob@TMPa{\the\c@pgf@counta}%
	\endgroup
	\expandafter\let\csname pgfapp@#2@smallbuf@c\endcsname=\pgf@glob@TMPa
	\ifnum\csname pgfapp@#2@smallbuf@c\endcsname<40
		\t@pgf@toka=\expandafter\expandafter\expandafter{\csname pgfapp@#2@smallbuf\endcsname#1}%
		\expandafter\edef\csname pgfapp@#2@smallbuf\endcsname{\the\t@pgf@toka}%
	\else
		\pgfapplistpushback@smallbufoverfl{#1}{#2}%
	\fi
}%
\long\def\pgfapplistpushback@smallbufoverfl#1#2{%
	\begingroup
		\c@pgf@counta=\csname pgfapp@#2@bigbuf@c\endcsname\relax
		\advance\c@pgf@counta by1
		\xdef\pgf@glob@TMPa{\the\c@pgf@counta}%
	\endgroup
	\expandafter\let\csname pgfapp@#2@bigbuf@c\endcsname=\pgf@glob@TMPa
	%
	\ifnum\csname pgfapp@#2@bigbuf@c\endcsname<30
		\t@pgf@toka=\expandafter\expandafter\expandafter{\csname pgfapp@#2@bigbuf\endcsname}%
		\t@pgf@tokb=\expandafter\expandafter\expandafter{\csname pgfapp@#2@smallbuf\endcsname#1}%
		\expandafter\edef\csname pgfapp@#2@bigbuf\endcsname{\the\t@pgf@toka\the\t@pgf@tokb}%
		\expandafter\let\csname pgfapp@#2@smallbuf\endcsname=\pgfutil@empty
		\expandafter\def\csname pgfapp@#2@smallbuf@c\endcsname{0}%
	\else%
		\t@pgf@toka=\expandafter\expandafter\expandafter{\csname pgfapp@#2\endcsname}%
		\t@pgf@tokb=\expandafter\expandafter\expandafter{\csname pgfapp@#2@bigbuf\endcsname}%
		\t@pgf@tokc=\expandafter\expandafter\expandafter{\csname pgfapp@#2@smallbuf\endcsname#1}%
		\expandafter\edef\csname pgfapp@#2\endcsname{\the\t@pgf@toka\the\t@pgf@tokb\the\t@pgf@tokc}%
		\expandafter\let\csname pgfapp@#2@smallbuf\endcsname=\pgfutil@empty
		\expandafter\def\csname pgfapp@#2@smallbuf@c\endcsname{0}%
		\expandafter\let\csname pgfapp@#2@bigbuf\endcsname=\pgfutil@empty
		\expandafter\def\csname pgfapp@#2@bigbuf@c\endcsname{0}%
	\fi%
}%
\def\pgfapplist@flushbuffers#1{%
	\t@pgf@toka=\expandafter\expandafter\expandafter{\csname pgfapp@#1\endcsname}%
	\t@pgf@tokb=\expandafter\expandafter\expandafter{\csname pgfapp@#1@bigbuf\endcsname}%
	\t@pgf@tokc=\expandafter\expandafter\expandafter{\csname pgfapp@#1@smallbuf\endcsname}%
	\expandafter\edef\csname pgfapp@#1\endcsname{\the\t@pgf@toka\the\t@pgf@tokb\the\t@pgf@tokc}%
	\expandafter\let\csname pgfapp@#1@smallbuf\endcsname=\pgfutil@empty
	\expandafter\def\csname pgfapp@#1@smallbuf@c\endcsname{0}%
	\expandafter\let\csname pgfapp@#1@bigbuf\endcsname=\pgfutil@empty
	\expandafter\def\csname pgfapp@#1@bigbuf@c\endcsname{0}%
}%

\def\pgfapplistlet#1=#2{%
	\pgfapplist@flushbuffers{#2}%
	\expandafter\let\expandafter#1\csname pgfapp@#2\endcsname
}%
	

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 
% A variant of applist which has the same runtime requirements, but
% does PUSH FRONT only.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


% Usage: 
% \pgfprependlistnewempty{list}
\def\pgfprependlistnewempty#1{%
	\expandafter\let\csname pgfpPRP@#1\endcsname=\pgfutil@empty
	\expandafter\let\csname pgfpPRP@#1@smallbuf\endcsname=\pgfutil@empty
	\expandafter\let\csname pgfpPRP@#1@bigbuf\endcsname=\pgfutil@empty
	\expandafter\def\csname pgfpPRP@#1@smallbuf@c\endcsname{0}%
	\expandafter\def\csname pgfpPRP@#1@bigbuf@c\endcsname{0}%
}%

% #1: the item to append
% #2: the list as macro name
\long\def\pgfprependlistpushfront#1\to#2{%
	\begingroup
		\c@pgf@counta=\csname pgfpPRP@#2@smallbuf@c\endcsname\relax
		\advance\c@pgf@counta by1
		\xdef\pgf@glob@TMPa{\the\c@pgf@counta}%
	\endgroup
	\expandafter\let\csname pgfpPRP@#2@smallbuf@c\endcsname=\pgf@glob@TMPa
	\ifnum\csname pgfpPRP@#2@smallbuf@c\endcsname<40
		\t@pgf@toka=\expandafter\expandafter\expandafter{\csname pgfpPRP@#2@smallbuf\endcsname}%
		\t@pgf@tokb={#1}%
		\expandafter\edef\csname pgfpPRP@#2@smallbuf\endcsname{\the\t@pgf@tokb\the\t@pgf@toka}%
	\else
		\pgfprependlistpushfront@smallbufoverfl{#1}{#2}%
	\fi
}%
\long\def\pgfprependlistpushfront@smallbufoverfl#1#2{%
	\begingroup
		\c@pgf@counta=\csname pgfpPRP@#2@bigbuf@c\endcsname\relax
		\advance\c@pgf@counta by1
		\xdef\pgf@glob@TMPa{\the\c@pgf@counta}%
	\endgroup
	\expandafter\let\csname pgfpPRP@#2@bigbuf@c\endcsname=\pgf@glob@TMPa
	%
	\ifnum\csname pgfpPRP@#2@bigbuf@c\endcsname<30
		\t@pgf@toka=\expandafter\expandafter\expandafter{\csname pgfpPRP@#2@bigbuf\endcsname}%
		\t@pgf@tokb=\expandafter\expandafter\expandafter{\csname pgfpPRP@#2@smallbuf\endcsname}%
		\t@pgf@tokc={#1}%
		\expandafter\edef\csname pgfpPRP@#2@bigbuf\endcsname{\the\t@pgf@tokc\the\t@pgf@tokb\the\t@pgf@toka}%
		\expandafter\let\csname pgfpPRP@#2@smallbuf\endcsname=\pgfutil@empty
		\expandafter\def\csname pgfpPRP@#2@smallbuf@c\endcsname{0}%
	\else%
		\pgfprependlist@flushbuffers{#2}%
		\t@pgf@toka=\expandafter\expandafter\expandafter{\csname pgfpPRP@#2\endcsname}%
		\t@pgf@tokb={#1}%
		\expandafter\edef\csname pgfpPRP@#2\endcsname{\the\t@pgf@tokb\the\t@pgf@toka}%
	\fi%
}%
\def\pgfprependlist@flushbuffers#1{%
	\t@pgf@toka=\expandafter\expandafter\expandafter{\csname pgfpPRP@#1\endcsname}%
	\t@pgf@tokb=\expandafter\expandafter\expandafter{\csname pgfpPRP@#1@bigbuf\endcsname}%
	\t@pgf@tokc=\expandafter\expandafter\expandafter{\csname pgfpPRP@#1@smallbuf\endcsname}%
	\expandafter\edef\csname pgfpPRP@#1\endcsname{\the\t@pgf@tokc\the\t@pgf@tokb\the\t@pgf@toka}%
	\expandafter\let\csname pgfpPRP@#1@smallbuf\endcsname=\pgfutil@empty
	\expandafter\def\csname pgfpPRP@#1@smallbuf@c\endcsname{0}%
	\expandafter\let\csname pgfpPRP@#1@bigbuf\endcsname=\pgfutil@empty
	\expandafter\def\csname pgfpPRP@#1@bigbuf@c\endcsname{0}%
}%
\def\pgfprependlistlet#1=#2{%
	\pgfprependlist@flushbuffers{#2}%
	\expandafter\let\expandafter#1\csname pgfpPRP@#2\endcsname
}%

pgfutil-common.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.


% 
% This file provides utitiliy commands that are used throughout pgf.
%
% For most commands, the definition of these commands is just given
% below. We cannot use the LaTeX definition of these commands since
% LaTeX may not be the current format and since LaTeX packages tend to
% redefine these commands.
%
% For some commands the actual definition of the format (like latex or
% context) is to be preferred over the generic definition below. In
% this case, the definition of the format is installed when the file
% pgfutil-XXXX.tex is read, where XXXX is the format name (latex,
% plain, or context). 



\catcode`\@=11\relax


% Which format is loaded?
\newif\ifpgfutil@format@is@latex
\newif\ifpgfutil@format@is@plain
\newif\ifpgfutil@format@is@context


% Simple stuff

% \pgfutil@ifundefined{<macro name with backslash>}
%  {<is undefined code>}{<is defined code>}
%
% This will let #1 to \relax if it undefined.
%
% This macro is expandable.
\def\pgfutil@ifundefined#1{%
  \expandafter\ifx\csname#1\endcsname\relax
    \expandafter\pgfutil@firstoftwo
  \else
    \expandafter\pgfutil@secondoftwo
  \fi}

% A variant of \pgfutil@ifundefined which will NOT let #1 to \relax it
% is undefined. However, this macro is not expandable.
\def\pgfutil@IfUndefined#1{%
  \begingroup\expandafter\expandafter\expandafter\endgroup
  \expandafter\ifx\csname#1\endcsname\relax
    \expandafter\pgfutil@firstoftwo
  \else
    \expandafter\pgfutil@secondoftwo
  \fi
}
\long\def\pgfutil@firstofone#1{#1}
\long\def\pgfutil@firstoftwo#1#2{#1}
\long\def\pgfutil@secondoftwo#1#2{#2}
\def\pgfutil@empty{}
\def\pgfutil@gobble@until@relax#1\relax{}
\def\pgfutil@gobble#1{}
\def\pgfutil@gobbletwo#1#2{}
\def\pgfutil@namedef#1{\expandafter\def\csname #1\endcsname}
\def\pgfutil@namelet#1{\expandafter\pgfutil@@namelet\csname#1\endcsname}
\def\pgfutil@@namelet#1#2{\expandafter\let\expandafter#1\csname#2\endcsname}
\long\def\pgfutil@g@addto@macro#1#2{%
  \begingroup
    \pgfutil@toks@\expandafter{#1#2}%
    \xdef#1{\the\pgfutil@toks@}%
 \endgroup}
\newif\ifpgfutil@tempswa
\newif\ifpgfutil@tempswb

% pgfutil@ifnextchar

\long\def\pgfutil@ifnextchar#1#2#3{%
  \let\pgfutil@reserved@d=#1%
  \def\pgfutil@reserved@a{#2}%
  \def\pgfutil@reserved@b{#3}%
  \futurelet\pgfutil@let@token\pgfutil@ifnch}
\def\pgfutil@ifnch{%
  \ifx\pgfutil@let@token\pgfutil@sptoken
    \let\pgfutil@reserved@c\pgfutil@xifnch
  \else
    \ifx\pgfutil@let@token\pgfutil@reserved@d
      \let\pgfutil@reserved@c\pgfutil@reserved@a
    \else
      \let\pgfutil@reserved@c\pgfutil@reserved@b
    \fi
  \fi
  \pgfutil@reserved@c}
{%
  \def\:{\global\let\pgfutil@sptoken= } \:
  \def\:{\pgfutil@xifnch} \expandafter\gdef\: {\futurelet\pgfutil@let@token\pgfutil@ifnch}
}

% pgfutil@in@

\newif\ifpgfutil@in@

% Usage:
% \pgfutil@in@{one}{three two one}
% \ifpgfutil@in@
% 	-> will be true!
% \else
% \fi
%
% \pgfutil@in@{,}{1234,456567}
% \ifpgfutil@in@
% 	-> will be true!
% \else
% \fi
\def\pgfutil@in@#1#2{%
 \def\pgfutil@in@@##1#1##2##3\pgfutil@in@@{%
  \ifx\pgfutil@in@##2\pgfutil@in@false\else\pgfutil@in@true\fi}%
 \pgfutil@in@@#2#1\pgfutil@in@\pgfutil@in@@}


% pgfutil@for

\def\pgfutil@nnil{\pgfutil@nil}
\def\pgfutil@fornoop#1\@@#2#3{}
\long\def\pgfutil@for#1:=#2\do#3{%
  \expandafter\def\expandafter\pgfutil@fortmp\expandafter{#2}%
  \ifx\pgfutil@fortmp\pgfutil@empty \else
    \expandafter\pgfutil@forloop#2,\pgfutil@nil,\pgfutil@nil\@@#1{#3}\fi}
\long\def\pgfutil@forloop#1,#2,#3\@@#4#5{\def#4{#1}\ifx #4\pgfutil@nnil \else
       #5\def#4{#2}\ifx #4\pgfutil@nnil \else#5\pgfutil@iforloop #3\@@#4{#5}\fi\fi}
\long\def\pgfutil@iforloop#1,#2\@@#3#4{\def#3{#1}\ifx #3\pgfutil@nnil
       \expandafter\pgfutil@fornoop \else
      #4\relax\expandafter\pgfutil@iforloop\fi#2\@@#3{#4}}
\def\pgfutil@tfor#1:={\pgfutil@tf@r#1 }
\long\def\pgfutil@tf@r#1#2\do#3{\def\pgfutil@fortmp{#2}\ifx\pgfutil@fortmp\pgfutil@space\else
    \pgfutil@tforloop#2\pgfutil@nil\pgfutil@nil\@@#1{#3}\fi}
\long\def\pgfutil@tforloop#1#2\@@#3#4{\def#3{#1}\ifx #3\pgfutil@nnil
       \expandafter\pgfutil@fornoop \else
      #4\relax\expandafter\pgfutil@tforloop\fi#2\@@#3{#4}}

\def\pgfutil@space{ }

% pgfutil@IfFileExists

%\chardef\pgfutil@inputcheck0
\def\pgfutil@IfFileExists#1#2#3{%
  \openin\pgfutil@inputcheck=#1 %
  \ifeof\pgfutil@inputcheck
     #3\relax
  \else
    #2\relax
  \fi
  \closein\pgfutil@inputcheck}

\def\pgfutil@InputIfFileExists#1#2#3{\pgfutil@IfFileExists{#1}{\input #1\relax#2}{#3}}%


% pgfutil@loop (from plain.tex)

\def\pgfutil@loop#1\pgfutil@repeat{\def\pgfutil@body{#1}\pgfutil@iterate}
\def\pgfutil@iterate{\pgfutil@body \let\pgfutil@next\pgfutil@iterate \else\let\pgfutil@next\relax\fi \pgfutil@next}
\let\pgfutil@repeat=\fi % this makes \loop...\if...\repeat skippable


% aux-read-hook

\let\pgfutil@aux@read@hook=\relax


% Tokens for the end of the typesetting -- they will be added at the
% end of every job (hopefully...).

\newtoks\pgfutil@everybye


%
% PDF-Resource management -- might seem strange that this is here, but
% it turns out to be the correct place since latex and context handle
% this stuff quite differently
%

% Adding something to the pdf-resources:

\def\pgfutil@addpdfresource@extgs#1{\pgf@sys@addpdfresource@extgs@plain{#1}}
\def\pgfutil@addpdfresource@colorspaces#1{\pgf@sys@addpdfresource@colorspaces@plain{#1}}
\def\pgfutil@addpdfresource@patterns#1{\pgf@sys@addpdfresource@patterns@plain{#1}}
\def\pgfutil@setuppdfresources{\pgf@sys@setuppdfresources@plain}


% Inserts the argument at the begin of the current page (hopefully)

\let\pgfutil@insertatbegincurrentpage=\relax


% Ragged left and ragged right

\def\pgfutil@raggedright{\rightskip\z@ plus2em \spaceskip.3333em \xspaceskip.5em\relax}
\def\pgfutil@raggedleft{\leftskip\z@ plus2em \rightskip\z@ \spaceskip.3333em \xspaceskip.5em\parfillskip0pt\relax}


% Error Messages
\def\pgfutil@packageerror#1#2#3{\errhelp{#3}\errmessage{Package #1 Error: #2}}
\def\pgfutil@packagewarning#1#2{\immediate\write17{Package #1: Warning! #2.}}
\def\pgferror#1{\pgfutil@packageerror{pgf}{#1}{}}
\def\pgfwarning#1{\pgfutil@packagewarning{pgf}{#1}}


% Library files inclusion


% Include a library file.
%
% #1 = List of names of library file.
%  
% Description:
%
% This command includes a list of library files. For each file X in the
% list, the file pgflibraryX.code.tex is included, provided this has
% not been done earlier. 
%
% For the convenience of Context users, both round and square brackets
% are possible for the argument.
%
% Example:
%
% \usepgflibrary{arrows}
% \usepgflibrary[patterns,snakes]

\def\usepgflibrary{\pgfutil@ifnextchar[{\use@pgflibrary}{\use@@pgflibrary}}%}
\def\use@pgflibrary[#1]{\use@@pgflibrary{#1}}
\def\use@@pgflibrary#1{%
  \edef\pgf@list{#1}%
  \pgfutil@for\pgf@temp:=\pgf@list\do{%
    \expandafter\pgfkeys@spdef\expandafter\pgf@temp\expandafter{\pgf@temp}%
    \ifx\pgf@temp\pgfutil@empty
    \else
      \expandafter\ifx\csname pgf@library@\pgf@temp @loaded\endcsname\relax%
      \expandafter\let\csname pgf@library@\pgf@temp @loaded\endcsname=\pgfutil@empty%
      \expandafter\edef\csname pgf@library@#1@atcode\endcsname{\the\catcode`\@}
      \expandafter\edef\csname pgf@library@#1@barcode\endcsname{\the\catcode`\|}
      \expandafter\edef\csname pgf@library@#1@dollarcode\endcsname{\the\catcode`\$}
      \catcode`\@=11
      \catcode`\|=12
      \catcode`\$=3
      \pgfutil@InputIfFileExists{pgflibrary\pgf@temp.code.tex}{}{%
          \pgferror{I did not find the pgf library
            '\pgf@temp'. I looked for the file named
            pgflibrary\pgf@temp.code.tex, but could not find it in in
            the current texmf trees.} 
        }%
      \catcode`\@=\csname pgf@library@#1@atcode\endcsname
      \catcode`\|=\csname pgf@library@#1@barcode\endcsname
      \catcode`\$=\csname pgf@library@#1@dollarcode\endcsname
      \fi%
    \fi
  }%
}


% Include a module file.
%
% #1 = List of names of module files.
%  
% Description:
%
% This command includes a list of module files. For each file X in the
% list, the file pgfmoduleX.code.tex is included, provided this has
% not been done earlier. 
%
% For the convenience of Context users, both round and square brackets
% are possible for the argument.
%
% Example:
%
% \usepgfmodule{matrix}

\def\usepgfmodule{\pgfutil@ifnextchar[{\use@pgfmodule}{\use@@pgfmodule}}%}
\def\use@pgfmodule[#1]{\use@@pgfmodule{#1}}
\def\use@@pgfmodule#1{%
  \edef\pgf@list{#1}%
  \pgfutil@for\pgf@temp:=\pgf@list\do{%
    \expandafter\ifx\csname pgf@module@\pgf@temp @loaded\endcsname\relax%
      \expandafter\let\csname pgf@module@\pgf@temp @loaded\endcsname=\pgfutil@empty%
      \expandafter\edef\csname pgf@module@#1@atcode\endcsname{\the\catcode`\@}
      \expandafter\edef\csname pgf@module@#1@barcode\endcsname{\the\catcode`\|}
      \expandafter\edef\csname pgf@module@#1@dollarcode\endcsname{\the\catcode`\$}
      \catcode`\@=11
      \catcode`\|=12
      \catcode`\$=3
      \input pgfmodule\pgf@temp.code.tex
      \catcode`\@=\csname pgf@module@#1@atcode\endcsname
      \catcode`\|=\csname pgf@module@#1@barcode\endcsname
      \catcode`\$=\csname pgf@module@#1@dollarcode\endcsname
    \fi%
  }%
}

\def\pgfutilensuremath#1{%
  \ifmmode#1\else$#1$\fi
}


%
% Guess the driver:
%

\begingroup
	\catcode`\"=12
	\edef\pgf@loc@TMPa{"}%
	%
	% prepares file names by checking for double colons.
	%
	% If '#1' is a usual file name without anything fancy, \pgfretval
	% will simply contain it. However, if '#1' contains double colons
	% (introduces, for example, by pdftex because there are white
	% spaces in '#1'), the routine 
	% - removes the double colons,
	% - re-inserts them outside of the string.
	%
	% \pgfutilpreparefilename{file.tex} -> file.tex
	% \pgfutilpreparefilename{"A file name".file} -> "A file name.file"
	%
	% The resulting file name is returned in '\pgfretval',
	% furthermore, a *quoted* version of the file name is returned in
	% \pgfretvalquoted. The latter result is to have some sort of
	% output normalisation: if the file name as such contains double
	% quotes, we don't want to insert another set of them.
	%
	% This special handling has the following purposes:
	% 1. Both, treatment of white spaces and double colons is not
	% properly defined in TeX. Thus, we should only work with them if
	% necessary and maintain backwards compatibility as far as
	% possible.
	% 2. It *should* work if there are spaces.
	%
	\gdef\pgfutilpreparefilename#1{%
		\begingroup
			\ifnum\the\catcode`\"=13
				\pgfutilconvertdcolon
			\fi
			\xdef\pgf@temp{#1}%
		\endgroup
		\expandafter\pgfutil@in@\expandafter"\expandafter{\pgf@temp}%
		\ifpgfutil@in@
			\def\pgf@loc@TMPa{\pgfutilstrreplace{"}{}}%
			\expandafter\pgf@loc@TMPa\expandafter{\pgf@temp}%
			\edef\pgfretval{"\pgfretval"}% re-insert quotes! Otherwise, TeX can't use the file name.
			\let\pgfretvalquoted=\pgfretval
		\else
			\let\pgfretval=\pgf@temp
			\edef\pgfretvalquoted{"\pgfretval"}%
		\fi
	}%
	\catcode`\"=13
	\xdef\pgfutilconvertdcolon{%
		\noexpand\def\noexpand"{\pgf@loc@TMPa}%
	}%
\endgroup

% Usage:
% \pgfutilstrreplace{<token>}{<replacement>}{<string>}
%
% -> will assign the modified string into \pgfretval.
%
% #1: the string to search (one or more tokens)
% #2: zero, one or more tokens which will be inserted instead of '#1'.
% #3: the string to search in
\long\def\pgfutilstrreplace#1#2#3{%
	\def\pgfretval{}%
	\long\def\pgfutil@search@and@replace@@##1#1##2\pgf@EOI{%
		\expandafter\def\expandafter\pgfretval\expandafter{\pgfretval ##1#2}%
		\pgfutil@search@and@replace@loop{#1}{##2}%
	}%
	\pgfutil@search@and@replace@loop{#1}{#3}%
}
\long\def\pgfutil@search@and@replace@loop#1#2{%
	\pgfutil@in@{#1}{#2}%
	\ifpgfutil@in@
		\def\pgf@loc@TMPa{\pgfutil@search@and@replace@@ #2\pgf@EOI}%
	\else
		\expandafter\def\expandafter\pgfretval\expandafter{\pgfretval #2}%
		\let\pgf@loc@TMPa=\relax
	\fi
	\pgf@loc@TMPa
}%

% Solves a linear equation system of size 2x2 using gauss elimination.
%
% It employs TeX register arithmetics to do so.
% #1: should contain 4 sets of braces with matrix entries, 
% 	{<a11>}{<a12>}
% 	{<a21>}{<a22>}
% 	where each entry should be a number without unit.
% 	It is acceptable if '#1' is a macro which expands to the expected
% 	format.
% #2: should contain 2 sets of braces with the right-hand-side,
% 	{<r1>}{<r2>}
% 	where each entry should be a number without unit.
% 	It is acceptable if '#2' is a macro which expands to the expected
% 	format.
%
% It will assign \pgfmathresult to contain two sets of braces with the
% result.
%
% Example:
% \pgfutilsolvetwotwoleq{
% 	{0.24}{1}
% 	{-0.97}{0}
% }{
% 	{-7}
% 	{18}
% }
% -> yields \pgfmathresult={−18.55618}{−2.54642}
%
% The algorithm employs column pivotisation.
\def\pgfutilsolvetwotwoleq#1#2{%
	\begingroup
		\dimendef\aa=0
		\dimendef\ab=1
		\dimendef\ba=2
		\dimendef\bb=3
		\dimendef\ra=4
		\dimendef\rb=5
		\dimendef\tmpa=6
		\dimendef\tmpb=7
		\edef\pgf@temp{#1}%
		\expandafter\pgfutilsolvetwotwoleq@A\pgf@temp
		\edef\pgf@temp{#2}%
		\expandafter\pgfutilsolvetwotwoleq@r\pgf@temp
		%
		\pgfutilsolvetwotwoleq@ifislarger\aa\ba{%
			% identity "permutation":
			\def\Pa{a}%
			\def\Pb{b}%
		}{%
			% permutation matrix: switch rows!
			\def\Pa{b}%
			\def\Pb{a}%
		}%
		% \pivot := 1/aa
		\pgfmathreciprocal@
			{\csname m\Pa a\endcsname}%
		\let\pivot=\pgfmathresult
		%
		% \factor := 1/aa * ba 
		\csname \Pb a\endcsname=\pivot\csname \Pb a\endcsname
		\edef\factor{\expandafter\pgf@sys@tonumber\csname \Pb a\endcsname}%
		%
		% bb -= ba/aa * ab
		\tmpa=-\factor\csname \Pa b\endcsname
		\advance\csname \Pb b\endcsname by\tmpa
		%
		% rb -= ba/aa * ra
		\tmpa=-\factor\csname r\Pa\endcsname
		\advance\csname r\Pb\endcsname by\tmpa
		%
		% xb := rb / bb (the modified rb and modified bb!)
		\pgfmathdivide@
			{\expandafter\pgf@sys@tonumber\csname r\Pb\endcsname}
			{\expandafter\pgf@sys@tonumber\csname \Pb b\endcsname}%
		\expandafter\let\csname pgfmathresult\Pb\endcsname=\pgfmathresult
		%
		% ra -= xb * ab
		\tmpa=\csname pgfmathresult\Pb\endcsname\csname \Pa b\endcsname
		\advance\csname r\Pa\endcsname by-\tmpa
		%
		% xa := 1/aa * ra  (the modified ra!)
		\tmpa=\pivot\csname r\Pa\endcsname
		\expandafter\edef\csname pgfmathresult\Pa\endcsname{\pgf@sys@tonumber\tmpa}%
		%
		\edef\pgfmathresult{%
			{\csname pgfmathresult\Pa\endcsname}%
			{\csname pgfmathresult\Pb\endcsname}%
		}%
		\pgfmath@smuggleone\pgfmathresult
	\endgroup
}%
\def\pgfutilsolvetwotwoleq@ifislarger#1#2#3#4{%
	\tmpa=#1
	\ifdim\tmpa<0pt
		\multiply\tmpa by-1
	\fi
	\tmpb=#2
	\ifdim\tmpb<0pt
		\multiply\tmpb by-1
	\fi
	\ifdim\tmpa>\tmpb
		#3%
	\else
		#4%
	\fi
}%
\def\pgfutilsolvetwotwoleq@A#1#2#3#4{%
	\def\maa{#1}\def\mab{#2}%
	\def\mba{#3}\def\mbb{#3}%
	\aa=#1pt \ab=#2pt
	\ba=#3pt \bb=#4pt
}
\def\pgfutilsolvetwotwoleq@r#1#2{%
	\ra=#1pt \rb=#2pt
}%

% there are funny programs which overwrite \read and \write (like
% tabularx).
\let\pgfutil@write=\write
\let\pgfutil@read=\read

% curtesy for latex:
\let\pgfutil@protect\relax


% new tempdims:
\newdimen\pgfutil@tempdima
\newdimen\pgfutil@tempdimb


% luatex stuff
% We assume luatex version > 0.39:
%   - \directlua <general text> will work
%   - \directlua is the only luatex primitive that we can assume
%     accessible without being prefixed by the format via
%     tex.enableprimitives.
% Ideas taken from the ifluatex package (Heiko Oberdiek)
\let\pgfutil@ifluatex\iffalse
\begingroup\expandafter\expandafter\expandafter\endgroup
\expandafter\ifx\csname directlua\endcsname\relax
\else
  \expandafter\let\csname pgfutil@ifluatex\expandafter\endcsname
    \csname iftrue\endcsname
\fi

\pgfutil@ifluatex
  \let\pgfutil@directlua\directlua
  \pgfutil@directlua{%
    tex.enableprimitives('pgfutil@',{'luaescapestring'})}
\else
  \def\pgfutil@directlua#1{}
  \def\pgfutil@luaescapestring#1{}
\fi
% End of luatex stuff

% Advances a number stored in a macro and writes the result back into
% the macro.
% #1 is a macro containing a number. 
\def\pgfutil@advancestringcounter#1{%
	\begingroup
		\c@pgf@counta=#1\relax
		\advance\c@pgf@counta by1
		\edef#1{\the\c@pgf@counta}%
		\pgfmath@smuggleone#1%
	\endgroup
}%
\input pgfutil-common-lists.tex

\endinput

BT_Rank.tex
\begin{figure}[!ht]
	\centering\begin{tikzpicture}[x=0.7cm,y=-1cm,scale=\textwidthScaling]
		\pgfmathsetmacro{\diameter}{\nodeRadiusInEx*2ex}
		\tikzstyle{every node}+=[tree]
		\tikzstyle{every edge}+=[line cap=butt]
		\tikzstyle{rank}=[draw=none, rectangle]
		\tikzstyle{projection}=[black!40, -latex, shorten >=2pt]
		\tikzstyle{transversal_down}=[blue,-latex]
		\tikzstyle{transversal_up}=[red,-latex]
		\tikzstyle{bend1}=[bend right=10]
		\tikzstyle{bend2}=[bend right=26]
		\tikzstyle{bend3}=[bend right=30]
		\tikzstyle{bend4}=[bend right=40]
		
		%
		\node (n1)  at ( 1,2)  {1};
		\node (n2)  at ( 2,1)  {2};
		\node (n3)  at ( 3,2)  {3};
		\node (n4)  at ( 4,3)  {4};
		\node (n5)  at ( 5,0)  {5};
		\node (n6)  at ( 6,3)  {6};
		\node (n7)  at ( 7,2)  {7};
		\node (n8)  at ( 8,3)  {8};
		\node (n9)  at ( 9,1)  {9};
		\node (n10) at (10,3) {10};
		\node (n11) at (11,2) {11};
			
		%
		\begin{pgfonlayer}{background}
			\draw (n5) edge (n2) edge (n9);
			\draw (n2) edge (n1) edge (n3);
			\draw (n3) edge (n4);
			\draw (n9) edge (n7) edge (n11);
			\draw (n7) edge (n6) edge (n8);
			\draw (n11) edge (n10);
		\end{pgfonlayer}
		
		%
		\foreach \i in {1,2,...,11} {
			\node[rank] (r\i) at (\i, 4.3) {\i};
			\draw[projection] (n\i) to (r\i);
		}
		\node[rank,anchor=base east] at (r1.base west) {ranks: };
		
		%
		\newcommand{\midangle}[4]{
			\begin{pgfinterruptboundingbox}
				\coordinate (tmp3) at ($(#2)!3cm!(#3)$);
				\coordinate (tmp4) at ($(#2)!3cm!(#4)$);
				\path (tmp3) to[bend right=120, looseness=2] coordinate[pos=0.5] (tmpm) (tmp4);
				\coordinate (#1) at ($(#2)!\nodeRadiusInEx ex!(tmpm)$);
			\end{pgfinterruptboundingbox}
		}

		\midangle{n2down}{n2}{n5}{n1}
		\midangle{n2switch}{n2}{n1}{n3}
		\midangle{n2up}{n2}{n3}{n5}

		\midangle{n3down}{n3}{n2}{n4}
		\midangle{n3up}{n3}{n4}{n2}

		\midangle{n5switch}{n5}{n2}{n9}
		
		\midangle{n7down}{n7}{n9}{n6}
		\midangle{n7switch}{n7}{n6}{n8}
		\midangle{n7up}{n7}{n8}{n9}
		
		\midangle{n9down}{n9}{n5}{n7}
		\midangle{n9switch}{n9}{n7}{n11}
		\midangle{n9up}{n9}{n11}{n5}
		
		\midangle{n11down}{n11}{n9}{n10}
		\midangle{n11up}{n11}{n10}{n9}
		
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%

	\end{tikzpicture}
	\caption{Binary tree with root~$5$, and left (right) childs depicted left (right) of their parent. In such a depiction, the inscribed ranks of the nodes increase from left to right.}
	\label{figure:BT_Rank}
\end{figure}

BT_Repetition.tex
\begin{figure}[!h]
	\centering\begin{tikzpicture}[scale=\textwidthScaling]
		\LiftingTrees
		\tikzstyle{desc}=[rectangle, draw=none, inner sep=0.5\smm]
		\def\shorten{0.8\smm}
		\tikzstyle{pin}=[black!80, shorten <=\shorten]
		
		%
		\foreach \i/\d in {1/3,2/4,3/2,4/3,5/1} {
			\node[tree] (n\i) at (\i-1,-\d) {\i};
		}
		\foreach \i/\d in {6/0,7/4,8/3,9/4,10/2,11/1,12/2} {
			\node[tree] (n\i) at (\i,-\d) {\i};
		}
		
		%
		\foreach \i/\j in {6/5,5/3,3/1,1/2,3/4,6/11,11/10,10/8,8/7,8/9,11/12} {
			\draw (n\i) edge (n\j);
		}
		
		%
		\begin{pgfonlayer}{background}
			\coordinate (h11) at ($(n11)-(0,0.7ex)$);
			\fill[S1] \convexcycle{n7,n8,h11,n12,n9}{\convexRadiusB};
			\fill[S2] \convexcycle{n7,n8,n10,n9}{\convexRadiusA};
			\fill[S3] (n12) circle (\convexRadiusA);
		\end{pgfonlayer}

		%
			\node[desc,anchor=base east] (rank) at (n1.west |- 0,-5.7) {rank:};
		\foreach \i in {1,...,12} {
			\node[desc,anchor=base] (rank\i) at (rank.base -| n\i) {\i};
			\draw  (rank\i) edge[pin,shorten >=\shorten] (n\i);
		}

		%

		%
		\path (n6) ++(25:1.7) node[desc] (root) {$\root(B)$};
		\draw (root) edge[pin] (n6);

		\begin{pgfinterruptboundingbox}
		
			%
			\path (n3) ++ (122:1.1) node[desc] (t) {$t$};
			\path (n5) ++ (122:1.1) node[desc] (p) {$\parent(t)$};
			\path (n1 |- n3.base) node[desc,anchor=base] (l) {$\leftChild(t)$};
			\path ($(n4)+(0.7,0)$) node[desc,anchor=west] (r) {$\rightChild(t)$};
			\draw (n3) edge[pin] (t);
			\draw (n5) edge[pin] (p);
			\draw (n1) edge[pin] (l);
			\draw (n4) edge[pin] (r);
			
			\path (n11) ++ (60:1.1) node[desc] (tt) {\tau};
			\path ($(n11)!0.5!(n12)$) ++ (0,-2.15) node[desc,S1text] (S) {$\subtree(\tau)$};
			\path (n8)  ++ (140:1.2) node[desc,S2text] (L) {$\leftSubtree(\tau)$};
			\path (n12) ++ (35:1.2) node[desc,S3text] (R) {$\rightSubtree(\tau)$};
			\draw (n11) edge[pin] (tt);
			
		\end{pgfinterruptboundingbox}
		
		\draw [decorate,decoration={brace,amplitude=1.5\smm}] (rank.south -| 10.5,0) -- +(-4,0) node (leftSize) [desc,anchor=north,midway,fill=none,yshift=-2\smm] {$\leftSize(\tau) = 4$};
		\draw [decorate,decoration={brace,amplitude=1.5\smm}] (rank.south -| 12.5,0) -- +(-1,0) node (rightSize) [desc,anchor=north,midway,fill=none,yshift=-2\smm] {$\rightSize(\tau) = 1$};
		\draw [decorate,decoration={brace,amplitude=1.5\smm,aspect=0.375}] (leftSize.south -| 12.5,0) -- +(-6,0) node (size) [desc,anchor=north,pos=0.375,fill=none,yshift=-2\smm] {$\size(\tau) = 6$};
	\end{tikzpicture}
	\caption[A binary tree with nodes labeled by ranks, basic node relationships and subtrees]{A binary tree with nodes labeled by ranks from $1$ to $12$, and $\root(B) = 6$. The parent of node $t = 3$ is $\parent(t) = 5$, its left child is $\leftChild(t) = 1$ and its right child is $\rightChild(t) = 4$. The principal subtree~$\subtree(\tau)$ in $\tau=11$ is marked in blue, its left subtree~$\leftSubtree(\tau)$ in green and its right subtree~$\rightSubtree(\tau)$ in red. The respective subtree sizes are $\size(\tau)$, $\leftSize(\tau)$ and $\rightSize(\tau)$.}
	\label{figure:BT_Repetition}
\end{figure}

BT_TopRightLeft.tex
\begin{figure}[!ht]
	\centering\begin{tikzpicture}[x=0.7cm,y=-1cm,scale=\textwidthScaling]
		\tikzstyle{every node}+=[tree]
		\tikzstyle{every edge}+=[thick]
		\tikzstyle{every pin}=[rectangle, inner sep=0pt, draw=none, pin position=10]
		
		\colorlet{topleft}{blue}
		\colorlet{topright}{red}
		\tikzset{
			topleft/.style={fill=topleft!10},
			topright/.style={fill=topright!10},
			root/.style={path picture={
				\fill[topleft!10] (path picture bounding box.south west) rectangle (path picture bounding box.north);
				\fill[topright!10] (path picture bounding box.south east) rectangle (path picture bounding box.north);
			}},
            topleftPin/.style={topleft!80!black,fill=none,pin edge={draw=topleft}},
			toprightPin/.style={topright!80!black,fill=none,pin edge={draw=topright}}
		}
		
		%
		\node[topleft,pin={[topleftPin]170:$\mathllap{\topleft(\topleftN)=\topleft(3)}$}] (n1)  at ( 1,2)  {1};
		\node[topleft,pin={[topleftPin]170:$\topleft(2)$}] (n2)  at ( 2,1)  {2};
		\node (n3)  at ( 3,2)  {3};
		\node (n4)  at ( 4,3)  {4};
		\node[root,pin={[toprightPin]$\topright(1)$}, pin={[topleftPin]170:$\topleft(1)$}] (n5)  at ( 5,0)  {5};
		\node (n6)  at ( 6,3)  {6};
		\node (n7)  at ( 7,2)  {7};
		\node (n8)  at ( 8,3)  {8};
		\node[topright,pin={[toprightPin]$\topright(2)$}] (n9)  at ( 9,1)  {9};
		\node (n10)  at (10,3) {10};
		\node[topright,pin={[toprightPin]$\topright(3)\mathrlap{\ = \topright(\toprightN)}$}] (n11) at (11,2) {11};
			
		%
		\draw (n5) edge (n2) edge (n9);
		\draw (n2) edge (n1) edge (n3);
		\draw (n3) edge (n4);
		\draw (n9) edge (n7) edge (n11);
		\draw (n7) edge (n6) edge (n8);
		\draw (n11) edge (n10);
	\end{tikzpicture}
	\caption[A binary tree with top-left and top-right nodes]{A binary tree with top-left nodes $\topleft(i)$ and top-right nodes $\topright(i)$. Both $\topleft(1)$ and $\topright(1)$ always equal $\root(B)$. The last top-left node $\topleft(\topleftN)$ is always the node with rank~1, and the last top-right node $\topright(\toprightN)$ is always the node with maximal rank.}
	\label{figure:BT_TopRightLeft}
\end{figure}

Common.tex
%

%
%
%
%
%
%
\edef\spt{*\textwidthScalingInv pt}
\edef\sex{*\textwidthScalingInv ex}

%
%
%
%
\edef\smm{*\textwidthScaling mm}


%
\newcommand{\nodeRadiusInEx}{2}
\tikzset{
	tree/.style={
		circle,
		draw=black,
		fill=white,
		inner sep=0pt,
		minimum width=\nodeRadiusInEx*2ex
	},
	lifted/.style={
		fill=onOffBack
	},
	every picture/.style={
		%
		node font=\normalsize,
		%
		line width=\textwidthScaling*0.4pt,
		ultra thin/.style={line width=\textwidthScaling*0.1pt},
		very thin/.style={line width=\textwidthScaling*0.2pt},
		thin/.style={line width=\textwidthScaling*0.4pt},
		semithick/.style={line width=\textwidthScaling*0.6pt},
		thick/.style={line width=\textwidthScaling*0.8pt},
		very thick/.style={line width=\textwidthScaling*1.2pt},
		ultra thick/.style={line width=\textwidthScaling*1.6pt}
	}
}

%
\newcommand{\convexRadiusA}{2.9\sex}
\newcommand{\convexRadiusB}{3.7\sex}
\newcommand{\convexRadiusC}{4.5\sex}

%
%
%
%
%
\NewDocumentCommand{\drawTimeAxis}{sO{t}mm}{{
	\def\coord{($({(#3)*(#4)},0)+(3mm,0)$)}
	\draw[-latex] (-2mm,0) -- \coord;
	\ifthenelse{\equal{#2}{}}{}{
		\node[anchor=west] at \coord {$#2$};
	}
	\begin{scope}[xscale={#3}]
		\pgfmathtruncatemacro\dTAmax{#4}
		\foreach \t in {1,...,\dTAmax} {
			\draw (\t,-1.5mm) -- +(0,3mm);
			\IfBooleanTF #1 {}{ \node[anchor=north] (t\t) at (\t-0.5,0) {\t}; }
		}
	\end{scope}
}}

%
%
%
\NewDocumentCommand{\drawVarAxis}{om}{{
	\draw[-latex] (0,-2mm) -- ($(0,{#2})+(0,3mm)$);
	\begin{scope}[yscale=(#2)]
		\draw (-1.5mm,1) -- +(3mm,0);
		\IfValueTF{#1}{
			\node[anchor=east] at (-1.5mm,1) {#1};
		}{}
	\end{scope}
}}

%
%
%
\newcommand{\drawOnOff}[1]{
	\expandafter\drawOnOffA\expandafter{#1}
}
%
\newcommand{\drawOnOffA}[1]{
	\draw[onOffColor, fill=onOffBack, very thick] (0,0)
		\foreach \t[remember=\t as \lastk]/\v in {#1} {
			|- (\t,\v)
		} -- (\lastk,0);
	\foreach \t/\v in {#1} {
		\node (onOff\t) at (\t-0.5, 0.5) {$\v$};
	}
}

\newcommand{\drawStartupProductionProfileTemplate}{
		\def\w{12}
		\def\h{6}
		
		%
		\begin{scope}[yscale=\h]
			\node[anchor=east] at (0, 0.6) {$\minProd(i)$};
			\node[anchor=east] at (0, 1) {$\maxProd(i)$};
			
			\draw[prodColor!30] (-0.08, 0.6) -- (\w, 0.6)
			 	           (-0.08, 1) -- (\w, 1);
			\begin{scope}[draw=black!30]
				\draw (10, 0) -- (10, 1);
			\end{scope}
		\end{scope}			
		
		%
   		\node (top) at (0, \h) {};
		\draw[->] (-0.5, 0) -- (\w+0.5, 0);
		\draw[->] (0, -0.5) -- (0, \h+0.5);
		\draw[->] (\w, -0.5) -- (\w, \h+0.5);
		\draw (\w-0.08, \h) -- (\w+0.08, \h);
}

%
\newcommand{\TemperatureGraphicsParams}{
	\def\T{11}
	\def\lambda{0.25}
	\def\h{3}
	\def\fT(##1){(exp(-\lambda*(##1))}
	\def\fdT(##1){\lambda*(exp(-\lambda*(##1)))}
}

%
\newcommand{\decompositionDefinitions}{
	\def\bigw{11}
	\def\bigh{40}
	\def\smallw{6}
	\def\smallh{8}

	%
	\tikzstyle{part}=[draw=black,fill=none,thick];
	\tikzstyle{part1}=[part,fill=black!25];
	\tikzstyle{part2}=[part,fill=blue!30];
	\tikzstyle{part3}=[part,fill=green!30];
	\tikzstyle{part4}=[part,fill=yellow!50];
	\tikzstyle{part5}=[part,fill=red!30];
	
	\tikzstyle{part1back}=[fill=black!12]
	\tikzstyle{part2back}=[fill=blue!15]
	\tikzstyle{part3back}=[fill=green!15]
	\tikzstyle{part4back}=[fill=yellow!25]
	\tikzstyle{part5back}=[fill=red!15]

	%
	\def\onOffV{{0,0.65,0.1,0.4,0.2,0.95}}
	
	%
	\def\sigmaV{{0,5,1,3,4,2,0}}
	\def\onOffSV{{0,0.1,0.2,0.4,0.65,0.95,1}}
	\def\sigmaInfV{{0,2,5,3,4,1,0}}
		
	\def\vmu{0.5}
}

\newcommand{\decompositionComparison}{
	\def\w{15}
	\def\h{40}

	%
	\tikzstyle{part}=[draw=black,fill=none,thick];
	\tikzstyle{part1}=[part,fill=red!30];
	\tikzstyle{part2}=[part,fill=blue!30];
	\tikzstyle{part3}=[part,fill=green!30];
	\tikzstyle{part4}=[part,fill=yellow!50];
	\tikzstyle{part5}=[part,fill=black!30];

	%
	\def\onOffV{{0,1,0.7,0.2,0.6,0.2,0.9}}
}

\NewDocumentCommand{\decompositionAxis}{smm}{
	%
	\IfBooleanTF #1
		{ \drawTimeAxis*[]{#2}{5} }
		{ \drawTimeAxis*{#2}{5} }
	\draw[-latex] (0, -2) -- (0, #3+3);
%
	%
	\IfBooleanTF #1 {}{ 
		\foreach \t in {1,2,3,4,5}{
			\node[anchor=south] at ({(\t-0.5)*(#2)},\onOffV[\t]*#3) {$\onOff(i,\t)$};
		}
	}
%
	%
	\begin{scope}[yscale=#3]
		\draw (-1,1) -- (1,1);
		\IfBooleanTF #1 {}{
			\node[anchor=east] at (0,1) {$1$};
		}
	\end{scope}
}

\newcommand{\segmentDefinitions}{
	\def\bigw{9}
	\def\bigh{35}

	%
	\tikzstyle{part}=[draw=black,fill=none,thick];
	\tikzstyle{part1}=[part,fill=black!25];
	\tikzstyle{part2}=[part,fill=blue!30];
	\tikzstyle{part3}=[part,fill=green!30];
	\tikzstyle{part4}=[part,fill=yellow!50];
	\tikzstyle{part5}=[part,fill=red!30];
	\tikzstyle{part6}=[part,fill=cyan!20];
	
	\tikzstyle{part1back}=[fill=black!12]
	\tikzstyle{part2back}=[fill=blue!15]
	\tikzstyle{part3back}=[fill=green!15]
	\tikzstyle{part4back}=[fill=yellow!25]
	\tikzstyle{part5back}=[fill=red!15]
	\tikzstyle{part6back}=[fill=cyan!10]


	%
	\def\onOffV{{0,0.7,0.2,0.5,0.1,0.3,0.9,0}}
	\def\onOffS{{0,0.9,0.7,0.5,0.3,0.2,0.1,0}}
	\def\sigmaV{{0,6,1,3,5,2,4,0}}
	\def\sigmaInfV{{0,6,2,3,4,1,5,0}}
}

%
%
%
\NewDocumentCommand{\segmentationAxis}{smm}{
	%
	\IfBooleanTF #1
		{ \drawTimeAxis*[]{#2}{6} }
		{ \drawTimeAxis*{#2}{6} }
		
%
	%
	\IfBooleanTF #1 {}{ 
		\foreach \t in {1,2,3,4,5,6}{
			\node[anchor=south] at ({(\t-0.5)*(#2)},\onOffV[\t]*#3) {$\onOff(i,\t)$};
		}
	}
	
	\draw[-latex] (0, -2) -- (0, #3+3);
	
	\draw (-1,#3) -- (1,#3);
	
	%
	%
	%
	%
	%
}


\newcommand{\liftingTreeEdges}{
	\draw (v11) edge (v2) edge (v12);
	\draw (v2)  edge (v1) edge (v6);
	\draw (v6)  edge (v4) edge (v9);
	\draw (v4)  edge (v3) edge (v5);
	\draw (v9)  edge (v7)  edge (v10);
	\draw (v7)  edge (v8);
}
\newcommand{\liftingAunlifted}{1/9, 3/11, 4/6, 5/8, 7/10, 8/12, 9/5, 10/7, 12/4}
\newcommand{\liftingAlifted}{2/2, 6/3, 11/1}
\edef\liftingA{\liftingAunlifted, \liftingAlifted}
\newcommand{\liftingB}{1/5, 2/2, 3/9, 4/6, 5/11, 6/4, 7/8, 8/10, 9/7, 10/12, 11/1, 12/3}
\newcommand{\liftingInput}{1/0, 2/1, 3/0, 4/0, 5/0, 6/0, 7/0, 8/0, 9/0, 10/0, 11/1, 12/0}
\newcommand{\liftingResult}{1/0, 2/1, 3/0, 4/0, 5/0, 6/1, 7/0, 8/0, 9/0, 10/0, 11/1, 12/0}

\newcommand{\LiftingTrees}{
	%
	\providecommand{\liftNext}{{q}}

	\colorlet{marker}{red}
	\tikzstyle{markerLine}=[draw=marker, dashed, shorten >=6pt]
	\colorlet{markerText}{red!90!black}

	\tikzstyle{every node}+=[circle, draw, fill=white]
	\tikzstyle{every pin}+=[rectangle, inner sep=0pt, draw=none, fill=none, text=marker, pin distance=4ex, pin edge={marker, shorten >=6pt}]
	
	\tikzstyle{description}=[draw=none,fill=none,rectangle]
	\tikzstyle{vector}=[description,inner sep=0.5pt]

	\tikzstyle{S1fill}=[fill=blue,fill opacity=0.17]
	\tikzstyle{S1}=[draw=blue,very thick,S1fill]
	\tikzstyle{S1text}=[description,text=blue!80!black]
	
	\tikzstyle{S2fill}=[fill=green,fill opacity=0.2]
	\tikzstyle{S2}=[draw=green,very thick,S2fill]
	\tikzstyle{S2text}=[description,text=green!70!black]

	\tikzstyle{S3fill}=[fill=red,fill opacity=0.2]
	\tikzstyle{S3}=[draw=red,very thick,S3fill]
	\tikzstyle{S3text}=[description,text=red!75!black]
}

\newcommand{\StartupProfiles}{
	%
	\def\height{6}
	\def\ti{11}
	\def\rate{0.2}
	\def\H{0.316}
	
	%
	\def\heatingLength##1{(ln( \H / (\H - \rate*(1-exp(-\rate*(##1))) ) ) / \rate)}
	\pgfmathsetmacro\ts{\ti - \heatingLength{\ti}}
	\pgfmathsetmacro{\tsFloor}{floor(\ts)}
	\pgfmathsetmacro{\tsCeil}{\tsFloor+1}
	\pgfmathsetmacro\maxHeatingLength{ln(\H/(\H-\rate))/\rate}
	
	%
	\def\tempCooling##1{(exp(-\rate*(##1)))}
	\def\tempHeating##1{( \H/\rate - (\H/\rate - exp(-\rate*\ts)) * exp(-\rate*((##1) - \ts)) )}
	
	%
	\edef\neededHeating##1{(\H*\heatingLength{##1})}
	\pgfmathsetmacro\maxNeededHeating{\H*\maxHeatingLength}
	
	%
	\def\tempIncreaseByPart##1{\H/\rate * (1 - exp(-\ti*\rate*(##1)))}
	\pgfmathsetmacro\maxTempIncrease{\H/\rate * (1 - exp(-\ti*\rate))}
	\def\heatingByTempIncrease##1{\H/\rate * ln( \H / (\H-\rate*(##1)) ) }
	\pgfmathsetmacro\maxHeating{\H*\ti}
	\def\heatingByTempIncreaseDiff##1{\H / (\H - \rate*(##1))}
}

Decomposition.tex
\begin{figure}[!h]
\centering
\begin{tikzpicture}[x=1mm,y=1mm,scale=\textwidthScaling]
	\decompositionDefinitions

	%
	\decompositionAxis{\bigw}{\bigh}
	
	%
	\begin{scope}[xscale=\bigw, yscale=\bigh]
		\node (original) at (2.5,1.2) {fractional vector $\onOff(i,) \in [0,1]^5$};
		\foreach \t in {1,2,3,4,5} {
			\foreach \i in {5,4,3,2,1}{
				\pgfmathparse{int(5-\i+1)}
				\path[part\pgfmathresult] ({\t-1},{\onOffV[\sigmaV[\i+1]]}) rectangle (\t,\onOffV[\sigmaV[\i]]);
				\pgfmathparse{\sigmaV[\i]}
				\ifnum\t=\pgfmathresult
					\breakforeach
				\fi
			}
			\node[anchor=north] at ({\t-0.5},0) {$\pgfmathparse{\sigmaInfV[\t]}\sigma(\pgfmathprintnumber[int trunc]{\pgfmathresult})$};
		}
	\end{scope}

	%
	\newcommand{\smallPic}[4]{
		\begin{scope}[yshift={-47mm+#1*14.5mm}]
			\decompositionAxis*{\smallw}{\smallh}
			\begin{scope}[xscale=\smallw, yscale=\smallh]
				\ifthenelse{\not\isempty{#3}}{
					\node[anchor=east] (p#1) at (-0.2,0.5) {$\onOff{i}{#2}-\onOff{i}{#3} \ \cdot$};
				}{
					\node[anchor=east] (p#1) at (-0.2,0.5) {$\onOff{i}{#2} \ \cdot$};
				}
%
				\foreach \k in {#4}{
					\path[part#1] (\k-1,0) rectangle (\k,1);
					\node at (\k-0.5,0.5) {1};
				}
			\end{scope}
		\end{scope}
	}
	
	\begin{scope}[xshift=\bigw*5mm+49mm, yshift=\bigh*0.5mm]
		\node (vectorsText) at (2.5*\smallw,43) {vectors};
		\draw [decorate,decoration={brace,amplitude=2mm}]
($(0,0 |- vectorsText.south)-(0,3)$) -- ($(5*\smallw,0 |- vectorsText.south)-(0,3)$);
		\node[anchor=east] (factorsText) at (-0.3*\smallw,0 |- vectorsText) {factors};
		\draw [decorate,decoration={brace,amplitude=2mm,aspect=0.65}]
($(-3*\smallw,0 |- vectorsText.south)-(0,3)$) -- ($(-0.7*\smallw,0 |- vectorsText.south)-(0,3)$);
		\node[anchor=base] at ($(vectorsText.base west)!0.5!(factorsText.base east)$) {and};
		\node[anchor=base east] (convexCombinationText) at (factorsText.base west) {convex combination:};
		
		\smallPic{5}{5}{1}{5}
		\smallPic{4}{1}{3}{1,5}
		\smallPic{3}{3}{4}{1,3,5}
		\smallPic{2}{4}{2}{1,3,4,5}
		\smallPic{1}{2}{}{1,2,3,4,5}
	\end{scope}
	
	\begin{scope}[xscale=\bigw, yscale=\bigh]
		\tikzstyle{conn}=[-latex, shorten >=3, shorten <=5, looseness=1.8];
		\draw[conn] (5,{\onOffV[\sigmaInfV[1]]/2}) -- ++(0.4,0) to[out=0, in=180] (p1);
		\foreach \i in {2,3,4,5} {
			\draw[conn, out=0, in=180] (5,{\onOffV[\sigmaV[5-\i+1]]/2+\onOffV[\sigmaV[5-\i+2]]/2}) to (p\i);
		}
	\end{scope}
\end{tikzpicture}
	\caption[Decomposition of a fractional vector into vectors known to lie on a single facet (with appropriate summed start-up costs).]{Decomposition of a fractional vector $\onOff(i,) \in [0,1]^5$ into binary vectors $\onOff(j,) \in \set{0,1}^5$, such that all points $(\onOff(j,),\StartupCostSum(\onOff(j,)))$ lie on the same facet.}
	\label{figure:SCS_Decomposition}
\end{figure}

Function.tex
\begin{figure}[!ht]
	\centering
	\def\fixed{8}
	\def\variable{25}
	\def\lambda{0.03}
	\def\maxT{12}
	\def\T{9}
	\def\offset{20}
%
	\begin{tikzpicture}[x=0.8mm,y=0.8mm,scale=\textwidthScaling]
		\tikzstyle{every node}+=[inner sep=0pt]
%
		%
		\draw[->] (-2,0) -- (\T*\maxT+5, 0);
		\draw[anchor=west] (\T*\maxT+7,0) node (D) {$l$};
		%
%
		%
		\draw[->] (0,-2) -- (0, \variable+\fixed+2);
		\draw (-6,\variable+\fixed+4) node[anchor=north] {cost};
%
		%
		\draw[blue!30] (0, \fixed+\variable) -- (\T*\maxT,\fixed+\variable);
		\draw[blue!30] (0, \fixed) -- (\T*\maxT,\fixed);
		\begin{pgfinterruptboundingbox}
			\draw [decorate,decoration={brace,amplitude=1.5\smm},xshift=-2]
				(0,0) -- (0, \fixed) node [anchor=east, black,midway,xshift=-2mm] {$\fixedStartupCost(i)$};
			\draw [decorate,decoration={brace,amplitude=1.5\smm},xshift=-2]
				(0,\fixed) -- (0, \variable + \fixed) node [anchor=east, black,midway,xshift=-2mm] {$\heatingCost(i)$};
		\end{pgfinterruptboundingbox}
%
		%
		\draw[blue,very thick] (0,0) plot[smooth,domain=0:\T*\maxT,samples=100] (\x,{\fixed+\variable*(1-exp(-\lambda*\x))});
		\fill[blue] (0,0) circle (0.6mm);

		\begin{pgfinterruptboundingbox}
			\node[blue, anchor=west] at (\T*\maxT+5,\fixed+\variable) {$\StartupCostFunction(i,l)$};
		\end{pgfinterruptboundingbox}
	\end{tikzpicture}
	\caption{Typical exponential start-up cost function of a thermal unit}
	\label{figure:SC_Function}
\end{figure}

IntGapRel.tex
\begin{tikzpicture}
	\begin{axis}[
		tick label style={font=\small},	%
%
		boxplot/draw direction=y,
		width = \chartwidth,
		height = \chartheight,
%
		xtick={0.5,1.5,2.5,3.5,4.5,5.5},
		x tick label as interval=true,
		xticklabels={1-Bin,1-Bin*,3-Bin,Temp,BTI},
		enlarge x limits = 0.05,
%
	%
		ymin=0.5,
		ymax=20,
		ytick={1,3,5,10,15,20},
		yticklabels={$100\%$,$300\%$,$500\%$,$1000\%$,$1500\%$,$2000\%$},
		minor ytick={1.02,1.04,1.06},
%
%
%
%
%
		boxplot/every box/.style={fill=quantileBack,draw=quantileColor,mark=quantileColor,thick},
		boxplot/every whisker/.style={draw=quantileColor,thick},
		boxplot/every median/.style={draw=medianColor,very thick},
	]

		\addplot[mark=+,boxplot prepared={
			lower whisker=2.048432929,
			lower quartile=12.91824627,
			median=10.0512265,
			upper quartile=4.684969478,
			upper whisker=18.47902544
        }] table[row sep=\\,y index=0] {data\\};
        \node[anchor=south,medianColor] at (axis cs:1,10.0512265) {\scriptsize$1035\%$};
%
		\addplot[mark=+,boxplot prepared={
			lower whisker=1.911802364,
			lower quartile=11.39629007,
			median=8.895200798,
			upper quartile=4.225629963,
			upper whisker=16.9135323
        }] table[row sep=\\,y index=0] {data\\};
        \node[anchor=south,medianColor] at (axis cs:2,8.895200798) {\scriptsize$890\%$};
%
		\addplot[mark=+,boxplot prepared={
			lower whisker=1.253844115,
			lower quartile=4.683965487,
			median=3.153664099,
			upper quartile=2.345760198,
			upper whisker=8.204796746
        }] table[row sep=\\,y index=0] {data\\};
        \node[medianColor] at (axis cs:3,3.75) {\scriptsize$315\%$};
%
		\addplot[mark=+,boxplot prepared={
			lower whisker=0.991563807,
			lower quartile=0.99999999,
			median=0.999960426,
			upper quartile=0.999302728,
			upper whisker=1.000000023
        }] table[row sep=\\,y index=0] {data\\};
        \node[medianColor] at (axis cs:4,2) {\scriptsize$100\%$};
%
		\addplot[mark=+,boxplot prepared={
			lower whisker=1,
			lower quartile=1,
			median=1,
			upper quartile=1,
			upper whisker=1
        }] table[row sep=\\,y index=0] {data\\};
        %
        \node[medianColor] at (axis cs:5,2) {\scriptsize$100\%$};
%
    \end{axis}
\end{tikzpicture}%

IntGap.tex
\begin{tikzpicture}
	\begin{axis}[
		tick label style={font=\small},	%
%
		boxplot/draw direction=y,
		width = \chartwidth,
		height = \chartheight,
%
		xtick={0.5,1.5,2.5,3.5,4.5,5.5},
		x tick label as interval=true,
		xticklabels={1-Bin,1-Bin*,3-Bin,Temp,BTI},
		enlarge x limits = 0.05,
%
		%
		ymin=0,
		ymax=0.07,
		ytick={0,0.01,0.03,0.05,0.07},
		yticklabels={$0\%$,$1\%$,$3\%$,$5\%$,$7\%$},
		scaled y ticks = false,
		minor ytick={0.02,0.04,0.06},
%
%
%
%
%
		boxplot/every box/.style={fill=quantileBack,draw=quantileColor,mark=quantileColor,thick},
		boxplot/every whisker/.style={draw=quantileColor,thick},
		boxplot/every median/.style={draw=medianColor,very thick},
	]

		\addplot[mark=+,boxplot prepared={
			lower whisker=0.008249911,
			lower quartile=0.029534731,
			median=0.023473796,
			upper quartile=0.0219909,
			upper whisker=0.064282901
        }] table[row sep=\\,y index=0] {data\\};
        \node[anchor=south,medianColor] at (axis cs:1,0.023473796) {\scriptsize$2.34\%$};
%
		\addplot[mark=+,boxplot prepared={
			lower whisker=0.007288354,
			lower quartile=0.026200701,
			median=0.021492432,
			upper quartile=0.01921532,
			upper whisker=0.054309791
        }] table[row sep=\\,y index=0] {data\\};
        \node[anchor=south,medianColor] at (axis cs:2,0.021492432) {\scriptsize$2.21\%$};
%
		\addplot[mark=+,boxplot prepared={
			lower whisker=0.002203362,
			lower quartile=0.014194978,
			median=0.010220268,
			upper quartile=0.0079585,
			upper whisker=0.019434
        }] table[row sep=\\,y index=0] {data\\};
        \node[medianColor] at (axis cs:3,0.0123) {\scriptsize$1.01\%$};
%
		\addplot[mark=+,boxplot prepared={
			lower whisker=0.000943012,
			lower quartile=0.004972636,
			median=0.002488546,
			upper quartile=0.001950082,
			upper whisker=0.011463192
        }] table[row sep=\\,y index=0] {data\\};
        \node[medianColor] at (axis cs:4,0.015) {\scriptsize$0.25\%$};
%
		\addplot[mark=+,boxplot prepared={
			lower whisker=0.000943012,
			lower quartile=0.004972966,
			median=0.002488546,
			upper quartile=0.001951774,
			upper whisker=0.011463192
        }] table[row sep=\\,y index=0] {data\\};
        %
        \node[medianColor] at (axis cs:5,0.015) {\scriptsize$0.25\%$};
%
    \end{axis}
\end{tikzpicture}%

LiftingExampleStripped.tex
\begin{figure}[!ht]
	\centering
	\def\extraScale{0.9}
	\begin{tikzpicture}[x=1cm,y=1cm,scale=\textwidthScaling]
		\def\doit#1{
			\node[anchor=east] at (0,0.5) {$#1$};
			\draw[->] (0,-0.3) -- (0,1.1);
			\draw[->] (-0.3,0) -- (12.5,0) node[anchor=west] {$t$};
			\foreach \i in {1,2,...,12} {
				\node[anchor=north] at (\i-0.5, 0) {$\i$};
				\draw (\i, 0) +(0, -0.08) -- +(0, 0.08);
			}
		}
		
		\def\jo#1{
			\fill[red!20] (2,0) rectangle +(1,1);
			\fill[blue!20] (4,0) rectangle +(1,1);
			\draw [decorate,decoration={brace,amplitude=1.5\smm},yshift=0.5mm] (2,1) -- +(1,0) node [midway,anchor=south,yshift=1mm] {$\offlineNumber{4}{#1}$};
			\draw [decorate,decoration={brace,amplitude=1.5\smm},yshift=0.5mm] (4,1) -- +(1,0) node [midway,anchor=south,yshift=1mm] {$\offlineNumberRight{4}{#1}$};
		}

		\def\je#1{
			\fill[red!20] (6,0) rectangle +(2,1);
			\fill[blue!20] (9,0) rectangle +(1,1);
			\draw [decorate,decoration={brace,amplitude=1.5\smm},yshift=0.5mm] (6,1) -- +(2,0) node [midway,anchor=south,yshift=1mm] {$\offlineNumber{9}{#1}$};
			\draw [decorate,decoration={brace,amplitude=1.5\smm},yshift=0.5mm] (9,1) -- +(1,0) node [midway,anchor=south,yshift=1mm] (h) {$\offlineNumberRight{9}{#1}$};
		}
		
		\begin{scope}[yshift=0mm,scale=\extraScale]
			%
			\drawOnOff{\liftingResult}
			\doit{\onOff(\idx-1,)}
			
			\coordinate (lifting1) at (0,0);
		\end{scope}

		\begin{scope}[xshift=-8mm, yshift=-24mm,scale=0.7*\extraScale]
			%
			\jo{\onOff(\idx,)}
			
			\drawOnOff{1/0,2/1,3/0,4/1,5/0,6/1,7/0,8/0,9/0,10/0,11/1,12/0}
			
			\doit{\onOff(\idx,)}

			\coordinate (liftingA) at (6,0);
		\end{scope}
		
		\begin{scope}[xshift=43mm,yshift=-41mm,scale=0.7*\extraScale]
			%
			\je{\tildeOnOff(\idx,)}
			
			\drawOnOff{1/0,2/1,3/0,4/0,5/0,6/1,7/0,8/0,9/1,10/0,11/1,12/0}
			\doit{\tildeOnOff(\idx,)}

			\coordinate (liftingB) at (10,0);
		\end{scope}

		\begin{scope}[yshift=-66mm,scale=\extraScale]
			%
			\jo{\onOff(\idx+1,)}
			\je{\onOff(\idx+1,)}
			
			\drawOnOff{1/0,2/1,3/0,4/1,5/0,6/1,7/0,8/0,9/1,10/0,11/1,12/0}
			\doit{\onOff(\idx+1,)}

			\coordinate (lifting3) at (0,0);
		\end{scope}
		
		\begin{scope}[thick]
			\tikzset{every node/.append style={rectangle,inner sep=2mm}}
			
			\draw[->,shorten <=6.5\smm,shorten >=9\smm] (lifting1 -| liftingA) to node[pos=0.5,anchor=west] {lifting $\bticoeff(4)$} (liftingA);
			
			\draw[->,shorten <=6.5\smm, shorten >=20.5\smm] (liftingA) to node[pos=0.38,anchor=east] {lifting $\bticoeff(9)$}  (lifting3 -| liftingA);
			
			\draw[->,shorten <=6.5\smm,shorten >=17\smm] (lifting1 -| liftingB) to node[pos=0.45,anchor=west] {lifting $\bticoeff(9)$}   (liftingB);

			\draw[->,shorten <=5.3\smm,shorten >=12\smm] (liftingB) to node[pos=0.35,anchor=west] {lifting $\bticoeff(4)$} (lifting3 -| liftingB);
		\end{scope}
	\end{tikzpicture}
	\caption{Lifting coefficients~$\protect\bticoeff(4)$ and $\protect\bticoeff(9)$ in both orders, with intermediate vectors.}
	\label{figure:SCS_LiftingExampleStripped}
\end{figure}

LiftingExample.tex
\begin{figure}[!ht]
	\centering
	\begin{tikzpicture}[x=1cm,y=1cm,scale=\textwidthScaling]
		%
		\begin{scope}[yshift=1.5cm]
			\node[anchor=east] at (0,0.5) {$\onOff(i,)$};
			\drawOnOff{\liftingInput}
		\end{scope}

		%
		\begin{scope}
			\node[anchor=east] at (0,0.5) {$\tildeOnOff(i,)$};
			\drawOnOff{\liftingResult};
		\end{scope}

		%
		\begin{pgfonlayer}{background}
			\fill[red!10,yshift=-0.57cm,yscale=4,rounded corners=2ex]
						  %
			              (5,0) rectangle +(1,1)
			              (10,0) rectangle +(1,1);
		\end{pgfonlayer}
		\node (idx)  at (5.5,3) {$t$};
		\node (next) at (10.5,3) {$\liftNext$};
		
		%
		\draw[->] (0,-0.3) -- (0,2.8);
		\draw[->] (-0.3,1.5) -- (12.5,1.5);
		\draw[->] (-0.3,0) -- (12.5,0) node[anchor=west] {$t$};
		\foreach \i in {1,2,...,12} {
			\node[anchor=north] (t\i) at (\i-0.5, 0) {$\i$};
			\draw (\i, 0) +(0, -0.08) -- +(0, 0.08);
			\draw (\i, 1.5) +(0, -0.08) -- +(0, 0.08);
		}

		%
		\draw [decorate,decoration={brace,amplitude=2\smm,mirror}] ($(2.1,0 |- t1.south)+(0,1mm)$) -- ($(4.9,0 |- t1.south)+(0,1mm)$) node [midway,anchor=north,yshift=-2\smm] {$\offlineNumber{t}{\tildeOnOff(i,)}$};
		\draw [decorate,decoration={brace,amplitude=2\smm,mirror}] ($(6.1,0 |- t1.south)+(0,1mm)$) -- ($(9.9,0 |- t1.south)+(0,1mm)$) node (h1) [midway,anchor=north,yshift=-2\smm] {$\offlineNumberRight{t}{\tildeOnOff(i,)}$};
		\draw [decorate,decoration={brace,amplitude=2\smm,mirror}] ($(2.1,0 |- h1.south)+(0,1mm)$) -- ($(9.9,0 |- h1.south)+(0,1mm)$) node [midway,anchor=north,yshift=-2\smm] {$\offlineNumber{t}{\tildeOnOff(i,)} + \offlineNumberRight{t}{\tildeOnOff(i,)} + 1$};

	\end{tikzpicture}
	\caption[A step of the sequential lifting method]{A step of the sequential lifting method, from the vector $\onOff(i,)$ to the vector $\tildeOnOff(i,)$. By setting $\smash{\onOff{\idx}{t}} = 1$, the offline time of length~$\offlineNumber{t}{\tildeOnOff(i,)} + \offlineNumberRight{t}{\tildeOnOff(i,)} + 1$ is split into two offline times of lengths~$\offlineNumber{t}{\tildeOnOff(i,)}$ and $\offlineNumberRight{t}{\tildeOnOff(i,)}$, thereby changing the summed start-up costs.}
	\label{figure:SCS_LiftingExample}
\end{figure}

LiftingFromTreeExample.tex
\begin{figure}[htb]
	\providecommand{\liftNext}{{q}}
	\centering
	\begin{tikzpicture}[x=1cm,y=1cm,scale=\textwidthScaling]
		\tikzstyle{subtree}=[fill=blue!10, rounded corners=\convexRadiusA]

		\begin{scope}[yscale=0.35,yshift=158mm,xshift=-5mm]
			\foreach \k/\s in \liftingAunlifted {
				\node[tree] (v\k) at (\k, -\s) {\k};
			}
			\foreach \k/\s in \liftingAlifted {
				\node[tree, lifted] (v\k) at (\k, -\s) {\k};
			}

			\liftingTreeEdges
		\end{scope}

		%
		\drawOnOff{\liftingResult}

		%
		\node[anchor=east] at (0,0.5) {$\onOff(\idx,)$};
		\draw[->] (0,-0.3) -- (0,1.3);
		\draw[->] (-0.3,0) -- (12.5,0) node[anchor=west] {$t$};
		\foreach \i in {1,2,...,12} {
			\node[anchor=north] (t\i) at (\i-0.5, 0) {$\i$};
			\draw (\i, 0) +(0, -0.08) -- +(0, 0.08);
		}

		%
		\begin{pgfonlayer}{background}
			\fill[subtree,rounded corners=0pt] \convexcycle{v3,v4,v5}{\convexRadiusA};
			\fill[subtree,rounded corners=0pt] \convexcycle{v7,v9,v10,v8}{\convexRadiusA};
			\fill[subtree] ($(v3.center) - (\convexRadiusA,0)$) |- (4.5,-0.57) -| ($(v5.center)+(\convexRadiusA,0)$);
			\fill[subtree] ($(v7.center) - (\convexRadiusA,0)$) |- (7,-0.57) -| ($(v10.center)+(\convexRadiusA,0)$);
		\end{pgfonlayer}
		\node[anchor=north] at (4,0 |- v8.north) {$\leftSubtree{\sigma(\idx)}$};
		\node at ($(v8)!0.5!(v10)$) {$\rightSubtree{\sigma(\idx)}$};
		\draw [decorate,decoration={brace,amplitude=3\smm,mirror}] ($(2.1,0 |- t1.south)+(0,0.5mm)$) -- ($(4.9,0 |- t1.south)+(0,0.5mm)$) node [midway,xshift=-4mm,anchor=north,yshift=-2\smm] (subtext) {$\offlineNumber{\sigma(\idx)}{\onOff(\idx,)} = \leftSize(\sigma(\idx))$};
		\draw [decorate,decoration={brace,amplitude=3\smm,mirror}] ($(6.1,0 |- t1.south)+(0,1mm)$) -- ($(9.9,0 |- t1.south)+(0,1mm)$) node (h1) [midway,anchor=north,yshift=-2\smm] {$\offlineNumberRight{\sigma(\idx)}{\onOff(\idx,)} = \rightSize(\sigma(\idx))$};
		%
		%
		%
		
		%
		%
		\node[anchor=north] (idx)  at (v6 |- 0,-0.4) {$\sigma(\idx)$};
		\begin{pgfonlayer}{background}
			\fill[red!10,yshift=-0.57cm,rounded corners=2ex]
			              ($(idx.south) - (0.5,0.1)$) rectangle ($(v6.north) + (0.5,0.12)$)
			              (10,0) rectangle ($(v11.north) + (0.5,0.12)$)
			              (1,0) rectangle ($(v2.north) + (0.5,0.12)$);
		\end{pgfonlayer}
		
	\end{tikzpicture}
	\caption[The lifting step as shown in \cref{figure:SCS_LiftingExample}, with a possible lifting order represented by a binary tree]{The lifting step as shown in \cref{figure:SCS_LiftingExample}, with a possible lifting order represented by a binary tree $B$. The offline lengths~$\offlineNumber{\sigma(\idx)}{\onOff(\idx,)}$ and $\offlineNumberRight{\sigma(\idx)}{\onOff(\idx,)}$ adjacent to period~$\sigma(\idx)$ are equal to the sizes of the left and right subtree of node~$\sigma(\idx)$ in $B$.}
	\label{figure:SCS_LiftingFromTreeExample}
\end{figure}

LiftNext.tex
\begin{figure}[htb]
	\centering
	\begin{tikzpicture}[x=0.53cm,y=-1cm,scale=\textwidthScaling]
		\LiftingTrees
		
		\node[tree] (n1)  at ( 1,2)  {1};
		\node[tree] (n2)  at ( 2,1)  {2};
		\node[tree] (n3)  at ( 3,2)  {3};
		\node[tree] (n4)  at ( 4,3)  {4};
		\node[tree] (n5)  at ( 5,0)  {5};
		\node[tree] (n6)  at ( 6,3)  {6};
		\node[tree] (n7)  at ( 7,2)  {7};
		\node[tree] (n8)  at ( 8,3)  {8};
		\node[tree,pin={[pin distance=2.9ex] 90:$t$}, draw=marker] (n9)  at ( 9,1)  {9};
		\node[tree] (n10) at (10,3) {10};
		\node[tree] (n11) at (11,2) {11};
	
		\draw (n5) edge (n2) edge (n9);
		\draw (n2) edge (n1) edge (n3);
		\draw (n3) edge (n4);
		\draw (n9) edge (n7) edge (n11);
		\draw (n7) edge (n6) edge (n8);
		\draw (n11) edge (n10);
		
		\begin{pgfonlayer}{background}
			\fill[S1] \convexcycle{n5,n9}{\convexRadiusA};
			\path[S2] \convexcycle{n6,n7,n9,n11,n10}{\convexRadiusA};
			\node[S1text,anchor=east] at ($(n5.west)-(0.25,0)$) {$\oneSubtree{\onOff(i,)}$};
			\node[S2text,anchor=south] at ($(n11)+(-60:0.85)$) {$\subtree(t)$};
		\end{pgfonlayer}
		
		\draw[draw=marker,decorate,decoration={brace,amplitude=1.5\smm,mirror}] ($(9,0 |- n10)-(0,\convexRadiusA+0.5mm)$) -- ($(12,0 |- n10)-(0,\convexRadiusA+0.5mm)$) node [anchor=north,rectangle,inner sep=0pt,draw=none,fill=none,markerText,midway,yshift=-2\smm] (or) {$\squeeze{\offlineNumberRight{t}{\onOff(i,)}}$};

		\foreach \i in {1,2,3,4,6,7,8,10,11} {
			\node[vector, anchor=north, yshift=-1\smm] (v\i) at (\i,0 |- or.south) {$0$};
		}
		\foreach \i in {5,9} {
			\node[vector, anchor=north, yshift=-1\smm] (v\i) at (\i,0 |- or.south) {$1$};
		}
		\node[vector,anchor=base east] at (v1.base west) {$\onOff(i,) = ($};
		\node[vector,anchor=base west] at (v11.base east) {$)$};
				
		\draw[markerLine] (n9) -- (v9);
		
		\node[description, anchor=north,yshift=-1\smm] at (6,0 |- v1.south) {\llap{a) }$t$ is a top-right node};
	
	\begin{scope}[xshift=7.5cm]
	
		\node[tree] (n1)  at ( 1,2)  {1};
		\node[tree] (n2)  at ( 2,1)  {2};
		\node[tree] (n3)  at ( 3,2)  {3};
		\node[tree] (n4)  at ( 4,3)  {4};
		\node[tree] (n5)  at ( 5,0)  {5};
		\node[tree] (n6)  at ( 6,3)  {6};
		\node[tree,pin={180:$t$}, draw=marker] (n7)  at ( 7,2)  {7};
		\node[tree] (n8)  at ( 8,3)  {8};
		\node[tree,pin={35:$\tilde{r}$}, draw=marker] (n9)  at ( 9,1)  {9};
		\node[tree] (n10) at (10,3) {10};
		\node[tree] (n11) at (11,2) {11};
		
		\draw (n5) edge (n2) edge (n9);
		\draw (n2) edge (n1) edge (n3);
		\draw (n3) edge (n4);
		\draw (n9) edge (n7) edge (n11);
		\draw (n7) edge (n6) edge (n8);
		\draw (n11) edge (n10);
		
		\begin{pgfonlayer}{background}
			\path[S1] \convexcycle{n5,n9,n7}{\convexRadiusA};
			\path[S2] \convexcycle{n7,n8,n6}{\convexRadiusA};
			\node[S1text] at ($(n5)!0.5!(n7)!0.2!(n9)$) {$\oneSubtree{\onOff(i,)}$};
			\node[S2text,anchor=north east] at ($(n6)+(-220:0.5)$) {$\subtree(t)$};
		\end{pgfonlayer}

		\draw[draw=marker,decorate,decoration={brace,amplitude=1.5\smm,mirror}] ($(7,0 |- n8)-(0,\convexRadiusA+0.5mm)$) -- ($(9,0 |- n8)-(0,\convexRadiusA+0.5mm)$) node [anchor=north,rectangle,inner sep=0pt,draw=none,fill=none,markerText,midway,yshift=-2\smm] (or) {$\squeeze{\offlineNumberRight{t}{\onOff(i,)}}$};

		\foreach \i in {1,2,3,4,6,10,11} {
			\node[vector, anchor=north, yshift=-1\smm] (v\i) at (\i,0 |- or.south) {$0$};
		}
		\foreach \i in {5,7,8,9} {
			\node[vector, anchor=north, yshift=-1\smm] (v\i) at (\i,0 |- or.south) {$1$};
		}
		\node[vector,anchor=base east] at (v1.base west) {$\onOff(i,) = ($};
		\node[vector,anchor=base west] at (v11.base east) {$)$};

		\draw[markerLine] (n9) -- (n9 |- v11.north);
		\draw[markerLine] (n7) -- (v7);
	
		\node[description, anchor=north,yshift=-1\smm] at (6,0 |- v1.south) {\llap{b) }$t$ is a top-right node in $\leftSubtree(\tilde{r})$};
	\end{scope}
	\end{tikzpicture}
	\caption{Number of offline periods~$\protect\offlineNumberRight{t}{\protect\onOff(i,)}$ in vector $\protect\onOff(i,)$ after period~$t$, which is either bounded by the end of the model or by the first right ancestor~$\tilde{r}$ of node~$t$}
	\label{figure:SCS_LiftNext}
\end{figure}

LiftPrev.tex
\begin{figure}[htb]
	\begin{tikzpicture}[x=0.53cm,y=-1cm,scale=\textwidthScaling]
		\LiftingTrees
	
		\node[tree] (n1)  at ( 1,2)  {1};
		\node[tree,pin={$t$}, draw=marker] (n2)  at ( 2,1)  {2};
		\node[tree] (n3)  at ( 3,2)  {3};
		\node[tree] (n4)  at ( 4,3)  {4};
		\node[tree] (n5)  at ( 5,0)  {5};
		\node[tree] (n6)  at ( 6,3)  {6};
		\node[tree] (n7)  at ( 7,2)  {7};
		\node[tree] (n8)  at ( 8,3)  {8};
		\node[tree] (n9)  at ( 9,1)  {9};
		\node[tree] (n10) at (10,3) {10};
		\node[tree] (n11) at (11,2) {11};
		
		\draw (n5) edge (n2) edge (n9);
		\draw (n2) edge (n1) edge (n3);
		\draw (n3) edge (n4);
		\draw (n9) edge (n7) edge (n11);
		\draw (n7) edge (n6) edge (n8);
		\draw (n11) edge (n10);
		
		\begin{pgfonlayer}{background}
			\fill[S1] \convexcycle{n5,n2}{\convexRadiusA};
			\fill[S2] \convexcycle{n1,n2,n4}{\convexRadiusA};
			\node[S1text,anchor=south east] at (n5.north west) {$\oneSubtree{\onOff(i,)}$};
			\node[S2text,anchor=west] at ($(n3)+(-20:0.9)$) {$\subtree(t)$};
		\end{pgfonlayer}
		
%
		\coordinate (hh) at (n4);
		\draw[draw=marker,decorate,decoration={brace,amplitude=1.5\smm,mirror}] ($(0,0 |- hh)-(0,\convexRadiusA+0.5mm)$) -- ($(2,0 |- hh)-(0,\convexRadiusA+0.5mm)$) node[anchor=north,rectangle,inner sep=0pt,draw=none,fill=none,markerText,midway,yshift=-2\smm] (or) {$\offlineNumber{t}{\onOff(,)}$};

		\foreach \i in {1,3,4,6,7,...,11} {
			\node[vector, anchor=north, yshift=-1\smm] (v\i) at (\i,0 |- or.south) {$0$};
		}
		\foreach \i in {2,5} {
			\node[vector, anchor=north, yshift=-1\smm] (v\i) at (\i,0 |- or.south) {$1$};
		}
		\node[vector,anchor=base east] at (v1.base west) {$\onOff(,) = ($};
		\node[vector,anchor=base west] at (v11.base east) {$)$};
		
		\draw[markerLine] (n2) -- (v2);
		
		\node[description, anchor=north,yshift=-1\smm] at (6,0 |- v1.south) {\llap{a) }$t$ is a top-left node};
	
	\begin{scope}[xshift=7.5cm]
	
		\node[tree] (n1)  at ( 1,2)  {1};
		\node[tree] (n2)  at ( 2,1)  {2};
		\node[tree] (n3)  at ( 3,2)  {3};
		\node[tree] (n4)  at ( 4,3)  {4};
		\node[tree,pin={165:$\tilde{l}$}, draw=marker] (n5)  at ( 5,0)  {5};
		\node[tree] (n6)  at ( 6,3)  {6};
		\node[tree,pin={[pin distance=6.3ex] 0:$t$}, draw=marker] (n7)  at ( 7,2)  {7};
		\node[tree] (n8)  at ( 8,3)  {8};
		\node[tree] (n9)  at ( 9,1)  {9};
		\node[tree] (n10) at (10,3) {10};
		\node[tree] (n11) at (11,2) {11};
		
		\draw (n5) edge (n2) edge (n9);
		\draw (n2) edge (n1) edge (n3);
		\draw (n3) edge (n4);
		\draw (n9) edge (n7) edge (n11);
		\draw (n7) edge (n6) edge (n8);
		\draw (n11) edge (n10);
		
		\begin{pgfonlayer}{background}
			\fill[S1] \convexcycle{n7,n5,n9}{\convexRadiusA};
			\fill[S2] \convexcycle{n6,n7,n8}{\convexRadiusA};
			\node[S1text,anchor=188] at ($(n5)!0.55!(n7)!0.05!(n9)$) {$\oneSubtree{\onOff(i,)}$};
		\end{pgfonlayer}
			\node[S2text,anchor=north west] at ($(n8)+(40:0.5)$) {$\subtree(t)$};
		
		\draw[draw=marker,decorate,decoration={brace,amplitude=1.5\smm,mirror}] ($(5,0 |- n6)-(0,\convexRadiusA+0.5mm)$) -- ($(7,0 |- n6)-(0,\convexRadiusA+0.5mm)$) node[anchor=north,rectangle,inner sep=0pt,draw=none,fill=none,markerText,midway,yshift=-2\smm] (or) {$\offlineNumber{t}{\onOff(,)}$};

		\foreach \i in {1,2,3,4,6,8,10,11} {
			\node[vector, anchor=north, yshift=-1\smm] (v\i) at (\i,0 |- or.south) {$0$};
		}
		\foreach \i in {5,7,9} {
			\node[vector, anchor=north, yshift=-1\smm] (v\i) at (\i,0 |- or.south) {$1$};
		}
		\node[vector,anchor=base east] at (v1.base west) {$\onOff(,) = ($};
		\node[vector,anchor=base west] at (v11.base east) {$)$};
		\draw[markerLine] (n5) -- (v5);
		\draw[markerLine] (n7) -- (v7);
		
		\node[description, anchor=north,yshift=-1\smm] at (6,0 |- v1.south) {\llap{b) }$t$ is a top-left node in $\rightSubtree(\tilde{l})$};
	\end{scope}
	\end{tikzpicture}
	\caption{Number of offline periods~$\protect\offlineNumber{t}{\protect\onOff(i,)}$ in $\protect\onOff(i,)$ before period~$t$, which is either bounded by the start of the model or by the first left ancestor~$\tilde{l}$ of node~$t$}
	\label{figure:SCS_LiftPrev}
\end{figure}

LiftUnexact.tex
\begin{figure}[bht]
	\centering\begin{tikzpicture}[x=0.6cm,y=-1.2cm,scale=\textwidthScaling]
		\LiftingTrees
		
		\node[tree] (n1)  at ( 1,2)  {1};
		\node[tree] (n2)  at ( 2,1)  {2};
		\node[tree] (n3)  at ( 3,2)  {3};
		\node[tree] (n4)  at ( 4,3)  {4};
		\node[tree] (n5)  at ( 5,0)  {5};
		\node[tree] (n6)  at ( 6,3)  {6};
		\node[tree,pin={90:$t$}, draw=marker] (n7)  at ( 7,2)  {7};
		\node[tree] (n8)  at ( 8,3)  {8};
		\node[tree] (n9)  at ( 9,1)  {9};
		\node[tree] (n10) at (10,3) {10};
		\node[tree] (n11) at (11,2) {11};
		
		\draw (n5) edge (n2) edge (n9);
		\draw (n2) edge (n1) edge (n3);
		\draw (n3) edge (n4);
		\draw (n9) edge (n7) edge (n11);
		\draw (n7) edge (n6) edge (n8);
		\draw (n11) edge (n10);
		
		\begin{pgfonlayer}{background}
			\coordinate (helper) at ($(n2)+(1.6,0)$);
			\fill[S1] \convexpath{helper,n2,n9,n7}{\convexRadiusB};
			\fill[white] \convexcycle{n9,n2}{\convexRadiusA};	%
			\fill[S2] \convexcycle{n9,n2}{\convexRadiusA};
			\node[S1text,anchor=south,rectangle,draw=none,inner sep=0pt] at ($(n7)!0.4!(n3)$) {$\oneSubtree{\onOff(i,)}$};
			\node[S2text,anchor=base] at ($(n2.base)!0.3!(n9.base)$) {$\oneSubtree{\tildeOnOff(i,)}$};
		\end{pgfonlayer}
		
		\foreach \i in {1,3,4,5,6,7,8,10,11} {
			\node[vector] (vt\i) at (\i,4.4) {$0$};
		}
		\foreach \i in {2,9} {
			\fill[S2fill] (\i,4.4) circle (1.5\sex);
			\node[vector] (vt\i) at (\i,4.4) {$1$};
		}
		\node[vector,anchor=base east] at (vt1.base west) {$\tildeOnOff(i,) = ($};
		\node[vector,anchor=base west] at (vt11.base east) {$)$};
		\foreach \i in {1,3,4,5,6,8,10,11} {
			\node[vector] (v\i) at (\i,5) {$0$};
		}
		\foreach \i in {2,7,9} {
			\fill[S1fill] (\i,5) circle (1.5\sex);
			\node[vector] (v\i) at (\i,5) {$1$};
		}
		\node[vector,anchor=base east] at (v1.base west) {$\onOff(i,) = ($};
		\node[vector,anchor=base west] at (v11.base east) {$)$};

		\draw[markerLine] (n2) -- (vt2);
		\draw[markerLine] (n7) -- (vt7);
		\draw[markerLine] (n9) -- (vt9);
		\draw[draw=marker,decorate,decoration={brace,amplitude=1.5\smm,mirror}] ($(2,0 |- n4.south)-(0,0.5mm)$) -- ($(7,0 |- n4.south)-(0,0.5mm)$) node[anchor=north,rectangle,inner sep=0pt,draw=none,fill=none,markerText,midway,yshift=-2\smm] {$\offlineNumber{7}{\onOff(i,)}$};
		\draw[draw=marker,decorate,decoration={brace,amplitude=1.5\smm,mirror}] ($(7,0 |- n4.south)-(0,0.5mm)$) -- ($(9,0 |- n4.south)-(0,0.5mm)$) node[anchor=north,rectangle,inner sep=0pt,draw=none,fill=none,markerText,midway,yshift=-2\smm] {$\offlineNumberRight{7}{\onOff(i,)}$};
	\end{tikzpicture}
	\caption[Removing the leaf from the induced subgraph \oneSubtree{\protect\onOff(i,)}$ results in the subgraph $\protect\oneSubtree{\protect\tildeOnOff(i,)}, induced by $\protect\tildeOnOff(i,)$$]{Removing the leaf $t = 7$ from the induced subgraph~$\oneSubtree{\onOff(i,)}$ results in the subgraph $\oneSubtree{\tildeOnOff(i,)}$ induced by~$\tildeOnOff(i,)$. The lengths $\offlineNumber{7}{\onOff(i,)}$ and $\offlineNumberRight{7}{\onOff(i,)}$ denote the offline lengths before and after period~7 (see \eqref{equation:SC_OfflineNumber} and \eqref{equation:SCS_OfflineNumberRight}).}
	\label{figure:SCS_LiftUnexact}
\end{figure}

PermutationAndTree.tex
\begin{figure}[htb]
	\centering
	\begin{tikzpicture}[x=3.9mm,y=4.625mm,scale=\textwidthScaling]
		\tikzstyle{permutation}=[draw=none,inner sep=0pt,rectangle,fill=none]
		\tikzstyle{permutation_to_tree}=[blue!15]
		
		\newcommand{\drawPermTree}[2]{
			\foreach \k/\s in {#1} {
				%
				\node[tree] (v\k) at (\k, -\s) {\k};

				%
				\node[permutation,anchor=east] (t\s) at (-1, -\s) {\k};
				\ifthenelse{\s < 12}{
					\node[permutation, anchor=base west] at (t\s.base east) {,};
				}{}
				%
				\begin{pgfonlayer}{background}
					\ifthenelse{\isodd{\s}}{
 						\fill[permutation_to_tree] ($(t\s.west) + (0,0.5)$) -| (v\k.center)  |- ($(t\s.west) - (0,0.5)$) -- ($(t\s.west) + (0,0.5)$);
					}{}
				\end{pgfonlayer}
			}
		
			\node[permutation,anchor=east] at (t1.west) {$\squeeze{#2 =(}$};
			\node[permutation,anchor=west] at (t12.east) {$)$};
			
			%
			%

			%
			\liftingTreeEdges
		}
		
		\expandafter\drawPermTree\expandafter{\liftingA}{\sigma}
		\begin{scope}[xshift=7.1cm]
			\expandafter\drawPermTree\expandafter{\liftingB}{\overline{\sigma}}
		\end{scope}
	\end{tikzpicture}
	\caption{A partial order determining the lifted coefficients (twice, as a Hasse-diagram) and two possible linearizations (as permutations~$\sigma$ and $\overline{\sigma}$) leading to the same lifted inequality.}
	\label{figure:SCS_PermutationAndTree}
\end{figure}

Schedule.tex
\begin{figure}[ht]
	\centering
	\begin{tikzpicture}[x=1mm,y=1mm,scale=\textwidthScaling]
	
		\def\w{10.7}
		\def\h{10}
		

		%
		\begin{scope}[xscale=\w,yscale=\h]
			\drawOnOff{1/0, 2/1, 3/1, 4/1, 5/1, 6/0, 7/0, 8/0, 9/1, 10/0}

			\draw[onOffColor,very thick] (0,0) -- (-1.7,0) |- (-2.25,1);
			\fill[onOffBack] (-1.7,0) rectangle (-2.25,1);
			\node at (-0.85,0.5) {$\preOffline(i) = 2$};
		\end{scope}
		
		%
		\drawTimeAxis{\w}{10}
		\draw[-latex] (0,0) -- (-2.5*\w,0);
		\drawVarAxis[]{\h}
		\begin{pgfinterruptboundingbox}
			\node[anchor=-45,onOffText] at (0,\h) {$\onOff(i,)$};
		\end{pgfinterruptboundingbox}

		\begin{scope}[xscale=\w,yscale=\h]
			\node (arrow_base) at (0,-0.5) {};
			
			\begin{scope}
				%
%
%
%
%
				
				%
				\node (cu2) at ($(onOff2.south)-(1,1.4)$) {$\DiscreteStartupCost(i,2)(\onOff(i,)) = \StartupCost(i,2,1) = \StartupCostFunction(i,3)$};
				\node[below of=onOff9, node distance=20.5\smm] (cu9) {$\DiscreteStartupCost(i,9)(\onOff(i,)) = \StartupCost(i,9,3) = \StartupCostFunction(i,3)$};
				\node[anchor=base] (cu5) at ($(cu2.base east)!0.5!(cu9.base west)$) {$\DiscreteStartupCost(i,5)(\onOff(i,)) = 0$};
				\foreach \t in {2,5,9}{
					\draw (cu\t.north -| onOff\t) edge[-latex,shorten <=-1mm] (onOff\t |- arrow_base);
				}
			\end{scope}
		\end{scope}
	\end{tikzpicture}
	\caption[Incurred start-up costs for an exemplary operational schedule]{Incurred start-up costs for an exemplary operational schedule ($\periodLengthBraces{1} = \ldots = \periodLengthBraces{T} = 1$). The operational schedule $\onOff(i,) \in \set{0,1}^T$ over the course of $T=10$ periods is shown in green. The first start-up takes place in period~2, with costs $\DiscreteStartupCost(i,2)(\onOff(i,))$ of $\StartupCostFunction(i,3)$ due to the preceding offline period with length $\periodLength(1) = 1$ and the pre-offline time $\preOffline(i)$ of 2. The only other start-up costs are incurred in period~9, after three offline periods with a total length of $\periodLength(6)+\periodLength(7)+\periodLength(8) = 3$.}
	\label{figure:SC_Schedule}
\end{figure}

IntroductionGeneral.tex
\section{Introduction}
\label{section:SCS_IntroductionGeneral}

%
Start-up costs have been an integral part of the Unit Commitment problem since its first formulation \cite{garver_power_1962}, and gain further importance due to the increasing penetration of variable renewable energy. Electricity production from such sources, i.e. mainly from wind and solar, increases the variability of the net load met by thermal generators, resulting in a more frequent cycling and a higher number of start-ups (\cite{kumar_power_2012}). Hence, the percentage of start-up costs within the total production costs rises and an accurate modeling of the start-up costs becomes increasingly important.

%

%
In contrast to the detailed incorporation of start-up costs in other methodologies (\eg Lagrangean Relaxation, Dynamic Programming, meta-heuristics), Mixed Integer Programming formulations were restricted to constant start-up costs (\cite{garver_power_1962}) for a long time. The first model capable of representing arbitrary start-up cost functions was introduced in \cite{arroyo_optimal_2000}. Since then, two major formulations have emerged: the model of \cite{carrion_computationally_2006}, based on \cite{nowak_stochastic_2000}, and the model of \cite{simoglou_optimal_2010}. Their comparison in \cite{morales-espana_tight_2013} highlights the importance of a low integrality gap, demonstrating a significantly reduced solution time. This motivates a thorough polyhedral analysis.

%
In a Unit Commitment Problem, the operational state of each unit~$i \in \Units$ is represented by a binary vector~$\onOff(i,) \in \set{0,1}^T$, where for each period~$t \in \Periods$, $\onOff(i,t) = 1$ iff the unit is online. As defined in \eqref{equation:SCS_DiscreteStartupCostSum}, we denote by $\DiscreteStartupCostSum$ the summed start-up cost function, such that $\DiscreteStartupCostSum(\onOff(i,))$ equals the total start-up costs incurred by unit~$i$ in the course of~$\onOff(i,)$. Our major result is a correspondence between the facets of $\conv(\epi(\DiscreteStartupCostSum))$ and binary trees of size~$T$ for concave start-up cost functions~$\StartupCostFunction(i,)$, which is bijective if $\StartupCostFunction(i,)$ is strictly concave. We derive the exponential class of \emph{binary tree inequalities} (BTIs), which together with the trivial inequalities $0 \leq \onOff(i,t) \leq 1$, define an \hrepresentation of $\conv(\epi(\DiscreteStartupCostSum))$, and give an exact linear separation algorithm for the BTIs.

This result is important, both from the theoretical and practical point of view, since
\begin{itemize*}
  \item the BTIs, and in particular the proof of~\cref{result:SCS_FracPointsOnFacet}, strengthen our understanding of the start-up costs,
  \item the existing start-up cost models are extended formulations of $\conv(\epi(\DiscreteStartupCostSum))$, and may therefore be analyzed and tightened using the BTIs, and
  \item separated in a cutting plane approach, the BTIs reduce the integrality gap of the current state-of the art models (\cite{carrion_computationally_2006,simoglou_optimal_2010}) to match those of the the temperature model (\cite{silbernagl_improving_2014}).
\end{itemize*}

Conclusion.tex
\section{Conclusion}
\label{section:Conclusion}

We were able to derive a complete \hrepresentation of the epigraph of the summed start-up costs. The resulting Unit Commitment formulation significantly outperforms two state-of-the-art formulations in terms of the integrality gap. While applying the BTIs in a cutting plane algorithm does not improve the solution times, they provide the theoretical basis for an efficient extended formulation.

In future work one may also take into account the interdependencies of multiple units for the development of further inequalities. Consider for example a demand-driven Unit Commitment problem: during a sharp increase in demand, some number of units may be forced to start up, resulting in a bound on the total start-up costs of all units, which has to be modeled by multi-unit inequalities not considered in any Unit Commitment model so far.
Experiments.tex
\newpage
\section{Experiments}
\label{section:Experiments}

\def\defaultCompany{}

This section mainly compares the integrality gap of a Unit Commitment problem which models $\scsEpigraph$ using binary tree inequalities (\emph{BTI}) to a Unit Commitment problem using the start-up cost formulations presented in \cite{carrion_computationally_2006} (\emph{1-Bin}), \cite{simoglou_optimal_2010} (\emph{3-Bin}), and \cite{silbernagl_improving_2014} (\emph{1-Bin*} and \emph{Temp}).

\subsection{Scenario}
\label{section:EX_Parameters}

We model the German electricity system in 2025, using the same scenario as \cite{silbernagl_improving_2014}. For each unit~$i \in \Units$, we consider the following parameters:
\begin{itemize*}
  \item the variable and fixed production cost coefficients $A_i$ and $B_i$,
  \item the minimal and maximal production $\minProd(i)$ and $\maxProd(i)$,
  \item the maximal upward ramping speed while online ($\rampup(i)$) and at start-up ($\startupRamp(i)$), and
  \item the maximal downward ramping speed while online ($\rampdown(i)$) and at shutdown ($\shutdownRamp(i)$).
\end{itemize*}
The values of these parameters are based on the the German power system (\cite{german_federal_network_agency_list_2014}) and complemented by assumptions on minimal production, efficiency, and start-up costs, which are partly derived from \cite{kumar_power_2012}, \cite{eurelectric_efficiency_2003}, and \cite{egerer_electricity_2014}. As is expected for 2025, all nuclear units are replaced by combined cycle plants, resulting in a total of 223 thermal units.

The demand data is taken from \cite{entsoe_hourly_2007} and scaled to a yearly consumption of 520~TWh. As wind, solar, biomass, and hydro plants are not modeled explicitly, their expected production is subtracted from this demand, yielding the residual demand~$d^t$. The production from wind and solar plants is computed based on \cite{rienecker_merra:_2011} in combination with the expected installed capacity in 2025 (50~GW wind capacity, 50~GW solar capacity). Biomass and hydro plants are assumed to produce at full capacity (5.5~GW biomass capacity, 4.5~GW hydro capacity).

\subsection{Base Unit Commitment Formulation}

As the focus of the experiments lies on comparing start-up cost formulations, we restrict ourselves to a basic model for the Unit Commitment problem. Its objective is to fulfill the residual demand~$d^t$ in each period~$t$ \eqref{equation:EX_Demand}, while minimizing production costs~$\prodCost(i,t)$ and start-up costs~$\startupCostSum$ \eqref{equation:EX_Objective}. The production costs~$\prodCost(i,t)$ of unit~$i$ in period~$t$ are modeled as a linear function of its electricity output~$\prod(i,t)$ and its operational state~$\onOff(i,t)$ in \eqref{equation:EX_ProdCosts}. The production limits in \eqref{equation:EX_ProdLimits} and the ramping limits in \eqref{equation:EX_RampUp}-\eqref{equation:EX_Shutdown} are modeled as in \cite{carrion_computationally_2006}.

\begin{alignat}{2}
	\label{equation:EX_Objective}
	& \min \smash[b]{\sum_{i \in \Units\mkern3mu} \sum_{t \in \Periods} \prodCost(i,t) + \sum_{i \in \Units} \startupCostSum}&&\\[1.5ex]
	%
	\label{equation:EX_Demand}
	\textstyle\sum_{i \in \Units} \prod(i,t) &= d^t &\qquad& \forallPeriods,\\
	%
	\label{equation:EX_ProdCosts}
	\prodCost(i,t) &= A_i \prod(i,t) + B_i \onOff(i,t) && \forallUnitsPeriods\\
	%
	\label{equation:EX_ProdLimits}
	\minProd(i) \onOff(i,t) &\leq \prod(i,t) \leq \maxProd(i) \onOff(i,t) && \forall\,i \in \Units, t \in \discrange{1}{T},\\
%
	\label{equation:EX_RampUp}
	\prod(i,t) &\leq \prod(i,t-1) + \rampup(i) \onOff(i,t-1) + \startupRamp(i) (\onOff(i,t) - \onOff(i,t-1)) + \maxProd(i)(1-\onOff(i,t)) && \forall\,i \in \Units, t \in \discrange{2}{T},\\
%
	\label{equation:EX_RampDown}
	\prod(i,t) &\geq \prod(i,t-1) - \rampdown(i) \onOff(i,t) - \shutdownRamp(i) (\onOff(i,t-1) - \onOff(i,t)) + \maxProd(i)(1-\onOff(i,t-1)) && \forall\,i \in \Units, t \in \discrange{2}{T},\\
%
	\label{equation:EX_Shutdown}
	\prod(i,t) &\leq \maxProd(i) \onOff(i,t+1) + \shutdownRamp(i) (\onOff(i,t) - \onOff(i,t+1)) && \forall\,i \in \Units,t \in \discrange*{1}{T-1},\\
	%
	\label{equation:EX_OperationalState}
	\onOff(i,t) &\in \set{0,1},	\prod(i,t), \prodCost(i,t) \in \nnreals && \forallUnitsPeriods.
\end{alignat}

\subsection{Start-up Cost Formulations}

The term~$\startupCostSum$ in \eqref{equation:EX_Objective} 
represents the summed start-up costs of unit~$i$ according to the thermal start-up cost function in \eqref{equation:SC_ThermalStartupCosts},
\begin{equation*}
	\forallUnits, L \in \nnreals: \qquad \StartupCostFunction(i,L) = \smash[t]{\begin{cases}
		\heatingCost(i) (1 - \exp{\heatloss(i) L}) + \fixedStartupCost(i) & \text{if $L > 0$,}\\
		0 & \text{else.}
	\end{cases}}
\end{equation*}
In \eqref{equation:SC_FunctionForPeriods}, this function is discretized such that $\StartupCost(i,t,l)$ corresponds to the start-up cost incurred by unit~$i$ in period~$t$ after an offline time of $l$ periods. While the formulations 1-Bin, 1-Bin* and 3-Bin generally model a piece-wise constant approximation of these start-up costs, we use the unapproximated values $\StartupCost(i,t,l)$ for comparability with Temp.

\begin{samepage}
Each of the start-up cost formulations models $\startupCostSum$ differently:
\begin{itemize}
\item In 1-Bin (\cite{carrion_computationally_2006}), the start-up costs~$\startupCost(i,t)$ in period~$t$ are modeled as
\begin{alignat}{2}
	\label{equation:Ex_1Bin}
	\startupCost(i,t) &\geq \StartupCost(i,t,l) \Big( \onOff(i,t) - \sum_{\idx \in \discrange{1}{l}} \onOff(i,t-\idx) \Big) &\qquad&
	\forallUnitsPeriods, l \in \discrange*{0}{t-1},
	%
%
	%
\end{alignat}
and the summed start-up cost of unit~$i$ is $\startupCostSum := \sum_{t \in \Periods} \startupCost(i,t)$.

\item Similarly, 1-Bin* (\cite{silbernagl_improving_2014}) models $\startupCostSum := \sum_{t \in \Periods} \startupCost(i,t)$, with
\begin{alignat}{2}
	\label{equation:Ex_1BinT}
	\hskip-1em\startupCost(i,t) &\geq \StartupCost(i,t,l)\onOff(i,t) - \sum_{\mathclap{\idx \in \discrange{1}{l}}} \Big(\StartupCost(i,t,l) - \StartupCost(i,t,\idx\!-\!1)\Big) \onOff(i,t-\idx) &\quad& \forallUnitsPeriods, l \in \discrange*{0}{t-1}.%
%
%
\end{alignat}

\item 3-Bin (\cite{simoglou_optimal_2010}) uses the start-up and shutdown indicators (\cite{garver_power_1962}),
\begin{alignat}{2}
	\label{equation:Ex_IndicatorsFirst}
	\startupIndicator(i,1) - \shutdownIndicator(i,1) &= \begin{cases}
		\onOff(i,1) & \text{if $\preOffline(i) > 0$,}\\
		\onOff(i,1) - 1 & \text{else,}
	\end{cases} &\qquad& \forallUnits,\\
	%
	\label{equation:Ex_Indicators}
	\startupIndicator(i,t) - \shutdownIndicator(i,t) &= \onOff(i,t) - \onOff(i,t-1) && \forallUnits, t \in \discrange{2}{T},\\
	%
	\label{equation:Ex_IndicatorsNN}
	\startupIndicator(i,t),\shutdownIndicator(i,t) &\geq 0 && \forallUnitsPeriods.
\end{alignat}
In the special case of unapproximated start-up costs, this formulation simplifies to
\begin{alignat}{2}
	\startupIndicator(i,t) &= \sum_{l \in \discrange*{1}{t-1}} \startupType(i,t,l) &\qquad& \forallUnitsPeriods,\\
	%
	\startupType(i,t,l) &\leq \shutdownIndicator(i,t-l) && \forallUnitsPeriods,l \in \discrange*{1}{t-2},\\
	%
	\startupType(i,t,l) &\geq 0 && \forallUnitsPeriods,l \in \discrange*{1}{t-1},\\
	%
	\startupCostSum &:= \sum_{t \in \Periods} \sum_{l \in \discrange*{1}{t-1}} \StartupCost(i,t,l) \startupType(i,t,l) && \forallUnits.
\end{alignat}

\item Temp (\cite{silbernagl_improving_2014}) also uses the start-up and shutdown indicators in \eqref{equation:Ex_IndicatorsFirst}-\eqref{equation:Ex_IndicatorsNN}, and models the start-up costs as
\begin{alignat}{2}
	\temp(i,1) &= \exp{-\heatloss(i)\preOffline(i)} + \heating(i,0) &\qquad& \forallUnits,\\
%
	\temp(i,t+1) &= \exp{-\heatloss(i)\periodLength(t)} \temp(i,t) + (1 - \exp{-\heatloss(i)\periodLength(t)}) \onOff(i,t) + \heating(i,t) && \forallUnits, t \in \discrange*{1}{T-1},\\
%
	\onOff(i,t) &\leq \temp(i,t) \leq 1  && \forallUnitsPeriods,\\
%
	\label{equation:EX_RTI0}
	\temp(i,t) &\geq \onOff(i,t) + \exp{-\heatloss(i)\offlineLength(t,t-1)}(1-\onOff(i,t)) && \forallUnitsPeriods,\\
%
	\label{equation:EX_RTI}
	\temp(i,t) &\geq \onOff(i,t) + \exp{-\heatloss(i)\offlineLength(t,l)}(\temp(i,t-l)-\onOff(i,t)) && \forallUnitsPeriods,l \in \discrange*{1}{t-2},\\
%
	\heating(i,t) &\geq 0 && \forallUnits,t \in \discrange*{0}{T-1},\\
%
	\startupCostSum &:= \fixedStartupCost(i) \sum_{t \in \Periods} \startupIndicator(i,t) + \heatingCost(i) \sum_{t \in \discrange*{0}{T-1}} \heating(i,t) && \forallUnits.
\end{alignat}
\item Finally BTI denotes the \hrepresentation of $\scsEpigraph$ in \cref{result:SCS_HRepresentation}.
\end{itemize}
\end{samepage}

\subsection{Integrality Gap}
\label{section:EX_IntGap}

\cref{figure:IntGap} shows the integrality gaps of all formulations for 14 test cases with $72$ one-hourly periods, \ie $T = 72$ and $\periodLength(1) = \ldots = \periodLength(T) = 1 \text{ hour}$. The modeled time ranges are spread uniformly over  the year 2025, starting in its $S$-th hour with $S \in \set{433 + 624\idx \given \idx \in \discrange{0}{13}}$. The values of $S$ are chosen such that each time range starts at midnight, and exactly two time ranges start on each day of the week.

\cite{silbernagl_thesis} shows that Temp is an extended formulation of $\scsEpigraph$, reducing the number of constraints by introducing the additional variables $\temp(i,t)$, $\heating(i,t-1)$ and $\startupIndicator(i,t)$ for all $i \in \Units$, $t \in \Periods$. Hence its integrality gap is equal to that of BTI, up to numerical inaccuracies. Both lead to the smallest integrality gap, which is expected since all start-up cost formulations model a set which encloses $\scsEpigraph$; The integrality gaps of 3-Bin, 1-Bin* and 1-Bin are significantly larger on average (\cref{figure:IntGap}, left chart). By expressing their integrality gaps relative to BTI, we see that BTI and Temp dominate the other models. (\cref{figure:IntGap}, right chart).

\begin{figure*}[htb]
	\label{fig:base}
	\newcommand{\chartwidth}{74mm}
	\newcommand{\chartheight}{70.7mm}
	\centering
	\begin{subfigure}[]{.477\columnwidth}
		\flushleft
		\input{pics/IntGap}
		\caption{Integrality gap}
	\end{subfigure}
	\begin{subfigure}[]{.513\columnwidth}
		\centering
		\input{pics/IntGapRel}
		\caption{Integrality gap relative to BTI}
	\end{subfigure}
	\caption{The integrality gap of the start-up cost formulation for 14 test cases, absolute (left chart) and relative to BTI (right chart). BTI and Temp provide equal integrality gaps, up to numerical inaccuracies, and dominate the other models.}
	\label{figure:IntGap}
\end{figure*}

Despite these results, augmenting 1-Bin, 1-Bin* and 3-Bin with binary tree inequalities as cutting planes does not improve the solution times considerably. While 1-Bin was able to solve more test cases within a time limit of 1 hour when paired with BTIs, no advantage was determined for 3-Bin. The cutting plane algorithm of the BTI exhibits a very slow convergence of the lower bound and numerical problems, leading to long computation times for each reoptimization step in the IBM ILOG CPLEX and the FICO Xpress Optimizers. Further research on the selection and implementation of the BTIs might overcome the numerical problems encountered.

Temp however does not suffer from the numerical problems and the slow convergence of the BTIs, and, as substantiated experimentally in \cite{silbernagl_improving_2014}, outperforms the start-up cost formulations in current literature. Still, the description of $\scsEpigraph$ we provide in this paper is the theoretical basis for Temp, and in particular justifies the separation algorithm for inequalities~\eqref{equation:EX_RTI0},\eqref{equation:EX_RTI}.

BinaryTrees.tex
\section{Notation for Binary Trees}
\label{section:SCS_BT}

Describing the lifted inequalities of the last subsection necessitates non-standard notation for binary trees, which is presented in this section. A binary tree is defined as an undirected, rooted tree, where each node~$t$ has at most two child nodes: a left child~$\leftChild(t)$ and a right child~$\rightChild(t)$ (\cf \cref{figure:BT_Repetition}).

Basic notation includes:
\begin{itemize*}
	\item Each binary tree $B$ has a \emph{root} denoted by $\root(B)$.
	\item The path from a node~$t$ to the root is unique. The number~$\depth(t)$ of its edges is called the \emph{depth} of~$t$, and its nodes are the \emph{ancestors} of~$t$ (including $t$ itself). Vice versa, $t$ is called a descendant of each of its ancestors.
	\item The first ancestor, \ie the node immediately succeeding $t$ on the path to the root, is called the \emph{parent}~$\parent(t)$ of $t$. Conversely, $t$ is said to be a \emph{child} of $\parent(t)$.  
	\item The subtree~$\subtree(t)$ comprising all descendants of a node~$t$ (including $t$) is the \emph{principal subtree in~$t$}. If the left/right child of $t$ exists, then its principal subtree is the \emph{left subtree}~$\leftSubtree(t)$/\emph{right subtree}~$\rightSubtree(t)$~of~$t$. All of these subtrees are binary trees as well.
	\item The number of nodes in these subtrees in $t$ are denoted by $\size(t) := \abs{\subtree(t)}$, $\leftSize(t) := \abs{\leftSubtree(t)}$ and $\rightSize(t) := \abs{\rightSubtree(t)}$.
	\item  The \emph{rank} function is the unique mapping from the nodes~$V$ of a binary tree~$B$ to $1,\ldots,\abs{V}$ such that
	\begin{equation*}
		\forall\, t \in V \setminus \set{\root(B)}: \qquad \rank(t) \smash[t]{\begin{cases}
			< \rank{\parent(t)} & \text{if $t$ is the left child of $\parent(t)$,}\\
			> \rank{\parent(t)} & \text{if $t$ is the right child of $\parent(t)$,}
		\end{cases}}
	\end{equation*}
	and such that the nodes of each principal subtree~$\subtree(t)$ are a mapped to a contiguous interval.
\end{itemize*}

\noindent The rank function has a straight-forward interpretation: When drawing a binary tree such that left (right) childs are located below left (right) of their parents, the rank numbers the nodes from left to right (see \cref{figure:BT_Repetition}). Several basic properties can be derived from this observation:
\begin{itemize}
	\item For each binary tree~$B$ and $t \in B$, it holds that
\begin{equation*}
	\set{\rank(\tau) \given \tau \in \subtree(t)} = \set{\rank(\tau) \given \tau \in \leftSubtree(t)} \cup \set{\rank(t)} \cup \set{\rank(\tau) \given \tau \in \rightSubtree(t)}.
\end{equation*}
	\item Since by definition the ranks of nodes in a subtree are contiguous, it holds that
\begin{gather}
	\label{equation:BT_SubtreeRanks}
	\begin{aligned}
		\set{\rank(\tau) \given \tau \in \leftSubtree(t)} &= \discrange*{\rank(t)-\leftSize(t)}{\rank(t)-1},\\
%
		\set{\rank(\tau) \given \tau \in \rightSubtree(t)} &= \discrange*{\rank(t)+1}{\rank(t)+\rightSize(t)},\text{ and}\\
%
		\set{\rank(\tau) \given \tau \in \subtree(t)} &= \discrange*{\rank(t)-\leftSize(t)}{\rank(t)+\rightSize(t)}.
	\end{aligned}
\end{gather}
	\item Finally, since $\leftSubtree(t) = \subtree{\leftChild(t)}$ and $\rightSubtree(t) = \subtree{\rightChild(t)}$, we have
\begin{equation}
	\label{equation:BT_ChildRank}
	\rank{\leftChild(t)} + \rightSize{\leftChild(t)} + 1 = \rank(t) = \rank{\rightChild(t)} - \leftSize{\rightChild(t)} - 1.
\end{equation}
\end{itemize}
For example, in the binary tree shown in \cref{figure:BT_Repetition} it holds that
\begin{gather*}
	\set{\rank(\tau) \given \tau \in \subtree(t)} = \underbrace{\discrange{7}{10}}_{\set{\rank(\tau) \given \tau \in \leftSubtree(t)}} \cup \underbrace{\set{11}}_{\rank(\tau)} \cup \underbrace{\set{12}}_{\set{\rank(\tau) \given \tau \in \rightSubtree(t)}}\quad\text{and}\\[2ex]
%
	\underbrace{1}_{\rank{\leftChild(t)}} + \underbrace{1}_{\rightSize{\leftChild(t)}} + 1 = \underbrace{3}_{\rank(t)} = \underbrace{4}_{\rank{\rightChild(t)}} - \underbrace{0}_{\leftSize{\rightChild(t)}} - 1.
\end{gather*}

\input{pics/BT_Repetition}

The special nature of the coefficients of the facets of $\scsEpigraph$ is best characterized by some non-standard notation, the \emph{top-left} and \emph{top-right} nodes (see \cref{figure:BT_TopRightLeft}). These nodes are defined recursively, with the root being the first top-left and top-right node. Left childs of top-left nodes are also top-left nodes, and right childs of top-right nodes are top-right nodes too. The last top-left node has rank~$1$, and the last top-right node has rank~$\abs{V}$.
\begin{definition}
	\label[definition]{definition:TopLeftRightNodes}
	For each binary tree~$B$ on $n$ nodes, define $\topleft(1) := \topright(1) := \root(B)$,
	\begin{equation*}
		\forall\, \idx \in \discrange{1}{\depth(1)}: \quad \topleft(\idx+1) := \leftChild{\topleft(\idx)}, \qquad\qquad\forall\, \idx \in \discrange{1}{\depth(n)}: \quad \topright(\idx+1) := \rightChild{\topright(\idx)},
	\end{equation*}
	where $\topleft(\idx)$ denotes the $\idx$-th top-left node and $\topright(\idx)$ denotes the $\idx$-th top-right node.
\end{definition}
\noindent Conversely, ancestors of top-left (top-right) nodes must be top-left (top-right) nodes as well.

\input{pics/BT_TopRightLeft}

We continue by proving basic facts regarding top-right nodes, and transfer them to top-left nodes by \enquote{mirroring} the binary trees.

%

The node~$n$ is contained in the principal subtree of each top-right node~$\topright(\idx)$, and by definition possesses the maximal rank. Since the principal subtree of $\topright(\idx)$ spans the ranks $\discrange*{\rank(\topright{\idx})-\leftSize{\topright(\idx)}}{\rank(\topright{\idx}) + \rightSize{\topright(\idx)}}$ (see \eqref{equation:BT_SubtreeRanks}), it must hold that $\rank{\topright(i)} + \rightSize{\topright(i)} = n$. On the other hand, if the rank of a node~$t$ fulfills $\rank(t)+\rightSize(t) = n$, then $n$ lies in the right subtree of $t$. So, $t$ is an ancestor of $n$, and thus a top-right node.
\begin{proposition}
	\label[proposition]{result:TopRightOnlyRanks}
	  For each binary tree $B$ on $n$ nodes, a node $t$ is a top-right node in $B$ iff \mbox{$\rank(t) + \rightSize(t) = n$}.
\end{proposition}

This result may be extended to subtrees as well.
\begin{lemma}
	\label[lemma]{result:TopRightSubtree}
	  For each binary tree $B$ on $n$ nodes, a node $t$ is a top-right node in the left subtree of a node~$\tau$ iff $\rank(t) + \rightSize(t) + 1 = \rank(\tau)$.
\end{lemma}
\begin{proof}
	By \eqref{equation:BT_SubtreeRanks}, the nodes in the left subtree~$\leftSubtree(\tau)$ have ranks $\discrange*{\rank(\tau)-\leftSize(\tau)}{\rank(\tau)-1}$. Thus, the rank function~$\rankT(\leftSubtree{\tau},)$ of $\leftSubtree(\tau)$, which must keep the same order as $\rank()$ and ranges from $1$ to $\leftSize(\tau)$ equates
	\begin{equation*}
		\rankT{\leftSubtree{\tau}}{t} = \rank(t) - \rank(\tau) + \leftSize(\tau)+1.
	\end{equation*}
	Hence, each node~$t \in \leftSubtree(\tau)$ is a top-right node in $\leftSubtree(\tau)$ iff $\rankT{\leftSubtree{\tau}}{t} + \rightSize(t) = \abs{\leftSubtree(\tau)} = \leftSize(\tau)$ (see \cref{result:TopRightOnlyRanks}), which may be rewritten as
	\begin{equation*}
		\rank(t) + \rightSize(t) + 1 = \rankT{\leftSubtree{\tau}}{t} + \rank(\tau) - \leftSize(\tau) - 1  + \rightSize(t) + 1 = \rank(\tau).
	\end{equation*}
	
	Assume now that there exists a node~$t$ of $B$ with $t \notin \leftSubtree(\tau)$ but $\squeeze{\rank(t) = \rank(\tau) - \rightSize(t) - 1}$. Then $\rank(t) < \rank(\tau)$, and $t \notin \subtree(\tau)$. On the other hand, $\rank(\tau) > \rank(t) + \rightSize(t)$ and hence $\tau \notin \subtree(t)$.
	
	Choose the first common ancestor $t$ of $t$ and $\tau$, which due to $t \notin \subtree(\tau)$ and $\tau \notin \subtree(t)$ equals neither $t$ nor $\tau$. By choice of $t$ it holds that $t \in \leftSubtree(t)$ and $\tau \in \rightSubtree(t)$, and thus
	\begin{equation*}
		\rank(t) + \rightSize(t) < \rank(t) < \rank(\tau) - \leftSize(\tau),
	\end{equation*}
	a contradiction to $\rank(t) + \rightSize(t) + 1 = \rank(\tau)$.\manualqed
\end{proof}

Note that since $\rank(t)+\rightSize(t) + 1 \in \discrange*{\rank(t)+1}{n+1}$, $t$ must be either a top-right node or a top-right node in the left subtree of some node~$\tau$.

\begin{samepage}
\begin{corollary}
	\label[corollary]{result:TopRightRanks}
	For each binary tree on $n$ nodes, a node $t$ is
	\begin{itemize}
		\item a top-right node iff $\rank(t) + \rightSize(t) = n$, and
		\item a top-right node in the left subtree of the node~$\tau$ iff $\rank(\tau) = \rank(t) + \rightSize(t) + 1$ iff $\rank(t) + \rightSize(t) < n$.
	\end{itemize}
\end{corollary}
\end{samepage}

Let $\overline{B}$ denote the \enquote{mirrored} version of a binary tree $B$ of size $n$, \ie the binary tree that results from exchanging the left and right childs of each node. The depth, parent and subtree size functions remain unchanged ($\depthT(\overline{B},) = \depthT(B,)$, $\parentT(\overline{B},) = \parentT(B,)$, $\sizeT(\overline{B},) = \sizeT(B,)$), the left and right subtree size functions are exchanged ($\rightSizeT(\overline{B},) = \leftSizeT(B,)$, $\leftSizeT(\overline{B},) = \rightSizeT(B,)$), and the rank function is mirrored ($\rankT(\overline{B},t) = n+1-\rankT(B,)$). By applying this mirroring to the properties of the top-right nodes, we can derive equivalent properties of the top-left nodes. 

\begin{corollary}
	\label[corollary]{result:TopLeftRanks}
	For each binary tree, a node $t$ is
	\begin{itemize}
		\item a top-left node iff $\rank(t) = \leftSize(t) + 1$, and
		\item a top-left node in the right subtree of the node~$\tilde{l}$ with $\rank(\tilde{l}) = \rank(t) - \leftSize(t) - 1$ iff $\rank(t) > \leftSize(t) + 1$.
	\end{itemize}
\end{corollary}

The root of a binary tree on $n$ nodes is both a top-right and top-left node, and thus its rank equals $\rank{\root(B)} = n - \rightSize(r) = \leftSize(r) + 1$.

Abstract.tex
\begin{abstract}
	We consider the sum of the incurred start-up costs of a single unit in a Unit Commitment problem. Our major result is a correspondence between the facets of its epigraph and some binary trees for concave start-up cost functions~$\StartupCostFunction(,)$, which is bijective if $\StartupCostFunction(,)$ is strictly concave. We derive an exponential \hrepresentation of this epigraph, and provide an exact linear separation algorithm. These results significantly reduce the integrality gap of the Mixed Integer formulation of a Unit Commitment Problem compared to current literature.
\end{abstract}

\iffalse
{
\setlength{\columnsep}{0em}
\setlength{\tabcolsep}{2pt}
\begin{multicols*}{2}
\noindent
\begin{tabulary}{\columnwidth}{cL}
	\multicolumn{2}{l}{\textbf{Parameters:}}\\[1ex]
	$i \in \Units$ & Set of units\\
	$t \in \Periods$ & Time periods, $\Periods := \set{1, \ldots, T}$\\
	$\periodLength(t)$ & Length of period\\
	$\preOffline(i)$ & Offline time prior to time range\\
	$\StartupCostFunction(i,L)$ & Start-up costs after offline time~$L$
\end{tabulary}

\columnbreak
\noindent
\begin{tabulary}{\columnwidth}{cL}
	\multicolumn{2}{l}{\textbf{Variables:}}\\[1ex]
	$\onOff(i,t)$ & Operational state, binary\\
	$\startupCostSum(i)$ & Summed start-up costs\\[2ex]
	\multicolumn{2}{l}{\textbf{Derived functions:}}\\[1ex]
	$\StartupCost(i,t,l)$ & Start-up costs after $l$ offline periods\\
	$\DiscreteStartupCost(i,t)(\onOff(i,))$ & Start-up costs due to $\onOff(i,)$\\
	$\DiscreteStartupCostSum(\onOff(i,))$ & Summed start-up costs due to $\onOff(i,)$
\end{tabulary}
\end{multicols*}
}
\fi
Separation.tex
\section{Separation}
\label{section:SCS_Separation}

Generally, the \hrepresentation of $\scsEpigraph$ given in the last subsection is of exponential size, and thus not (directly) suitable for computational purposes. This is overcome by a cutting plane approach based on an exact separation algorithm for $\scsEpigraph$ presented in this section. Assuming that the start-up cost function~$\StartupCostFunction{i}{}$ can be evaluated in $\bigO(1)$, as is the case for the exponential start-up cost function \eqref{equation:SC_FunctionForTime}, we show that this separation algorithm has a running time of $\bigO(T)$. Otherwise, the running time would change proportionally.

\Cref{result:SCS_FracPointsOnFacet} states that a point $(\onOff(i,),\startupCostSum) \in [0,1]^T \times \reals$ lies in $\scsEpigraph$ iff the BTI induced by the Cartesian tree for~$\onOff(i,)$ is fulfilled. Thus, the idea of the separation algorithm for $\scsEpigraph$ is to find a Cartesian tree for the vector~$\onOff(i,)$, and construct its induced BTI.

A linear-time algorithm for finding a Cartesian tree for $\onOff(i,)$ has already been given in \cite{gabow_scaling_1984}, and is denoted as \emph{FindCartesianTree}. In summary, this algorithm starts with a tree with a single node $1$, and iteratively adds the remaining nodes~$t \in \discrange{2}{T}$. The key observation is that the node~$t$ in each iteration must be added such that it results to be
\begin{itemize*}
  \item the last top-right node (as to receive the correct rank~$t$), and to be
  \item beneath all top-right nodes~$\tau$ with $\onOff{i}{\tau} > \onOff(i,t)$ and above all top-right nodes~$\tau$ with $\onOff{i}{\tau} < \onOff(i,t)$.
\end{itemize*}

The algorithm represents the resulting Cartesian tree by the left and right childs~$\leftChild(t)$ and $\rightChild(t)$ of each node~$t \in \Periods$. To construct the induced BTI, its coefficients
\begin{equation}
	\label{equation:SCS_CoefficientsForAlg}
	\bticoeff(t) = \scsSumDiff{t}(\leftSize(t),\rightSize(t)) = \StartupCostFunction{i}{\offlineLengthTree{\leftSubtree(t)}} + \StartupCostFunction{i}{\offlineLengthTree{\rightSubtree(t)}} - \StartupCostFunction{i}{\offlineLengthTree{\subtree(t)}}
\end{equation}
need to be computed. This requires the subtree sizes~$\leftSize(t)$, $\rightSize(t)$ and $\size(t)$, which due to \eqref{equation:BT_SubtreeRanks} and \eqref{equation:BT_ChildRank} equal
\begin{align}
	\label{equation:SCS_LeftSizeAlg}
	\leftSize(t) &= \size{\leftChild(t)} = \leftSize{\leftChild(t)} + 1 + \rightSize{\leftChild(t)} = \leftSize{\leftChild(t)} + t - \leftChild(t),\\
%
	\label{equation:SCS_RightSizeAlg}
	\rightSize(t) &= \size{\rightChild(t)} = \leftSize{\rightChild(t)} + 1 + \rightSize{\rightChild(t)} = \rightChild(t) - t + \rightSize{\rightChild(t)},\\
%
	\label{equation:SCS_SizeAlg}
	\size(t) &= \leftSize(t) + 1 + \rightSize(t).
\end{align}

\noindent By the definition of the offline lengths $\offlineLength(t,l)$ (see \eqref{equation:SC_OfflineLength}), we have
\begin{equation*}
	\forall\ t \in \Periods, l_1 \in \discrange*{0}{t-1}, l_2 \in \discrange*{1}{t-l_1-1}: \quad \offlineLength(t,l_1 + l_2) = \offlineLength(t,l_1) + \offlineLength(t-l_1,l_2),
\end{equation*}
and the desired offline lengths $\offlineLengthTree{\leftSubtree(t)}$, $\offlineLengthTree{\rightSubtree(t)}$ and $\offlineLengthTree{\subtree(t)}$ may be derived from \eqref{equation:SC_OfflineLengthTree},\eqref{equation:SC_OfflineLengthTreeLeftRight} for each $t \in \Periods$ as
\begin{align}
	\label{equation:SCS_OLTLeft_Formula}
	\offlineLengthTree{\leftSubtree(t)} &= \offlineLength{t}{\leftSize(t)} = \offlineLength(t,t-1) - \begin{cases}
			\offlineLength{t - \leftSize(t)}{t - \leftSize(t)-1} & \text{if $\leftSize(t) < t-1$},\\
			0 & \text{else.}
	\end{cases}\\
%
	\label{equation:SCS_OLTRight_Formula}
	\offlineLengthTree{\rightSubtree(t)} &= \offlineLength{t+\rightSize(t)+1}{\rightSize(t)} = \offlineLength{t + \rightSize(t)+1}{t+\rightSize(t)} - \offlineLength{t+1}{t},\\
%
	\label{equation:SCS_OLTPrincipal_Formula}
	\offlineLengthTree{\subtree(t)} &= \offlineLength{t+\rightSize(t)+1}{\size(t)} = \offlineLengthTree{\leftSubtree(t)} + \offlineLengthTree{\rightSubtree(t)} + \periodLength(t).
\end{align}

\noindent Using \eqref{equation:SCS_CoefficientsForAlg}-\eqref{equation:SCS_OLTPrincipal_Formula}, the coefficients $\bticoeff(t)$ of the induced BTI can be computed in linear time.

\newpage
\begin{proposition}
	\label[proposition]{result:SCS_SeparationAlgorithm}
	Algorithm~\ref{algorithm:SCS_Separation} solves the separation problem for $\scsEpigraph$ in $\bigO(T)$.
\end{proposition}

\begin{algorithm}[!ht]
	\caption{SeparateBTI}
	\label{algorithm:SCS_Separation}
	\SetKwInOut{Input}{Input}
	\SetKwInOut{Output}{Output}
	\SetKwFunction{FindCartesianTree}{FindCartesianTree}

	\Input{Point $(\onOff(i,),\startupCostSum) \in [0,1]^T \times \reals$}
	\Output{$(\onOff(i,),\startupCostSum) \in \scsEpigraph$, or a separating inequality.}

	\vskip2.5ex
	$B \gets$ FindCartesianTree($\onOff(i,)$)\;

	\vskip2.5ex
	\For{$t = 1, \ldots, T$}{
		$\leftSize(t) := \begin{cases}
			\leftSize{\leftChild(t)} + t - \leftChild(t) & \text{if $\leftChild(t) \neq \emptyset$}\\
			0 & \text{else\;}
		\end{cases}$
	}
	\For{$t = T, \ldots, 1$}{
		$\rightSize(t) := \begin{cases}
			\rightChild(t) - t + \rightSize{\rightChild(t)} & \text{if $\rightChild(t) \neq \emptyset$}\\
			0 & \text{else\;}
		\end{cases}$\\
		$\size(t) := \rightSize(t) + \leftSize(t) + 1$\;
	}

	\vskip2.5ex
	$\offlineLength(1,0) := \preOffline(i)$\;
	\For{$t = 2,\ldots,T$}{
		$\offlineLength(t,t-1) := \offlineLength(t-1,t-2) + \periodLength(t-1)$\;
	}
	\For{$t = 1,\ldots,T$}{
		$\offlineLengthTree{\leftSubtree(t)} := \offlineLength(t,t-1) - \begin{cases}
			\offlineLength{t - \leftSize(t)}{t - \leftSize(t)-1} & \text{if $\leftSize(t) < t-1$},\\
			0 & \text{else.}\;
		\end{cases}$\\
		$\offlineLengthTree{\rightSubtree(t)} := \offlineLength(t + \rightSize(t)+1,t + \rightSize(t)) - \offlineLength{t+1}{t}$\;
		$\offlineLengthTree{\subtree(t)} := \offlineLengthTree{\leftSubtree(t)} + \periodLength(t) + \offlineLengthTree{\rightSubtree(t)}$\;
	}

	\vskip2.5ex
	\For{$t \in \Periods$}{
		$\bticoeff(t) := \begin{cases}
			\StartupCostFunction{i}{\offlineLengthTree{\leftSubtree(t)}} + \StartupCostFunction{i}{\offlineLengthTree{\rightSubtree(t)}} - \StartupCostFunction{i}{\offlineLengthTree{\subtree(t)}} & \text{if $t + \rightSize(t) < T$,}\\
			\StartupCostFunction{i}{\offlineLengthTree{\leftSubtree(t)}} & \text{else.}\;
		\end{cases}$
	}
	\If{$\ds\startupCostSum \geq \sum_{t \in \Periods} \bticoeff(t) \onOff(i,t)$}{
		\Return $(\onOff(i,),\startupCostSum) \in \scsEpigraph$\;
	} \Else {
		\Return $(\onOff(i,),\startupCostSum)$ may be separated from $\scsEpigraph$ by the BTI with coefficients~$\bticoeff(t)$\;
	}
\end{algorithm}

BTI.tex
\section{The Binary Tree Inequalities}
\label{section:SCS_BinaryTreeInequalities}

\def\oleq{\preccurlyeq}

In this subsection, we show that all lifted inequalities correspond in a one-to-one way to binary trees, which motivates naming them \emph{binary tree inequalities (BTIs)}. Together with $0 \leq \onOff(i,t) \leq 1$, these inequalities induce all facets of $\scsEpigraph$.

We start with an example where $\bticoeff(4)$ and $\bticoeff(9)$ are lifted in both possible orders,
\begin{itemize*}
  \item $\bticoeff(4)$ before $\bticoeff(9)$ with intermediate vector $\onOff(\idx,)$, and
  \item $\bticoeff(9)$ before $\bticoeff(4)$ with intermediate vector $\tildeOnOff(\idx,)$ (\cf \cref{figure:SCS_LiftingExampleStripped}).
\end{itemize*}

\input{pics/LiftingExampleStripped}

\noindent If the coefficient~$\bticoeff(6)$ is already lifted, the relative order in which $\bticoeff(4)$ and $\bticoeff(9)$ are lifted does not influence the period counts,
\begin{alignat*}{2}
	\offlineNumber{4}{\onOff(\idx,)} &= \offlineNumber{4}{\onOff(\idx+1,)} &\qquad\text{and}\qquad \offlineNumberRight{4}{\onOff(\idx,)} &= \offlineNumberRight{4}{\onOff(\idx+1,)},\\
%
	\offlineNumber{9}{\tildeOnOff(\idx,)} &= \offlineNumber{9}{\onOff(\idx+1,)} &\qquad\text{and}\qquad \offlineNumber{9}{\tildeOnOff(\idx,)} &= \offlineNumber{9}{\onOff(\idx+1,)}.
\end{alignat*}
Thereby, the values of the lifted coefficients~$\bticoeff(4)$ and $\bticoeff(9)$ are equal for both cases. This holds in general: As soon as a coefficient $\bticoeff(t)$ has been lifted, for each subsequently lifted coefficient~$\bticoeff(\tau)$ with $\tau < t$ we have $\offlineNumberRight{\tau}{\onOff(i,)} < t - \tau$. Thus, the period counts, and by extension the coefficient~$\bticoeff(\tau)$, do not depend on the lifting order of coefficients~$\bticoeff(\tilde{t})$ with ${\tilde{t}} > t$. Analogously if $t' > t$, the coefficient~$\bticoeff(\tau)$ does not depend on the lifting order of coefficients~$\bticoeff(\tilde{t})$ with ${\tilde{t}} < t$.

\def\a{{t_1}}
\def\b{{t_2}}
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%

A lifting order~$\sigma$ corresponds to a linear order~$\oleq_\sigma$ on $\Periods$ with
\begin{equation*}
 	\forall\, \a, \b \in \Periods: \qquad \a \oleq_\sigma \b \quad:\Leftrightarrow\quad \sigma^{-1}(\a) \leq \sigma^{-1}(\b).
\end{equation*}
As argued above, the lifted coefficients~$\bticoeff(t_1),\bticoeff(t_2)$ do not depend on whether $t_1 \oleq_\sigma t_2$ or $t_2 \oleq_\sigma t_1$ if
\begin{equation*}
%
	\exists\ t_3 \in (t_1,t_2) \cup (t_1,t_2),\quad t_3 \oleq_\sigma t_1, \quad t_3 \oleq_\sigma t_2.
\end{equation*}
Eliminating such relationships from $\oleq_\sigma$ yields a partial order~$\oleq_\sigma'$ which fully determines the lifted inequality, \ie each linearization of this partial order leads to the same lifted inequality. \cref{figure:SCS_PermutationAndTree} shows an exemplary partial order (twice, as a Hasse-diagram) and two possible linearizations~$\oleq_{\sigma}$ and $\oleq_{\overline{\sigma}}$ represented by the permutations~$\sigma$ and $\overline{\sigma}$.

\input{pics/PermutationAndTree}

As \cref{figure:SCS_PermutationAndTree} suggests, the Hasse-diagrams of these partial orders are binary trees, where each coefficient~$\bticoeff(t)$ corresponds to a node~$t$. The partial order then prescribes that each coefficient~$\bticoeff(t)$ must be lifted before the coefficients associated with the descendants of node~$t$.

Observe that for a lifting order~$\sigma$ and the corresponding linear order~$\oleq_\sigma$, the vectors~$\onOff(\idx,)$ encountered in the lifting process by definition \eqref{equation:SCS_LiftingVectors} fulfill
\begin{equation*}
	\forall\, \idx \in \Periods, t \in \Periods: \qquad \onOff(j,t) = \begin{cases}
		1 & \text{if $t \oleq_\sigma \sigma(\idx)$,}\\
		0 & \text{else.}
	\end{cases}
\end{equation*}
Therefore, the offline lengths~$\offlineNumber{\sigma(\idx)}{\onOff(\idx,)}$ and $\offlineNumberRight{\sigma(\idx)}{\onOff(\idx,)}$, which define $\bticoeff{\sigma(\idx)}$, equate to
\begin{align*}
	\offlineNumber{\sigma(\idx)}{\onOff(\idx,)} &= \max \set[\big]{l \in \discrange*{0}{\sigma(\idx)-1}\: \given \forall\, t \in \discrange*{\sigma(\idx)-l}{\sigma(\idx)-1}: t \oleq_\sigma \sigma(\idx)}, \text{ and}\\
%
	\offlineNumberRight{\sigma(\idx)}{\onOff(\idx,)} &= \max \set[\big]{l \in \discrange*{0}{T-\sigma(\idx)} \given \forall\, t \in \discrange*{\sigma(\idx)+1}{\sigma(\idx)+l}: t \oleq_\sigma \sigma(\idx)}.
\end{align*}
As argued, these lengths remain unchanged when replacing $\oleq_\sigma$ by the corresponding partial order~$\oleq_\sigma'$. Furthermore, their above representation shows that they can be derived from the Hasse-diagram of $\oleq_\sigma'$: The size~$\leftSize{\sigma(\idx)}$ of the left subtree of $\sigma(\idx)$ equals $\offlineNumber{\sigma(\idx)}{\onOff(\idx,)}$ and the size~$\rightSize{\sigma(\idx)}$ of the right subtree of~$\sigma(j)$ equals $\offlineNumberRight{\sigma(\idx)}{\onOff(\idx,)}$ (see \cref{figure:SCS_LiftingFromTreeExample}).

\input{pics/LiftingFromTreeExample}

A coefficient~$\bticoeff(t)$ therefore solely depends on the partial order~$\oleq_\sigma'$ and may be expressed as
\begin{equation*}
	\bticoeff(t) = \scsSumDiff{t}(\leftSize{t},\rightSize{t}),
\end{equation*}
where $t = \sigma(j)$, and $\leftSize(t), \rightSize(t)$ are determined by the partial order.

Each of the start-up cost terms in $\scsSumDiff{t}(\leftSize(t),\rightSize(t))$ corresponds to the cost incurred when starting up after being offline during the periods contained in either the left subtree~$\leftSubtree(t)$ of~$t$, the right subtree~$\rightSubtree(t)$ of~$t$, or the principal subtree~$\subtree(t)$ of~$t$ (see \eqref{equation:BT_SubtreeRanks}),
\begin{equation*}
	\scsSumDiff{t}(\leftSize(t),\rightSize(t)) = \underbrace{\StartupCost{i}{t}{\leftSize(t)}}_{\text{offline in $\leftSubtree(t)$}}
	+ \underbrace{\StartupCost{i}{t+\rightSize(t)+1}{\rightSize(t)}}_{\text{offline in $\rightSubtree(t)$}}
	- \underbrace{\StartupCost{i}{t+\rightSize(t)+1}{\leftSize(t)+1+\rightSize(t)}}_{\text{offline in $\subtree(t)$}}
\end{equation*}

To simplify the notation, we generalize the definition (see \eqref{equation:SC_FunctionForPeriods}) of the offline length~$\offlineLength(,)$: for each $B \in \scsBinaryTrees$ and $t \in \Periods$, we abbreviate
\begin{gather}
	\label{equation:SC_OfflineLengthTree}
	\offlineLengthTree{\subtree(t)} := \offlineLength{t+\rightSize(t)+1}{\size(t)},\\[-1.5ex]
%
	\intertext{and consequently, by \eqref{equation:BT_SubtreeRanks}}
%
	\label{equation:SC_OfflineLengthTreeLeftRight}
	\offlineLengthTree{\leftSubtree(t)} = \offlineLength{t}{\leftSize(t)} \quad\text{and}\quad \offlineLengthTree{\rightSubtree(t)} = \offlineLength{t+\rightSize(t)+1}{\rightSize(t)}.
\end{gather}
Since by definition $\StartupCost(i,t,l) = \StartupCostFunction{i}{\offlineLength(t,l)}$, it follows that
\begin{equation}
	\label{equation:SCS_SumUpdateDiffTree}
	\scsSumDiff{t}(\leftSize(t),\rightSize(t)) = \StartupCostFunction(i,\offlineLengthTree{\leftSubtree(t)}) + \StartupCostFunction(i,\offlineLengthTree{\rightSubtree(t)}) - \StartupCostFunction{i}{\offlineLengthTree{\subtree(t)}}.
\end{equation}

\newpage
\begin{definition}
	\label[definition]{definition:SCS_BinaryTreeInequality}
	A \emph{rank-labeled} binary tree is a binary tree~$B$ on nodes~$\discrange{1}{n}$, where $n \in \naturals$, and $\rank(i) = i$ for all $i \in \discrange{1}{n}$. Let $\scsBinaryTrees$ denote the family of all rank-labeled binary trees on $\Periods$. For each $B \in \scsBinaryTrees$, we define the \emph{binary tree inequality (BTI)} as
	\begin{equation*}
		\startupCostSum \geq \sum_{t \in \Periods} \scsSumDiff{t}( \leftSize(t), \rightSize(t)) \, \onOff(i,t),%
	\end{equation*}
	using the sizes~$\leftSize(t)$ or $\rightSize(t)$ of the left or right subtrees of~$t$, respectively, and $\scsSumDiff{t}$ as defined in \cref{result:SCS_SumUpdate}.
\end{definition}

In the following, we confirm that the binary tree inequalities, together with the trivial inequalities~$0 \leq \onOff(i,t) \leq 1$, define all non-trivial facets of $\scsEpigraph$ by proving that
\begin{itemize*}
  \item they are feasible (\cref{result:SCS_EpigraphInPolyhedron}),
  \item they are fulfilled with equality by all points $(\onOff(\idx,),\DiscreteStartupCostSum(\onOff(\idx,)))$ encountered during the lifting process (\cref{result:SCS_PointsOnFacet}), and
  \item these points are linearly independent (\cref{result:SCS_Facets}).
\end{itemize*}
Moreover, we will show that all points not in $\scsEpigraph$ can be separated by the BTIs or the trivial inequalities $0 \leq \onOff(i,t) \leq 1$ in $\bigO(T)$.

In the following, we need to put the vertices $(\onOff(i,),\DiscreteStartupCostSum(\onOff(i,)))$ of the epigraph $\scsEpigraph$ into relation with the binary trees $B \in \scsBinaryTrees$.
\begin{definition}
	\label[definition]{definition:SCS_Induced_Subtree}
	For each $B \in \scsBinaryTrees$ with edges $E$ and $\onOff(i,) \in \set{0,1}^T$, define $\oneSubtree{\onOff(i,)}$ as the subgraph of $B$ induced by the 1-entries of $\onOff(i,)$,
	\begin{equation*}
		\oneSubtree{\onOff(i,)} := (V_S, E_S) \quad\text{where}\quad  V_S := \set[\big]{t \in \Periods \given \onOff(i,t) = 1} \quad\text{and}\quad E_S := \set[\big]{e \in E \given e \subseteq V_S}.
	\end{equation*}
\end{definition}
Note that in general, $\oneSubtree{\onOff(i,)}$ is not connected.

The proof that the binary tree inequalities are valid implicitly follows from the concavity of $\StartupCostFunction(i,)$, which is exploited through the monotonicity of $\scsSumDiff{t}$ (\cref{result:SCS_SumDiffIncreasing}).

\begin{lemma}
	\label[lemma]{result:SCS_EpigraphInPolyhedron}
	For each $B \in \scsBinaryTrees$, the BTI induced by $B$ is valid for $\scsEpigraph$.
\end{lemma}
\begin{proof}
	Due to the convexity of $\scsEpigraph$ and since a binary tree inequality bounds $\startupCostSum$ only from below, it suffices to prove that all vertices $(\onOff(i,),\DiscreteStartupCostSum(\onOff(i,))) \in \scsVertices$ of $\scsEpigraph$ fulfill all BTIs. To do so, for each $B \in \scsBinaryTrees$, we prove that its induced BTI is valid by induction over the number of nodes $n$ in its induced subtree $\oneSubtree{\onOff(i,)}$.
	
	For $n = 0$, the only such point is $0 \in \scsVertices$. Since each BTI is homogeneous, $0$ fulfills all of them with equality. For $n \geq 1$, choose a leaf $t$ in $\oneSubtree{\onOff(i,)}$, \ie a node such that the subtree of $t$ in $B$ does not contain any other nodes from $\oneSubtree{\onOff(i,)}$. Define the vector $\tildeOnOff(,)$ as
	\begin{align*}
		\tildeOnOff(i,\tau) &:= \begin{cases}
			\onOff(i,\tau) & \text{if } \tau \neq t,\\
			0 & \text{if } \tau = t,
		\end{cases},
	\end{align*}
	differing from $\onOff(i,)$ only in period $t$. By \cref{result:SCS_SumUpdate}, we get
	\begin{equation*}
		\DiscreteStartupCostSum(\onOff(i,)) = \DiscreteStartupCostSum(\tildeOnOff(i,)) + \scsSumDiff{t}(\offlineNumber{t}{\onOff(i,)},\offlineNumberRight{t}{\onOff(i,)}).
	\end{equation*}
	These vectors, the induced subtrees, and the offline lengths $\offlineNumber{t}{\onOff(i,)}$, $\offlineNumberRight{t}{\onOff(i,)}$ are shown in \cref{figure:SCS_LiftUnexact}.

	\input{pics/LiftUnexact}
	
	By the choice of $t$, its left subtree, which contains the nodes~$t-\leftSize(t),\ldots,t-1$, does not contain any nodes from $\oneSubtree{\onOff(i,)}$. Hence, $\onOff{i}{t-\leftSize(t)} = \ldots = \onOff(i,t-1) = 0$, implying $\offlineNumber{t}{\onOff(i,)} \geq \leftSize(t)$. Since the right subtree of $t$ does not contain any nodes from $\oneSubtree{\onOff(i,)}$ either, we analogously obtain $\offlineNumberRight{t}{\onOff(i,)} \geq \rightSize(t)$.
	
	\newpage
	Thus, using the monotonicity of $\scsSumDiff{t}$, it holds that
	\begin{align*}
		\DiscreteStartupCostSum(\onOff(i,)) &= \DiscreteStartupCostSum(\tildeOnOff(i,)) + \scsSumDiff{t}(\offlineNumber{t}{\onOff(i,)},\offlineNumberRight{t}{\onOff(i,)}) \geq \DiscreteStartupCostSum(\tildeOnOff(i,)) + \scsSumDiff{t}(\leftSize(t), \rightSize(t))\\
%
			&\withtextl{ind.hyp.}{\geq} \sum_{\tau \in \Periods} \scsSumDiff{\tau}(\leftSize(\tau), \rightSize(\tau)) \, \tildeOnOff(i,\tau) + \scsSumDiff{t}(\leftSize(t), \rightSize(t))
%
			= \sum_{\tau \in \Periods} \scsSumDiff{\tau}(\leftSize(\tau), \rightSize(\tau)) \, \onOff(i,\tau).\eqqed{1em}
	\end{align*}
\end{proof}

The central argument of the proof of the last lemma is that in each step of the induction, the inequality
\begin{equation*}
	\scsSumDiff{t}(\offlineNumber{t}{\onOff(i,)},\offlineNumberRight{t}{\onOff(i,)}) \geq \scsSumDiff{t}(\leftSize(t),\rightSize(t))
\end{equation*}
holds due to $\offlineNumber{t}{\onOff(i,)} \geq \leftSize(t)$ and $\offlineNumberRight{t}{\onOff(i,)} \geq \rightSize(t)$. Assume that, for a given binary tree $B$ and a vertex of $\scsEpigraph$, this inequality is fulfilled with equality in each induction step. Then the vertex also fulfills the BTI induced by $B$ with equality. We characterize such vertices in the next lemma.
\begin{lemma}
	\label[lemma]{result:SCS_PointsOnFacet}
	For each $B \in \scsBinaryTrees$, $(\onOff(i,),\DiscreteStartupCostSum(\onOff(i,))) \in \scsVertices$, if the induced subgraph $\oneSubtree{\onOff(i,)}$ is a tree containing $\root(B)$, then $(\onOff(i,),\DiscreteStartupCostSum(\onOff(i,)))$ fulfills the BTI induced by $B$ with equality.
\end{lemma}
\begin{proof}
	Analogously to the proof of \cref{result:SCS_EpigraphInPolyhedron}, we show that $(\onOff(i,),\DiscreteStartupCostSum(\onOff(i,)))$ fulfills the binary tree inequality induced by $B \in \scsBinaryTrees$ by induction over the number of nodes~$n$ in the subgraph $\oneSubtree{\onOff(i,)}$.

	For $n = 0$, the only such vertex is $0 \in \scsVertices$, which fulfills all BTIs with equality. For $n \geq 1$, let $t$ be a leaf of $\oneSubtree{\onOff(i,)}$, and define $\tildeOnOff(i,) := \onOff(i,)-\unitVec{t}$ as in the proof of \cref{result:SCS_EpigraphInPolyhedron}. Note that since $\oneSubtree{\onOff(i,)}$ is a tree and $\root(B) \in \oneSubtree{\onOff(i,)}$, also the subgraph $\oneSubtree{\tildeOnOff(i,)}$ is a tree with $n-1$ nodes, which contains $\root(B)$ in case of $n \geq 2$.

	Since no nodes in the principal subtree of $t$, except $t$ itself, are in $\oneSubtree{\onOff(i,)}$, analogeously to the proof of \cref{result:SCS_EpigraphInPolyhedron}, it holds that $\offlineNumber{t}{\onOff(i,)} \geq \leftSize(t)$ and $\offlineNumberRight{t}{\onOff(i,)} \geq \rightSize(t)$. We show that these bounds are sharp by examining two cases for $\offlineNumber{t}{\onOff(i,)} = \leftSize(t)$ (see \cref{figure:SCS_LiftPrev}) and two cases for $\offlineNumberRight{t}{\onOff(i,)} = \rightSize(t)$ (see \cref{figure:SCS_LiftNext}).
	
	\input{pics/LiftPrev}
	\input{pics/LiftNext}

	If $t$ is a top-left node, then $\squeeze{t = \leftSize(t) + 1}$ (see \cref{result:TopLeftRanks}), implying $\squeeze{\leftSize(t) \leq \offlineNumber{t}{\onOff(i,)} \leq t - 1 = \leftSize(t)}$, and thus $\offlineNumber{t}{\onOff(i,)} = \leftSize(t)$. Otherwise, there exists a node~$\tilde{l}$ such that $t$ is a top-left node in the right subtree~$\rightSubtree(\tilde{l})$ of $\tilde{l}$. Since $\tilde{l}$ is an ancestor of $t$, we have $\tilde{l} \in \oneSubtree{\onOff(i,)}$. Hence,
	\begin{equation*}
		\leftSize(t) \leq \offlineNumber{t}{\onOff(i,)} \leq t - \tilde{l} - 1 \withtext{\cref{result:TopLeftRanks}}{=} \left(\tilde{l} + \leftSize(t) + 1 \right) - \tilde{l} - 1 = \leftSize(t).
	\end{equation*}
	
	\vskip-0.5ex
	If $t$ is a top-right node, then $t = \rightSize(t) - 1$, implying $\rightSize(t) \leq \offlineNumberRight{t}{\onOff(i,)} \leq t + 1 = \rightSize(t)$. Else, $t$ is a top-right node in the left subtree of a node $\tilde{r}$. Since $\tilde{r}$ is an ancestor of $t$, we have $\tilde{r} \in \oneSubtree{\onOff(i,)}$, and thus again
	\begin{equation*}
		\rightSize(t) \leq \offlineNumberRight{t}{\onOff(i,)} \leq \tilde{r} - t - 1 \smash{\withtext{\cref{result:TopRightSubtree}}{=}} \rightSize(t).
	\end{equation*}
	
	In conclusion, we have shown $\squeeze[0.75]{\offlineNumber{t}{\onOff(i,)} = \leftSize(t)}$ and $\squeeze[0.75]{\offlineNumberRight{t}{\onOff(i,)} = \rightSize(t)}$. Analogous to \cref{result:SCS_EpigraphInPolyhedron},
	\begin{align*}
		\DiscreteStartupCostSum(\onOff(i,)) &= \DiscreteStartupCostSum(\tildeOnOff(i,)) + \scsSumDiff{t}(\offlineNumber{t}{\onOff(i,)},\offlineNumberRight{t}{\onOff(i,)}) = \DiscreteStartupCostSum(\tildeOnOff(i,)) + \scsSumDiff{t}(\leftSize(t), \rightSize(t))\\
%
			&\vphantom{\Big(}\smash{\withtextl{ind.hyp.}{=}} \smash[b]{\sum_{\tau \in \Periods}} \scsSumDiff{\tau}(\leftSize(\tau), \rightSize(\tau)) \, \tildeOnOff(i,\tau) + \scsSumDiff{t}(\leftSize(t), \rightSize(t)) = \smash[b]{\sum_{\tau \in \Periods}} \scsSumDiff{\tau}(\leftSize(\tau), \rightSize(\tau)) \, \onOff(i,\tau).\eqqed{0.4em}
	\end{align*}
\end{proof}

In general, a vertex $(\onOff(i,),\DiscreteStartupCostSum(\onOff(i,)))$ may lie on a facet induced by a binary tree $B$ which does not meet the requirements of the preceding lemma, \eg for a linear start-up cost function. The next result shows that this does not happen for strictly concave start-up cost functions~$\StartupCostFunction(,)$.

\begin{lemma}
	\label[lemma]{result:SCS_PointsNotOnFacet}
	Let $\StartupCostFunction(,)$ be strictly concave, $B \in \scsBinaryTrees$, and $(\onOff(i,),\DiscreteStartupCostSum(\onOff(i,))) \in \scsVertices$. If $(\onOff(i,),\DiscreteStartupCostSum(\onOff(i,)))$ fulfills the BTI induced by $B$ with equality, then either $\onOff(i,) = 0$ or the induced subgraph $\oneSubtree{\onOff(i,)}$ is a tree containing $\root(B)$.
\end{lemma}
\begin{proof}
	Again we prove the statement by induction over the number of nodes~$n$ in the subgraph $\oneSubtree{\onOff(i,)}$. The case $n = 0$ is fulfilled trivially.
	
	For $n \geq 1$, analogously to the proof of \cref{result:SCS_EpigraphInPolyhedron}, choose a node~$t$ such that the subtree of~$t$ in $B$ does not contain any other nodes from $\oneSubtree{\onOff(i,)}$. This choice implies $\offlineNumber{t}{\onOff(i,)} \geq \leftSize(t)$ and $\offlineNumberRight{t}{\onOff(i,)} \geq \rightSize(t)$, and thus, because of concavity,
	\begin{equation*}
		\scsSumDiff{t}(\offlineNumber{t}{\onOff(i,)},\offlineNumberRight{t}{\onOff(i,)}) \geq \scsSumDiff{t}(\leftSize(t),\rightSize(t)).
	\end{equation*}
	For $\tildeOnOff(i,) := \onOff(i,) - \unitVec{t}$, \cref{result:SCS_SumUpdate} yields
	\begin{align*}
		\DiscreteStartupCostSum(\onOff(i,)) &- \scsSumDiff{t}(\offlineNumber{t}{\onOff(i,)},\offlineNumberRight{t}{\onOff(i,)})
		= \DiscreteStartupCostSum(\tildeOnOff(i,))
%
		\intertext{which, since $(\tildeOnOff(i,),\DiscreteStartupCostSum(\tildeOnOff(i,))) \in \scsEpigraph$, may be bounded by}
%
		&\geq \sum_{\tau \in \Periods} \scsSumDiff{\tau}(\leftSize(\tau),\rightSize(\tau)) \tildeOnOff(i,\tau)
		= \sum_{\tau \in \Periods} \scsSumDiff{\tau}(\leftSize(\tau),\rightSize(\tau)) \onOff(i,\tau) - \scsSumDiff{t}(\leftSize(t),\rightSize(t))
	%
		\intertext{and, by the choice of $\onOff(i,)$ and $t$, equals}
	%
		&= \DiscreteStartupCostSum(\onOff(i,)) - \scsSumDiff{t}(\leftSize(t),\rightSize(t))
		\geq \DiscreteStartupCostSum(\onOff(i,)) - \scsSumDiff{t}(\offlineNumber{t}{\onOff(i,)},\offlineNumberRight{t}{\onOff(i,)}).
	\end{align*}
	Therefore, the above inequality is fulfilled with equality, and we conclude
	\begin{equation*}
		\scsSumDiff{t}(\offlineNumber{t}{\onOff(i,)},\offlineNumberRight{t}{\onOff(i,)}) = \scsSumDiff{t}(\leftSize(t),\rightSize(t)) \quad\text{and}\quad \DiscreteStartupCostSum(\tildeOnOff(i,)) = \sum_{\tau \in \Periods} \scsSumDiff{\tau}(\leftSize(\tau),\rightSize(\tau)) \tildeOnOff(i,\tau).
	\end{equation*}
	
	Firstly, as $\StartupCostFunction(,)$ is assumed to be strictly concave, $\scsSumDiff{t}$ is strictly increasing in $l$ and $r$ (see \cref{result:SCS_SumUpdate}). Recalling that $\offlineNumber{t}{\onOff(i,)} \geq \leftSize(t)$ and $\offlineNumberRight{t}{\onOff(i,)} \geq \rightSize(t)$ by the choice of $t$, we infer $\offlineNumber{t}{\onOff(i,)} = \leftSize(t)$ and $\offlineNumberRight{t}{\onOff(i,)} = \rightSize(t)$.
	
	Secondly, since $\abs{\oneSubtree{\tildeOnOff(i,)}} = \abs{\oneSubtree{\onOff(i,)}} - 1$, the induction hypothesis states that either $\tildeOnOff(i,) = 0$ or $\oneSubtree{\tildeOnOff(i,)}$ is a tree containing $\root(B)$. If $\tildeOnOff(i,) = 0$, then
	\begin{equation*}
		\size(t) = \leftSize(t) + 1 + \rightSize(t) = \offlineNumber{t}{\onOff(i,)} + 1 + \offlineNumberRight{t}{\onOff(i,)} = t - 1 + 1 + (T-t) = T,
	\end{equation*}
	hence $t$ is the root of $B$ and $\oneSubtree{\onOff(i,)}$ is the single-noded tree consisting of $t = \root(B)$.
	
	Else $\tildeOnOff(i,) \neq 0$, implying that $\oneSubtree{\tildeOnOff(i,)}$ is a tree containing $\root(B)$. Therefore $t \neq \root(B)$, meaning that $t$ has a parent~$\parent(t)$. By \eqref{equation:BT_ChildRank}, if $t$ is a right child, then
	\begin{align*}
		\parent(t) &= t - \leftSize(t) - 1 = t - \offlineNumber{t}{\onOff(i,)} - 1,
		\intertext{and if $t$ is a left child, then}
		\parent(t) &= t + \rightSize(t) + 1 = t + \offlineNumberRight{t}{\onOff(i,)} + 1.
	\end{align*}
	In both cases, $\onOff{i}{\parent(t)} = 1$ by definition of $\offlineNumber{t}{\onOff(i,)}$ or $\offlineNumberRight{t}{\onOff(i,)}$ (\eqref{equation:SC_OfflineNumber} and \eqref{equation:SCS_OfflineNumberRight}), and thus $\parent(t) \in \oneSubtree{\onOff(i,)}$. Given that $\oneSubtree{\tildeOnOff(i,)}$ is a tree containing $\root(B)$, we obtain that $\oneSubtree{\onOff(i,)}$ must be a tree containing $\root(B)$ too.\manualqed
\end{proof}

The vectors $\onOff(i,)$ encountered during a lifting process gain a non-zero entry in every step, and are thus linearly independent.

\begin{theorem}
	\label[theorem]{result:SCS_Facets}
	All binary tree inequalities induce facets of $\scsEpigraph$.
\end{theorem}
\begin{proof}
	For each binary tree $B \in \scsBinaryTrees$, the induced BTI is valid for $\scsEpigraph$ (see \cref{result:SCS_EpigraphInPolyhedron}).
	
	Choose a permutation~$\sigma$ of $\Periods$ such that the nodes $\sigma(t)$ are ordered by their depth~$\depth{\sigma(t)}$ in $B$, \ie such that for each $t \in \discrange{1}{T-1}$ it holds that $\depth{\sigma(t)} \leq \depth{\sigma(t + 1)}$. For each $\idx \in \Periods$, define the vector
	\begin{equation*}
		\forallPeriods: \qquad \onOff(\idx,t) := \begin{cases}
			1 & \text{if $\sigma^{-1}(t) \leq \idx$,}\\
			0 & \text{else,}
		\end{cases}
	\end{equation*}
	which induces the subgraph $\oneSubtree{\onOff(\idx,)}$ containing the nodes $\set{\sigma(1), \ldots, \sigma(\idx)}$. $\oneSubtree{\onOff(\idx,)}$ fulfills the requirements of \cref{result:SCS_PointsOnFacet}, and thus the vertex~$(\onOff(\idx,), \DiscreteStartupCostSum(\onOff(\idx,)))$ fulfills the BTI with equality.
	
	Denoting the permutation matrix associated to $\sigma$ with $\Pi_\sigma$, we obtain
	\begin{equation*}
		\Pi_\sigma \cdot
		\begin{pmatrix}
			\onOff(1,) & \onOff(2,) & \ldots & \onOff(T,)
		\end{pmatrix} = 
		\begin{pmatrix}
			1 & \cdots & \cdots & 1\\
			0 & 1 & \cdots & 1\\
			\vdots & \ddots & \ddots & \vdots\\
			0 & \cdots & 0 & 1
		\end{pmatrix},
	\end{equation*}
	and thus $0, (\onOff(1,), \DiscreteStartupCostSum(\onOff(1,)))$, $\ldots$, $(\onOff(T,), \DiscreteStartupCostSum(\onOff(T,)))$ are affine linearly independent. Since they amount to $\squeeze{T+1}$ points on the face~$F$ of $\scsEpigraph$ induced by the BTI, $F$ must be a facet.\hbox{\manualqed}
\end{proof}

Sufficiency.tex
\section{Sufficiency of the BTIs}
\label{section:SCS_HRepresentation}


In this subsection, we prove that the binary tree inequalities (\cref{definition:SCS_BinaryTreeInequality}), together with the trivial facets $0 \leq \onOff(i,t) \leq 1$, are sufficient for an \hrepresentation of $\scsEpigraph$. To do so we show that the facets induced by all the BTIs fully describe the lower boundary of $\scsEpigraph$. To this end, we extend the characterization of the facets on which a vertex $(\onOff(i,),\DiscreteStartupCostSum(\onOff(i,)))$ lies (\cref{result:SCS_PointsOnFacet}) to points with $\onOff(i,) \in [0,1]^T$.

\Cref{result:SCS_PointsOnFacet} provides the sufficient (but not necessary) condition for the vertices of $\scsEpigraph$ lying on a certain facet: \enquote{A vertex $(\onOff(i,),\DiscreteStartupCostSum(\onOff(i,)))$ lies on the facet corresponding to a binary tree $B \in \scsBinaryTrees$, if the induced subgraph $\oneSubtree{\onOff(i,)}$ is a tree containing $\root(B)$.} In other words, each node~$t \in \oneSubtree{\onOff(i,)}$ needs to be connected to $\root(B)$ within $\oneSubtree{\onOff(i,)}$. The unique path $P_t$ from $t$ to $\root(B)$ consists of its ancestors,
\begin{equation*}
	P_t = t \to \parent(t) \to \parentBraces{\parent(t)} \to \parentBraces{\parentBraces{\parent(t)}} \to \ldots \to \root(B).
\end{equation*}
By definition, $t \in \oneSubtree{\onOff(i,)} \equals \onOff(i,t) = 1$. So, $\oneSubtree{\onOff(i,)}$ contains the paths $P_t$ for all $t \in \oneSubtree{\onOff(i,)}$ iff
\begin{equation*}
	\onOff(i,t) = 1 \implies \onOffBraces{i}{\parent(t)} = 1 \quad \text{for all $t \in \Periods \setminus \set{\root(B)}$},
\end{equation*}
which, since $\onOff(i,) \in \set{0,1}^T$, is equivalent to
\begin{equation}
	\label{equation:SCS_CartesianCondition}
	\onOff(i,t) \leq \onOff{i}{\parent(t)} \quad \text{for all $t \in \Periods \setminus \set{\root(B)}$}.
\end{equation}

Coincidentally, this condition is also important when searching efficiently in a point set in the Cartesian plane, and is denoted by \enquote{$B$ is a Cartesian tree for $\onOff(i,)$} in \cite{vuillemin_unifying_1980}. We use a definition adapted to our purposes, equivalent to the recursive definition of Cartesian trees in \cite{gabow_scaling_1984}.
\begin{definition}
	\label[definition]{definition:CartesianTree}
	For each $\onOff(i,) \in \reals^T$, a binary tree~$B \in \scsBinaryTrees$ with
	\begin{equation*}
		\onOff(i,t) \leq \onOff{i}{\parent(t)} \quad \text{for all $t \in \Periods \setminus \set{\root(B)}$}
	\end{equation*}
	is called a \emph{Cartesian tree} for $\onOff(i,)$.
\end{definition}

The following lemma shows that condition~(\ref{equation:SCS_CartesianCondition}) applies to any $\onOff(i,) \in [0,1]^T$ as well.
\begin{lemma}
	\label[lemma]{result:SCS_FracPointsOnFacet}
	If $\onOff(i,) \in [0,1]^T$ and $B \in \scsBinaryTrees$ is a Cartesian tree for $\onOff(i,)$, then $(\onOff(i,),\StartupCostSum(\onOff(i,)))$ lies on the facet of $\scsEpigraph$ induced by $B$.
\end{lemma}
\begin{proof}
For each $\onOff(i,) \in [0,1]^T$ and each Cartesian tree $B \in \scsBinaryTrees$ for $\onOff(i,)$, we decompose the vector~$\onOff(i,)$ into binary vectors $\tildeOnOff(\idx,)$, which, paired with the summed start-up costs~$\DiscreteStartupCostSum(\tildeOnOff(\idx,))$, lie on the facet of $\scsEpigraph$ induced by $B$. This decomposition is depicted schematically in \cref{figure:SCS_Decomposition}.

\input{pics/Decomposition}
	
Choose a permutation $\sigma$ which orders the indices $t \in \Periods$ by decreasing value of~$\onOff(i,t)$, and increasing depth $\depth(t)$ in $B$ if the values $\onOff(i,t)$ are equal, \ie such that
	\begin{align*}
		\forall\,\idx_1, \idx_2 \in \Periods, \idx_1 < \idx_2: \qquad \onOff{i}{\sigma(\idx_1)} &\geq \onOff{i}{\sigma(\idx_2)} \quad\text{and}\\
		\onOff{i}{\sigma(\idx_1)} &= \onOff{i}{\sigma(\idx_2)} \quad \implies \quad \depth(\sigma(\idx_1)) \leq \depth(\sigma(\idx_2)).
	\end{align*}

	\noindent For all $\idx \in \Periods$, define the vectors $\tildeOnOff(\idx,) \in \set{0,1}^T$ and the coefficients $\lambda_\idx$ as
	\begin{equation*}
		\tildeOnOff(\idx,t) := \begin{cases}
			1 & \text{if } \sigma^{-1}(t) \leq \idx,\\
			0 & \text{else,}
		\end{cases}
		\qquad\text{and}\qquad
		\lambda_\idx := \begin{cases}
			\onOff{i}{\sigma(\idx)} - \onOff{i}{\sigma(\idx+1)} & \text{for } \idx \leq T-1,\\
			\onOff{i}{\sigma(T)} & \text{else.}
		\end{cases}
	\end{equation*}
	By definition of $\sigma$, all $\lambda_\idx$ are non-negative, and obviously they sum up to $\onOff{i}{\sigma(1)}$. Hence, for each $t \in \Periods$, it holds that
\begin{equation*}
	\sum_{\idx = 1}^T \lambda_\idx \tildeOnOff(\idx,t) =
%
	\sum_{\idx = \sigma^{-1}(t)}^T \lambda_\idx =
%
	\sum_{\idx = \sigma^{-1}(t)}^{T-1} (\onOff{i}{\sigma(\idx)} - \onOff{i}{\sigma(\idx+1)}) + \onOff{i}{\sigma(T)} =
%
	\onOff{i}{\sigma(\sigma^{-1}(t))} = \onOff(i,t).
\end{equation*}

\noindent Therefore, the vector~$\onOff(i,)$ indeed is a convex combination of the vectors $\tildeOnOff(\idx,)$ and $0$,
	\begin{equation*}
		\onOff(i,) = \sum_{\idx = 1}^T \lambda_\idx \tildeOnOff(\idx,) + (1 - \onOff{i}{\sigma(1)}) \:0.
	\end{equation*}

	We proceed by showing that the vertices $(\tildeOnOff(\idx,), \DiscreteStartupCostSum(\tildeOnOff(\idx,)))$ lie on the facet induced by $B$. For each $\idx \in \Periods$, the induced subgraph $\oneSubtree{\tildeOnOff(\idx,)}$ is the induced subgraph of $B$ on nodes $\set*{t \in \Periods \given \sigma^{-1}(t) \leq \idx}$. Consider an arbitrary node~$t \in \oneSubtree{\tildeOnOff(\idx,)}$ and its parent $\parent(t)$. Due to the definition of $B$, both
	\begin{equation*}
		\onOff(i,t) \leq \onOff{i}{\parent(t)} \quad\text{and}\quad \depth(t) > \depth(\parent(t)) \quad \text{hold.}
	\end{equation*}
	So, by choice of the permutation~$\sigma$, we have
	\begin{equation*}
		\sigma^{-1}(\parent(t)) < \sigma^{-1}(t) \leq \idx,
	\end{equation*}
	and hence $\parent(t) \in \oneSubtree{\tildeOnOff(\idx,)}$ too. As noted in the motivation preceding this lemma, this condition is equivalent to \enquote{$\oneSubtree{\tildeOnOff(\idx,)}$ contains the root of $B$ and is a tree}, and thus \cref{result:SCS_PointsOnFacet} implies that $(\tildeOnOff(\idx,), \DiscreteStartupCostSum(\tildeOnOff(\idx,)))$ lies on the facet induced by $B$.

	Being a convex combination of such points, the point $(\onOff(i,), \sum_{\idx = 1}^T \lambda_\idx \DiscreteStartupCostSum(\tildeOnOff(\idx,)))$ lies on the same facet, implying $\StartupCostSum(\onOff(i,)) = \sum_{\idx = 1}^T \lambda_\idx \DiscreteStartupCostSum(\tildeOnOff(\idx,))$ and therefore that $(\onOff(i,),\StartupCostSum(\onOff(i,)))$ lies on the facet of $\scsEpigraph$ induced by $B$.\manualqed
\end{proof}

Note that \cref{result:SCS_FracPointsOnFacet} is a generalization of \cref{result:SCS_PointsOnFacet}, since for discrete vectors $\squeeze{\onOff(i,) \in \set{0,1}^T}$ the induced subgraph $\oneSubtree{\onOff(i,)}$ is a Cartesian tree for~$\onOff(i,)$ iff it is empty or a tree containing $\root(B)$.

By the last result, each BTI defines a part of the lower boundary of $\scsEpigraph$, and thereby also a part of $\StartupCostSum$.
\begin{corollary}
	\label[corollary]{result:SCS_ExplicitFunction}
	If $B \in \scsBinaryTrees$ is a Cartesian tree for $\onOff(i,) \in [0,1]^T$, then
	\begin{equation*}
		\StartupCostSum(\onOff(i,)) = \sum_{t \in \Periods} \scsSumDiff{t}(\leftSize(t),\rightSize(t)) \, \onOff(i,t).
	\end{equation*}
\end{corollary}

%
By definition, a Cartesian tree for some~$\onOff(i,)$ is also a Cartesian tree for~$\lambda\onOff(i,)$ with $\lambda \geq 0$, which means \cref{result:SCS_ExplicitFunction} states that $\StartupCostSum$ is homogeneous.
\begin{corollary}
	\label[corollary]{result:SCS_Homogeneous}
	$\StartupCostSum$ is homogeneous, \ie
	\begin{equation*}
		\forall\, \lambda \in [0,1], \onOff(i,) \in [0,1]^T: \qquad \lambda\StartupCostSum(\onOff(i,)) = \StartupCostSum(\lambda \onOff(i,)).
	\end{equation*}
\end{corollary}
%

Since epigraphs are characterized by their lower boundary, this is equivalent to:
\begin{corollary}
	\label[corollary]{result:SCS_Separation}
	If $(\onOff(i,),\startupCostSum) \in [0,1]^T \times \reals$ and $B \in \scsBinaryTrees$ is a Cartesian tree for $\onOff(i,)$, then $(\onOff(i,), \startupCostSum)$ lies in $\scsEpigraph$ iff it fulfills the BTI induced by $B$.
\end{corollary}
\begin{proof}
\mbox{}\vskip-2.3\baselineskip
\begin{align*}
	(\onOff(i,),\startupCostSum) \in \scsEpigraph &\equals \startupCostSum \geq \StartupCostSum(\onOff(i,)) = \sum_{t \in \Periods} \scsSumDiff{t}(\leftSize(t),\rightSize(t)) \onOff(i,t)\\
	&\equals (\onOff(i,),\startupCostSum) \text{ fulfills the BTI induced by $B$}.\eqqed{3.9em}
\end{align*}
\end{proof}

Finally, since there exists a rank-labeled Cartesian tree for each $\onOff(i,) \in [0,1]^T$ (\cite{gabow_scaling_1984}), the BTIs and the trivial inequalities $0 \leq \onOff(i,t) \leq 1$ completely describe $\scsEpigraph$.
\begin{theorem}
	\label[theorem]{result:SCS_HRepresentation}
	\begin{equation}
		\label{equation:SCS_HRepresentation}
		\scsEpigraph = \set*{
			\begin{gathered}
				(\onOff(i,),\startupCostSum) \in \reals^{T+1} \subjectTo \hspace*{\fill}\\
				\qquad\begin{alignedat}{2}
					\startupCostSum &\geq \sum_{t \in \Periods} \scsSumDiff{t}( \leftSize(t), \rightSize(t)) \, \onOff(i,t), &\qquad& B \in \scsBinaryTrees\\
				0 & \leq \onOff(i,t) \leq 1, && t \in \Periods
				\end{alignedat}\
			\end{gathered}}.
	\end{equation}
\end{theorem}

It remains to discuss whether this \hrepresentation is irredundant. As noted in the paragraph before \cref{result:SCS_PointsNotOnFacet}, if the start-up cost function~$\StartupCostFunction(i,)$ is not strictly concave, \eg if $\StartupCostFunction(i,)$ is linear, then a vertex~$(\onOff(i,),\DiscreteStartupCostSum(\onOff(i,)))$ may fulfill a BTI induced by a binary tree~$B \in \scsBinaryTrees$ which is not a Cartesian tree for~$\onOff(i,)$. This leads to multiple binary trees inducing the same facet of $\scsEpigraph$, rendering the above \hrepresentation redundant.

However, if $\StartupCostFunction(i,)$ is strictly concave, \cref{result:SCS_PointsNotOnFacet} describes all vertices~$(\onOff(i,),\DiscreteStartupCostSum(\onOff(i,)))$ on a facet. By showing that different binary trees induce facets with different vertices, we prove that the given \hrepresentation is irredundant.
\begin{theorem}
	\label[theorem]{result:SCS_StrictlyConcave_Irredundant}
	If $\StartupCostFunction(i,)$ is strictly concave, then the \hrepresentation~\eqref{equation:SCS_HRepresentation} of $\scsEpigraph$ is irredundant.
\end{theorem}
\begin{proof}
	For each $B_1,B_2 \in \scsBinaryTrees$ with $B_1 \neq B_2$, we construct a vertex~$(\onOff(,),\DiscreteStartupCostSum(\onOff(,))) \in \scsVertices$ such that $B_1$ is a Cartesian tree for $\onOff(,)$, but $B_2$ is not a Cartesian tree for $\onOff(,)$. Then, by \cref{result:SCS_PointsOnFacet}, $(\onOff(,),\DiscreteStartupCostSum(\onOff(,)))$ lies on the facet induced by $B_1$, and by \cref{result:SCS_PointsNotOnFacet}, $(\onOff(,),\DiscreteStartupCostSum(\onOff(,)))$ does not lie on the facet induced by $B_2$, proving that the induced facets are not equal.
	
	If $\root(B_1) \neq \root(B_2)$, then $(\unitVec{\root(B_1)},\DiscreteStartupCostSum(\unitVec{\root(B_1)}))$ clearly is such a vertex. Otherwise, we have $r := \root(B_1) = \root(B_2)$, and therefore the edge sets~$E_1$ of $B_1$ and $E_2$ of $B_2$ differ. Each edge in $B_1$ connects a node~$t$ to its parent~$\parentT(B_1,t)$. Choose $e = \set{t,\parentT(B_1,t)} \in E_1 \setminus E_2$ with minimal~$\depth(t)$. Since $e \notin E_2$ and $t \neq r$, $t$ has different parents $p_1 := \parentT(B_1,t)$ and $p_2 := \parentT(B_2,t)$ in $B_1$ and $B_2$. Now, denote the path from $r$ to $p_1$ in $B_1$ by $P$, and define $\onOff(,) \in \set{0,1}^T$ as
	\begin{equation*}
		\forall\, \tau \in \Periods: \qquad \onOff(,\tau) := \begin{cases}
			1 & \text{if $\tau = t$ or $\tau \in P$,}\\
			0 & \text{else.}
		\end{cases}
	\end{equation*}
	By definition, $B_1$ is a Cartesian tree for $\onOff(,)$.
	
	We conclude this proof by showing that $p_2 \notin P$, which implies $\onOff(,p_2) = 0$, and thereby that $B_2$ is not a Cartesian tree for $\onOff(,)$: Assume $p_2 \in P$. Then, since choosing $e$ such that $\depth(t)$ is minimal, we have $P \subseteq B_2$, and therefore $p_1$ is a descendant of $p_2$ in both $B_1$ and $B_2$. Since $t$ is a child of $p_2$ in $B_2$ and $t \notin P$, it holds that $t$ and $p_1$ are separated to the subtrees~$\leftSubtreeT(B_2,p_2)$ and $\rightSubtreeT(B_2,p_2)$ of $p_2$, and thus either $t < p_2 < p_1$ or $p_1 < p_2 < t$. However, $t$ is a child of $p_1$ in $B_1$, and thus both, $p_1$ and $t$, either lie in the left subtree~$\leftSubtreeT(B_1,p_2)$ or right subtree~$\rightSubtreeT(B_1,p_2)$ of $p_2$ in $B_1$. Since this implies either $t,p_1 < p_2$ or $p_2 < t,p_1$, we obtain a contradiction, proving $p_2 \notin P$.\manualqed
\end{proof}

By \cite{rosen_handbook_1999}, the number of different binary trees on $T$ nodes is the $T$-th Catalan number, which allows us to count the number of facets of $\scsEpigraph$.
\begin{corollary}
	\label[corollary]{result:SCS_CatalanManyFacets}
	If $\StartupCostFunction(i,)$ is strictly concave, the number of facets of $\scsEpigraph$ is
	\begin{equation*}
		C_T + 2T \sim \frac{4^T}{T^{\frac{3}{2}} \sqrt{\pi}},
	\end{equation*}
	where $C_T$ denotes the $T$-th Catalan number.
\end{corollary}

IntroductionSpecific.tex
\section{Preliminaries}
\label{section:IntroductionSpecific}

Every unit incurs costs on start-up, mainly due to the need for reheating and extra maintenance to mitigate the effects of thermal stress. These start-up costs depend on the length~$L$ of the preceding offline time, and are assumed to be given for each unit~$i$ as
\begin{equation}
	\label{equation:SC_FunctionForTime}
 	\StartupCostFunction(i,): \quad \nonnegativeReals \to \nonnegativeReals, \quad L \mapsto \text{cost after offline time of length~$L$.}
\end{equation}

\noindent $\StartupCostFunction(i,)$ is usually described as \enquote{exponential} (\cite{wood_power_1996}), and defined as
\begin{equation}
	\label{equation:SC_ThermalStartupCosts}
	\forallUnits, L \in \nnreals: \qquad \StartupCostFunction(i,L) = \smash[t]{\begin{cases}
		\heatingCost(i) (1 - \exp{\heatloss(i) L}) + \fixedStartupCost(i) & \text{if $L > 0$,}\\
		0 & \text{else.}
	\end{cases}}
\end{equation}
with parameters $\heatingCost(i) > 0$, $\fixedStartupCost(i) \geq 0$, $\heatloss(i) > 0$ (\cf \cref{figure:SC_Function}).

\input{pics/Function}

In \cite{silbernagl_improving_2014} we present how to exploit the exponential definition of the start-up costs. Here however, we only need $\StartupCostFunction(i,)$ to be non-negative, increasing, and concave, with $\StartupCostFunction(i,0) = 0$.

The modeled time range is discretized into $T$ periods of possibly varying lengths~$\periodLength(1)\mkern-3mu, \ldots, \periodLength(T)\mkern-5mu$. Furthermore, we assume the unit's offline time prior to period~$1$ to be given as $\preOffline(i)$ (\emph{p}re-model \emph{o}ffline \emph{t}ime). To simplify notation, we also discretize the start-up cost functions such that $\StartupCost(i,t,l)$ denotes the costs of a start-up of unit~$i$ in period~$t$, which was offline during the previous~$l$ periods. To this end, we define the function $\offlineLength(t,l)$ as the offline time in that situation, that is
\begin{equation}
	\label{equation:SC_OfflineLength}
	\forallPeriods,\, l \in \discrange*{0}{t-1}: \qquad \offlineLength(t,l) := \begin{cases}
		\sum_{\idx = 1}^{l} \periodLength(t-\idx) & \text{if $l < t-1$,}\\
		\sum_{\idx = 1}^{l} \periodLength(t-\idx) + \preOffline(i) & \text{if $l = t-1$.}
	\end{cases}
\end{equation}

The above case distinction differentiates between the case where the offline time lies completely within the modeled time range and the case where it stretches to include the pre-model offline time $\preOffline(i)$. The corresponding start-up costs $\StartupCost(i,t,l)$ are
\begin{equation}
	\label{equation:SC_FunctionForPeriods}
	\forallPeriods,\, l \in \discrange*{0}{t-1}: \qquad \StartupCost(i,t,l) := \StartupCostFunction{i}{\offlineLength(t,l)}.
\end{equation}

 As noted, the operational state of a unit is modeled by the variables~$\onOff(i,t) \in \set{0,1}$, where $\onOff(i,t) = 1$ iff unit~$i$ is online in period~$t$. Deriving the start-up costs in each period~$t$ from these variables yields the \emph{discrete start-up cost functions}
\begin{gather}
	\label{equation:SC_FunctionForVector}
	\forallUnitsPeriods: \quad \DiscreteStartupCost(i,t): \ \ \set{0,1}^T \to \nnreals, \ \ \onOff(i,) \mapsto \begin{cases}\StartupCost{i}{t}{\offlineNumber(t,\onOff(i,))} & \text{if } \onOff(i,t) = 1\\
		0 & \text{else,}
	\end{cases}
	%
	\shortintertext{where}
	%
	\label{equation:SC_OfflineNumber}
	\offlineNumber(t,\onOff(i,)) := \max \set[\big]{l \in \discrange*{1}{t-1} \given \onOff(i,t-1) = \ldots = \onOff(i,t-l) = 0}.
\end{gather}%

\noindent In \cref{figure:SC_Schedule} this relationship is depicted for an exemplary operational schedule. Note that $\offlineNumber(,)$ and $\offlineLength(,)$ follow the notational convention of $l$ and $\periodLength()$ to denote numbers of periods in lower case and time lengths in upper case.

\input{pics/Schedule}

In virtually all published Unit Commitment formulations which consider start-up costs, the sum of the start-up costs is minimized, motivating the definition
\begin{equation}
	\label{equation:SCS_DiscreteStartupCostSum}
	\forallUnits: \qquad \DiscreteStartupCostSum: \quad \set{0,1}^T \to \nnreals,\quad \onOff(i,) \mapsto \sum_{t=1}^T \DiscreteStartupCost(i,t)(\onOff(i,)).
\end{equation}

\newcommand{\allOnOff}{\squeeze{\onOff(1,),\ldots,\onOff(\abs{\Units},)}}

\noindent Using $\DiscreteStartupCostSum$, any Unit Commitment problem with start-up costs can be written as
\begin{equation}
	\label{equation:SCS_GeneralUnitCommitment}
	\min \set[\bigg]{ c(\allOnOff,z) + \sum_{i \in \Units} \DiscreteStartupCostSum(\onOff(i,)) \given (\allOnOff,z) \in \mathcal{F}},
\end{equation}
with additional variables~$z \in \reals^n$, feasible set~$\squeeze{\mathcal{F} \subseteq \set{0,1}^{T\abs{\Units}} \times \reals^n}$, and objective function~$c$. For example, in a typical Unit Commitment problem $z$ may stand for electricity output and cost variables, and $\mathcal{F}$ may model production limits and costs, ramping speed limits, and minimal up- and downtime. Recognize, even in case the objective~$c$ is linear, due to $\DiscreteStartupCostSum$ the extended objective is non-linear.

Since the domain~$\set{0,1}^T$ of $\DiscreteStartupCostSum$ is finite, the convex hull of its epigraph,
\begin{gather}
	\label{equation:SCS_EpigraphVRepresentation}
	\begin{aligned}
		\conv(\epi(\DiscreteStartupCostSum)) &= \conv\left(\set[\big]{(\onOff(i,),\startupCostSum) \given \onOff(i,) \in \set{0,1}^T, \startupCostSum \geq \DiscreteStartupCostSum(\onOff(i,))}\right)\\
	%
			&= \conv(\scsVertices) + \pos(\unitVec{T+1}),
	\end{aligned}
	%
	\intertext{is a polyhedron with unbounded direction $\unitVec{T+1}$ (where $\unitVec{T+1}$ denotes the unit vector in the direction of the last coordinate $\startupCostSum$), and with vertices}
	%
	\label{equation:SCS_Vertices}
	\scsVertices= \set[\big]{(\onOff(i,),\DiscreteStartupCostSum(\onOff(i,))) \given \onOff(i,) \in \set{0,1}^T}.
\end{gather}
The domain~$\set{0,1}^T$ of $\DiscreteStartupCostSum$ is extremal in its convex hull~$[0,1]^T$. Therefore, using the convex hull corresponds to extending $\DiscreteStartupCostSum$ to fractional vectors~$\onOff(i,) \in [0,1]^T$, \ie to the unique function~$\StartupCostSum$ with
\vskip-1ex
\begin{equation}
	\label{equation:SCS_StartupCostSum}
	\scsEpigraph = \conv(\epi(\DiscreteStartupCostSum)).
\end{equation}
So, by introducing the variables~$\startupCostSum$, the minimization problem~\eqref{equation:SCS_GeneralUnitCommitment} can be rewritten as
\begin{equation}
	\label{equation:SCS_GeneralUnitCommitmentEpigraph}
	\min \set[\bigg]{ c(\allOnOff,z) + \sum_{\mathclap{i \in \Units}} \startupCostSum \given \forall\, i \in \mkern-2mu\Units: (\onOff(i,),\startupCostSum) \in \scsEpigraph, (\allOnOff,z) \in \mathcal{F}}.
\end{equation}
If $c$ is affine linear and $\mathcal{F}$ is expressible in a Mixed Integer Program (MIP), then \eqref{equation:SCS_GeneralUnitCommitmentEpigraph} is a MIP as well, since the polyhedral~$\scsEpigraph$ may be modeled using its \vrepresentation in \eqref{equation:SCS_EpigraphVRepresentation} (see \cite{dantzig_decomposition_1960} for details).

Due to the $2^T$ vertices of~$\scsEpigraph$ however, this would lead to an excessive model size. All existing approaches, including among others \cite{nowak_stochastic_2000,carrion_computationally_2006,simoglou_optimal_2010}, mitigate this by modeling sets which enclose $\scsEpigraph$, in \hrepresentation. In this publication, we provide an exact \hrepresentation of $\scsEpigraph$, accompanied by an exact separation algorithm with running time~$\bigO(T)$. At its core, our contribution results from four observations:
\begin{enumerate}
  \item Iteratively lifting a trivial inequality variable by variable results in facets of $\scsEpigraph$ and in coefficients which can be derived explicitly from the lifting order.
  \item Multiple lifting orders result in the same facet. Each lifted facet is already uniquely described by a special partial order, which can be expressed as a binary tree, warranting the name \emph{binary tree inequality} (BTI) for the lifted inequalities.
  \item The binary tree associated to a lifted facet readily identifies the points on this facet. Furthermore, these facets describe the complete lower boundary (with respect to the last coordinate~$\startupCostSum$) of the epigraph, proving that it does not have further non-trivial facets.
  \item For a fractional point, a suitable binary tree and the coefficients of the respective lifted facet can be determined efficiently.
\end{enumerate}

\noindent These observations are presented as follows:
\begin{itemize}
  \item in Section~\ref{section:SCS_Lifting} the result of lifting a trivial inequality is analyzed,
  \item in Section~\ref{section:SCS_BT} special notation for binary trees is introduced,
  \item in Section~\ref{section:SCS_BinaryTreeInequalities} the so-called \emph{binary tree inequalities} are derived and shown to be facet-inducing,
  \item in Section~\ref{section:SCS_HRepresentation} these inequalities are shown to complete the \hrepresentation of the epigraph of the summed start-up costs, and finally
  \item in Section~\ref{section:SCS_Separation} an exact separation algorithm is presented.
\end{itemize}
Since all these sections consider the epigraph~$\scsEpigraph$ of a single unit, we drop the unit index~$i$ in the following.
\def\defaultCompany{i}

Lifting.tex
\section{Lifting Inequalities}
\label{section:SCS_Lifting}

\providecommand{\liftNext}{{q}}

In this subsection, we observe that by lifting the trivial inequality $\startupCostSum \geq 0$, we gain facet-inducing inequalities with explicitly derivable coefficients.

%
The choice of~$\startupCostSum \geq 0$ as a starting point is motivated by the properties of $\DiscreteStartupCost(i,t)$, which imply that $\StartupCostSum$ is homogeneous, \ie that $\lambda\StartupCostSum(\onOff(i,)) = \StartupCostSum(\lambda \onOff(i,))$ for all $\lambda \in [0,1]$, $\onOff(i,) \in [0,1]^T$ (this follows explicitly from \cite{silbernagl_thesis} and implicitly from \cref{result:SCS_Homogeneous} later).
It holds for all $(x,y) \in [0,1]^T \mkern-4mu\times \reals$, $\lambda \in (0,1]$ that
%
\begin{align*}
	(\onOff(i,),\startupCostSum) \in \scsEpigraph &\equals \startupCostSum \geq \StartupCostSum(\onOff(i,)) \equals \lambda \startupCostSum \geq \lambda \StartupCostSum(\onOff(i,)) = \StartupCostSum(\lambda \onOff(i,))\\
	&\equals \lambda(\onOff(i,),\startupCostSum) \in \scsEpigraph.
\end{align*}
This means, $\scsEpigraph$ is the intersection of a cone with $[0,1]^T \times \reals$, and thus all facets of $\scsEpigraph$, except those induced by $0 \leq \onOff(i,t) \leq 1$, must also be facets of this cone. Hence, the facet-inducing inequalities are homogeneous, \ie without constant term, and since $\startupCostSum$ is not bounded from above in $\scsEpigraph$, of the kind
\begin{equation}
	\label{equation:SCS_LiftedInequality}
	\startupCostSum \geq \sum_{t \in \Periods} \bticoeff(t) \onOff(i,t).
\end{equation}

\newvar{liftSpace}{1}{\mathcal{F}^{#1}(\sigma)}
\newvar{liftVector}{2}{\onOff{#1}{#2}(\sigma)}
\newvar{liftSpaceInc}{1}{\mathcal{F}^{#1}_1(\sigma)}
Starting from $\startupCostSum \geq 0$, such facets can be identified using the standard sequential lifting method (see \eg \cite{bertsimas_optimization_2005}). For each order $\sigma: \Periods \to \Periods$, this method determines the coefficients~$\bticoeff{\sigma(\idx)}$ consecutively by considering the start-up costs for operational schedules~$\onOff(i,)$ with coordinates~$\sigma(\idx+1), \ldots, \sigma(T)$ fixed to $0$,
\begin{align*}
	\forall\, \idx \in \discrange{0}{T}: \qquad \liftSpace(\idx) &:= \set[\Big]{\onOff(i,) \in \set{0,1}^T \given \forall\, k \in \discrange*{\idx+1}{T}: \onOff{\idx}{\sigma(\idxx)} = 0}.\\
%
	\intertext{Here, each $\smash{\liftSpace(\idx)}$ extends $\smash{\liftSpace(\idx-1)}$ by all $\onOff(i,)$ with $\smash{\onOff{\idx}{\sigma(\idx)}} = 1$,}
%
	\forall\, \idx \in \discrange{1}{T}: \qquad \liftSpaceInc(\idx) &:= \liftSpace(\idx) \setminus \liftSpace(\idx-1) = \set{\onOff(,) \in \liftSpace(\idx), \onOff{}{\sigma(\idx)} = 1}.
\end{align*}
Being fulfilled by $0 \in \scsEpigraph$ with equality, $\startupCostSum \geq 0$ induces a 0-dimensional face of $\scsEpigraph$. By determining the coefficients~$\bticoeff{\sigma(\idx)}$ as
\begin{equation}
	\label{equation:SCS_LiftingCoefficient}
	\forall\, \idx \in \discrange{1}{T}: \qquad \bticoeff{\sigma(\idx)} := \min \set[\bigg]{\DiscreteStartupCostSum(\onOff(i,)) - \sum_{\idxx=1}^{\idx-1} \bticoeff{\sigma(\idxx)} \onOffBraces{i}{\sigma(\idxx)} \given \onOff(,) \in \liftSpaceInc(\idx)},
\end{equation}
the sequential lifting method produces a series of inequalities defining $\idx$-faces of $\scsEpigraph$, culminating in a facet of $\scsEpigraph$.

We claim that the minimum in \eqref{equation:SCS_LiftingCoefficient} is attained by the vectors $\liftVector(\idx,) \in \liftSpaceInc(\idx)$ with
\begin{equation}
	\label{equation:SCS_LiftingVectors}
	\forallPeriods: \qquad \liftVector(\idx,) := \liftVector(\idx-1,) + \unitVec{\idx},
\end{equation}
using $\liftVector(0,) := (0,\ldots,0)$. The coefficients of the lifted inequality would thus equate to
\begin{equation}
	\label{equation:SCS_LiftingCoefficientsClaim1}
	\begin{aligned}
		\forall\, j \in \discrange{1}{T}: \qquad \bticoeff{\sigma(\idx)} &= \DiscreteStartupCostSum(\liftVector(\idx,))-\DiscreteStartupCostSum(\liftVector(\idx-1,))\\
		&= \DiscreteStartupCostSum(\liftVector(\idx-1,) + \unitVec{\sigma(\idx)})-\DiscreteStartupCostSum(\liftVector(\idx-1,)).
	\end{aligned}
\end{equation}

To prove this, a closer look at the change of the summed start-up costs that defines $\bticoeff{\sigma(\idx)}$ is necessary. This change depends on $\liftVector(\idx-1,)$ and $\sigma(\idx)$, and not on the relative lifting order of $\sigma(1), \ldots, \sigma(\idx-1)$ and $\sigma(\idx+1), \ldots, \sigma(T)$. We express this by considering $\smash{\onOff(i,),\tildeOnOff(i,) \in \set{0,1}^T}$ and $t \in \Periods$ with $\tildeOnOff(i,) = \onOff(i,) + \unitVec{t}$ in place of $\liftVector(\idx-1,)$, $\liftVector(\idx,)$, and $\sigma(\idx)$.

\newpage
As can be seen in \cref{figure:SCS_LiftingExample}, there are at most two indices $\tau \in \Periods$ such that the start-up costs $\StartupCost{i}{\tau}{\onOff(i,)}$ and $\StartupCost{i}{\tau}{\tildeOnOff(i,)}$ differ,
\begin{enumerate*}
  		\item the index $t$ itself, and
  		\item the minimal index $\liftNext \in \discrange*{t+1}{T}$ with $\onOff(i,\liftNext) = 1$, if such an index exists.
\end{enumerate*}

These start-up costs depend on the number of offline periods immediately before and after period~$\sigma(\idx)$. The number of offline periods preceding $\sigma(\idx)$ is given by $\offlineNumber{\sigma(\idx)}{\tildeOnOff(i,)}$ (see \eqref{equation:SC_OfflineLength}). For each $\onOff(i,) \in \set{0,1}^T$, $t \in \Periods$, we define a symmetric function for the offline periods succeeding $t$ as
\begin{equation}
	\label{equation:SCS_OfflineNumberRight}
	\offlineNumberRight{t}{\onOff(i,)} := \max\set{\idx \in \discrange*{0}{T-t} \given \tildeOnOff(i,t+1) = \tildeOnOff(i,t+2) = \ldots = \tildeOnOff(i,t+\idx) = 0}.
\end{equation}

\input{pics/LiftingExample}

So, for two operational schedules~$\onOff(i,),\tildeOnOff(i,) \in \set{0,1}^T$ which differ solely in period~$t$, the start-up costs are unequal in periods~$t$ and $t + \offlineNumberRight{t}{\tildeOnOff(i,)}$.
	Abbreviating $l := \offlineNumber{t}{\tildeOnOff(i,)}$ and $r := \offlineNumberRight{t}{\tildeOnOff(i,)}$, we obtain
\begin{equation*}
	\DiscreteStartupCostSum(\tildeOnOff(i,)) - \DiscreteStartupCostSum(\onOff(i,))
%
	= \begin{cases}
		\DiscreteStartupCost(i,t)(\tildeOnOff(i,)) + \DiscreteStartupCost{i}{t + r + 1}(\tildeOnOff(i,)) - \DiscreteStartupCost{i}{t + r + 1}(\onOff(,)) & \text{ if $t + r < T$},\\
%
		\DiscreteStartupCost(i,t)(\tildeOnOff(i,)) & \text{ else.}
	\end{cases}
\end{equation*}
Thus, the change in the summed start-up costs depends only on the offline periods prior and after~$t$, and can be further simplified.

\begin{proposition}
	\label[proposition]{result:SCS_SumUpdate}
	For each $\onOff(i,), \tildeOnOff(i,) \in \set{0,1}^T$ and $t \in \Periods$ with $\tildeOnOff(i,) = \onOff(i,) + \unitVec{t}$, it holds
	\begin{gather*}
		\DiscreteStartupCostSum(\tildeOnOff(i,)) - \DiscreteStartupCostSum(\onOff(i,)) = \scsSumDiff{t}(\offlineNumber{t}{\tildeOnOff(i,)},\offlineNumberRight{t}{\tildeOnOff(i,)}),
%
		\shortintertext{where}
%
		\begin{aligned}
			\scsSumDiff{t}:\quad &\discrange*{0}{t-1} \times \discrange*{0}{T-t} \to \reals\\
			&(l,r) \mapsto \begin{cases}
			\StartupCost(i,t,l) + \StartupCost(i,t + r + 1, r) - \StartupCost(i,t + r + 1,l + r + 1) & \text{ if $t + r < T$},\\
%
			\StartupCost(i,t,l) & \text{else.}
		\end{cases}
		\end{aligned}
	\end{gather*}
\end{proposition}

The following lemma shows where the concavity of the start-up cost function~$\StartupCostFunction(i,)$ is used.
\begin{lemma}
	\label[lemma]{result:SCS_SumDiffIncreasing}
	For each $t \in \Periods$, $\scsSumDiff{t}$ is increasing in $l$ and $r$ if $\StartupCostFunction(i,)$ is concave, and strictly increasing if $\StartupCostFunction(i,)$ is strictly concave.
\end{lemma}
\begin{proof}
	Let $t \in \Periods$, $l, \tilde{l} \in \discrange*{0}{t-1}$ with $l < \tilde{l}$ and $r,\tilde{r} \in \discrange*{0}{T-t}$  with $r < \tilde{r}$ be given. Denote the period indices
	\begin{equation*}
		\liftNext := t + r + 1 \quad\text{and}\quad \tilde{\liftNext} := t + \tilde{r} + 1,
	\end{equation*}
	as seen in \cref{figure:SCS_LiftingExample}, implying $\liftNext < \tilde{\liftNext}$.  Recall that by definition, $\StartupCost(i,t,l) = \StartupCostFunction{i}{\offlineLength(t,l)}$, where $\offlineLength(t,l)$ denotes the offline length corresponding to $l$ offline periods prior to period~$t$ (see \eqref{equation:SC_FunctionForPeriods}). In \cref{figure:SCS_LiftingExample} for example, $l$ corresponds to $\offlineNumber{t}{\tildeOnOff(i,)}$ and $r$ corresponds to $\offlineNumberRight{t}{\tildeOnOff(i,)}$. So, $\offlineLength(q,l+r+1)$ is the offline time prior to~$q$ in $\onOff(i,)$, and $\offlineLength(q,r)$ and $\offlineLength(t,l)$ are the offline times prior to $q$ and $t$ in $\tildeOnOff(i,)$, respectively. Hence
	\begin{equation*}
		\offlineLength(q,l+r+1) = \offlineLength(q,r+1) + \offlineLength(t,l).
%
	\end{equation*}
		
	\noindent We start by proving that $\scsSumDiff{t}$ is increasing in $l$. For $t + r = T$, $\scsSumDiff{t}$ increases in~$l$ since $\StartupCost(i,t,)$ increases,
	\begin{equation*}
		\scsSumDiff{t}(\tilde{l},r) - \scsSumDiff{t}(l,r) = \StartupCost(i, t, \tilde{l}) - \StartupCost(i, t, l) \geq 0.
	\end{equation*}
	
	\noindent For $t+r < T$, we obtain 
	\begin{align*}
		\scsSumDiff{t}(\tilde{l},&r) - \scsSumDiff{t}(l,r)
%
		= \StartupCost(i,q,r) + \StartupCost(i,t,\tilde{l}) - \StartupCost(i,q,\tilde{l}+r+1)\\
%
		&\phantom{r)- \scsSumDiff{t}(l,r) =} - \Big(\StartupCost(i,q,r) + \StartupCost(i,t,l) - \StartupCost(i,q,l+r+1)\Big)\\
%
		&= \left(\StartupCost(i,t,\tilde{l}) - \StartupCost(i,t,l)\right) - \left(\StartupCost(i,q,\tilde{l}+r+1) - \StartupCost(i,1,l+r+1)\right)\\
%
		&= \left(\StartupCostFunction{i}{\offlineLength(t, \tilde{l})} - \StartupCostFunction{i}{\offlineLength(t, l)}\right) - \left(\StartupCostFunction{i}{\offlineLength(\liftNext, \tilde{l} + r + 1)} - \StartupCostFunction{i}{\offlineLength(\liftNext, l + r + 1)}\right)\\
%
		&= \left(\StartupCostFunction{i}{\offlineLength(t, l) + \offlineLength(t-l-1, \tilde{l} - l)} - \StartupCostFunction{i}{\offlineLength(t, l)}\right)\\
		&\phantom{=}- \left(\StartupCostFunction{i}{\offlineLength(\liftNext, l + r + 1) + \offlineLength(t-l-1, \tilde{l} - l)} - \StartupCostFunction{i}{\offlineLength(\liftNext, l + r + 1)}\right)\\
%
		\intertext{which, when abbreviating $x := \offlineLength(t, l)$, $y := \offlineLength(\liftNext, l + r + 1)$, and $s := \offlineLength(t-l-1, \tilde{l} - l)$, equals}
%
		&= \Big(\StartupCostFunction{i}{x+s} - \StartupCostFunction{i}{x}\Big) - \Big(\StartupCostFunction{i}{y+s} - \StartupCostFunction{i}{y}\Big).
	\end{align*}
	The non-negativity of the final term follows from the characterization of concave functions by subdifferentials, using that $x < y$ and $s > 0$.

	The statement that $\scsSumDiff{t}$ is increasing in $r$ follows analogously in the case of $t + \tilde{r} < T$. If $t + \tilde{r} = T$, then
	\begin{align*}
		\scsSumDiff{t}(l,\tilde{r}) - \scsSumDiff{t}(l,r)
%
		&= \StartupCost(i,t, l) - \Big( \StartupCost(i,t, l) + \StartupCost(i, \liftNext, r) - \StartupCost(i, \liftNext, l + r + 1)\Big)\\
%
			&= \StartupCost(i, \liftNext, l + r + 1) - \StartupCost(i, \liftNext, r) \geq 0.
	\end{align*}
	
	Finally, in case of a strictly concave start-up cost function $\StartupCostFunction(i,)$, all of the above inequalities are also strict.\manualqed
\end{proof}

Using $\scsSumDiff{\sigma(j)}$, our claim regarding the lifted coefficients~(see \eqref{equation:SCS_LiftingCoefficientsClaim1}) may be restated as
\def\claim{\scsSumDiff{\sigma(j)}(\offlineNumber{\sigma(\idx)}{\onOff(\idx,)},\offlineNumberRight{\sigma(\idx)}{\onOff(\idx,)})}
\begin{gather*}
	\bticoeff{\sigma(\idx)} = \claim.
\end{gather*}

\newpage
Based on \cref{result:SCS_SumDiffIncreasing}, this could be proved by induction over $\idx$. Furthermore, \cite{bertsimas_optimization_2005} show that, as $\startupCostSum \geq 0$ is valid for $\scsEpigraph$, these inequalities define facets of $\scsEpigraph$. Since the current subsection is intended to be purely motivational, we prefer to re-introduce the lifted inequalities in Section~\ref{section:SCS_BinaryTreeInequalities}, and prove that they induce facets without referring to the sequential lifting method. The necessary steps are essentially the same:
\begin{itemize}
  \item proving that the lifted inequalities are feasible requires the same arguments as showing $\bticoeff{\sigma(\idx)} \leq \claim$, and
  \item proving that these inequalities induce facets requires the same arguments as showing $\bticoeff{\sigma(\idx)} \geq \claim$.
\end{itemize}

tikz.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesPackageRCS[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/frontendlayer/tikz/tikz.code.tex,v 1.142 2013/12/13 15:11:58 tantau Exp $


\def\tikzerror#1{\pgfutil@packageerror{tikz}{#1}{}}

% Always-present libraries (|\usepgflibrary| defined in
% \file{pgfutil-common.tex}).
\usepgflibrary{plothandlers}

\newdimen\tikz@lastx
\newdimen\tikz@lasty
\newdimen\tikz@lastxsaved
\newdimen\tikz@lastysaved

\newdimen\tikzleveldistance
\newdimen\tikzsiblingdistance

\newbox\tikz@figbox
\newbox\tikz@figbox@bg
\newbox\tikz@tempbox
\newbox\tikz@tempbox@bg

\newcount\tikztreelevel
\newcount\tikznumberofchildren
\newcount\tikznumberofcurrentchild

\newcount\tikz@fig@count

\newif\iftikz@node@is@a@label
\newif\iftikz@snaked
\newif\iftikz@decoratepath

% |\pgfutil@empty| is defined in \file{pgfutil-common.tex}.
\let\tikz@options=\pgfutil@empty
% |\tikz@addoption| adds \texttt{#1} at the end of the replacement
% text of |\tikz@options| without expansion.
\def\tikz@addoption#1{%
  \expandafter\def\expandafter\tikz@options\expandafter{\tikz@options#1}}
% Same as |tikz@addoption| for |\tikz@mode|. Note that |\tikz@mode| is
% initially let to |\pgfutil@empty| later (see path usage options).
\def\tikz@addmode#1{%
  \expandafter\def\expandafter\tikz@mode\expandafter{\tikz@mode#1}}
% Same as |tikz@addoption| for |\tikz@transform|. Works even if
% |\tikz@transform| is not defined. In that case, nothing is added to
% |\tikz@transform|: \texttt{#1} is expanded.
\def\tikz@addtransform#1{%
  \ifx\tikz@transform\relax
    #1%
  \else
    \expandafter\def\expandafter\tikz@transform\expandafter{\tikz@transform#1}%
  \fi}


% TikZ options management.

% Setting up the tikz key family (key management needs
% \file{pgfkeys.code.tex});
\pgfkeys{/tikz/.is family}

% |\tikzset| is a shortcut to set keys that belongs to the tikz
% family.
\def\tikzset{\pgfqkeys{/tikz}}

% Note: |\tikzoption| is supported for compatibility only. |\tikzset|
% should be used instead.
\def\tikzoption#1{%
  \pgfutil@ifnextchar[%]
    {\tikzoption@opt{#1}}{\tikzoption@noopt{#1}}}
\def\tikzoption@opt#1[#2]#3{%
  \pgfkeysdef{/tikz/#1}{#3}%
  \pgfkeyssetvalue{/tikz/#1/.@def}{#2}}
\def\tikzoption@noopt#1#2{%
  \pgfkeysdef{/tikz/#1}{#2}%
  \pgfkeyssetvalue{/tikz/#1/.@def}{\pgfkeysvaluerequired}}

% Baseline options
\tikzoption{baseline}[0pt]{%
  \pgfutil@ifnextchar(%)
    {\tikz@baseline@coordinate}{\tikz@baseline@simple}#1\@nil}
\def\tikz@baseline@simple#1\@nil{\pgfsetbaseline{#1}}
\def\tikz@baseline@coordinate#1\@nil{%
  \pgfsetbaselinepointlater{\tikz@scan@one@point\pgfutil@firstofone#1}}

\tikzoption{trim left}[0pt]{\pgfutil@ifnextchar({\tikz@trim@coordinate{left}}{\tikz@trim@simple{left}}#1\@nil}%)
\tikzoption{trim right}{\pgfutil@ifnextchar({\tikz@trim@coordinate{right}}{\tikz@trim@simple{right}}#1\@nil}%)
\def\tikz@trim@simple#1#2\@nil{\csname pgfsettrim#1\endcsname{#2}}
\def\tikz@trim@coordinate#1#2\@nil{\csname pgfsettrim#1pointlater\endcsname{\tikz@scan@one@point\pgfutil@firstofone#2}}

% Draw options
\tikzoption{line width}{\tikz@semiaddlinewidth{#1}}%

\def\tikz@semiaddlinewidth#1{\tikz@addoption{\pgfsetlinewidth{#1}}\pgfmathsetlength\pgflinewidth{#1}}

\tikzoption{cap}{\tikz@addoption{\csname pgfset#1cap\endcsname}}
\tikzoption{join}{\tikz@addoption{\csname pgfset#1join\endcsname}}
\tikzoption{line cap}{\tikz@addoption{\csname pgfset#1cap\endcsname}}
\tikzoption{line join}{\tikz@addoption{\csname pgfset#1join\endcsname}}
\tikzoption{miter limit}{\tikz@addoption{\pgfsetmiterlimit{#1}}}

\tikzoption{dash pattern}{% syntax: on 2pt off 3pt on 4pt ...
  \def\tikz@temp{#1}%
  \ifx\tikz@temp\pgfutil@empty%
    \def\tikz@dashpattern{}%
    \tikz@addoption{\pgfsetdash{}{0pt}}%
  \else%
    \def\tikz@dashpattern{}%
    \expandafter\tikz@scandashon\pgfutil@gobble#1o\@nil%
    \edef\tikz@temp{{\tikz@dashpattern}{\noexpand\tikz@dashphase}}%
    \expandafter\tikz@addoption\expandafter{\expandafter\pgfsetdash\tikz@temp}%
  \fi}
\tikzoption{dash phase}{%
  \def\tikz@dashphase{#1}%
  \edef\tikz@temp{{\tikz@dashpattern}{\noexpand\tikz@dashphase}}%
  \expandafter\tikz@addoption\expandafter{\expandafter\pgfsetdash\tikz@temp}%
}%
\def\tikz@dashphase{0pt}
\def\tikz@dashpattern{}

\def\tikz@scandashon n#1o{%
  \expandafter\def\expandafter\tikz@dashpattern\expandafter{\tikz@dashpattern{#1}}%
  \pgfutil@ifnextchar\@nil{\pgfutil@gobble}{\tikz@scandashoff}}
\def\tikz@scandashoff ff#1o{%
  \expandafter\def\expandafter\tikz@dashpattern\expandafter{\tikz@dashpattern{#1}}%
  \pgfutil@ifnextchar\@nil{\pgfutil@gobble}{\tikz@scandashon}}

\tikzoption{draw opacity}{\tikz@addoption{\pgfsetstrokeopacity{#1}}}

% Double draw options
\tikzoption{double}[]{%
  \def\tikz@temp{#1}%
  \ifx\tikz@temp\tikz@nonetext%
    \tikz@addmode{\tikz@mode@doublefalse}%
  \else%
    \ifx\tikz@temp\pgfutil@empty%
    \else%
      \pgfsetinnerstrokecolor{#1}%
    \fi%
    \tikz@addmode{\tikz@mode@doubletrue}%
    \tikzset{every double/.try}%
  \fi}
\tikzoption{double distance}{%
  \pgfmathsetlength{\pgf@x}{#1}%
  \edef\tikz@double@setup{%
    \pgf@x=\the\pgf@x%
    \advance\pgf@x by2\pgflinewidth%
    \pgflinewidth=\pgf@x%
    \noexpand\pgfsetlinewidth{\pgflinewidth}%
    \noexpand\pgfsetinnerlinewidth{\the\pgf@x}%
  }%
  \tikzset{double}}
\def\tikz@double@setup{%
  \pgf@x=2\pgflinewidth%
  \advance\pgf@x by0.6pt%
  \pgflinewidth=\pgf@x%
  \pgfsetlinewidth{\pgflinewidth}%
  \pgfsetinnerlinewidth{0.6pt}%
}%
\tikzset{double distance between line centers/.code={
  \pgfmathsetlength{\pgf@x}{#1}%
  \edef\tikz@double@setup{%
    \pgf@x=\pgflinewidth%
    \pgf@xa=\the\pgf@x%
    \advance\pgf@x by\pgf@xa%
    \advance\pgf@xa by-\pgflinewidth%
    \pgflinewidth=\pgf@x%
    \noexpand\pgfsetlinewidth{\pgflinewidth}%
    \noexpand\pgfsetinnerlinewidth{\pgf@xa}%
  }%
  \tikzset{double}}}
\tikzset{double equal sign distance/.style={double distance between line centers=0.45ex}}




% Fill options

\tikzoption{even odd rule}[]{\tikz@addoption{\pgfseteorule}}
\tikzoption{nonzero rule}[]{\tikz@addoption{\pgfsetnonzerorule}}

\tikzoption{fill opacity}{\tikz@addoption{\pgfsetfillopacity{#1}}}


% Joined fill/draw options

\tikzoption{opacity}{\tikz@addoption{\pgfsetstrokeopacity{#1}\pgfsetfillopacity{#1}}}


% Blend mode

\tikzset{blend mode/.code={\tikz@addoption{\pgfsetblendmode{#1}}}}


% Main color options
\tikzoption{color}{%
  \tikz@addoption{%
    \ifx\tikz@fillcolor\pgfutil@empty%
      \ifx\tikz@strokecolor\pgfutil@empty%
      \else%
        \pgfsys@color@reset@inorderfalse%
        \let\tikz@strokecolor\pgfutil@empty%
        \let\tikz@fillcolor\pgfutil@empty%
      \fi%
    \else%
      \pgfsys@color@reset@inorderfalse%
      \let\tikz@strokecolor\pgfutil@empty%
      \let\tikz@fillcolor\pgfutil@empty%
    \fi%
    \pgfutil@colorlet{tikz@color}{#1}%
    \pgfutil@colorlet{.}{tikz@color}%
    %
    \pgfsetcolor{.}%
    \pgfsys@color@reset@inordertrue%
  }%
  \def\tikz@textcolor{#1}}



% Rounding options
\tikzoption{rounded corners}[4pt]{\pgfsetcornersarced{\pgfpoint{#1}{#1}}}
\tikzoption{sharp corners}[]{\pgfsetcornersarced{\pgfpointorigin}}

% Radii and arc options
\tikzset{x radius/.initial=0pt}
\tikzset{y radius/.initial=0pt}
\tikzset{radius/.style={/tikz/x radius=#1,/tikz/y radius=#1}}
\tikzset{start angle/.initial=}
\tikzset{end angle/.initial=}
\tikzset{delta angle/.initial=}


% Coordinate options
\tikzoption{x}{\tikz@handle@vec{\pgfsetxvec}{\tikz@handle@x}#1\relax}
\tikzoption{y}{\tikz@handle@vec{\pgfsetyvec}{\tikz@handle@y}#1\relax}
\tikzoption{z}{\tikz@handle@vec{\pgfsetzvec}{\tikz@handle@z}#1\relax}

\def\tikz@handle@vec#1#2{\pgfutil@ifnextchar({\tikz@handle@coordinate#1}{\tikz@handle@single#2}}
\def\tikz@handle@coordinate#1{\tikz@scan@one@point#1}
\def\tikz@handle@single#1#2\relax{#1{#2}}
\def\tikz@handle@x#1{\pgfsetxvec{\pgfpoint{#1}{0pt}}}
\def\tikz@handle@y#1{\pgfsetyvec{\pgfpoint{0pt}{#1}}}
\def\tikz@handle@z#1{\pgfsetzvec{\pgfpoint{#1}{#1}}}


% Transformation options
\tikzoption{scale}{\tikz@addtransform{\pgftransformscale{#1}}}
\tikzoption{scale around}{\tikz@addtransform{\def\tikz@aroundaction{\pgftransformscale}\tikz@doaround{#1}}}
\tikzoption{xscale}{\tikz@addtransform{\pgftransformxscale{#1}}}
\tikzoption{xslant}{\tikz@addtransform{\pgftransformxslant{#1}}}
\tikzoption{yscale}{\tikz@addtransform{\pgftransformyscale{#1}}}
\tikzoption{yslant}{\tikz@addtransform{\pgftransformyslant{#1}}}
\tikzoption{rotate}{\tikz@addtransform{\pgftransformrotate{#1}}}
\tikzoption{rotate around}{\tikz@addtransform{\def\tikz@aroundaction{\pgftransformrotate}\tikz@doaround{#1}}}
\def\tikz@doaround#1{%
  \edef\tikz@temp{#1}% get rid of active stuff
  \expandafter\tikz@doparseA\tikz@temp%
}%
\def\tikz@doparseA#1:{%
  \def\tikz@temp@rot{#1}%
  \tikz@scan@one@point\tikz@doparseB%
}
\def\tikz@doparseB#1{%
  \pgf@process{#1}%
  \pgf@xc=\pgf@x%
  \pgf@yc=\pgf@y%
  \pgftransformshift{\pgfqpoint{\pgf@xc}{\pgf@yc}}%
  \tikz@aroundaction{\tikz@temp@rot}%
  \pgftransformshift{\pgfqpoint{-\pgf@xc}{-\pgf@yc}}%
}

\tikzoption{shift}{\tikz@addtransform{\tikz@scan@one@point\pgftransformshift#1\relax}}
\tikzoption{xshift}{\tikz@addtransform{\pgftransformxshift{#1}}}
\tikzoption{yshift}{\tikz@addtransform{\pgftransformyshift{#1}}}
\tikzoption{cm}{\tikz@addtransform{\tikz@parse@cm#1\relax}}
\tikzoption{reset cm}[]{\tikz@addtransform{\pgftransformreset}}
\tikzoption{shift only}[]{\tikz@addtransform{\pgftransformresetnontranslations}}

\def\tikz@parse@cm#1,#2,#3,#4,{%
  \def\tikz@p@cm{{#1}{#2}{#3}{#4}}%
  \tikz@scan@one@point\tikz@parse@cmA}
\def\tikz@parse@cmA#1{%
  \expandafter\pgftransformcm\tikz@p@cm{#1}%
}

\tikzset{transform canvas/.code=%
  {%
    \tikz@addoption
    {%
      {%
        \pgftransformreset%
        \let\tikz@transform=\relax%
        \tikzset{#1}%
        \pgflowlevelsynccm%
      }%
      \pgf@relevantforpicturesizefalse%
    }%
  }%
}

\tikzset{turn/.code={%
    \pgf@x=0pt%
    \pgf@y\pgf@x%
    \pgf@process{\tikz@tangent}%
    \advance\pgf@x by-\tikz@lastx%
    \advance\pgf@y by-\tikz@lasty%
    \pgfpointnormalised{}% x/y = normalised vector
    \pgf@x=-\pgf@x%
    \pgf@ya=-\pgf@y%
    \pgftransformcm%
    {\pgf@sys@tonumber{\pgf@x}}{\pgf@sys@tonumber{\pgf@ya}}%
    {\pgf@sys@tonumber{\pgf@y}}{\pgf@sys@tonumber{\pgf@x}}{\pgfqpoint{\tikz@lastx}{\tikz@lasty}}%
  }%
}

\def\tikz@tangent@lookup{%
  \pgfgetpath\tikz@temp%
  \pgfprocesspathextractpoints\tikz@temp%
  \pgfpointsecondlastonpath%
}

% Code for rotating the xyz coordinate system
% around the x, y, or z vector.
%
\def\tikz@xyz@rotate@let{%
  \let\pgf@z=\pgf@yc
  \let\pgf@za=\pgf@xc%
}

\def\tikz@xyz@rotate@xyz@xaxis#1#2#3#4{%
  \tikz@xyz@rotate@let%
  \pgf@x=#1\relax%
  \pgf@ya=#2\relax%
  \pgf@za=#3\relax%
  \pgfmathsin@{#4}\let\tikz@xyz@sin=\pgfmathresult%
  \pgfmathcos@{#4}\let\tikz@xyz@cos=\pgfmathresult%
  \pgf@y=\tikz@xyz@cos\pgf@ya%
  \advance\pgf@y by-\tikz@xyz@sin\pgf@za%
  \pgf@z=\tikz@xyz@sin\pgf@ya%
  \advance\pgf@z by\tikz@xyz@cos\pgf@za%
}

\def\tikz@xyz@rotate@xyz@yaxis#1#2#3#4{%
  \tikz@xyz@rotate@let%
  \pgf@xa=#1\relax%
  \pgf@y=#2\relax%
  \pgf@za=#3\relax%
  \pgfmathsin@{#4}\let\tikz@xyz@sin=\pgfmathresult%
  \pgfmathcos@{#4}\let\tikz@xyz@cos=\pgfmathresult%
  \pgf@x=\tikz@xyz@cos\pgf@xa%
  \advance\pgf@x by\tikz@xyz@sin\pgf@za%
  \pgf@z=-\tikz@xyz@sin\pgf@xa%
  \advance\pgf@z by\tikz@xyz@cos\pgf@za%
}

\def\tikz@xyz@rotate@xyz@zaxis#1#2#3#4{%
  \tikz@xyz@rotate@let%
  \pgf@xa=#1\relax%
  \pgf@ya=#2\relax%
  \pgf@z=#3\relax%
  \pgfmathsin@{#4}\let\tikz@xyz@sin=\pgfmathresult%
  \pgfmathcos@{#4}\let\tikz@xyz@cos=\pgfmathresult%
  \pgf@x=\tikz@xyz@cos\pgf@xa%
  \advance\pgf@x by-\tikz@xyz@sin\pgf@ya%
  \pgf@y=\tikz@xyz@sin\pgf@xa%
  \advance\pgf@y by\tikz@xyz@cos\pgf@ya%
}

\tikzset{rotate around x/.code={%
    \tikz@xyz@rotate@let%
    \tikz@xyz@rotate@xyz@xaxis{0pt}{1pt}{0pt}{#1}%
    \pgfextract@process\tikz@xyz@rotate@yvec{\pgfpointxyz{\pgf@sys@tonumber{\pgf@x}}{\pgf@sys@tonumber{\pgf@y}}{\pgf@sys@tonumber{\pgf@z}}}%
    \tikz@xyz@rotate@xyz@xaxis{0pt}{0pt}{1pt}{#1}%
    \pgfsetzvec{\pgfpointxyz{\pgf@sys@tonumber{\pgf@x}}{\pgf@sys@tonumber{\pgf@y}}{\pgf@sys@tonumber{\pgf@z}}}%
    \pgfsetyvec{\tikz@xyz@rotate@yvec}%
  },
  rotate around y/.code={%
    \tikz@xyz@rotate@let%
    \tikz@xyz@rotate@xyz@yaxis{1pt}{0pt}{0pt}{#1}%
    \pgfextract@process\tikz@xyz@rotate@xvec{\pgfpointxyz{\pgf@sys@tonumber{\pgf@x}}{\pgf@sys@tonumber{\pgf@y}}{\pgf@sys@tonumber{\pgf@z}}}%
    \tikz@xyz@rotate@xyz@yaxis{0pt}{0pt}{1pt}{#1}%
    \pgfsetzvec{\pgfpointxyz{\pgf@sys@tonumber{\pgf@x}}{\pgf@sys@tonumber{\pgf@y}}{\pgf@sys@tonumber{\pgf@z}}}%
    \pgfsetxvec{\tikz@xyz@rotate@xvec}%
  },
  rotate around z/.code={%
    \tikz@xyz@rotate@let%
    \tikz@xyz@rotate@xyz@zaxis{1pt}{0pt}{0pt}{#1}%
    \pgfextract@process\tikz@xyz@rotate@xvec{\pgfpointxyz{\pgf@sys@tonumber{\pgf@x}}{\pgf@sys@tonumber{\pgf@y}}{\pgf@sys@tonumber{\pgf@z}}}%
    \tikz@xyz@rotate@xyz@zaxis{0pt}{1pt}{0pt}{#1}%
    \pgfsetyvec{\pgfpointxyz{\pgf@sys@tonumber{\pgf@x}}{\pgf@sys@tonumber{\pgf@y}}{\pgf@sys@tonumber{\pgf@z}}}%
    \pgfsetxvec{\tikz@xyz@rotate@xvec}%
  }
}

% Grid options
\tikzoption{xstep}{\def\tikz@grid@x{#1}}
\tikzoption{ystep}{\def\tikz@grid@y{#1}}
\tikzoption{step}{\tikz@handle@vec{\tikz@step@point}{\tikz@step@single}#1\relax}
\def\tikz@step@single#1{\def\tikz@grid@x{#1}\def\tikz@grid@y{#1}}
\def\tikz@step@point#1{\pgf@process{#1}\edef\tikz@grid@x{\the\pgf@x}\edef\tikz@grid@y{\the\pgf@y}}

\def\tikz@grid@x{1cm}
\def\tikz@grid@y{1cm}


% Current point updates
\newif\iftikz@current@point@local
\tikzset{current point is local/.is if=tikz@current@point@local}

% Path usage options
\newif\iftikz@mode@double
\newif\iftikz@mode@fill
\newif\iftikz@mode@draw
\newif\iftikz@mode@clip
\newif\iftikz@mode@boundary
\newif\iftikz@mode@shade
\newif\iftikz@mode@fade@path
\newif\iftikz@mode@fade@scope
\let\tikz@mode=\pgfutil@empty

\def\tikz@nonetext{none}

\tikzoption{path only}[]{\let\tikz@mode=\pgfutil@empty}
\tikzset{
  shade/.is choice,
  shade/.default=true,
  shade/true/.code=\tikz@addmode{\tikz@mode@shadetrue},
  shade/false/.code=\tikz@addmode{\tikz@mode@shadefalse},
  shade/none/.code=\tikz@addmode{\tikz@mode@shadefalse},
}

\tikzoption{fill}[]{%
  \edef\tikz@temp{#1}%
  \ifx\tikz@temp\tikz@nonetext%
    \tikz@addmode{\tikz@mode@fillfalse}%
  \else%
    \ifx\tikz@temp\pgfutil@empty%
    \else%
      \tikz@addoption{\pgfsetfillcolor{#1}}%
      \def\tikz@fillcolor{#1}%
    \fi%
    \tikz@addmode{\tikz@mode@filltrue}%
  \fi%
}
\tikzoption{draw}[]{%
  \edef\tikz@temp{#1}%
  \ifx\tikz@temp\tikz@nonetext%
    \tikz@addmode{\tikz@mode@drawfalse}%
  \else%
    \ifx\tikz@temp\pgfutil@empty%
    \else%
      \tikz@addoption{\pgfsetstrokecolor{#1}}%
      \def\tikz@strokecolor{#1}%
    \fi%
    \tikz@addmode{\tikz@mode@drawtrue}%
  \fi%
}
\tikzoption{clip}[]{\tikz@addmode{\tikz@mode@cliptrue}}
\tikzoption{use as bounding box}[]{\tikz@addmode{\tikz@mode@boundarytrue}}

\tikzoption{save path}{\tikz@addmode{\pgfsyssoftpath@getcurrentpath#1\global\let#1=#1}}

\let\tikz@fillcolor=\pgfutil@empty
\let\tikz@strokecolor=\pgfutil@empty

% Insert a path using an option
\tikzset{insert path/.code=\tikz@scan@next@command#1\pgf@stop}

% Pattern options
\tikzset{pattern/.code=\tikzerror{You need to say \string\usetikzlibrary{patterns}},
         pattern color/.style=pattern}

% Path pictures
\tikzset{path picture/.code=\tikz@addmode{\def\tikz@path@picture{#1}}}       

% Fading options
\tikzset{path fading/.code={
  \def\tikz@temp{#1}%
  \ifx\tikz@temp\tikz@nonetext%
    \tikz@addmode{\tikz@mode@fade@pathfalse}%
  \else%
    \ifx\tikz@temp\pgfutil@empty%
    \else%
      \def\tikz@path@fading{#1}%
    \fi%
    \tikz@addmode{\tikz@mode@fade@pathtrue}%
  \fi%
  },
  path fading/.default=, 
  scope fading/.code={
  \def\tikz@temp{#1}%
  \ifx\tikz@temp\tikz@nonetext%
    \tikz@addmode{\tikz@mode@fade@scopefalse}%
  \else%
    \ifx\tikz@temp\pgfutil@empty%
    \else%
      \def\tikz@scope@fading{#1}%
    \fi%
    \tikz@addmode{\tikz@mode@fade@scopetrue}%
  \fi%
  },
  scope fading/.default=}
\tikzset{fit fading/.is if=tikz@fade@adjust}
\tikzset{fading transform/.store in=\tikz@fade@transform}
\tikzset{fading angle/.style={fading transform={rotate=#1}}}

\newif\iftikz@fade@adjust
\tikz@fade@adjusttrue
\let\tikz@fade@transform\pgfutil@empty

\pgfutil@colorlet{transparent}{pgftransparent}
\def\tikz@do@fade@transform{\let\tikz@transform=\relax\expandafter\tikzset\expandafter{\tikz@fade@transform}}



% Transparency groups
\newif\iftikz@transparency@group
\tikzset{/tikz/transparency group/.code=\tikz@transparency@grouptrue\def\tikz@transparency@group@options{isolated=true,#1}\let\tikz@blend@group\pgfutil@empty}
\tikzset{/tikz/blend group/.code=\tikz@transparency@grouptrue\def\tikz@transparency@group@options{isolated=true}\def\tikz@blend@group{\pgfsetblendmode{#1}}}

\let\tikz@blend@group\pgfutil@empty

% Shading options
\tikzoption{shading}{\def\tikz@shading{#1}\tikz@addmode{\tikz@mode@shadetrue}}
\tikzoption{shading angle}{\def\tikz@shade@angle{#1}\tikz@addmode{\tikz@mode@shadetrue}}
\tikzoption{top color}{%
  \pgfutil@colorlet{tikz@axis@top}{#1}%
  \pgfutil@colorlet{tikz@axis@middle}{tikz@axis@top!50!tikz@axis@bottom}%
  \def\tikz@shading{axis}\def\tikz@shade@angle{0}\tikz@addmode{\tikz@mode@shadetrue}}
\tikzoption{bottom color}{%
  \pgfutil@colorlet{tikz@axis@bottom}{#1}%
  \pgfutil@colorlet{tikz@axis@middle}{tikz@axis@top!50!tikz@axis@bottom}%
  \def\tikz@shading{axis}\def\tikz@shade@angle{0}\tikz@addmode{\tikz@mode@shadetrue}}
\tikzoption{middle color}{%
  \pgfutil@colorlet{tikz@axis@middle}{#1}%
  \def\tikz@shading{axis}\tikz@addmode{\tikz@mode@shadetrue}}
\tikzoption{left color}{%
  \pgfutil@colorlet{tikz@axis@top}{#1}%
  \pgfutil@colorlet{tikz@axis@middle}{tikz@axis@top!50!tikz@axis@bottom}%
  \def\tikz@shading{axis}\def\tikz@shade@angle{90}\tikz@addmode{\tikz@mode@shadetrue}}
\tikzoption{right color}{%
  \pgfutil@colorlet{tikz@axis@bottom}{#1}%
  \pgfutil@colorlet{tikz@axis@middle}{tikz@axis@top!50!tikz@axis@bottom}%
  \def\tikz@shading{axis}\def\tikz@shade@angle{90}\tikz@addmode{\tikz@mode@shadetrue}}
\tikzoption{ball color}{\pgfutil@colorlet{tikz@ball}{#1}\def\tikz@shading{ball}\tikz@addmode{\tikz@mode@shadetrue}}
\tikzoption{inner color}{\pgfutil@colorlet{tikz@radial@inner}{#1}\def\tikz@shading{radial}\tikz@addmode{\tikz@mode@shadetrue}}
\tikzoption{outer color}{\pgfutil@colorlet{tikz@radial@outer}{#1}\def\tikz@shading{radial}\tikz@addmode{\tikz@mode@shadetrue}}

\def\tikz@shading{axis}
\def\tikz@shade@angle{0}

\pgfdeclareverticalshading[tikz@axis@top,tikz@axis@middle,tikz@axis@bottom]{axis}{100bp}{%
  color(0bp)=(tikz@axis@bottom);
  color(25bp)=(tikz@axis@bottom);
  color(50bp)=(tikz@axis@middle);
  color(75bp)=(tikz@axis@top);
  color(100bp)=(tikz@axis@top)}

\pgfutil@colorlet{tikz@axis@top}{gray}
\pgfutil@colorlet{tikz@axis@middle}{gray!50!white}
\pgfutil@colorlet{tikz@axis@bottom}{white}

\pgfdeclareradialshading[tikz@ball]{ball}{\pgfqpoint{-10bp}{10bp}}{%
 color(0bp)=(tikz@ball!15!white);
 color(9bp)=(tikz@ball!75!white);
 color(18bp)=(tikz@ball!70!black);
 color(25bp)=(tikz@ball!50!black);
 color(50bp)=(black)}

\pgfutil@colorlet{tikz@ball}{blue}

\pgfdeclareradialshading[tikz@radial@inner,tikz@radial@outer]{radial}{\pgfpointorigin}{%
 color(0bp)=(tikz@radial@inner);
 color(25bp)=(tikz@radial@outer);
 color(50bp)=(tikz@radial@outer)}

\pgfutil@colorlet{tikz@radial@inner}{gray}
\pgfutil@colorlet{tikz@radial@outer}{white}


% Pin options
\tikzset{
  pin distance/.store in=\tikz@pin@distance,
  pin distance=3ex,
  pin position/.store in=\tikz@pin@default@pos,
  pin position=above,
  pin edge/.store in=\tikz@pin@edge@style,
  pin edge={},
  tikz@pin@post/.code={\global\let\tikz@pin@edge@style@smuggle=\tikz@pin@edge@style},
  tikz@pre@pin@edge/.code={%
    \def\pgf@marshal{\tikzstyle{tikz@pin@options}=}
    \expandafter\pgf@marshal\expandafter[\tikz@pin@edge@style@smuggle]%
  }%
}

\tikzset{%
  pin/.code={%
    \begingroup
      \ifnum\the\catcode`\:=\active\relax
        \def\tikz@next{%
          \endgroup
          \tikz@parse@pin@active@i{#1}}%
      \else
        \def\tikz@next{%
          \endgroup
          \pgfutil@ifnextchar[%]
            {\tikz@parse@pin@nonactive}
            {\tikz@parse@pin@nonactive[]}#1:\pgf@nil}%
      \fi
    \tikz@next}}

\begingroup
  \catcode`\:=\active\relax

  \gdef\tikz@parse@pin@active@i#1{%
    \pgfutil@ifnextchar[%]
      {\tikz@parse@pin@active}
      {\tikz@parse@pin@active[]}#1:\pgf@nil}
  
  \long\gdef\tikz@parse@pin@active[#1]#2:#3\pgf@nil{%
    \def\tikz@temp{#3}%
    \ifx\tikz@temp\pgfutil@empty
      % no position, use default
      \tikz@@parse@pin@active[#1]\tikz@pin@default@pos:#2:\pgf@nil%
    \else
      \tikz@@parse@pin@active[#1]#2:#3\pgf@nil%
    \fi}

  \long\gdef\tikz@@parse@pin@active[#1]#2:#3:\pgf@nil{%
    \tikzset{%
      append after command = {%
        \bgroup
          [current point is local = true]
          \pgfextra{\let\tikz@save@last@node=\tikzlastnode\tikz@node@is@a@labelfalse}%
          node [every pin,
                tikz@label@angle = #2,
                #1,
                append after command = {%
                  (\tikz@save@last@node) 
                  edge [every pin edge,
                        tikz@pre@pin@edge,
                        tikz@pin@options] 
                  (\tikzlastnode)},
                tikz@label@post = \tikz@pin@distance,
                tikz@pin@post] {#3}
        \egroup}}}
\endgroup

\long\def\tikz@parse@pin@nonactive[#1]#2:#3\pgf@nil{%
  \def\tikz@temp{#3}%
  \ifx\tikz@temp\pgfutil@empty
    % no position, use default
    \tikz@@parse@pin@nonactive[#1]\tikz@pin@default@pos:#2:\pgf@nil%
  \else
    \tikz@@parse@pin@nonactive[#1]#2:#3\pgf@nil%
  \fi}

\long\def\tikz@@parse@pin@nonactive[#1]#2:#3:\pgf@nil{%
  \tikzset{%
    append after command = {%
      \bgroup
        [current point is local = true]
        \pgfextra{\let\tikz@save@last@node=\tikzlastnode\tikz@node@is@a@labelfalse}%
        node [every pin,
              tikz@label@angle = #2,
              #1,
              append after command = {%
                (\tikz@save@last@node) 
                edge [every pin edge,
                      tikz@pre@pin@edge,
                      tikz@pin@options] 
                (\tikzlastnode)},
              tikz@label@post = \tikz@pin@distance,
              tikz@pin@post] {#3}
      \egroup}}}

% Label and pin options

\tikzset{
  label distance/.store in=\tikz@label@distance,
  label distance=0pt,
  label position/.store in=\tikz@label@default@pos,
  label position=above,
  absolute/.is if=tikz@absolute,
  tikz@label@angle/.store in=\tikz@label@angle
}

\newif\iftikz@absolute
\def\tikz@on@text{center}

\tikzset{tikz@label@post/.code 2 args={
  \edef\tikz@label@angle{\tikz@label@angle}%
  \csname tikz@label@angle@is@\tikz@label@angle\endcsname
  \ifx\tikz@label@angle\tikz@on@text%
    \def\tikz@node@at{\pgfpointanchor{\tikzlastnode}{center}}%
    \def\tikz@anchor{center}%
  \else%
    \iftikz@absolute%
      \pgftransformreset%
      \pgf@process{%
        \pgfpointshapeborder{\tikzlastnode}%
        {\pgfpointadd{\pgfpointanchor{\tikzlastnode}{center}}{\pgfpointpolar{\tikz@label@angle}{1pt}}}}%
      \edef\tikz@node@at{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
      \tikz@compute@direction{\tikz@label@angle}%
      \tikz@addtransform{\pgftransformshift{\pgfpointpolar{\tikz@label@angle}{#1}}}%  
    \else%
      \pgf@process{\pgfpointanchor{\tikzlastnode}{\tikz@label@angle}}%
      \edef\tikz@node@at{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
      \pgf@xb=\pgf@x%
      \pgf@yb=\pgf@y%
      \pgf@process{\pgfpointanchor{\tikzlastnode}{center}}%
      \pgf@xc=\pgf@x%
      \pgf@yc=\pgf@y%
      \tikz@label@simplefalse%
      \iftikz@fullytransformed%
        \tikz@label@simpletrue%
      \else
        \ifdim\pgf@xc=\pgf@xb\relax%
          \ifdim\pgf@yc=\pgf@yb\relax%
            \tikz@label@simpletrue%
          \fi%
        \fi%
      \fi%
      \iftikz@label@simple%  
        \tikz@compute@direction{\tikz@label@angle}%
        \tikz@addtransform{\pgftransformshift{\pgfpointpolar{\tikz@label@angle}{#1}}}%  
      \else%
        \pgf@process{\pgfpointnormalised{%
            \pgfpointdiff{\pgfpointtransformed{\pgfqpoint{\pgf@xc}{\pgf@yc}}}{\pgfpointtransformed{\pgfqpoint{\pgf@xb}{\pgf@yb}}}}}%
        \edef\pgf@marshal{%
          \noexpand\tikz@addtransform{\noexpand\pgftransformshift{\noexpand\pgfpointscale{#1}{
                \noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}}}}%
        \pgf@marshal%
        \pgf@xc=\pgf@x%
        \pgf@yc=\pgf@y%
        \pgf@x=\pgf@yc%
        \pgf@y=-\pgf@xc%
        \tikz@auto@anchor%
      \fi%
    \fi%
  \fi}
}
  
\newif\iftikz@label@simple%

\tikzset{%
  label/.code={%
    \begingroup
      \ifnum\the\catcode`\:=\active\relax
        \def\tikz@next{%
          \endgroup
          \tikz@parse@label@active@i{#1}}%
      \else
        \def\tikz@next{%
          \endgroup
          \pgfutil@ifnextchar[%]
            {\tikz@parse@label@nonactive}
            {\tikz@parse@label@nonactive[]}#1:\pgf@nil}%
      \fi
    \tikz@next}}

\begingroup
  \catcode`\:=\active\relax

  \gdef\tikz@parse@label@active@i#1{%
    \pgfutil@ifnextchar[%]
      {\tikz@parse@label@active}
      {\tikz@parse@label@active[]}#1:\pgf@nil}
    
  \gdef\tikz@parse@label@active[#1]#2:#3\pgf@nil{%
    \def\tikz@temp{#3}%
    \ifx\tikz@temp\pgfutil@empty
    % no position, use default
      \tikz@@parse@label@active[#1]\tikz@label@default@pos:#2:\pgf@nil%
    \else
      \def\tikz@temp{#2}%
      \ifx\tikz@temp\pgfutil@empty
        \tikz@@parse@label@active[#1]\tikz@label@default@pos:#3\pgf@nil%
      \else
        \tikz@@parse@label@active[#1]#2:#3\pgf@nil%
      \fi
    \fi
  }

  \gdef\tikz@@parse@label@active[#1]#2:#3:\pgf@nil{%
    \tikzset{%
      append after command = {%  
        \bgroup
          [current point is local=true]
          \pgfextra{\let\tikz@save@last@fig@name=\tikz@last@fig@name\tikz@node@is@a@labelfalse}
          node [every label,
                tikz@label@angle = #2,
                #1,
                tikz@label@post = \tikz@label@distance] {\iftikz@handle@active@nodes\expandafter\scantokens\else\expandafter\pgfutil@firstofone\fi{#3}}
          \pgfextra{\global\let\tikz@last@fig@name=\tikz@save@last@fig@name}
        \egroup}}}
\endgroup

\def\tikz@parse@label@nonactive[#1]#2:#3\pgf@nil{%
  \def\tikz@temp{#3}%
  \ifx\tikz@temp\pgfutil@empty
    % no position, use default
    \tikz@@parse@label@nonactive[#1]\tikz@label@default@pos:#2:\pgf@nil%
  \else
    \def\tikz@temp{#2}%
    \ifx\tikz@temp\pgfutil@empty
      \tikz@@parse@label@nonactive[#1]\tikz@label@default@pos:#3\pgf@nil%
    \else
      \tikz@@parse@label@nonactive[#1]#2:#3\pgf@nil%
    \fi
  \fi
}

\def\tikz@@parse@label@nonactive[#1]#2:#3:\pgf@nil{%
  \tikzset{%
    append after command = {%  
      \bgroup
        [current point is local=true]
        \pgfextra{\let\tikz@save@last@fig@name=\tikz@last@fig@name\tikz@node@is@a@labelfalse}
        node [every label, 
              tikz@label@angle = #2,
              #1,
              tikz@label@post = \tikz@label@distance] {\iftikz@handle@active@nodes\expandafter\scantokens\else\expandafter\pgfutil@firstofone\fi{#3}}
        \pgfextra{\global\let\tikz@last@fig@name=\tikz@save@last@fig@name}
      \egroup}}}

\expandafter\def\csname tikz@label@angle@is@right\endcsname{\def\tikz@label@angle{0}}
\expandafter\def\csname tikz@label@angle@is@above right\endcsname{\def\tikz@label@angle{45}}
\expandafter\def\csname tikz@label@angle@is@above\endcsname{\def\tikz@label@angle{90}}
\expandafter\def\csname tikz@label@angle@is@above left\endcsname{\def\tikz@label@angle{135}}
\expandafter\def\csname tikz@label@angle@is@left\endcsname{\def\tikz@label@angle{180}}
\expandafter\def\csname tikz@label@angle@is@below left\endcsname{\def\tikz@label@angle{225}}
\expandafter\def\csname tikz@label@angle@is@below\endcsname{\def\tikz@label@angle{270}}
\expandafter\def\csname tikz@label@angle@is@below right\endcsname{\def\tikz@label@angle{315}}

\def\tikz@compute@direction#1{%
  \let\tikz@do@auto@anchor=\relax
  \pgfmathsetcount{\c@pgf@counta}{#1}%
  \ifnum\c@pgf@counta<0\relax
    \advance\c@pgf@counta by 360\relax%
  \fi%
  \ifnum\c@pgf@counta>359\relax
    \advance\c@pgf@counta by-360\relax%
  \fi%
  \ifnum\c@pgf@counta<4\relax%
    \def\tikz@anchor{west}%
  \else\ifnum\c@pgf@counta<87\relax%
    \def\tikz@anchor{south west}%
  \else\ifnum\c@pgf@counta<94\relax%
    \def\tikz@anchor{south}%
  \else\ifnum\c@pgf@counta<177\relax%
    \def\tikz@anchor{south east}%
  \else\ifnum\c@pgf@counta<184\relax%
    \def\tikz@anchor{east}%
  \else\ifnum\c@pgf@counta<267\relax%
    \def\tikz@anchor{north east}%
  \else\ifnum\c@pgf@counta<274\relax%
    \def\tikz@anchor{north}%
  \else\ifnum\c@pgf@counta<357\relax%
    \def\tikz@anchor{north west}%
  \else%
    \def\tikz@anchor{west}%
  \fi\fi\fi\fi\fi\fi\fi\fi%
}


% General node options
\tikzset{
  name/.code={\edef\tikz@fig@name{\tikz@pp@name{#1}}},%
  name prefix/.initial=,%
  name suffix/.initial=%
}
\def\tikz@pp@name#1{\csname pgfk@/tikz/name prefix\endcsname#1\csname pgfk@/tikz/name suffix\endcsname}


\tikzset{
  node contents/.code=\def\tikz@node@content{#1},
  pic type/.code=\def\tikz@node@content{#1}, % alias  
}

\tikzset{
  behind path/.code=\def\tikz@whichbox{\tikz@figbox@bg},
  in front of path/.code=\def\tikz@whichbox{\tikz@figbox}
}
\def\tikz@whichbox{\tikz@figbox}

\tikzoption{at}{\tikz@scan@one@point\tikz@set@at#1}
\def\tikz@set@at#1{\def\tikz@node@at{#1}}%

\tikzoption{shape}{\edef\tikz@shape{#1}}

\tikzoption{nodes}{\tikzstyle{every node}+=[#1]}

\tikzset{alias/.code={\tikz@fig@mustbenamed\expandafter\def\expandafter\tikz@alias\expandafter{\tikz@alias\pgfnodealias{#1}{\tikz@fig@name}}}}

% deprecated:
\def\tikzaddafternodepathoption#1{#1\tikzset{prefix after command={\pgfextra{#1}}}}
\tikzset{after node path/.style={append after command={#1}}}


% Pic options
\newif\iftikz@node@is@pic
\tikzset{pic text/.store in=\tikzpictext}
\let\tikzpictext\relax
\tikzset{pic text options/.store in=\tikzpictextoptions}
\let\tikzpictextoptions\pgfutil@empty


% Anchoring

\tikzoption{anchor}{\def\tikz@anchor{#1}\let\tikz@do@auto@anchor=\relax}

\tikzoption{left}[]{\def\tikz@anchor{east}\tikz@possibly@transform{x}{-}{#1}}
\tikzoption{right}[]{\def\tikz@anchor{west}\tikz@possibly@transform{x}{}{#1}}
\tikzoption{above}[]{\def\tikz@anchor{south}\tikz@possibly@transform{y}{}{#1}}
\tikzoption{below}[]{\def\tikz@anchor{north}\tikz@possibly@transform{y}{-}{#1}}
\tikzoption{above left}[]%
  {\def\tikz@anchor{south east}%
    \tikz@possibly@transform{x}{-}{#1}\tikz@possibly@transform{y}{}{#1}}
\tikzoption{above right}[]%
  {\def\tikz@anchor{south west}%
    \tikz@possibly@transform{x}{}{#1}\tikz@possibly@transform{y}{}{#1}}
\tikzoption{below left}[]%
  {\def\tikz@anchor{north east}%
    \tikz@possibly@transform{x}{-}{#1}\tikz@possibly@transform{y}{-}{#1}}
\tikzoption{below right}[]%
  {\def\tikz@anchor{north west}%
    \tikz@possibly@transform{x}{}{#1}\tikz@possibly@transform{y}{-}{#1}}

\tikzoption{node distance}{\def\tikz@node@distance{#1}}
\def\tikz@node@distance{1cm}

% The following are deprecated:
\tikzoption{above of}{\tikz@of{#1}{90}}%
\tikzoption{below of}{\tikz@of{#1}{-90}}%
\tikzoption{left of}{\tikz@of{#1}{180}}%
\tikzoption{right of}{\tikz@of{#1}{0}}%
\tikzoption{above left of}{\tikz@of{#1}{135}}%
\tikzoption{below left of}{\tikz@of{#1}{-135}}%
\tikzoption{above right of}{\tikz@of{#1}{45}}%
\tikzoption{below right of}{\tikz@of{#1}{-45}}%
\def\tikz@of#1#2{%
  \def\tikz@anchor{center}%
  \let\tikz@do@auto@anchor=\relax%
  \tikz@addtransform{%
    \expandafter\tikz@extract@node@dist\tikz@node@distance and\pgf@stop%
    \pgftransformshift{\pgfpointpolar{#2}{\tikz@extracted@node@distance}}}%
  \def\tikz@node@at{\pgfpointanchor{#1}{center}}}
\def\tikz@extract@node@dist#1and#2\pgf@stop{%
  \def\tikz@extracted@node@distance{#1}}  

\tikzset{
  transform shape nonlinear/.is choice,
  transform shape nonlinear/.default=true,
  transform shape nonlinear/true/.code=\let\tikz@nlt\relax,
  transform shape nonlinear/false/.code=\def\tikz@nlt{\pgfapproximatenonlineartranslation},
  transform shape nonlinear=false
}


\tikzoption{transform shape}[true]{%
  \csname tikz@fullytransformed#1\endcsname%
  \iftikz@fullytransformed%
    \pgfresetnontranslationattimefalse%
  \else%
    \pgfresetnontranslationattimetrue%
  \fi%
}

\newif\iftikz@fullytransformed
\pgfresetnontranslationattimetrue%

\def\tikz@anchor{center}%
\def\tikz@shape{rectangle}%

\def\tikz@possibly@transform#1#2#3{%
  \let\tikz@do@auto@anchor=\relax%
  \def\tikz@test{#3}%
  \ifx\tikz@test\pgfutil@empty%
  \else%
    \pgfmathsetlength{\pgf@x}{#3}%
    \pgf@x=#2\pgf@x\relax%
    \edef\tikz@marshal{\noexpand\tikz@addtransform{%
        \expandafter\noexpand\csname  pgftransform#1shift\endcsname{\the\pgf@x}}}% 
    \tikz@marshal%
  \fi%
}


% Inter-picture options
\tikzoption{remember picture}[true]{\csname pgfrememberpicturepositiononpage#1\endcsname}
\tikzoption{overlay}[]{\pgf@relevantforpicturesizefalse}



% Line/curve label placement options
\tikzoption{sloped}[true]{\csname pgfslopedattime#1\endcsname}
\tikzoption{allow upside down}[true]{\csname pgfallowupsidedownattime#1\endcsname}

\tikzoption{pos}{\edef\tikz@time{#1}\ifx\tikz@time\pgfutil@empty\else\pgfmathsetmacro\tikz@time{\tikz@time}\fi}

\tikzoption{auto}[]{\csname tikz@install@auto@anchor@#1\endcsname}
\tikzoption{swap}[]{%
  \def\tikz@temp{left}%
  \ifx\tikz@auto@anchor@direction\tikz@temp%
    \def\tikz@auto@anchor@direction{right}%
  \else%
    \def\tikz@auto@anchor@direction{left}%
  \fi%
}
\tikzset{'/.style=swap} % shorthand


\def\tikz@install@auto@anchor@{\let\tikz@do@auto@anchor=\tikz@auto@anchor@on}
\def\tikz@install@auto@anchor@false{\let\tikz@do@auto@anchor=\relax}
\def\tikz@install@auto@anchor@left{\let\tikz@do@auto@anchor=\tikz@auto@anchor@on\def\tikz@auto@anchor@direction{left}}
\def\tikz@install@auto@anchor@right{\let\tikz@do@auto@anchor=\tikz@auto@anchor@on\def\tikz@auto@anchor@direction{right}}

\let\tikz@do@auto@anchor=\relax%

\def\tikz@auto@anchor@on{\csname tikz@auto@anchor@\tikz@auto@anchor@direction\endcsname}

\def\tikz@auto@anchor@left{\tikz@auto@pre\tikz@auto@anchor\tikz@auto@post}
\def\tikz@auto@anchor@right{\tikz@auto@pre\tikz@auto@anchor@prime\tikz@auto@post}

\def\tikz@auto@anchor@direction{left}

% Text options
\tikzoption{text}{\def\tikz@textcolor{#1}}
\tikzoption{font}{\def\tikz@textfont{#1}}
\tikzoption{node font}{\def\tikz@node@textfont{#1}}
\tikzoption{text opacity}{\def\tikz@textopacity{#1}}
\tikzoption{text width}{\def\tikz@text@width{#1}}
\tikzoption{text height}{\def\tikz@text@height{#1}}
\tikzoption{text depth}{\def\tikz@text@depth{#1}}
\tikzoption{text ragged}[]%
{\def\tikz@text@action{\pgfutil@raggedright\rightskip0pt plus2em \spaceskip.3333em \xspaceskip.5em\relax}}
\tikzoption{text badly ragged}[]{\def\tikz@text@action{\pgfutil@raggedright\relax}}
\tikzoption{text ragged left}[]%
{\def\tikz@text@action{\pgfutil@raggedleft\leftskip0pt plus2em \spaceskip.3333em \xspaceskip.5em\relax}}
\tikzoption{text badly ragged left}[]{\def\tikz@text@action{\pgfutil@raggedleft\relax}}
\tikzoption{text justified}[]{\def\tikz@text@action{\leftskip0pt\rightskip0pt\relax}}
\tikzoption{text centered}[]{\def\tikz@text@action{%
  \leftskip0pt plus2em%
  \rightskip0pt plus2em%
  \spaceskip.3333em \xspaceskip.5em%
  \parfillskip=0pt%
  \iftikz@warn@for@narrow@centered\else\hbadness10000\fi%
  \let\\=\@centercr% for latex
  \relax}}
\tikzoption{text badly centered}[]%
{\def\tikz@text@action{%
  \let\\=\@centercr% for latex
  \parfillskip=0pt%
  \rightskip\pgfutil@flushglue%
  \leftskip\pgfutil@flushglue\relax}}
\tikzset{badness warnings for centered text/.is if=tikz@warn@for@narrow@centered}
\newif\iftikz@warn@for@narrow@centered

\let\tikz@text@width=\pgfutil@empty
\let\tikz@text@height=\pgfutil@empty
\let\tikz@text@depth=\pgfutil@empty
\let\tikz@textcolor=\pgfutil@empty
\let\tikz@textfont=\pgfutil@empty
\let\tikz@textopacity=\pgfutil@empty
\let\tikz@node@textfont=\pgfutil@empty

\def\tikz@text@action{\pgfutil@raggedright\rightskip0pt plus2em \spaceskip.3333em \xspaceskip.5em\relax}


% Alignment
\tikzset{
  node halign header/.initial=,
  align/.is choice,
  align/left/.style  ={text ragged,node halign header=\tikz@align@left@header},
  align/flush left/.style  ={text badly ragged,node halign header=\tikz@align@left@header},
  align/right/.style ={text ragged left,node halign header=\tikz@align@right@header},
  align/flush right/.style ={text badly ragged left,node halign header=\tikz@align@right@header},
  align/center/.style={text centered,node halign header=\tikz@align@center@header},
  align/flush center/.style={text badly centered,node halign header=\tikz@align@center@header},
  align/justify/.style ={text justified,node halign header=\tikz@align@left@header},
  align/none/.style ={text justified,node halign header=}
}
\def\tikz@align@left@header{##\hfil\cr}
\def\tikz@align@right@header{\hfil##\cr}
\def\tikz@align@center@header{\hfil##\hfil\cr}



% Arrow options
\tikzoption{arrows}{\tikz@processarrows{#1}}


\tikzoption{>}{\pgfdeclarearrow{name=<->,means={#1}}}%
\pgfdeclarearrow{name=|<->|,   means={>[sep=0pt].|}}

\tikzoption{shorten <}{\pgfsetshortenstart{#1}}
\tikzoption{shorten >}{\pgfsetshortenend{#1}}

\def\tikz@processarrows#1{%
  \def\tikz@current@arrows{#1}%
  \def\tikz@temp{#1}%
  \ifx\tikz@temp\pgfutil@empty%
  \else%
    \pgfsetarrows{#1}%
  \fi%
}

\def\tikz@current@arrows{-}

% Parabola options
\tikzoption{bend}{\tikz@scan@one@point\tikz@set@parabola@bend#1\relax}%
\tikzoption{bend pos}{\def\tikz@parabola@bend@factor{#1}}
\tikzoption{parabola height}{%
  \def\tikz@parabola@bend@factor{.5}%
  \def\tikz@parabola@bend{\pgfpointadd{\pgfpoint{0pt}{#1}}{\tikz@last@position@saved}}}

\def\tikz@parabola@bend{\tikz@last@position@saved}
\def\tikz@parabola@bend@factor{0}

\def\tikz@set@parabola@bend#1{\def\tikz@parabola@bend{#1}}

% Axis options
\tikzoption{domain}{\edef\tikz@plot@domain{#1}\expandafter\tikz@plot@samples@recalc\tikz@plot@domain\relax}
\tikzoption{range}{\def\tikz@plot@range{#1}}
\tikzoption{yrange}{\def\tikz@plot@range{#1}}
\let\tikz@plot@range=\pgfutil@empty
\tikzoption{xrange}{\def\tikz@plot@xrange{#1}}
\let\tikz@plot@xrange=\pgfutil@empty

% Plot options
\tikzoption{smooth}[]{\let\tikz@plot@handler=\pgfplothandlercurveto}
\tikzoption{smooth cycle}[]{\let\tikz@plot@handler=\pgfplothandlerclosedcurve}
\tikzoption{sharp plot}[]{\let\tikz@plot@handler\pgfplothandlerlineto}
\tikzoption{sharp cycle}[]{\let\tikz@plot@handler\pgfplothandlerpolygon}

\tikzoption{tension}{\pgfsetplottension{#1}}

\tikzoption{xcomb}[]{\let\tikz@plot@handler=\pgfplothandlerxcomb}
\tikzoption{ycomb}[]{\let\tikz@plot@handler=\pgfplothandlerycomb}
\tikzoption{polar comb}[]{\let\tikz@plot@handler=\pgfplothandlerpolarcomb}
\tikzoption{ybar}[]{\let\tikz@plot@handler=\pgfplothandlerybar}
\tikzoption{ybar interval}[]{\let\tikz@plot@handler=\pgfplothandlerybarinterval}
\tikzoption{xbar interval}[]{\let\tikz@plot@handler=\pgfplothandlerxbarinterval}
\tikzoption{xbar}[]{\let\tikz@plot@handler=\pgfplothandlerxbar}
\tikzoption{const plot}[]{\let\tikz@plot@handler=\pgfplothandlerconstantlineto}
\tikzoption{const plot mark left}[]{\let\tikz@plot@handler=\pgfplothandlerconstantlineto}
\tikzoption{const plot mark right}[]{\let\tikz@plot@handler=\pgfplothandlerconstantlinetomarkright}
\tikzoption{const plot mark mid}[]{\let\tikz@plot@handler=\pgfplothandlerconstantlinetomarkmid}
\tikzoption{jump mark right}[]{\let\tikz@plot@handler=\pgfplothandlerjumpmarkright}
\tikzoption{jump mark mid}[]{\let\tikz@plot@handler=\pgfplothandlerjumpmarkmid}
\tikzoption{jump mark left}[]{\let\tikz@plot@handler=\pgfplothandlerjumpmarkleft}

\tikzoption{raw gnuplot}[true]{\csname tikz@plot@raw@gnuplot#1\endcsname}
\tikzoption{prefix}{\def\tikz@plot@prefix{#1}}
\tikzoption{id}{\def\tikz@plot@id{#1}}

\tikzoption{samples}{\pgfmathsetmacro\tikz@plot@samples{max(2,#1)}\expandafter\tikz@plot@samples@recalc\tikz@plot@domain\relax}
\tikzoption{samples at}{\def\tikz@plot@samplesat{#1}}
\tikzoption{parametric}[true]{\csname tikz@plot@parametric#1\endcsname}

\tikzoption{variable}{\def\tikz@plot@var{#1}}

\tikzoption{only marks}[]{\let\tikz@plot@handler\pgfplothandlerdiscard}

\tikzoption{mark}{%
	\def\tikz@plot@mark{#1}%
	\def\tikz@temp{none}%
	\ifx\tikz@temp\tikz@plot@mark
		\let\tikz@plot@mark=\pgfutil@empty
	\fi
}
\tikzset{
	no marks/.style={mark=none},%
	no markers/.style={mark=none},%
	every mark/.style={},
	mark options/.style={%
		every mark/.style={#1}%
	}}
\tikzoption{mark size}{\pgfsetplotmarksize{#1}}

\tikzoption{mark indices}{\def\tikz@mark@list{#1}}
\tikzoption{mark phase}{\pgfsetplotmarkphase{#1}}
\tikzoption{mark repeat}{\pgfsetplotmarkrepeat{#1}}

\let\tikz@mark@list=\pgfutil@empty

\let\tikz@plot@handler=\pgfplothandlerlineto
\let\tikz@plot@mark=\pgfutil@empty

\def\tikz@plot@samples{25}
\def\tikz@plot@domain{-5:5}
\def\tikz@plot@var{\x}
\def\tikz@plot@samplesat{-5,-4.5833333,...,5}
\def\tikz@plot@samples@recalc#1:#2\relax{%
  \begingroup
  \pgfmathparse{#1}%
  \let\tikz@temp@start=\pgfmathresult%
  \pgfmathparse{#2}%
  \let\tikz@temp@end=\pgfmathresult%
  \pgfmathsetmacro\tikz@temp@diff{(\tikz@temp@end-\tikz@temp@start)/(\tikz@plot@samples-1)}%
  %
  % this particular item is for backwards compatibility.
  % Pgfplots <= 1.8 called 'samples' in a context where the 'fpu' was
  % active... and I fear there is no simple solution to replace the
  % new \ifdim below. Sorry.
  \pgfkeys{/pgf/fpu/output format/fixed/.try}%
  %
  \pgfmathsetmacro\tikz@temp@diff@abs{abs(\tikz@temp@diff)}%
  \ifdim\tikz@temp@diff@abs pt<0.0001pt\relax%
    \edef\tikz@plot@samplesat{\tikz@temp@start,\tikz@temp@end}%
  \else%
    \pgfmathparse{\tikz@temp@start+\tikz@temp@diff}%
    \edef\tikz@plot@samplesat{\tikz@temp@start,\pgfmathresult,...,\tikz@temp@end}%
  \fi%
  \pgfmath@smuggleone\tikz@plot@samplesat
  \endgroup
}


\def\tikz@plot@prefix{\jobname.}
\def\tikz@plot@id{pgf-plot}

\newif\iftikz@plot@parametric
\newif\iftikz@plot@raw@gnuplot


%
% To and edge options
%
\tikzoption{to path}{\def\tikz@to@path{#1}}

\def\tikz@to@path{-- (\tikztotarget) \tikztonodes}

\tikzset{edge macro/.store in=\tikz@edge@macro}
\let\tikz@edge@macro\pgfutil@empty

\tikzset{
  edge node/.code={
    \expandafter\def\expandafter\tikz@tonodes\expandafter{\tikz@tonodes #1}
  },
  edge label/.style={/tikz/edge node={node[auto]{#1}}},
  edge label'/.style={/tikz/edge node={node[auto,swap]{#1}}}
}


% After command options
\tikzset{
  append after command/.code=\expandafter\def\expandafter\tikz@after@path\expandafter{\tikz@after@path#1},
  prefix after command/.code={%
    \def\tikz@temp{#1}%
    \expandafter\expandafter\expandafter\def%
    \expandafter\expandafter\expandafter\tikz@after@path%
    \expandafter\expandafter\expandafter{%
      \expandafter\tikz@temp\tikz@after@path}%
  }
}
\let\tikz@after@path\pgfutil@empty


% Tree options
\newif\iftikz@child@missing
\pgfkeys{/tikz/missing/.is if=tikz@child@missing}

\tikzset{edge from parent macro/.initial=\tikz@edge@from@parent@macro}
\def\tikz@edge@from@parent@macro#1#2{
  [style=edge from parent, #1, /utils/exec=\tikz@node@is@a@labeltrue] \tikz@edge@to@parent@path #2}

\tikzoption{edge from parent path}{\def\tikz@edge@to@parent@path{#1}}

\tikzoption{parent anchor}{\def\tikzparentanchor{.#1}\ifx\tikzparentanchor\tikz@border@text\let\tikzparentanchor\pgfutil@empty\fi}
\tikzoption{child anchor}{\def\tikzchildanchor{.#1}\ifx\tikzchildanchor\tikz@border@text\let\tikzchildanchor\pgfutil@empty\fi}

\tikzoption{level distance}{\pgfmathsetlength\tikzleveldistance{#1}}
\tikzoption{sibling distance}{\pgfmathsetlength\tikzsiblingdistance{#1}}

\tikzoption{growth function}{\let\tikz@grow=#1}

\tikzset{grow siblings on line/.style={growth function=\tikz@grow@direction}}

\tikzoption{growth parent anchor}{\def\tikz@growth@anchor{#1}}
\tikzoption{grow}{\tikz@set@growth{#1}\edef\tikz@special@level{\the\tikztreelevel}}%
\tikzoption{grow'}{\tikz@set@growth{#1}\tikz@swap@growth\edef\tikz@special@level{\the\tikztreelevel}}%

\def\tikz@growth@anchor{center}

\def\tikz@special@level{-1}% never

\def\tikz@swap@growth{%
  % Swap left and right
  \let\tikz@temp=\tikz@angle@grow@right%
  \let\tikz@angle@grow@right=\tikz@angle@grow@left%
  \let\tikz@angle@grow@left=\tikz@temp%
}%

\def\tikz@set@growth#1{%
  \let\tikz@grow=\tikz@grow@direction%
  \expandafter\ifx\csname tikz@grow@direction@#1\endcsname\relax%
    \c@pgf@counta=#1\relax%
  \else%
    \c@pgf@counta=\csname tikz@grow@direction@#1\endcsname%
  \fi%
  \edef\tikz@angle@grow{\the\c@pgf@counta}%
  \advance\c@pgf@counta by-90\relax%
  \edef\tikz@angle@grow@left{\the\c@pgf@counta}%
  \advance\c@pgf@counta by180\relax%
  \edef\tikz@angle@grow@right{\the\c@pgf@counta}%
}

\def\tikz@border@text{.border}
\let\tikzparentanchor=\pgfutil@empty
\let\tikzchildanchor=\pgfutil@empty
\def\tikz@edge@to@parent@path{(\tikzparentnode\tikzparentanchor) -- (\tikzchildnode\tikzchildanchor)}

\tikzleveldistance=15mm
\tikzsiblingdistance=15mm

\def\tikz@grow@direction@down{-90}
\def\tikz@grow@direction@up{90}
\def\tikz@grow@direction@left{180}
\def\tikz@grow@direction@right{0}

\def\tikz@grow@direction@south{-90}
\def\tikz@grow@direction@north{90}
\def\tikz@grow@direction@west{180}
\def\tikz@grow@direction@east{0}

\expandafter\def\csname tikz@grow@direction@north east\endcsname{45}
\expandafter\def\csname tikz@grow@direction@north west\endcsname{135}
\expandafter\def\csname tikz@grow@direction@south east\endcsname{-45}
\expandafter\def\csname tikz@grow@direction@south west\endcsname{-135}

\def\tikz@grow@direction{%
  \pgftransformshift{\pgfpointpolar{\tikz@angle@grow}{\tikzleveldistance}}%
  \ifnum\tikztreelevel=\tikz@special@level%
  \else%
    \pgf@xc=.5\tikzsiblingdistance%
    \c@pgf@counta=\tikznumberofchildren%
    \advance\c@pgf@counta by1\relax%
    \pgfutil@tempdima=\c@pgf@counta\pgf@xc%
    \pgftransformshift{\pgfpointpolar{\tikz@angle@grow@left}{\pgfutil@tempdima}}%
    \pgftransformshift{\pgfpointpolar{\tikz@angle@grow@right}{\tikznumberofcurrentchild\tikzsiblingdistance}}%
  \fi%
}

\tikzset{grow=down}


% Snakes are in a lib:
\tikzset{snake/.code=\tikzerror{You need to say \string\usetikzlibrary{snakes}}}

% Decorations
\tikzset{decorate/.code=\tikzerror{You need to load a  decoration library}}

% Matrix options
\usepgfmodule{matrix}

\tikzoption{matrix}[true]{\csname tikz@is@matrix#1\endcsname}

\tikzoption{matrix anchor}{\def\tikz@matrix@anchor{#1}}

\tikzoption{column sep}{\def\pgfmatrixcolumnsep{#1}}
\tikzoption{row sep}{\def\pgfmatrixrowsep{#1}}

\tikzoption{cells}{\tikzstyle{every cell}+=[#1]}

\tikzoption{ampersand replacement}{\def\tikz@ampersand@replacement{#1}}

\newif\iftikz@is@matrix
\let\tikz@matrix@anchor=\pgfutil@empty
\let\tikz@ampersand@replacement=\pgfutil@empty


% Automatic shorthand management
\tikzset{%
  handle active characters in code/.is if=tikz@handle@active@code,
  handle active characters in nodes/.is if=tikz@handle@active@nodes,
}
\newif\iftikz@handle@active@code
\newif\iftikz@handle@active@nodes


% Execute option
\tikzoption{execute at begin picture}{\expandafter\def\expandafter\tikz@atbegin@picture\expandafter{\tikz@atbegin@picture#1}}
\tikzoption{execute at end picture}{\expandafter\def\expandafter\tikz@atend@picture\expandafter{\tikz@atend@picture#1}}
\tikzoption{execute at begin scope}{\expandafter\def\expandafter\tikz@atbegin@scope\expandafter{\tikz@atbegin@scope#1}}
\tikzoption{execute at end scope}{\expandafter\def\expandafter\tikz@atend@scope\expandafter{\tikz@atend@scope#1}}
\tikzoption{execute at begin to}{\expandafter\def\expandafter\tikz@atbegin@to\expandafter{\tikz@atbegin@to#1}}
\tikzoption{execute at end to}{\expandafter\def\expandafter\tikz@atend@to\expandafter{\tikz@atend@to#1}}
\tikzoption{execute at begin node}{\expandafter\def\expandafter\tikz@atbegin@node\expandafter{\tikz@atbegin@node#1}}
\tikzoption{execute at end node}{\expandafter\def\expandafter\tikz@atend@node\expandafter{\tikz@atend@node#1}}
\tikzoption{execute at begin matrix}{\expandafter\def\expandafter\tikz@atbegin@matrix\expandafter{\tikz@atbegin@matrix#1}}
\tikzoption{execute at end matrix}{\expandafter\def\expandafter\tikz@atend@matrix\expandafter{\tikz@atend@matrix#1}}
\tikzoption{execute at begin cell}{\expandafter\def\expandafter\tikz@atbegin@cell\expandafter{\tikz@atbegin@cell#1}}
\tikzoption{execute at end cell}{\expandafter\def\expandafter\tikz@atend@cell\expandafter{\tikz@atend@cell#1}}
\tikzoption{execute at empty cell}{\expandafter\def\expandafter\tikz@at@emptycell\expandafter{\tikz@at@emptycell#1}}

\let\tikz@atbegin@picture=\pgfutil@empty
\let\tikz@atend@picture=\pgfutil@empty
\let\tikz@atbegin@scope=\pgfutil@empty
\let\tikz@atend@scope=\pgfutil@empty
\let\tikz@atbegin@to=\pgfutil@empty
\let\tikz@atend@to=\pgfutil@empty
\let\tikz@atbegin@node=\pgfutil@empty
\let\tikz@atend@node=\pgfutil@empty
\let\tikz@atbegin@cell=\pgfutil@empty
\let\tikz@atend@cell=\pgfutil@empty
\let\tikz@at@emptycell=\pgfutil@empty
\let\tikz@atbegin@matrix=\pgfutil@empty
\let\tikz@atend@matrix=\pgfutil@empty


% Pre and post actions
\tikzset{preaction/.code=\expandafter\def\expandafter\tikz@preactions\expandafter{\tikz@preactions\tikz@extra@preaction{#1}}}
\tikzset{postaction/.code=\expandafter\def\expandafter\tikz@postactions\expandafter{\tikz@postactions\tikz@extra@postaction{#1}}}
\let\tikz@preactions=\pgfutil@empty
\let\tikz@postactions=\pgfutil@empty

% Styles
\tikzoption{set style}{\tikzstyle#1}

% Handled in a special way.
\def\tikzstyle{\pgfutil@ifnextchar\bgroup\tikz@style@parseA\tikz@style@parseB}
\def\tikz@style@parseB#1={\tikz@style@parseA{#1}=}
\def\tikz@style@parseA#1#2=#3[#4]{% check for an optional argument
  \pgfutil@in@[{#2}%]
  \ifpgfutil@in@%
    \tikz@style@parseC{#1}#2={#4}%
  \else%
    \tikz@style@parseD{#1}#2={#4}%
  \fi%
}%

\def\tikz@style@parseC#1[#2]#3=#4{%
  \pgfkeys{/tikz/#1/.default={#2}}%
  \pgfutil@in@+{#3}%
  \ifpgfutil@in@%
    \pgfkeys{/tikz/#1/.append style={#4}}%
  \else%
    \pgfkeys{/tikz/#1/.style={#4}}%
  \fi}
\def\tikz@style@parseD#1#2=#3{%
  \pgfutil@in@+{#2}%
  \ifpgfutil@in@%
    \pgfkeys{/tikz/#1/.append style={#3}}%
  \else%
    \pgfkeys{/tikz/#1/.style={#3}}%
  \fi}


%
%
% Predefined styles
%
%

\tikzstyle{help lines}=              [color=gray,line width=0.2pt]

\tikzstyle{every picture}=           []
\tikzstyle{every path}=              []
\tikzstyle{every scope}=             []
\tikzstyle{every plot}=              []
\tikzstyle{every node}=              []
\tikzstyle{every child}=             []
\tikzstyle{every child node}=        []
\tikzstyle{every to}=                []
\tikzstyle{every cell}=              []
\tikzstyle{every matrix}=            []
\tikzstyle{every edge}=              [draw]
\tikzstyle{every label}=             [draw=none,fill=none]
\tikzstyle{every pin}=               [draw=none,fill=none]
\tikzstyle{every pin edge}=          [help lines]

\tikzstyle{ultra thin}=              [line width=0.1pt]
\tikzstyle{very thin}=               [line width=0.2pt]
\tikzstyle{thin}=                    [line width=0.4pt]
\tikzstyle{semithick}=               [line width=0.6pt]
\tikzstyle{thick}=                   [line width=0.8pt]
\tikzstyle{very thick}=              [line width=1.2pt]
\tikzstyle{ultra thick}=             [line width=1.6pt]

\tikzstyle{solid}=                   [dash pattern=]
\tikzstyle{dotted}=                  [dash pattern=on \pgflinewidth off 2pt]
\tikzstyle{densely dotted}=          [dash pattern=on \pgflinewidth off 1pt]
\tikzstyle{loosely dotted}=          [dash pattern=on \pgflinewidth off 4pt]
\tikzstyle{dashed}=                  [dash pattern=on 3pt off 3pt]
\tikzstyle{densely dashed}=          [dash pattern=on 3pt off 2pt]
\tikzstyle{loosely dashed}=          [dash pattern=on 3pt off 6pt]
\tikzstyle{dashdotted}=              [dash pattern=on 3pt off 2pt on \the\pgflinewidth off 2pt]
\tikzstyle{dash dot}=                [dash pattern=on 3pt off 2pt on \the\pgflinewidth off 2pt]
\tikzstyle{densely dashdotted}=      [dash pattern=on 3pt off 1pt on \the\pgflinewidth off 1pt]
\tikzstyle{densely dash dot}=        [dash pattern=on 3pt off 1pt on \the\pgflinewidth off 1pt]
\tikzstyle{loosely dashdotted}=      [dash pattern=on 3pt off 4pt on \the\pgflinewidth off 4pt]
\tikzstyle{loosely dash dot}=        [dash pattern=on 3pt off 4pt on \the\pgflinewidth off 4pt]
\tikzstyle{dashdotdotted}=           [dash pattern=on 3pt off 2pt on \the\pgflinewidth off 2pt on \the\pgflinewidth off 2pt]
\tikzstyle{densely dashdotdotted}=   [dash pattern=on 3pt off 1pt on \the\pgflinewidth off 1pt on \the\pgflinewidth off 1pt]
\tikzstyle{loosely dashdotdotted}=   [dash pattern=on 3pt off 4pt on \the\pgflinewidth off 4pt on \the\pgflinewidth off 4pt]
\tikzstyle{dash dot dot}=         [dash pattern=on 3pt off 2pt on \the\pgflinewidth off 2pt on \the\pgflinewidth off 2pt]
\tikzstyle{densely dash dot dot}=   [dash pattern=on 3pt off 1pt on \the\pgflinewidth off 1pt on \the\pgflinewidth off 1pt]
\tikzstyle{loosely dash dot dot}=   [dash pattern=on 3pt off 4pt on \the\pgflinewidth off 4pt on \the\pgflinewidth off 4pt]


\tikzstyle{transparent}=             [opacity=0]
\tikzstyle{ultra nearly transparent}=[opacity=0.05]
\tikzstyle{very nearly transparent}= [opacity=0.1]
\tikzstyle{nearly transparent}=      [opacity=0.25]
\tikzstyle{semitransparent}=         [opacity=0.5]
\tikzstyle{nearly opaque}=           [opacity=0.75]
\tikzstyle{very nearly opaque}=      [opacity=0.9]
\tikzstyle{ultra nearly opaque}=     [opacity=0.95]
\tikzstyle{opaque}=                  [opacity=1]

\tikzstyle{at start}=                [pos=0]
\tikzstyle{very near start}=         [pos=0.125]
\tikzstyle{near start}=              [pos=0.25]
\tikzstyle{midway}=                  [pos=0.5]
\tikzstyle{near end}=                [pos=0.75]
\tikzstyle{very near end}=           [pos=0.875]
\tikzstyle{at end}=                  [pos=1]

\tikzstyle{bend at start}=           [bend pos=0,bend={+(0,0)}]
\tikzstyle{bend at end}=             [bend pos=1,bend={+(0,0)}]

\tikzstyle{edge from parent}=        [draw]



%
% Setting keys
%

\pgfkeys{/tikz/style/.style=#1}

\pgfkeys{/tikz/.unknown/.code=%
  % Is it a pgf key?
  \let\tikz@key\pgfkeyscurrentname% 
  \pgfkeys{/pgf/\tikz@key/.try={#1}}%
  \ifpgfkeyssuccess%
  \else%
    \expandafter\pgfutil@in@\expandafter!\expandafter{\tikz@key}%
    \ifpgfutil@in@%
      % this is a color!
      \expandafter\tikz@addoption\expandafter{\expandafter\tikz@compat@color@set\expandafter{\tikz@key}}%
      \edef\tikz@textcolor{\tikz@key}%
    \else%
      \pgfutil@doifcolorelse{\tikz@key}
      {%     
        \expandafter\tikz@addoption\expandafter{\expandafter\tikz@compat@color@set\expandafter{\tikz@key}}%
        \edef\tikz@textcolor{\tikz@key}%
      }%
      {%
        % Ok, second chance: This might be an arrow specification:
        \expandafter\pgfutil@in@\expandafter-\expandafter{\tikz@key}%
        \ifpgfutil@in@%
          % Ah, an arrow spec!
          \expandafter\tikz@processarrows\expandafter{\tikz@key}%
        \else%
          % Ok, third chance: A shape!
          \expandafter\ifx\csname pgf@sh@s@\tikz@key\endcsname\relax%
            \pgfkeys{/errors/unknown key/.expand
            once=\expandafter{\expandafter/\expandafter t\expandafter
            i\expandafter k\expandafter z\expandafter/\tikz@key}{#1}}%
          \else%
            \edef\tikz@shape{\tikz@key}%
          \fi%
        \fi%
      }%
    \fi%
  \fi%
}
\def\tikz@compat@color@set#1{%
  \pgfutil@color{#1}\pgfutil@colorlet{pgffillcolor}{#1}%
  \expandafter\expandafter\expandafter\global%
  \expandafter\expandafter\expandafter\let\expandafter\csname\expandafter\string\expandafter\color@pgffillcolor\expandafter\endcsname\csname\string\color@pgffillcolor\endcsname%
  \expandafter\expandafter\expandafter\global%
  \expandafter\expandafter\expandafter\let\expandafter\csname\expandafter\string\expandafter\color@pgfstrokecolor\expandafter\endcsname\csname\string\color@pgffillcolor\endcsname%
}

\def\tikz@startup@env{%
  \ifnum\the\catcode`\;=\active\relax\expandafter\let\expandafter\tikz@origsemi\expandafter=\tikz@activesemicolon\fi%
  \ifnum\the\catcode`\:=\active\relax\expandafter\let\expandafter\tikz@origcolon\expandafter=\tikz@activecolon\fi%
  \ifnum\the\catcode`\|=\active\relax\expandafter\let\expandafter\tikz@origbar\expandafter=\tikz@activebar\fi%
  \tikz@deactivatthings%
  \iftikz@handle@active@code%
    \tikz@switchoff@shorthands%
  \fi%
}

%
% Main TikZ Environment
%

\def\tikzpicture{%
  \begingroup%
    \tikz@startup@env%
    \pgfutil@ifnextchar[\tikz@picture{\tikz@picture[]}}%}
\def\tikz@picture[#1]{%
  \pgfpicture%
  \let\tikz@atbegin@picture=\pgfutil@empty%
  \let\tikz@atend@picture=\pgfutil@empty%
  \let\tikz@transform=\relax%
  \def\tikz@time{.5}%
  \tikz@installcommands%
  \scope[every picture,#1]%
  \iftikz@handle@active@code%
    \tikz@switchoff@shorthands%
  \fi%
  \expandafter\tikz@atbegin@picture%
  \tikz@lib@scope@check%
}
\def\endtikzpicture{%
    \tikz@atend@picture%
    \global\let\pgf@shift@baseline@smuggle=\pgf@baseline%
    \global\let\pgf@trimleft@final@smuggle=\pgf@trimleft%
    \global\let\pgf@trimright@final@smuggle=\pgf@trimright%
    \global\let\pgf@remember@smuggle=\ifpgfrememberpicturepositiononpage%
	\pgf@remember@layerlist@globally
    \endscope%
    \let\pgf@baseline=\pgf@shift@baseline@smuggle%
    \let\pgf@trimleft=\pgf@trimleft@final@smuggle%
    \let\pgf@trimright=\pgf@trimright@final@smuggle%
    \let\ifpgfrememberpicturepositiononpage=\pgf@remember@smuggle%
	\pgf@restore@layerlist@from@global
  \endpgfpicture\endgroup}
  

% Inlined picture
%
% #1 - some code to be put in a tikzpicture environment.
%
% If the command is not followed by braces, everything up to the next
% semicolon is used as argument.
%
% Example:
%
% The rectangle \tikz{\draw (0,0) rectangle (1em,1ex)} has width 1em and
% height 1ex.


\def\tikz{%
  \begingroup%
    \tikz@startup@env%
    \pgfutil@ifnextchar[{\tikz@opt}{\tikz@opt[]}}
\def\tikz@opt[#1]{\tikzpicture[#1]\pgfutil@ifnextchar\bgroup{\tikz@}{\tikz@@single}}
\def\tikz@{\bgroup\tikz@auto@end@pathtrue\aftergroup\endtikzpicture\aftergroup\endgroup\let\pgf@temp=}
\def\tikz@@single#1{%
  \expandafter\ifx\csname tikz@protected@command\string#1\endcsname\relax%
    \expandafter\tikz@@%
  \else%
    \begingroup\def\tikz@path@do@at@end{\endgroup\endtikzpicture\endgroup}%
  \fi%
  #1%  
}  
 
\expandafter\let\csname tikz@protected@command\string\draw\endcsname\pgfutil@empty
\expandafter\let\csname tikz@protected@command\string\pattern\endcsname\pgfutil@empty
\expandafter\let\csname tikz@protected@command\string\fill\endcsname\pgfutil@empty
\expandafter\let\csname tikz@protected@command\string\filldraw\endcsname\pgfutil@empty
\expandafter\let\csname tikz@protected@command\string\shade\endcsname\pgfutil@empty
\expandafter\let\csname tikz@protected@command\string\shadedraw\endcsname\pgfutil@empty
\expandafter\let\csname tikz@protected@command\string\clip\endcsname\pgfutil@empty
\expandafter\let\csname tikz@protected@command\string\graph\endcsname\pgfutil@empty
\expandafter\let\csname tikz@protected@command\string\useasboundingbox\endcsname\pgfutil@empty
\expandafter\let\csname tikz@protected@command\string\node\endcsname\pgfutil@empty
\expandafter\let\csname tikz@protected@command\string\coordinate\endcsname\pgfutil@empty
\expandafter\let\csname tikz@protected@command\string\matrix\endcsname\pgfutil@empty
\expandafter\let\csname tikz@protected@command\string\datavisualization\endcsname\pgfutil@empty
\expandafter\let\csname tikz@protected@command\string\path\endcsname\pgfutil@empty
\expandafter\let\csname tikz@protected@command\string\pic\endcsname\pgfutil@empty

% Comment by TT: I hope I fixed the \tikz \foreach problem. The new
% version will take a conservative approach and will only do fancy
% stuff when the next keyword after \tikz is one of the following:
% \draw, \fill, \filldraw, \graph, \matrix, 
\def\tikz@@{%
  \let\tikz@next=\tikz@collectnormalsemicolon%
  \ifnum\the\catcode`\;=\active\relax%
    \let\tikz@next=\tikz@collectactivesemicolon%
  \fi%
  \tikz@next}
\def\tikz@collectnormalsemicolon#1;{#1;\endtikzpicture\endgroup}
{
  \catcode`\;=\active
  \gdef\tikz@collectactivesemicolon#1;{#1;\endtikzpicture\endgroup}
}
% End old code

% Invokes '#1' if the command is invoked withing a tikzpicture and
% '#2' if not.
\def\tikzifinpicture#1#2{%
	\pgfutil@ifundefined{filldraw}{#2}{#1}% TT: This is a wrong
                                % test! Who uses this?...
}%

%
% Environment for scoping graphic state settings
%
\def\tikz@scope@env{\pgfutil@ifnextchar[\tikz@@scope@env{\tikz@@scope@env[]}}
\def\tikz@@scope@env[#1]{%
  \pgfscope%
  \begingroup%
  \let\tikz@atbegin@scope=\pgfutil@empty%
  \let\tikz@atend@scope=\pgfutil@empty%
  \let\tikz@options=\pgfutil@empty%
  \let\tikz@mode=\pgfutil@empty%
  \tikz@transparency@groupfalse%
  \tikzset{every scope/.try,#1}%
  \tikz@options%
  \iftikz@transparency@group\expandafter\pgftransparencygroup\expandafter[\tikz@transparency@group@options]\tikz@blend@group\fi%
  \expandafter\tikz@atbegin@scope%
  \tikz@lib@scope@check%
}
\def\endtikz@scope@env{%
  \tikz@atend@scope%
  \iftikz@transparency@group\endpgftransparencygroup\fi%
  \endgroup%
  \endpgfscope%
  \tikz@lib@scope@check%
}


\def\tikz@scoped{\pgfutil@ifnextchar[{\tikz@scoped@opt}{\tikz@scoped@opt[]}}
\def\tikz@scoped@opt[#1]{\scope[#1]\pgfutil@ifnextchar\bgroup{\tikz@scoped@}{\tikz@scoped@@single}}
\def\tikz@scoped@{\bgroup\tikz@auto@end@pathtrue\aftergroup\endscope\let\pgf@temp=}
\def\tikz@scoped@@single#1{%
  \expandafter\ifx\csname tikz@scoped@protected@command\string#1\endcsname\relax%
    \expandafter\tikz@scoped@@%
  \else%
    \begingroup\def\tikz@scoped@path@do@at@end{\endgroup\endscope}%
  \fi%
  #1%  
}  
\def\tikz@scoped@@{%
  \let\tikz@scoped@next=\tikz@scoped@collectnormalsemicolon%
  \ifnum\the\catcode`\;=\active\relax%
    \let\tikz@scoped@next=\tikz@scoped@collectactivesemicolon%
  \fi%
  \tikz@scoped@next}
\def\tikz@scoped@collectnormalsemicolon#1;{#1;\endscope}
{
  \catcode`\;=\active
  \gdef\tikz@scoped@collectactivesemicolon#1;{#1;\endscope}
}
 

% Install a shortcut command which is only valid inside of a
% tikzpicture.
%
% It works in the same way as the '\path' shortcut does: it introduces
% a \let#1=#2 at the beginning of tikzpicture.
%
% #1: shortcut command inside of tikzpicture
% #2: real command name
\def\tikzaddtikzonlycommandshortcutlet#1#2{%
	\expandafter\def\expandafter\tikz@installcommands\expandafter{\tikz@installcommands
		\let#1=#2%
	}%
}%

% Has the same effect as \tikzaddtikzonlycommandshortcutlet but uses
% \def#1{#2} instead of \let.
\def\tikzaddtikzonlycommandshortcutdef#1#2{%
	\expandafter\def\expandafter\tikz@installcommands\expandafter{\tikz@installcommands
		\def#1{#2}%
	}%
}%

%
% Install the abbreviated commands
%
\def\tikz@installcommands{%
  \let\tikz@origscope=\scope%
  \let\tikz@origscoped=\scoped%
  \let\tikz@origendscope=\endscope%
  \let\tikz@origstartscope=\startscope%
  \let\tikz@origstopscope=\stopscope%
  \let\tikz@origpath=\path%
  \let\tikz@origagainpath=\againpath%
  \let\tikz@origdraw=\draw%
  \let\tikz@origpattern=\pattern%
  \let\tikz@origfill=\fill%
  \let\tikz@origfilldraw=\filldraw%
  \let\tikz@origshade=\shade%
  \let\tikz@origshadedraw=\shadedraw%
  \let\tikz@origclip=\clip%
  \let\tikz@origuseasboundingbox=\useasboundingbox%
  \let\tikz@orignode=\node%
  \let\tikz@origpic=\pic%
  \let\tikz@origcoordinate=\coordinate%
  \let\tikz@origmatrix=\matrix%
  \let\tikz@origcalendar=\calendar%
  \let\tikz@origdv=\datavisualization%
  \let\tikz@origgraph=\graph%
  %
  \let\scope=\tikz@scope@env%
  \let\scoped=\tikz@scoped%
  \let\endscope=\endtikz@scope@env%
  \let\startscope=\scope%
  \let\stopscope=\endscope%
  \let\path=\tikz@command@path%
  \let\againpath=\tikz@command@againpath%
  %
  \def\draw{\path[draw]}
  \def\pattern{\path[pattern]}
  \def\fill{\path[fill]}
  \def\filldraw{\path[fill,draw]}
  \def\shade{\path[shade]}
  \def\shadedraw{\path[shade,draw]}
  \def\clip{\path[clip]}
  \def\graph{\path graph}
  \def\useasboundingbox{\path[use as bounding box]}
  \def\node{\tikz@path@overlay{node}}
  \def\pic{\tikz@path@overlay{pic}}
  \def\coordinate{\tikz@path@overlay{coordinate}}
  \def\matrix{\tikz@path@overlay{node[matrix]}}
  \def\calendar{\tikz@lib@cal@calendar}% 
  \def\datavisualization{\tikz@lib@datavisualization}%
}
\ifx\tikz@lib@cal@calendar\@undefined
\def\tikz@lib@cal@calendar{\tikzerror{You need to say \string\usetikzlibrary{calendar} to use the \string\calendar{} command}}
\fi
\ifx\tikz@lib@datavisualization\@undefined
\def\tikz@lib@datavisualization{\tikzerror{You need to say \string\usetikzlibrary{datavisualization} to use the \string\datavisualization{} command}}
\fi

\def\tikz@path@overlay#1{%
  \let\tikz@signal@path=\tikz@signal@path% for detection at begin of matrix cell
  \pgfutil@ifnextchar<{\tikz@path@overlayed{#1}}{\path #1}}
\def\tikz@path@overlayed#1<#2>{\path<#2> #1}

\def\tikz@uninstallcommands{%
  \let\scope=\tikz@origscope%
  \let\scoped=\tikz@origscoped%
  \let\endscope=\tikz@origendscope%
  \let\startscope=\tikz@origstartscope%
  \let\stopscope=\tikz@origstopscope%
  \let\path=\tikz@origpath%
  \let\againpath=\tikz@origagainpath%
  \let\draw=\tikz@origdraw%
  \let\pattern=\tikz@origpattern%
  \let\fill=\tikz@origfill%
  \let\filldraw=\tikz@origfilldraw%
  \let\shade=\tikz@origshade%
  \let\shadedraw=\tikz@origshadedraw%
  \let\clip=\tikz@origclip%
  \let\useasboundingbox=\tikz@origuseasboundingbox%
  \let\node=\tikz@orignode%
  \let\pic=\tikz@origpic%
  \let\coordinate=\tikz@origcoordinate%
  \let\matrix=\tikz@origmatrix%
  \let\calendar=\tikz@origcalendar%
  \let\datavisualization=\tikz@origdv%
  \let\graph=\tikz@origgraph%
}


{
  \catcode`\;=12
  \gdef\tikz@nonactivesemicolon{;}
  \catcode`\:=12
  \gdef\tikz@nonactivecolon{:}
  \catcode`\|=12
  \gdef\tikz@nonactivebar{|}
  \catcode`\!=12
  \gdef\tikz@nonactiveexlmark{!}
  \catcode`\;=\active
  \catcode`\:=\active
  \catcode`\|=\active
  \catcode`\"=\active
  \catcode`\!=\active
  \gdef\tikz@activesemicolon{;}%
  \gdef\tikz@activecolon{:}%
  \gdef\tikz@activebar{|}%
  \gdef\tikz@activequotes{"}%
  \global\let\tikz@active@quotes@token="%
  \gdef\tikz@activeexlmark{!}%
  \gdef\tikz@deactivatthings{%
    \def;{\tikz@nonactivesemicolon}%
    \def:{\tikz@nonactivecolon}%
    \def|{\tikz@nonactivebar}%
    \def!{\tikz@nonactiveexlmark}%
  }
}

\let\tikz@orig@shorthands\pgfutil@empty
\def\tikz@switchoff@shorthands{%
  \ifx\tikz@orig@shorthands\pgfutil@empty%
    \edef\tikz@orig@shorthands{%
      \catcode\noexpand`\noexpand\;\the\catcode`\;\relax%
      \catcode\noexpand`\noexpand\:\the\catcode`\:\relax%
      \catcode\noexpand`\noexpand\|\the\catcode`\|\relax%
      \catcode\noexpand`\noexpand\!\the\catcode`\!\relax%
      \catcode\noexpand`\noexpand\,\the\catcode`\,\relax%
      \catcode\noexpand`\noexpand\<\the\catcode`\<\relax%
      \catcode\noexpand`\noexpand\>\the\catcode`\>\relax%
      \catcode\noexpand`\noexpand\"\the\catcode`\"\relax%
      \catcode\noexpand`\noexpand\'\the\catcode`\'\relax%
      \catcode\noexpand`\noexpand\-\the\catcode`\-\relax%
      \catcode\noexpand`\noexpand\=\the\catcode`\=\relax%
      \catcode\noexpand`\noexpand\.\the\catcode`\.\relax%
      \catcode\noexpand`\noexpand\$\the\catcode`\$\relax%
    }%
    \catcode`\;12\relax%
    \catcode`\:12\relax%
    \catcode`\|12\relax%
    \catcode`\!12\relax%
    \catcode`\,12\relax%
    \catcode`\<12\relax%
    \catcode`\>12\relax%
    \catcode`\"12\relax%
    \catcode`\'12\relax%
    \catcode`\-12\relax%
    \catcode`\=12\relax%
    \catcode`\.12\relax%
    \catcode`\$3\relax%
  \fi%
}



% Constructs a path and draws/fills them according to the current
% settings.  

\def\tikz@command@path{%
  \let\tikz@signal@path=\tikz@signal@path% for detection at begin of matrix cell
  \pgfutil@ifnextchar[{\tikz@check@earg}%]
  {\pgfutil@ifnextchar<{\tikz@doopt}{\tikz@@command@path}}}
\def\tikz@signal@path{\tikz@signal@path}%
\def\tikz@check@earg[#1]{%
  \pgfutil@ifnextchar<{\tikz@swap@args[#1]}{\tikz@@command@path[#1]}}
\def\tikz@swap@args[#1]<#2>{\tikz@command@path<#2>[#1]}

\def\tikz@doopt{%
  \let\tikz@next=\tikz@eargnormalsemicolon%
  \ifnum\the\catcode`\;=\active\relax%
    \let\tikz@next=\tikz@eargactivesemicolon%
  \fi%
  \tikz@next}
\long\def\tikz@eargnormalsemicolon<#1>#2;{\alt<#1>{\tikz@@command@path#2;}{\tikz@path@do@at@end}}
{
  \catcode`\;=\active
  \long\global\def\tikz@eargactivesemicolon<#1>#2;{\alt<#1>{\tikz@@command@path#2;}{\tikz@path@do@at@end}}
}

\def\tikz@@command@path{%
  \edef\tikzscope@linewidth{\the\pgflinewidth}%
  \begingroup%
    \setbox\tikz@figbox=\box\pgfutil@voidb@x%
    \setbox\tikz@figbox@bg=\box\pgfutil@voidb@x%
    \let\tikz@path@do@at@end=\tikz@lib@scope@check%
    \let\tikz@options=\pgfutil@empty%
    \let\tikz@mode=\pgfutil@empty%
    \let\tikz@moveto@waiting=\relax%
    \let\tikz@timer=\relax%
    \let\tikz@tangent=\relax%
    \let\tikz@collected@onpath=\pgfutil@empty%
    \let\tikz@preactions=\pgfutil@empty%
    \let\tikz@postactions=\pgfutil@empty%
    \tikz@snakedfalse%
    \tikz@decoratepathfalse%
    \tikz@node@is@a@labelfalse%
    \tikz@expandcount=100\relax%
    \pgf@path@lastx=0pt%
    \pgf@path@lasty=0pt%
    \tikz@lastx=0pt%
    \tikz@lasty=0pt%
    \tikz@lastxsaved=0pt%
    \tikz@lastysaved=0pt%
    \tikzset{every path/.try}%
    \tikz@scan@next@command%
}
\def\tikz@scan@next@command{%
  \ifx\tikz@collected@onpath\pgfutil@empty%
  \else%
    \tikz@invoke@collected@onpath%
  \fi%
  \afterassignment\tikz@handle\let\pgf@let@token=%
}
\newcount\tikz@expandcount

% Central dispatcher for commands
\def\tikz@handle{%
  \let\@next=\tikz@expand%
  \ifx\pgf@let@token(%)
    \let\@next=\tikz@movetoabs%
  \else%
    \ifx\pgf@let@token+%
      \let\@next=\tikz@movetorel%
    \else%
      \ifx\pgf@let@token-%
        \let\@next=\tikz@lineto%
      \else%
        \ifx\pgf@let@token.%
          \let\@next=\tikz@dot%
        \else%
          \ifx\pgf@let@token r%
            \let\@next=\tikz@rect%
          \else%
            \ifx\pgf@let@token n%
              \let\@next=\tikz@fig%
            \else%
              \ifx\pgf@let@token[%]
                \let\@next=\tikz@parse@options%
              \else%
                \ifx\pgf@let@token c%
                  \let\@next=\tikz@cchar%
                \else%
                  \ifx\pgf@let@token\bgroup%
                    \let\@next=\tikz@beginscope%
                  \else%
                    \ifx\pgf@let@token\egroup%
                      \let\@next=\tikz@endscope%
                    \else%
                      \ifx\pgf@let@token;%
                        \let\@next=\tikz@finish%
                      \else%
                        \let\@next=\tikz@handle@more%
                      \fi%
                    \fi%
                  \fi%
                \fi%
              \fi%
            \fi%
          \fi%
        \fi%
      \fi%
    \fi%
  \fi%
  \@next%
}

% Continued...
\def\tikz@handle@more{%
  \ifx\pgf@let@token a%
    \let\@next=\tikz@arcA%
  \else%
    \ifx\pgf@let@token e%
      \let\@next=\tikz@e@char%
    \else%
      \ifx\pgf@let@token g%
        \let\@next=\tikz@g@char%
      \else%
        \ifx\pgf@let@token s%
           \let\@next=\tikz@schar%
        \else%
          \ifx\pgf@let@token |%
             \let\@next=\tikz@vh@lineto%
          \else%
            \ifx\pgf@let@token p%
              \let\@next=\tikz@pchar%
              \pgfsetmovetofirstplotpoint%
            \else%
              \ifx\pgf@let@token t%
                \let\@next=\tikz@to%
              \else%
                \ifx\pgf@let@token\pgfextra%
                  \let\@next=\tikz@extra%
                \else%
                  \ifx\pgf@let@token\foreach%
                    \let\@next=\tikz@foreach%
                  \else%
                    \ifx\pgf@let@token f%
                      \let\@next=\tikz@fchar%
                    \else%
                      \ifx\pgf@let@token\pgf@stop%
                        \let\@next=\relax%
                      \else%
                        \ifx\pgf@let@token\par%
                          \let\@next=\tikz@scan@next@command%
                        \else%
                          \ifx\pgf@let@token d%
                            \let\@next=\tikz@decoration%
                          \else%
                            \ifx\pgf@let@token l%
                              \let\@next=\tikz@l@char%\tikz@let@command%
                            \else%
                              \let\@next=\tikz@expand%
                            \fi%      
                          \fi%      
                        \fi%      
                      \fi%      
                    \fi%      
                  \fi%      
                \fi%      
              \fi%      
            \fi%  
          \fi%  
        \fi%
      \fi%
    \fi%
  \fi%
  \ifx\@next\tikz@expand\else\tikz@expandcount=100\relax\fi%
  \@next%
}

\def\tikz@l@char{%
  \pgfutil@ifnextchar e{\tikz@let@command}{%
    \pgfutil@ifnextchar i{\tikz@lsystem}{%
      \pgfutil@ifnextchar-{\tikz@@lsystem}{\tikz@expand}%
    }%
  }%
}

\def\tikz@lsystem{%
  \tikzerror{You need to say \string\usetikzlibrary{lindenmayersystems} to draw Lindenmayer systems}
}

\def\tikz@@lsystem{%
  \tikzerror{You need to say \string\usetikzlibrary{lindenmayersystems} to draw L-systems}
}

\def\tikz@pchar{\pgfutil@ifnextchar l{\tikz@plot}{\pgfutil@ifnextchar i{\tikz@subpicture}{\tikz@parabola}}}
\def\tikz@cchar{%
  \pgfutil@ifnextchar i{\tikz@circle}%
  {\pgfutil@ifnextchar h{\tikz@children}{\tikz@cochar}}}%
\def\tikz@cochar o{%
  \pgfutil@ifnextchar o{\tikz@coordinate}{\tikz@cosine}}
\def\tikz@e@char{%
  \pgfutil@ifnextchar l{\tikz@ellipse}{\tikz@@e@char}}%
\def\tikz@@e@char dge{%
  \pgfutil@ifnextchar f{\tikz@edgetoparent}{\tikz@edge@plain}}%

\def\tikz@schar{\pgfutil@ifnextchar i{\tikz@sine}{\tikz@svg@path}}

\def\tikz@g@char r{\pgfutil@ifnextchar i{\tikz@grid}{\tikz@graph}}

% svg syntax
% svg[options] {...}

\def\tikz@svg@path{%
  \tikzerror{You need to say \string\usetikzlibrary{svg.path} to use the svg path command}
}


\def\tikz@finish{%
  % Rendering pipeline 
  % 
  % Step 1: The path background box
  %
  \box\tikz@figbox@bg%
  % 
  % Step 2: Decorate path
  % 
  \iftikz@decoratepath%
    \tikz@lib@dec@decorate@path%
  \fi%
  % 
  % Step 3: Preactions
  % 
  \pgfsyssoftpath@getcurrentpath\tikz@actions@path%
  \edef\tikz@restorepathsize{%
    \global\pgf@pathmaxx=\the\pgf@pathmaxx%
    \global\pgf@pathmaxy=\the\pgf@pathmaxy%
    \global\pgf@pathminx=\the\pgf@pathminx%
    \global\pgf@pathminy=\the\pgf@pathminy%
  }%
  \tikz@preactions%
  %
  % Step 4: Reset modes
  %
  \let\tikz@path@picture=\pgfutil@empty%
  \tikz@mode@fillfalse%
  \tikz@mode@drawfalse%
  \tikz@mode@doublefalse%
  \tikz@mode@clipfalse%
  \tikz@mode@boundaryfalse%
  \tikz@mode@fade@pathfalse%
  \tikz@mode@fade@scopefalse%
  \edef\tikz@pathextend{%
    {\noexpand\pgfqpoint{\the\pgf@pathminx}{\the\pgf@pathminy}}%
    {\noexpand\pgfqpoint{\the\pgf@pathmaxx}{\the\pgf@pathmaxy}}%
  }%
  \tikz@mode% installs the mode settings
  % Path fading counts as an option:
  \iftikz@mode@fade@path%
    \tikz@addoption{%
      \iftikz@fade@adjust%
        \iftikz@mode@draw%
          \pgfsetfadingforcurrentpathstroked{\tikz@path@fading}{\tikz@do@fade@transform}%
        \else%
          \pgfsetfadingforcurrentpath{\tikz@path@fading}{\tikz@do@fade@transform}%
        \fi%
      \else%
        \pgfsetfading{\tikz@path@fading}{\tikz@do@fade@transform}%
      \fi%
      \tikz@mode@fade@pathfalse% no more fading...
    }%
  \fi%
  %
  % Step 5: Install scope fading
  %
  \iftikz@mode@fade@scope%
    \iftikz@fade@adjust%
      \iftikz@mode@draw%
        \pgfsetfadingforcurrentpathstroked{\tikz@scope@fading}{\tikz@do@fade@transform}%
      \else%
        \pgfsetfadingforcurrentpath{\tikz@scope@fading}{\tikz@do@fade@transform}%
      \fi%
    \else%
      \pgfsetfading{\tikz@scope@fading}{\tikz@do@fade@transform}%
    \fi%
    \tikz@mode@fade@scopefalse%
  \fi%
  %
  % Step 3: Setup options
  % 
  \ifx\tikz@options\pgfutil@empty%
  \else%
    \pgfsys@beginscope%
      \begingroup%
      \tikz@options%
  \fi%
  % 
  % Step 6: Do a fill if shade or a path picture follows.
  %
  \iftikz@mode@fill%
    \iftikz@mode@shade%
      \pgfsyssoftpath@getcurrentpath\tikz@temppath
      \pgfprocessround{\tikz@temppath}{\tikz@temppath}% change the path
      \pgfsyssoftpath@setcurrentpath\tikz@temppath%
      \pgfsyssoftpath@invokecurrentpath%
      \pgfsys@fill%
      \tikz@mode@fillfalse% no more filling...
    \else%
      \ifx\tikz@path@picture\pgfutil@empty%
      \else%
        \pgfsyssoftpath@getcurrentpath\tikz@temppath
        \pgfprocessround{\tikz@temppath}{\tikz@temppath}% change the path
        \pgfsyssoftpath@setcurrentpath\tikz@temppath%
        \pgfsyssoftpath@invokecurrentpath%
        \pgfsys@fill%
        \tikz@mode@fillfalse% no more filling...
      \fi%
    \fi%
  \fi%
  % 
  % Step 7: Do a shade if necessary.
  %
  \iftikz@mode@shade%
    \pgfsyssoftpath@getcurrentpath\tikz@temppath
    \pgfprocessround{\tikz@temppath}{\tikz@temppath}% change the path
    \pgfsyssoftpath@setcurrentpath\tikz@temppath%
    \pgfshadepath{\tikz@shading}{\tikz@shade@angle}%
    \tikz@mode@shadefalse% no more shading...
  \fi%
  % 
  % Step 8: Do a path picture if necessary.
  %
  \ifx\tikz@path@picture\pgfutil@empty%
  \else%
    \begingroup%
      \pgfsys@beginscope%
        \pgfsyssoftpath@getcurrentpath\tikz@temppath
        \pgfprocessround{\tikz@temppath}{\tikz@temppath}% change the path
        \pgfsyssoftpath@setcurrentpath\tikz@temppath%
        \pgfsyssoftpath@invokecurrentpath%
        \pgfsys@clipnext%
        \pgfsys@discardpath%
        \pgf@relevantforpicturesizefalse%
        \expandafter\def\csname pgf@sh@ns@path picture bounding box\endcsname{rectangle}
        \expandafter\edef\csname pgf@sh@np@path picture bounding box\endcsname{%
          \def\noexpand\southwest{\noexpand\pgfqpoint{\the\pgf@pathminx}{\the\pgf@pathminy}}%
          \def\noexpand\northeast{\noexpand\pgfqpoint{\the\pgf@pathmaxx}{\the\pgf@pathmaxy}}%
        }
        \expandafter\def\csname pgf@sh@nt@path picture bounding box\endcsname{{1}{0}{0}{1}{0pt}{0pt}}
        \expandafter\def\csname pgf@sh@pi@path picture bounding box\endcsname{\pgfpictureid}
        \pgfinterruptpath%  
          \tikz@path@picture%
        \endpgfinterruptpath%
      \pgfsys@endscope%
    \endgroup%
    \let\tikz@path@picture=\pgfutil@empty%  
  \fi%
  % 
  % Step 9: Double stroke, if necessary
  %
  \iftikz@mode@draw%
    \iftikz@mode@double%
      % Change line width
      \begingroup%
        \pgfsys@beginscope%
          \tikz@double@setup%
    \fi%
  \fi%
  % 
  % Step 10: Do stroke/fill/clip as needed
  %
  \edef\tikz@temp{\noexpand\pgfusepath{%
    \iftikz@mode@fill fill,\fi%
    \iftikz@mode@draw draw,\fi%
    \iftikz@mode@clip clip\fi%
    }}%
  \tikz@temp%
  \tikz@mode@fillfalse% no more filling
  % 
  % Step 11: Double stroke, if necessary
  %
  \iftikz@mode@draw%
    \iftikz@mode@double%
        \pgfsys@endscope%
      \endgroup%
    \fi%
  \fi%
  \tikz@mode@drawfalse% no more stroking
  %
  % Step 12: Postactions
  %
  \tikz@postactions%
  % 
  % Step 13: Add labels and nodes
  %
  \box\tikz@figbox%
  %
  % Step 14: Close option brace
  %
  \ifx\tikz@options\pgfutil@empty%
  \else%
      \endgroup%
    \pgfsys@endscope%
    \iftikz@mode@clip%
      \tikzerror{Extra options not allowed for clipping path command.}%
    \fi%
  \fi%
  \iftikz@mode@clip%
    \aftergroup\pgf@relevantforpicturesizefalse%
  \fi%
  \iftikz@mode@boundary%
    \aftergroup\pgf@relevantforpicturesizefalse%
  \fi%
  \endgroup%
  \global\pgflinewidth=\tikzscope@linewidth%
  \tikz@path@do@at@end%
}
\let\tikz@lib@scope@check\pgfutil@empty% this is a hook for the scopes library
\def\tikz@path@do@at@end{\tikz@lib@scope@check}

% Extra actions

\def\tikz@extra@preaction#1{%
  {%
    \pgfsys@beginscope%
      \setbox\tikz@figbox=\box\pgfutil@voidb@x%
      \setbox\tikz@figbox@bg=\box\pgfutil@voidb@x%
      \path[#1];% do extra path
      \pgfsyssoftpath@setcurrentpath\tikz@actions@path% restore
      \tikz@restorepathsize%
    \pgfsys@endscope%
  }%
}

\def\tikz@extra@postaction#1{%
  {%
    \pgfsys@beginscope%
      \setbox\tikz@figbox=\box\pgfutil@voidb@x%
      \setbox\tikz@figbox@bg=\box\pgfutil@voidb@x%
      \tikz@restorepathsize%
      \path[#1]\pgfextra{\pgfsyssoftpath@setcurrentpath\tikz@actions@path};% do extra path
      \pgf@resetpathsizes%
    \pgfsys@endscope%
  }%
}



\def\tikz@skip#1{\tikz@scan@next@command#1}
\def\tikz@expand{%
  \advance\tikz@expandcount by -1%
  \ifnum\tikz@expandcount<0\relax%
    \tikzerror{Giving up on this path. Did you forget a semicolon?}%
    \let\@next=\tikz@finish%
  \else%
    \let\@next=\tikz@@expand
  \fi%
  \@next}

\def\tikz@@expand{%
  \expandafter\tikz@scan@next@command\pgf@let@token}



% Syntax for scopes: 
% {scoped path commands}

\newif\iftikz@auto@end@path

\def\tikz@beginscope{\begingroup\tikz@auto@end@pathfalse\tikz@scan@next@command}
\def\tikz@endscope{%
  \iftikz@auto@end@path\expandafter\tikz@finish\expandafter\egroup\else\expandafter\tikz@@endscope\fi%
}
\def\tikz@@endscope{% 
    \global\setbox\tikz@tempbox=\box\tikz@figbox%
    \global\setbox\tikz@tempbox@bg=\box\tikz@figbox@bg%
    \global\let\tikz@tangent@temp\tikz@tangent%
    \edef\tikz@marshal{%
      \tikz@lastx=\the\tikz@lastx%
      \tikz@lasty=\the\tikz@lasty%
      \iftikz@current@point@local%
      \else%
        \tikz@lastxsaved=\the\tikz@lastxsaved%
        \tikz@lastysaved=\the\tikz@lastysaved%
        \ifx\tikz@moveto@waiting\relax%
          \let\tikz@moveto@waiting\relax%
        \else%
          \def\noexpand\tikz@moveto@waiting{\tikz@moveto@waiting}%
        \fi%
        \iftikz@shapeborder%
          \noexpand\tikz@shapebordertrue%
          \def\noexpand\tikz@shapeborder@name{\tikz@shapeborder@name}%
        \else%
          \noexpand\tikz@shapeborderfalse%
        \fi%
      \fi%
    }%
    \expandafter%
  \endgroup\tikz@marshal%
  \setbox\tikz@figbox=\box\tikz@tempbox%
  \setbox\tikz@figbox@bg=\box\tikz@tempbox@bg%
  \let\tikz@tangent\tikz@tangent@temp%
  \tikz@scan@next@command}


% Syntax for pgfextra: 
% \pgfextra {normal tex text}
% \pgfextra normal tex text \endpgfextra

\def\tikz@extra{\pgfutil@ifnextchar\bgroup\tikz@@extra\relax}
\long\def\tikz@@extra#1{#1\tikz@scan@next@command}
\let\endpgfextra=\tikz@scan@next@command

\def\pgfextra{pgfextra}


% Syntax for foreach:
%
% foreach \var in {list} {path text}
% 
% or
%
% \foreach \var in {list} {path text}
%
% Example:
%
% \draw (0,0) \foreach \x in {1,2,3} {-- (\x,0) circle (1cm)} -- (5,5);

\def\tikz@fchar oreach{\tikz@foreach}

\def\tikz@foreach{%
  \def\pgffor@beginhook{%
    \tikz@lastx=\tikz@foreach@save@lastx%
    \tikz@lasty=\tikz@foreach@save@lasty%
    \tikz@lastxsaved=\tikz@foreach@save@lastxsaved%
    \tikz@lastysaved=\tikz@foreach@save@lastysaved%
    \setbox\tikz@figbox=\box\tikz@tempbox%
    \setbox\tikz@figbox@bg=\box\tikz@tempbox@bg%
    \expandafter\tikz@scan@next@command\pgfutil@firstofone}%
  \def\pgffor@endhook{\pgfextra{%
      \xdef\tikz@foreach@save@lastx{\the\tikz@lastx}%
      \xdef\tikz@foreach@save@lasty{\the\tikz@lasty}%
      \xdef\tikz@foreach@save@lastxsaved{\the\tikz@lastxsaved}%
      \xdef\tikz@foreach@save@lastysaved{\the\tikz@lastysaved}%
      \global\setbox\tikz@tempbox=\box\tikz@figbox%
      \global\setbox\tikz@tempbox@bg=\box\tikz@figbox@bg%
      \pgfutil@gobble}}%
  \def\pgffor@afterhook{%
    \tikz@lastx=\tikz@foreach@save@lastx%
    \tikz@lasty=\tikz@foreach@save@lasty%
    \tikz@lastxsaved=\tikz@foreach@save@lastxsaved%
    \tikz@lastysaved=\tikz@foreach@save@lastysaved%
    \let\pgffor@beginhook\relax%
    \let\pgffor@endhook\relax%
    \let\pgffor@afterhook\relax%
    \setbox\tikz@figbox=\box\tikz@tempbox%
    \setbox\tikz@figbox@bg=\box\tikz@tempbox@bg%
    \tikz@scan@next@command}%
  \global\setbox\tikz@tempbox=\box\tikz@figbox%
  \global\setbox\tikz@tempbox@bg=\box\tikz@figbox@bg%
  \xdef\tikz@foreach@save@lastx{\the\tikz@lastx}%
  \xdef\tikz@foreach@save@lasty{\the\tikz@lasty}%
  \xdef\tikz@foreach@save@lastxsaved{\the\tikz@lastxsaved}%
  \xdef\tikz@foreach@save@lastysaved{\the\tikz@lastysaved}%
  \foreach}

  
% Syntax for againpath: 
% \againpath \somepathname

\def\tikz@command@againpath#1{%
  \pgfextra{%
    \pgfsyssoftpath@getcurrentpath\tikz@temp%
    \expandafter\pgfutil@g@addto@macro\expandafter\tikz@temp\expandafter{#1}%
    \pgfsyssoftpath@setcurrentpath\tikz@temp%
  }
}




%
% When this if is set, a just-scanned point is a shape and its border
% position still needs to be determined, depending on subsequent
% commands. 
%

\newif\iftikz@shapeborder


% Syntax for moveto: 
% <point>
\def\tikz@movetoabs{\tikz@moveto(}
\def\tikz@movetorel{\tikz@moveto+}
\def\tikz@moveto{%
  \tikz@scan@one@point{\tikz@@moveto}}
\def\tikz@@moveto#1{%
  \tikz@make@last@position{#1}%
  \iftikz@shapeborder%
    % ok, the moveto will have to wait. flag that we have a moveto in
    % waiting:
    \edef\tikz@moveto@waiting{\tikz@shapeborder@name}%
  \else%
    \pgfpathmoveto{\tikz@last@position}%
    \let\tikz@moveto@waiting=\relax%
  \fi%
  \tikz@scan@next@command%
}

\let\tikz@moveto@waiting=\relax % normally, nothing is waiting...

\def\tikz@flush@moveto{%
  \ifx\tikz@moveto@waiting\relax%
  \else%
    \pgfpathmoveto{\tikz@last@position}%
  \fi%
  \let\tikz@moveto@waiting=\relax%
}


\def\tikz@flush@moveto@toward#1#2#3{%
  % #1 = a point towards which the last moveto should be corrected
  % #2 = a dimension to which the corrected x-coordinate should be stored
  % #3 = a dimension for the corrected y-coordinate
  \ifx\tikz@moveto@waiting\relax%
    % do nothing
  \else%
    \pgf@process{\pgfpointshapeborder{\tikz@moveto@waiting}{#1}}%
    #2=\pgf@x%
    #3=\pgf@y%
    \edef\tikz@timer@start{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
    \pgfpathmoveto{\pgfqpoint{\pgf@x}{\pgf@y}}%
  \fi%
  \let\tikz@moveto@waiting=\relax%
}


%
% Collecting labels on the path 
%

\def\tikz@collect@coordinate@onpath#1c{%
  \pgfutil@ifnextchar y{\tikz@cycle@expander@add#1}{\tikz@collect@coordinate@onpath@{#1}}}
\def\tikz@collect@coordinate@onpath@#1oordinate{%
  \pgfutil@ifnextchar[{\tikz@@collect@coordinate@opt#1}{\tikz@@collect@coordinate@opt#1[]}}%}
\def\tikz@@collect@coordinate@opt#1[#2]{%
  \pgfutil@ifnextchar({\tikz@@collect@coordinate#1[#2]}{%
  \tikz@collect@label@onpath#1node[shape=coordinate,#2]{}}}%}
\def\tikz@@collect@coordinate#1[#2](#3){%
  \tikz@collect@label@onpath#1node[shape=coordinate,#2](#3){}}

\newif\iftikz@collect@pic

\def\tikz@collect@label@onpath#1node{%
  \expandafter\def\expandafter\tikz@collected@onpath\expandafter{\tikz@collected@onpath node}%
  \let\tikz@collect@cont#1%
  \tikz@collect@picfalse%
  \tikz@collect@label@scan}

\def\tikz@collect@pic@onpath#1pic{%
  \expandafter\def\expandafter\tikz@collected@onpath\expandafter{\tikz@collected@onpath pic}%
  \let\tikz@collect@cont#1
  \tikz@collect@pictrue%
  \tikz@collect@label@scan}

\def\tikz@collect@label@scan{%  
  \pgfutil@ifnextchar f{\tikz@collect@nodes}{%
    \pgfutil@ifnextchar({\tikz@collect@paran}%
    {\pgfutil@ifnextchar[{\tikz@collect@options}%
      {\pgfutil@ifnextchar\bgroup{\tikz@collect@arg}%
        {\tikz@collect@cont}}}}% 
}%}}

\def\tikz@collect@nodes foreach#1in{%
  \expandafter\def\expandafter\tikz@collected@onpath\expandafter{\tikz@collected@onpath foreach#1in}%
  \pgfutil@ifnextchar\bgroup\tikz@collect@nodes@group\tikz@collect@nodes@one%
}
\def\tikz@collect@nodes@one#1{%
  \expandafter\def\expandafter\tikz@collected@onpath\expandafter{\tikz@collected@onpath #1}%  
  \tikz@collect@label@scan%
}
\def\tikz@collect@nodes@group#1{%
  \expandafter\def\expandafter\tikz@collected@onpath\expandafter{\tikz@collected@onpath{#1}}%  
  \tikz@collect@label@scan%
}

\def\tikz@collect@paran#1){%
  \expandafter\def\expandafter\tikz@collected@onpath\expandafter{\tikz@collected@onpath#1)}%
  \tikz@collect@label@scan%
}
\def\tikz@collect@options#1]{%
  \expandafter\def\expandafter\tikz@collected@onpath\expandafter{\tikz@collected@onpath#1]}%
  \tikz@collect@label@scan%
}
\def\tikz@collect@arg#1{%
  \iftikz@handle@active@nodes%
    \iftikz@collect@pic%
      \expandafter\def\expandafter\tikz@collected@onpath\expandafter{\tikz@collected@onpath{#1}}%
    \else%
      \expandafter\def\expandafter\tikz@collected@onpath\expandafter{\tikz@collected@onpath{\scantokens{#1}}}%
    \fi%
  \else%
    \expandafter\def\expandafter\tikz@collected@onpath\expandafter{\tikz@collected@onpath{#1}}%
  \fi%
  \tikz@collect@cont%
}

\def\tikz@invoke@collected@onpath{%
  \tikz@node@is@a@labeltrue%
  \let\tikz@temp=\tikz@collected@onpath%
  \let\tikz@collected@onpath=\pgfutil@empty%
  \expandafter\tikz@scan@next@command\tikz@temp\pgf@stop%
  \tikz@node@is@a@labelfalse%
}


%
% Macros for the cycle command
%

\def\tikz@cycle@expander#1{\pgfutil@ifnextchar c{\tikz@cycle@expander@{#1}}{#1}}
\def\tikz@cycle@expander@#1c{\pgfutil@ifnextchar y{\tikz@cycle@expander@add{#1}}{#1c}}
\def\tikz@cycle@expander@add#1ycle{#1(current subpath start)--cycle}




% Syntax for lineto: 
% -- <point>

\def\tikz@lineto{%
  \pgfutil@ifnextchar |%
  {\expandafter\tikz@hv@lineto\pgfutil@gobble}%
  {\expandafter\pgfutil@ifnextchar\tikz@activebar{\expandafter\tikz@hv@lineto\pgfutil@gobble}%
    {\expandafter\tikz@lineto@mid\pgfutil@gobble}}}
\def\tikz@lineto@mid{%
  \pgfutil@ifnextchar n{\tikz@collect@label@onpath\tikz@lineto@mid}%
  {%
    \pgfutil@ifnextchar c{\tikz@close}{%
      \pgfutil@ifnextchar p{\tikz@lineto@plot@or@pic}{\tikz@scan@one@point{\tikz@@lineto}}}}}
\def\tikz@lineto@plot@or@pic p{%
  \pgfutil@ifnextchar i{\tikz@collect@pic@onpath\tikz@lineto@mid p}{%
    \pgfsetlinetofirstplotpoint\tikz@plot}%
}
\def\tikz@@lineto#1{%
  % Record the starting point for later labels on the path:
  \edef\tikz@timer@start{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}
  \iftikz@shapeborder%
    % ok, target is a shape. recalculate end
    \pgf@process{\pgfpointshapeborder{\tikz@shapeborder@name}{\tikz@last@position}}%
    \tikz@make@last@position{\pgfqpoint{\pgf@x}{\pgf@y}}%
    \tikz@flush@moveto@toward{\tikz@last@position}\pgf@x\pgf@y%
    \tikz@path@lineto{\tikz@last@position}%
    \edef\tikz@timer@end{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}%
    \tikz@make@last@position{#1}%
    \edef\tikz@moveto@waiting{\tikz@shapeborder@name}%    
  \else%
    % target is a reasonable point...
    % Record the starting point for later labels on the path:
    \tikz@make@last@position{#1}%
    \tikz@flush@moveto@toward{\tikz@last@position}\pgf@x\pgf@y%
    \tikz@path@lineto{\tikz@last@position}%
    \edef\tikz@timer@end{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}%
  \fi%
  \let\tikz@timer=\tikz@timer@line%
  \let\tikz@tangent\tikz@timer@start%
  \tikz@scan@next@command%
}

% snake or lineto?
\def\tikz@path@lineto#1{%
  \iftikz@snaked%
    {
      \pgfsyssoftpathmovetorelevantfalse%
      \pgfpathsnakesto{\tikz@presnake,{\tikz@snake}{\tikz@mainsnakelength}{\noexpand\tikz@snake@install@trans}{},\tikz@postsnake}{#1}%
    }
  \else%
    \pgfpathlineto{#1}%
  \fi%
}

% snake or lineto?
\def\tikz@path@close#1{%
  \iftikz@snaked%
    {%
      \pgftransformreset%
      \pgfpathsnakesto{\tikz@presnake,{\tikz@snake}{\tikz@mainsnakelength}{\noexpand\tikz@snake@install@trans}{},\tikz@postsnake}{#1}%
    }%
  \fi%
  \pgfpathclose%
}


% Syntax for lineto horizontal/vertical: 
% -| <point>

\def\tikz@hv@lineto{%
  \pgfutil@ifnextchar n{\tikz@collect@label@onpath\tikz@hv@lineto}{
  \pgfutil@ifnextchar p{\tikz@collect@pic@onpath\tikz@hv@lineto}%
  {\pgfutil@ifnextchar c{\tikz@collect@coordinate@onpath\tikz@hv@lineto}%
    {\tikz@scan@one@point{\tikz@@hv@lineto}}}}}
\def\tikz@@hv@lineto#1{%
  \edef\tikz@timer@start{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}%
  \pgf@yc=\tikz@lasty%
  \tikz@make@last@position{#1}%
  \edef\tikz@tangent{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\pgf@yc}}%
  \tikz@flush@moveto@toward{\pgfqpoint{\tikz@lastx}{\pgf@yc}}\pgf@x\pgf@yc%
  \iftikz@shapeborder%
    % ok, target is a shape. have to work now:
    {%
      \pgf@process{\pgfpointshapeborder{\tikz@shapeborder@name}{\pgfqpoint{\tikz@lastx}{\pgf@yc}}}%
      \tikz@make@last@position{\pgfqpoint{\pgf@x}{\pgf@y}}%
      \tikz@path@lineto{\pgfqpoint{\tikz@lastx}{\pgf@yc}}%
      \tikz@path@lineto{\tikz@last@position}%
      \xdef\tikz@timer@end@temp{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}% move out of group
    }%
    \let\tikz@timer@end=\tikz@timer@end@temp%
    \edef\tikz@moveto@waiting{\tikz@shapeborder@name}%    
  \else%
    \tikz@path@lineto{\pgfqpoint{\tikz@lastx}{\pgf@yc}}%
    \tikz@path@lineto{\tikz@last@position}%
    \edef\tikz@timer@end{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}% move out of group
  \fi%
  \let\tikz@timer=\tikz@timer@hvline%
  \tikz@scan@next@command%
}

% Syntax for lineto vertical/horizontal: 
% |- <point>

\def\tikz@vh@lineto-{\tikz@vh@lineto@next}
\def\tikz@vh@lineto@next{%
  \pgfutil@ifnextchar n{\tikz@collect@label@onpath\tikz@vh@lineto@next}{%
  \pgfutil@ifnextchar p{\tikz@collect@pic@onpath\tikz@vh@lineto@next}%
  {\pgfutil@ifnextchar c{\tikz@collect@coordinate@onpath\tikz@vh@lineto@next}%
    {\tikz@scan@one@point\tikz@@vh@lineto}}}}
\def\tikz@@vh@lineto#1{%
  \edef\tikz@timer@start{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}%
  \pgf@xc=\tikz@lastx%
  \tikz@make@last@position{#1}%
  \edef\tikz@tangent{\noexpand\pgfqpoint{\the\pgf@xc}{\the\tikz@lasty}}%
  \tikz@flush@moveto@toward{\pgfqpoint{\pgf@xc}{\tikz@lasty}}\pgf@xc\pgf@y%
  \iftikz@shapeborder%
    % ok, target is a shape. have to work now:
    {%
      \pgf@process{\pgfpointshapeborder{\tikz@shapeborder@name}{\pgfqpoint{\pgf@xc}{\tikz@lasty}}}%
      \tikz@make@last@position{\pgfqpoint{\pgf@x}{\pgf@y}}%
      \tikz@path@lineto{\pgfqpoint{\pgf@xc}{\tikz@lasty}}%
      \tikz@path@lineto{\tikz@last@position}%
      \xdef\tikz@timer@end@temp{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}% move out of group
    }%
    \let\tikz@timer@end=\tikz@timer@end@temp%
    \edef\tikz@moveto@waiting{\tikz@shapeborder@name}%    
  \else%
    \tikz@path@lineto{\pgfqpoint{\pgf@xc}{\tikz@lasty}}%
    \tikz@path@lineto{\tikz@last@position}%
    \edef\tikz@timer@end{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}%
  \fi%
  \let\tikz@timer=\tikz@timer@vhline%
  \tikz@scan@next@command%
}

% Syntax for cycle: 
% -- cycle
\def\tikz@close c{%
  \pgfutil@ifnextchar o{\tikz@collect@coordinate@onpath\tikz@lineto@mid c}% oops, a coordinate
  {\tikz@@close c}}%
\def\tikz@@close cycle{%
  \tikz@flush@moveto%
  \edef\tikz@timer@start{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}
  \tikz@make@last@position{\expandafter\pgfpoint\pgfsyssoftpath@lastmoveto}%
  \tikz@path@close{\expandafter\pgfpoint\pgfsyssoftpath@lastmoveto}%
  \def\pgfstrokehook{}%
  \edef\tikz@timer@end{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}%
  \let\tikz@timer=\tikz@timer@line%
  \let\tikz@tangent\tikz@timer@start%
  \tikz@scan@next@command%
}


% Syntax for options: 
% [options]
\def\tikz@parse@options#1]{%
  \tikzset{#1}%
  \tikz@scan@next@command%
}

% Syntax for edges:
% edge [options] (coordinate)
% edge [options] node {node text} (coordinate)
\def\tikz@edge@plain{%
  \begingroup%
    \ifx\tikz@to@use@whom\pgfutil@undefined\else\tikz@to@use@whom\fi
    \let\tikz@to@or@edge@function=\tikz@do@edge%
    \tikz@to@or@edge}

% Syntax for to paths:
% to [options] (coordinate)
% to [options] node {node text} (coordinate)
\def\tikz@to o{%
  \tikz@to@use@last@coordinate%
  \let\tikz@to@or@edge@function=\tikz@do@to%
  \tikz@to@or@edge}
  
\def\tikz@to@or@edge{\pgfutil@ifnextchar[\tikz@@to@or@edge{\tikz@@to@or@edge[]}}%}
\def\tikz@@to@or@edge[#1]{%
  \def\tikz@@to@local@options{#1}%
  \let\tikz@collected@onpath=\pgfutil@empty%
  \tikz@@to@collect%
}
\def\tikz@@to@collect{%
  \pgfutil@ifnextchar(\tikz@@to@or@edge@coordinate%)
  {\pgfutil@ifnextchar n{\tikz@collect@label@onpath\tikz@@to@collect}%
    {\pgfutil@ifnextchar p{\tikz@collect@pic@onpath\tikz@@to@collect}%
      {\pgfutil@ifnextchar c{\tikz@collect@coordinate@onpath\tikz@@to@collect}%
        {\pgfutil@ifnextchar +{\tikz@scan@one@point\tikz@@to@or@edge@math}%
          {\tikzerror{(, +, coordinate, pic, or node expected}%)
            \tikz@@to@or@edge@coordinate()}}}}}%
}

\def\tikz@@to@or@edge@coordinate({%
  \pgfutil@ifnextchar${%$
    % Ok, parse directly
    \tikz@scan@one@point\tikz@@to@or@edge@math(%
  }{%
    \pgfutil@ifnextchar[{%]
      \tikz@scan@one@point\tikz@@to@or@edge@math(%
    }{%
      \tikz@@to@or@edge@@coordinate(%
    }%
  }%
}
\def\tikz@@to@or@edge@math#1{% 
  \pgf@process{#1}%
  \edef\tikztotarget{\the\pgf@x,\the\pgf@y}%
  \tikz@to@or@edge@function%
}

\def\tikz@@to@or@edge@@coordinate(#1){%
  \def\tikztotarget{#1}%
  \tikz@to@or@edge@function%
}

\def\tikz@do@edge{%
  \ifx\tikz@edge@macro\pgfutil@empty%
    \setbox\tikz@whichbox=\hbox\bgroup%
      \unhbox\tikz@whichbox%
      \hbox\bgroup
        \bgroup%
          \pgfinterruptpath%
            \pgfscope%
              \let\tikz@transform=\pgfutil@empty%
              \let\tikz@options=\pgfutil@empty%
              \let\tikz@tonodes=\tikz@collected@onpath%
              \def\tikztonodes{{\pgfextra{\tikz@node@is@a@labeltrue}\tikz@tonodes}}%
              \let\tikz@collected@onpath=\pgfutil@empty%
              \tikz@options%
              \tikz@transform%
              \let\tikz@transform=\relax%
              % Typeset node:
              \let\tikz@after@path\pgfutil@empty%
              \tikz@atbegin@to%
                \tikz@enable@edge@quotes%
                \path[style=every edge]\expandafter[\tikz@@to@local@options](\tikztostart)\tikz@to@path
                \pgfextra{\global\let\tikz@after@path@smuggle=\tikz@after@path};%
              \tikz@atend@to%
            \endpgfscope%
          \endpgfinterruptpath%
        \egroup
      \egroup%
    \egroup%
    \global\setbox\tikz@tempbox=\box\tikz@whichbox%
    \expandafter\endgroup%
    \expandafter\setbox\tikz@whichbox=\box\tikz@tempbox%  
  \else%
      \expandafter\expandafter\expandafter\tikz@edge@macro%
      \expandafter\expandafter\expandafter{\expandafter\tikz@@to@local@options\expandafter}\expandafter{\tikz@collected@onpath}%
    \endgroup%
    \let\tikz@after@path@smuggle=\pgfutil@empty%
  \fi%
  \expandafter\tikz@scan@next@command\tikz@after@path@smuggle%  
}

\def\tikz@do@to{%
  \let\tikz@tonodes=\tikz@collected@onpath%
  \def\tikztonodes{{\pgfextra{\tikz@node@is@a@labeltrue}\tikz@tonodes}}%
  \let\tikz@collected@onpath=\pgfutil@empty%
  \tikz@scan@next@command%
  {%
    \pgfextra{\let\tikz@after@path\pgfutil@empty}%
    \pgfextra{\tikz@atbegin@to}%
    \pgfextra{\tikz@enable@edge@quotes}%
    [style=every to]\expandafter[\tikz@@to@local@options]\tikz@to@path%
    \pgfextra{\tikz@atend@to}%
    \pgf@stop%
    \expandafter\tikz@scan@next@command\expandafter%
  }\tikz@after@path%
}


\def\tikz@to@use@last@coordinate{%
  \iftikz@shapeborder%
    \edef\tikztostart{\tikz@shapeborder@name}%
  \else%
    \edef\tikztostart{\the\tikz@lastx,\the\tikz@lasty}%
  \fi%
}
\def\tikz@to@use@last@fig@name{%
  \edef\tikztostart{\tikz@to@last@fig@name}%
}



% Syntax for graph path command:
% graph {...}
% See the graph library for details

\def\tikz@graph aph{\tikz@lib@graph@parser}

\def\tikz@lib@graph@parser{\pgfutil@ifnextchar[\tikz@graph@error{\tikz@graph@error[]}}%]
\def\tikz@graph@error[#1]#2{%
  \tikzerror{You need to say \string\usetikzlibrary{graphs} in order to use the graph syntax}% 
  \tikz@lib@graph@parser@done%
}

\def\tikz@lib@graph@parser@done{%
  \tikz@scan@next@command%
}




% Syntax for edge from parent: 
% edge from parent [options]
\def\tikz@edgetoparent from parent{\pgfutil@ifnextchar[\tikz@@edgetoparent{\tikz@@edgetoparent[]}}%}
\def\tikz@@edgetoparent[#1]{%
  \let\tikz@edge@to@parent@needed=\pgfutil@empty%
  \def\tikz@edgetoparent@options{#1}%
  \begingroup%
    \let\tikz@collected@onpath=\pgfutil@empty%
    \tikz@edgetoparentcollect%
}
\def\tikz@edgetoparentcollect{
  \pgfutil@ifnextchar n{\tikz@collect@label@onpath\tikz@edgetoparentcollect}%
  {%
      \expandafter%  
    \endgroup%
    \expandafter\tikz@edgetoparent@rollout\expandafter{\tikz@collected@onpath}%  
  }
}

\def\tikz@edgetoparent@rollout#1{%
  \pgfkeysgetvalue{/tikz/edge from parent macro}\tikz@etop@temp
  \expandafter\tikz@scan@next@command\expandafter\tikz@etop@temp\expandafter{\tikz@edgetoparent@options}{#1}%
}


% Syntax for bezier curves
% .. controls(point) and (point) .. (target)
% .. controls(point) .. (target) 
% .. (target) % currently not supported

\def\tikz@dot.{\tikz@@dot}%
\def\tikz@@dot{%
  \pgfutil@ifnextchar n{\tikz@collect@label@onpath\tikz@@dot}{%
  \pgfutil@ifnextchar p{\tikz@collect@pic@onpath\tikz@@dot}%
  {\pgfutil@ifnextchar c{\tikz@curveto@double}{\tikz@curveto@auto}}}%
}

\def\tikz@curveto@double co{%
  \pgfutil@ifnextchar o{\tikz@collect@coordinate@onpath\tikz@@dot co}
  {\tikz@cureveto@@double}}
\def\tikz@cureveto@@double ntrols#1{%
  \tikz@scan@one@point\tikz@curveA#1%
}
\def\tikz@curveA#1{%
  \edef\tikz@timer@start{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}%
  {%
    \tikz@lastxsaved=\tikz@lastx%
    \tikz@lastysaved=\tikz@lasty%
    \tikz@make@last@position{#1}%
    \xdef\tikz@curve@first{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}%
  }%
  \pgfutil@ifnextchar a
  {\tikz@curveBand}%
  {\let\tikz@curve@second\tikz@curve@first\tikz@curveCdots}%
}
\def\tikz@curveBand and{%
  \tikz@scan@one@point\tikz@curveB%
}
\def\tikz@curveB#1{%
  \def\tikz@curve@second{#1}%
  \tikz@curveCdots}
\def\tikz@curveCdots{%
  \afterassignment\tikz@curveCdot\let\@next=}
\def\tikz@curveCdot.{%
  \ifx\@next.%
  \else%
    \tikzerror{Dot expected}%
  \fi%
  \tikz@updatecurrenttrue%
  \tikz@curveCcheck%
}
\def\tikz@curveCcheck{%
  \pgfutil@ifnextchar n{\tikz@collect@label@onpath\tikz@curveCcheck}{%
  \pgfutil@ifnextchar p{\tikz@collect@pic@onpath\tikz@curveCcheck}%
  {\pgfutil@ifnextchar c{\tikz@collect@coordinate@onpath\tikz@curveCcheck}
    {\tikz@scan@one@point\tikz@curveC}}}%
}
\def\tikz@curveC#1{%
  \tikz@make@last@position{#1}%
  \edef\tikz@curve@third{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}%
  {%
    \tikz@lastxsaved=\tikz@lastx%
    \tikz@lastysaved=\tikz@lasty%
    \tikz@make@last@position{\tikz@curve@second}%
    \xdef\tikz@curve@second{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}%
  }%
  %
  % Start recalculating things in case start and end are shapes.
  %
  % First, the start:
  \ifx\tikz@moveto@waiting\relax%
  \else%
    \pgf@process{\pgfpointshapeborder{\tikz@moveto@waiting}{\tikz@curve@first}}%
    \edef\tikz@timer@start{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
    \pgfpathmoveto{\pgfqpoint{\pgf@x}{\pgf@y}}%
  \fi%
  \let\tikz@timer@cont@one=\tikz@curve@first%
  \let\tikz@timer@cont@two=\tikz@curve@second%    
  % Second, the end:
  \iftikz@shapeborder%
    % ok, target is a shape. recalculate third
    {%
      \pgf@process{\pgfpointshapeborder{\tikz@shapeborder@name}{\tikz@curve@second}}%
      \tikz@make@last@position{\pgfqpoint{\pgf@x}{\pgf@y}}%
      \edef\tikz@curve@third{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}%
      \pgfpathcurveto{\tikz@curve@first}{\tikz@curve@second}{\tikz@curve@third}%
      \global\let\tikz@timer@end@temp=\tikz@curve@third% move out of group
    }%
    \let\tikz@timer@end=\tikz@timer@end@temp%
    \edef\tikz@moveto@waiting{\tikz@shapeborder@name}%    
  \else%
    \pgfpathcurveto{\tikz@curve@first}{\tikz@curve@second}{\tikz@curve@third}%
    \let\tikz@timer@end=\tikz@curve@third
    \let\tikz@moveto@waiting=\relax%
  \fi%
  \let\tikz@timer=\tikz@timer@curve%
  \let\tikz@tangent=\tikz@curve@second%
  \tikz@scan@next@command%
}


% Syntax for rectangles: 
% rectangle <corner point> 
\def\tikz@rect ectangle{%
  \tikz@flush@moveto%
  \edef\tikz@timer@start{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}%
  \tikz@@rect}%
\def\tikz@@rect{%
  \pgfutil@ifnextchar n{\tikz@collect@label@onpath\tikz@@rect}{%
  \pgfutil@ifnextchar p{\tikz@collect@pic@onpath\tikz@@rect}%
  {\pgfutil@ifnextchar c{\tikz@collect@coordinate@onpath\tikz@@rect}%
    {
      \pgf@xa=\tikz@lastx\relax%
      \pgf@ya=\tikz@lasty\relax%
      \tikz@scan@one@point\tikz@rectB}}}}
\def\tikz@rectB#1{%
  \tikz@make@last@position{#1}%
  \edef\tikz@timer@end{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}%
  \let\tikz@timer=\tikz@timer@line%  
  \pgfpathmoveto{\pgfqpoint{\pgf@xa}{\pgf@ya}}%
  \tikz@path@lineto{\pgfqpoint{\pgf@xa}{\tikz@lasty}}%
  \tikz@path@lineto{\pgfqpoint{\tikz@lastx}{\tikz@lasty}}%
  \tikz@path@lineto{\pgfqpoint{\tikz@lastx}{\pgf@ya}}%
  \iftikz@snaked% 
    \tikz@path@lineto{\pgfqpoint{\pgf@xa}{\pgf@ya}}%
  \fi%
  \pgfpathclose%
  \pgfpathmoveto{\pgfqpoint{\tikz@lastx}{\tikz@lasty}}%
  \def\pgfstrokehook{}%
  \let\tikz@tangent\relax%
  \tikz@scan@next@command%
}



% Syntax for grids: 
% grid <corner point> 
\def\tikz@grid id{%
  \tikz@flush@moveto%
  \pgf@xa=\tikz@lastx\relax%
  \pgf@ya=\tikz@lasty\relax%
  \pgfutil@ifnextchar[{\tikz@gridA}{\tikz@gridA[]}}%}
\def\tikz@gridA[#1]{%
  \def\tikz@grid@options{#1}%
  \tikz@cycle@expander{\tikz@scan@one@point\tikz@gridB}}%
\def\tikz@gridB#1{%
  \tikz@make@last@position{#1}%
  \let\tikz@tangent\relax%
  {%
    \let\tikz@after@path\pgfutil@empty%
    \expandafter\tikzset\expandafter{\tikz@grid@options}
    \tikz@checkunit{\tikz@grid@x}%
    \iftikz@isdimension%
      \pgf@process{\pgfpoint{\tikz@grid@x}{0pt}}%
    \else%
      \pgf@process{\pgfpointxy{\tikz@grid@x}{0}}%
    \fi%
    \pgf@xb=\pgf@x%
    \pgf@yb=\pgf@y%
    \tikz@checkunit{\tikz@grid@y}%
    \iftikz@isdimension%
      \pgf@process{\pgfpoint{0pt}{\tikz@grid@y}}%
    \else%
      \pgf@process{\pgfpointxy{0}{\tikz@grid@y}}%
    \fi%
    \advance\pgf@xb by\pgf@x%
    \advance\pgf@yb by\pgf@y%
    \pgfpathgrid[stepx=\pgf@xb,stepy=\pgf@yb]%
      {\pgfqpoint{\pgf@xa}{\pgf@ya}}{\pgfqpoint{\tikz@lastx}{\tikz@lasty}}%
  \expandafter}%
  \expandafter\tikz@scan@next@command\tikz@after@path%
}



% Syntax for plot: 
% plot [local options] ...    % starts with a moveto
% -- plot [local options] ... % starts with a lineto
\def\tikz@plot lot{%
  \tikz@flush@moveto%
  \pgfutil@ifnextchar[{\tikz@@plot}{\tikz@@plot[]}}%}
\def\tikz@@plot[#1]{%
  \let\tikz@tangent\tikz@tangent@lookup%
  \begingroup%
    \let\tikz@after@path\pgfutil@empty%
    \let\tikz@options=\pgfutil@empty%
    \tikzset{every plot/.try}%
    \tikzset{#1}%
    \pgfutil@ifnextchar f{\tikz@plot@f}%
    {\pgfutil@ifnextchar c{\tikz@plot@scan@points}%
      {\pgfutil@ifnextchar ({\tikz@plot@expression}{%
      \tikzerror{Cannot parse this plotting data}%
       \endgroup}}}}
\def\tikz@plot@f f{\pgfutil@ifnextchar i{\tikz@plot@file}{\tikz@plot@function}}

\def\tikz@plot@file ile#1{\def\tikz@plot@data{\pgfplotxyfile{#1}}\tikz@@@plot}%
\def\tikz@plot@scan@points coordinates#1{%
  \pgfplothandlerrecord\tikz@plot@data%
  \pgfplotstreamstart%
  \pgfutil@ifnextchar\pgf@stop{\pgfplotstreamend\expandafter\tikz@@@plot\pgfutil@gobble}
  {\tikz@scan@one@point\tikz@plot@next@point}%
  #1\pgf@stop%
}
\def\tikz@plot@next@point#1{%
  \pgfplotstreampoint{#1}%
  \pgfutil@ifnextchar\pgf@stop{\pgfplotstreamend\expandafter\tikz@@@plot\pgfutil@gobble}%
  {\tikz@scan@one@point\tikz@plot@next@point}%
}  
\def\tikz@plot@function unction#1{%
  \def\tikz@plot@filename{\tikz@plot@prefix\tikz@plot@id}%  
  \iftikz@plot@raw@gnuplot%
    \def\tikz@plot@data{\pgfplotgnuplot[\tikz@plot@filename]{#1}}%
  \else%
    \iftikz@plot@parametric%   
      \def\tikz@plot@data{\pgfplotgnuplot[\tikz@plot@filename]{%
          set samples \tikz@plot@samples;
          set parametric;
          plot [t=\tikz@plot@domain]
          [\tikz@plot@xrange]
          [\tikz@plot@range]
          #1}}%
    \else%
      \def\tikz@plot@data{\pgfplotgnuplot[\tikz@plot@filename]{%
          set samples \tikz@plot@samples;
          plot [x=\tikz@plot@domain]
          \ifx\tikz@plot@range\pgfutil@empty\else[\tikz@plot@range]\fi
          #1}}%
    \fi%
  \fi%
  \tikz@@@plot%
}

\def\tikz@plot@no@resample{%
  \pgfutil@IfFileExists{\tikz@plot@filename.table}%
  {\def\tikz@plot@data{\pgfplotxyfile{\tikz@plot@filename.table}}}%
  {}%
}

\def\tikz@plot@expression(#1){%
  \edef\tikz@plot@data{\noexpand\pgfplotfunction{\expandafter\noexpand\tikz@plot@var}{\tikz@plot@samplesat}}%
  \expandafter\def\expandafter\tikz@plot@data\expandafter{\tikz@plot@data{\tikz@scan@one@point\pgfutil@firstofone(#1)}}%
  \tikz@@@plot%
}

\def\tikz@@@plot{%
    \def\pgfplotlastpoint{\pgfpointorigin}%
    \tikz@plot@handler%
    \tikz@plot@data%
    \global\let\tikz@@@temp=\pgfplotlastpoint%
    \ifx\tikz@plot@mark\pgfutil@empty%
    \else%
      % Marks are drawn after the path.
      \setbox\tikz@whichbox=\hbox{%
        \unhbox\tikz@whichbox%
        \hbox{{%
          \pgfinterruptpath%
            \pgfscope%
              \let\tikz@options=\pgfutil@empty%
              \let\tikz@transform=\pgfutil@empty%
              \tikzset{every mark}%
              \tikz@options%
              \ifx\tikz@mark@list\pgfutil@empty%
                \pgfplothandlermark{\tikz@transform\pgfuseplotmark{\tikz@plot@mark}}%
              \else
                \pgfplothandlermarklisted{\tikz@transform\pgfuseplotmark{\tikz@plot@mark}}{\tikz@mark@list}%
              \fi
              \tikz@plot@data%
            \endpgfscope
          \endpgfinterruptpath%
        }}%
      }%
    \fi%
    \global\setbox\tikz@tempbox=\box\tikz@whichbox%
    \global\let\tikz@after@path@smuggle=\tikz@after@path
  \expandafter\endgroup%
  \expandafter\setbox\tikz@whichbox=\box\tikz@tempbox%  
  \tikz@make@last@position{\tikz@@@temp}%  
  \expandafter\tikz@scan@next@command\tikz@after@path@smuggle%
}


\pgfdeclareplotmark{ball}
{%
  \def\tikz@shading{ball}%
  \shade (0pt,0pt) circle (\pgfplotmarksize);%
}




% Syntax for cosine curves:
% cos <end of quarter-period>
\def\tikz@cosine s{\tikz@cycle@expander{\tikz@scan@one@point\tikz@@cosine}}
\def\tikz@@cosine#1{%
  \let\tikz@tangent\tikz@tangent@lookup%
  \tikz@flush@moveto%
  \pgf@process{#1}%
  \pgf@xc=\pgf@x%
  \pgf@yc=\pgf@y%
  \advance\pgf@xc by-\tikz@lastx%
  \advance\pgf@yc by-\tikz@lasty%
  \advance\tikz@lastx by\pgf@xc%
  \advance\tikz@lasty by\pgf@yc%
  \tikz@lastxsaved=\tikz@lastx%
  \tikz@lastysaved=\tikz@lasty%
  \tikz@updatecurrenttrue%
  \pgfpathcosine{\pgfqpoint{\pgf@xc}{\pgf@yc}}%
  \tikz@scan@next@command%
}

% Syntax for sine curves:
% sin <end of quarter-period>
\def\tikz@sine in{\tikz@cycle@expander{\tikz@scan@one@point\tikz@@sine}}
\def\tikz@@sine#1{%
  \let\tikz@tangent\tikz@tangent@lookup%
  \tikz@flush@moveto%
  \pgf@process{#1}%
  \pgf@xc=\pgf@x%
  \pgf@yc=\pgf@y%
  \advance\pgf@xc by-\tikz@lastx%
  \advance\pgf@yc by-\tikz@lasty%
  \advance\tikz@lastx by\pgf@xc%
  \advance\tikz@lasty by\pgf@yc%
  \tikz@lastxsaved=\tikz@lastx%
  \tikz@lastysaved=\tikz@lasty%
  \tikz@updatecurrenttrue%
  \pgfpathsine{\pgfqpoint{\pgf@xc}{\pgf@yc}}%
  \tikz@scan@next@command%
}

% Syntax for parabolas: 
% parabola[options] bend <coordinate> <coordinate>
\def\tikz@parabola arabola{%
  \let\tikz@tangent\tikz@tangent@lookup%
  \pgfutil@ifnextchar[{\tikz@parabola@options}{\tikz@parabola@options[]}}%}

\def\tikz@parabola@options[#1]{%
  \def\tikz@parabola@option{#1}%
  \pgfutil@ifnextchar b{\tikz@parabola@scan@bend}{\tikz@cycle@expander{\tikz@scan@one@point\tikz@parabola@semifinal}}}
\def\tikz@parabola@scan@bend bend{\tikz@scan@one@point\tikz@parabola@scan@bendB}
\def\tikz@parabola@scan@bendB#1{%
  \def\tikz@parabola@bend{#1}%
  \tikz@cycle@expander{\tikz@scan@one@point\tikz@parabola@semifinal}%
}
\def\tikz@parabola@semifinal#1{%
  \tikz@flush@moveto%
  % Save original start:
  \pgf@xb=\tikz@lastx%
  \pgf@yb=\tikz@lasty%
  \tikz@make@last@position{#1}%
  \pgf@xc=\tikz@lastx%
  \pgf@yc=\tikz@lasty%
  \begingroup% now calculate bend:
    \let\tikz@after@path\pgfutil@empty%
    \expandafter\tikzset\expandafter{\tikz@parabola@option}%
    \tikz@lastxsaved=\tikz@parabola@bend@factor\tikz@lastx%
    \tikz@lastysaved=\tikz@parabola@bend@factor\tikz@lasty%
    \advance\tikz@lastxsaved by\pgf@xb%
    \advance\tikz@lastysaved by\pgf@yb%
    \advance\tikz@lastxsaved by-\tikz@parabola@bend@factor\pgf@xb%
    \advance\tikz@lastysaved by-\tikz@parabola@bend@factor\pgf@yb%
    \expandafter\tikz@make@last@position\expandafter{\tikz@parabola@bend}%
    % Calculate delta from bend
    \advance\pgf@xc by-\tikz@lastx%
    \advance\pgf@yc by-\tikz@lasty%
    % Ok, now calculate delta to bend
    \advance\tikz@lastx by-\pgf@xb%
    \advance\tikz@lasty by-\pgf@yb%
    \xdef\tikz@parabola@b{{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}{\noexpand\pgfqpoint{\the\pgf@xc}{\the\pgf@yc}}}%
  \expandafter\endgroup%
  \expandafter\expandafter\expandafter\pgfpathparabola\expandafter\tikz@parabola@b%
  \expandafter\tikz@scan@next@command\tikz@after@path%
}


% Syntax for circles:
% circle [options] % where options should set, at least, radius
% circle (radius) % deprecated
%
% Syntax for ellipses:
% ellipse [options] % identical to circle.
% ellipse (x-radius and y-radius) % deprecated
%
% radii can be dimensionless, then they are in the xy-system
\def\tikz@circle ircle{\tikz@flush@moveto\tikz@@circle}
\def\tikz@ellipse llipse{\tikz@flush@moveto\tikz@@circle}
\def\tikz@@circle{%
  \let\tikz@tangent\relax%
  \pgfutil@ifnextchar(\tikz@@@circle
  {\pgfutil@ifnextchar[\tikz@circle@opt{%])
    \advance\tikz@expandcount by -10\relax% go down quickly
    \ifnum\tikz@expandcount<0\relax%
      \let\@next=\tikz@@circle@normal%
    \else%
      \let\@next=\tikz@@circle@scanexpand%
    \fi%
    \@next%
  }}%
}
\def\tikz@@circle@scanexpand{\expandafter\tikz@@circle}
\def\tikz@@circle@normal{\tikz@circle@opt[]}

\def\tikz@circle@opt[#1]{%
  {%
    \def\tikz@node@at{\tikz@last@position}%
    \let\tikz@transform=\pgfutil@empty%
    \tikzset{every circle/.try,#1}%
    \pgftransformshift{\tikz@node@at}%
    \tikz@transform%
    \tikz@do@circle{\pgfkeysvalueof{/tikz/x radius}}{\pgfkeysvalueof{/tikz/y radius}}
  }%
  \tikz@scan@next@command%
}

\def\tikz@@@circle(#1){%
  {%
    \pgftransformshift{\tikz@last@position}%
    \pgfutil@in@{ and }{#1}%
    \ifpgfutil@in@%
      \tikz@@ellipseB(#1)%
    \else%
      \tikz@do@circle{#1}{#1}%
    \fi%
  }%
  \tikz@scan@next@command%
}
\def\tikz@@ellipseB(#1 and #2){%
  \tikz@do@circle{#1}{#2}
}
\def\tikz@do@circle#1#2{
  \pgfmathparse{#1}%
  \let\tikz@ellipse@x=\pgfmathresult%
  \ifpgfmathunitsdeclared%
    \pgfmathparse{#2}%
    \let\tikz@ellipse@y=\pgfmathresult%
    \ifpgfmathunitsdeclared%
      \pgfpathellipse{\pgfpointorigin}{%
        \pgfqpoint{\tikz@ellipse@x pt}{0pt}}{\pgfpoint{0pt}{\tikz@ellipse@y pt}}%
    \else%
      \tikzerror{You cannot mix dimensions and dimensionless values in an ellipse}%
    \fi%
  \else%
    \pgfmathparse{#2}%
    \let\tikz@ellipse@y=\pgfmathresult%
    \ifpgfmathunitsdeclared%
      \tikzerror{You cannot mix dimensions and dimensionless values in an ellipse}%
    \else%
      \pgfpathellipse{\pgfpointorigin}{%
        \pgfpointxy{\tikz@ellipse@x}{0}}{\pgfpointxy{0}{\tikz@ellipse@y}}%
    \fi%
  \fi%
}

% Syntax 1 for arcs:
% arc (start angle:end angle:radius)
%
% Syntax 2 for arcs:
% arc (start angle:end angle:x-radius and y-radius)
%
% radius can be dimensionless, then the arc is in the xy-coordinate system
\def\tikz@arcA rc{\tikz@flush@moveto\tikz@arc@cont}%
\def\tikz@arc@cont{%
  \pgfutil@ifnextchar(%)
  {\tikz@@arcto}{%
    \pgfutil@ifnextchar[%]
    {\tikz@arc@opt}%
    {%
      \advance\tikz@expandcount by -10\relax% go down quickly
      \ifnum\tikz@expandcount<0\relax%
        \let\@next=\tikz@@arc@normal%
      \else%
        \let\@next=\tikz@@arc@scanexpand%
      \fi%
      \@next%
    }%
  }%
}
\def\tikz@@arc@scanexpand{\expandafter\tikz@arc@cont}
\def\tikz@@arc@normal{\tikz@arc@opt[]}


\def\tikz@arc@opt[#1]{%
  {%
    \tikzset{every arc/.try,#1}%
    \pgfkeysgetvalue{/tikz/start angle}\tikz@s
    \pgfkeysgetvalue{/tikz/end angle}\tikz@e
    \pgfkeysgetvalue{/tikz/delta angle}\tikz@d
    \ifx\tikz@s\pgfutil@empty%
      \pgfmathsetmacro\tikz@s{\tikz@e-\tikz@d}
    \else
      \ifx\tikz@e\pgfutil@empty%    
        \pgfmathsetmacro\tikz@e{\tikz@s+\tikz@d}
      \fi%
    \fi%
    \xdef\pgf@marshal{\noexpand%
    \tikz@do@arc{\tikz@s}{\tikz@e}
      {\pgfkeysvalueof{/tikz/x radius}}
      {\pgfkeysvalueof{/tikz/y radius}}}%
  }%
  \pgf@marshal%
  \tikz@arcfinal%  
}

\def\tikz@@arcto(#1){%
  \edef\tikz@temp{(#1)}%
  \expandafter\tikz@@@arcto@check@slashand\tikz@temp%
}

\def\tikz@@@arcto@check@slashand(#1:#2:#3){%
  \pgfutil@in@{ and }{#3}%
  \ifpgfutil@in@% 
    \tikz@parse@arc@and(#1:#2:#3)%
  \else%
    \tikz@parse@arc@and(#1:#2:{#3} and {#3})%
  \fi%
  \tikz@arcfinal%  
}

\def\tikz@parse@arc@and(#1:#2:#3 and #4){%
  \tikz@do@arc{#1}{#2}{#3}{#4}%
}
\def\tikz@do@arc#1#2#3#4{%
  \let\tikz@tangent\tikz@tangent@lookup%
  \edef\tikz@timer@start{\noexpand\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}%
  \edef\tikz@timer@start@angle{#1}%
  \edef\tikz@timer@end@angle{#2}%
  \pgfmathparse{#3}%
  \let\tikz@arc@x=\pgfmathresult%
  \ifpgfmathunitsdeclared%
    \pgfmathparse{#4}%
    \let\tikz@arc@y=\pgfmathresult%
    \ifpgfmathunitsdeclared%
      \tikz@@@arcfinal{\pgfpatharc{#1}{#2}{\tikz@arc@x pt and \tikz@arc@y pt}}
      {\pgfpointpolar{#1}{\tikz@arc@x pt and \tikz@arc@y pt}}
      {\pgfpointpolar{#2}{\tikz@arc@x pt and \tikz@arc@y pt}}%
      \edef\tikz@timer@zero@axis{\noexpand\pgfqpoint{\tikz@arc@x pt}{0pt}}  
      \edef\tikz@timer@ninety@axis{\noexpand\pgfqpoint{0pt}{\tikz@arc@y pt}}  
    \else%
      \tikzerror{You cannot mix dimensions and dimensionless values in an arc}%
    \fi%
  \else%
    \pgfmathparse{#4}%
    \let\tikz@arc@y=\pgfmathresult%
    \ifpgfmathunitsdeclared%
      \tikzerror{You cannot mix dimensions and dimensionless values in an arc}%
    \else%
      \tikz@@@arcfinal{\pgfpatharcaxes{#1}{#2}{\pgfpointxy{\tikz@arc@x}{0}}{\pgfpointxy{0}{\tikz@arc@y}}}
      {\pgfpointpolarxy{#1}{\tikz@arc@x and \tikz@arc@y}}{\pgfpointpolarxy{#2}{\tikz@arc@x and \tikz@arc@y}}%
      \pgf@process{\pgfpointxy{\tikz@arc@x}{0}}
      \edef\tikz@timer@zero@axis{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}  
      \pgf@process{\pgfpointxy{0}{\tikz@arc@y}}
      \edef\tikz@timer@ninety@axis{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}  
     \fi%
  \fi%
}

\def\tikz@@@arcfinal#1#2#3{%
  #1%
  \pgf@process{#2}
  \xdef\tikz@arc@save@first{\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
  \pgf@process{#3}
  \xdef\tikz@arc@save@second{\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
}

\def\tikz@arcfinal{%
  \pgf@process{\tikz@arc@save@first}%
  \advance\tikz@lastx by-\pgf@x%
  \advance\tikz@lasty by-\pgf@y%
  \pgf@process{\tikz@arc@save@second}%
  \advance\tikz@lastx by\pgf@x%
  \advance\tikz@lasty by\pgf@y%
  \tikz@lastxsaved=\tikz@lastx%
  \tikz@lastysaved=\tikz@lasty%
  \let\tikz@timer=\tikz@timer@arc%
  \tikz@scan@next@command%
}


% Syntax for coordinates:
% coordinate[options] (coordinate name) at (point)
% where ``at (point)'' is optional
\def\tikz@coordinate ordinate{%
  \pgfutil@ifnextchar[{\tikz@@coordinate@opt}{\tikz@@coordinate@opt[]}}
\def\tikz@@coordinate@opt[#1]{%
  \pgfutil@ifnextchar({\tikz@@coordinate[#1]}
  {\tikz@fig ode[shape=coordinate,#1]{}}}%}
\def\tikz@@coordinate[#1](#2){%
  \pgfutil@ifnextchar a{\tikz@@coordinate@at[#1](#2)}
  {\tikz@fig ode[shape=coordinate,#1](#2){}}}
\def\tikz@@coordinate@at[#1](#2)a{%
  \pgfutil@ifnextchar t{\tikz@@coordinate@@at[#1](#2)a}%
  {\tikz@fig ode[shape=coordinate,#1](#2){}a}%
}
\def\tikz@@coordinate@@at[#1](#2)at#3({%
  \def\tikz@coordinate@caller{\tikz@fig ode[shape=coordinate,#1](#2)at}%
  \tikz@scan@one@point\tikz@@coordinate@at@math(%
}
\def\tikz@@coordinate@at@math#1{%
  \pgf@process{#1}%
  \edef\tikz@temp{(\the\pgf@x,\the\pgf@y)}%
  \expandafter\tikz@coordinate@caller\tikz@temp{}%
}
  


% Syntax for nodes:
% node foreach \var in {list} ... [options] (node name) at (pos) {label text}
%
% all of [options], (node name), at(pos), and foreach are
% optional. There can be multiple options and the ordering is not
% important as in node[draw] (a) [rotate=10] {text}, *except* that all
% foreach statements must come first.
%
% A label text always ``ends'' the node.
%
\def\tikz@fig ode{%
  \pgfutil@ifnextchar a\tikz@test@also{
    \pgfutil@ifnextchar f{\tikz@nodes@start}\tikz@normal@fig}}
\def\tikz@test@also a{\pgfutil@ifnextchar l\tikz@node@also{\tikz@normal@fig a}}%
\def\tikz@normal@fig{%
  \edef\tikz@save@line@width{\the\pgflinewidth}%
  \begingroup%
  \let\tikz@fig@name=\pgfutil@empty%
    \begingroup%
      \tikz@is@matrixfalse%
      \let\nodepart=\tikz@nodepart%
      \let\tikz@atbegin@scope=\pgfutil@empty%
      \let\tikz@atend@scope=\pgfutil@empty%
      \let\tikz@do@after@node=\tikz@scan@next@command%
      \let\tikz@options=\pgfutil@empty%
      \let\tikz@after@path=\pgfutil@empty%
      \let\tikz@transform=\pgfutil@empty%
      \let\tikz@mode=\pgfutil@empty%
      \tikz@decoratepathfalse%
      \let\tikz@preactions=\pgfutil@empty%
      \let\tikz@postactions=\pgfutil@empty%
      \let\tikz@alias=\pgfutil@empty%
      \def\tikz@node@at{\pgfqpoint{\the\tikz@lastx}{\the\tikz@lasty}}%
      \let\tikz@time@for@matrix\tikz@time%
      \let\tikz@node@content\relax%
      \pgfgetpath\tikzpathuptonow%
      \iftikz@node@is@a@label%
      \else%
        \let\tikz@time\pgfutil@empty%
      \fi%
      \tikz@node@reset@hook%
      \tikzset{every node/.try}%
      \tikz@@scan@fig}%
\def\tikz@@scan@fig{%
  \pgfutil@ifnextchar a{\tikz@fig@scan@at}
  {\pgfutil@ifnextchar({\tikz@fig@scan@name}
    {\pgfutil@ifnextchar[{\tikz@fig@scan@options}%
      {\pgfutil@ifnextchar\bgroup{\tikz@fig@main}%
      {\tikzerror{A node must have a (possibly empty) label text}%
       \tikz@fig@main{}}}}}}%}}
\def\tikz@fig@scan@at at{%
  \tikz@scan@one@point\tikz@@fig@scan@at}
\def\tikz@@fig@scan@at#1{%
  \def\tikz@node@at{#1}\tikz@@scan@fig}%
\def\tikz@fig@scan@name(#1){%
	\pgfkeysvalueof{/tikz/name/.@cmd}#1\pgfeov% CF : this is now ALWAYS consistent with 'name=' option; allows overrides.
	\tikz@@scan@fig}%
% make it \long to allow \par in "pin" options etc:
\long\def\tikz@fig@scan@options[#1]{\iftikz@node@is@pic\tikz@enable@pic@quotes\else\tikz@enable@node@quotes\fi\tikzset{#1}\ifx\tikz@node@content\relax\expandafter\tikz@@scan@fig\else\tikz@expand@node@contents\fi}%
\def\tikz@expand@node@contents{%
  \expandafter\tikz@@scan@fig\expandafter{\tikz@node@content}%
}
\let\tikz@node@reset@hook=\pgfutil@empty%
\let\tikz@node@begin@hook=\pgfutil@empty%
\def\tikz@fig@main{%
  \iftikz@node@is@pic%
    \tikz@node@is@picfalse%
    \expandafter\tikz@subpicture@handle%
  \else%
    \afterassignment\tikz@@fig@main\expandafter\let\expandafter\next\expandafter=%
  \fi}
\def\tikz@@fig@main{%
    \pgfutil@ifundefined{pgf@sh@s@\tikz@shape}%
    {\tikzerror{Unknown shape ``\tikz@shape.'' Using ``rectangle'' instead}%
      \def\tikz@shape{rectangle}}%
    {}%
    \tikzset{every \tikz@shape\space node/.try}%
    \tikz@node@textfont%  
    \tikz@node@begin@hook%
    \iftikz@is@matrix%
      \let\tikz@next=\tikz@do@matrix%
    \else%
      \let\tikz@next=\tikz@do@fig%
    \fi%
    \tikz@next%  
}
\let\tikz@nodepart@list\pgfutil@empty
\def\tikz@do@fig{%  
    % Ok, reset all node part boxes
    \pgfutil@for\tikz@temp:=\tikz@nodepart@list\do{%
      \expandafter\setbox\csname pgfnodepart\tikz@temp box\endcsname=\box\pgfutil@voidb@x%
    }%
    \setbox\pgfnodeparttextbox=\hbox%
      \bgroup%
        \tikzset{every text node part/.try}%
        \ifx\tikz@textopacity\pgfutil@empty%
        \else%
          \pgfsetfillopacity{\tikz@textopacity}%
          \pgfsetstrokeopacity{\tikz@textopacity}%
        \fi%
        \pgfinterruptpicture%
          \ifx\tikz@text@width\pgfutil@empty%
            \tikz@textfont%  
          \else%
            \begingroup%
            	\pgfmathsetlength{\pgf@x}{\tikz@text@width}%
              \pgfutil@minipage[t]{\pgf@x}\leavevmode\hbox{}%
                \tikz@textfont%  
                \tikz@text@action%
          \fi%
          \tikz@atbegin@node%
          \bgroup%
            \aftergroup\unskip%
            \ifx\tikz@textcolor\pgfutil@empty%
            \else%
              \pgfutil@colorlet{.}{\tikz@textcolor}%
            \fi%
            \pgfsetcolor{.}%
            \setbox\tikz@figbox=\box\pgfutil@voidb@x%
            \setbox\tikz@figbox@bg=\box\pgfutil@voidb@x%
            \tikz@uninstallcommands%
            \iftikz@handle@active@code%  
              \tikz@orig@shorthands%
              \let\tikz@orig@shorthands\pgfutil@empty%
            \fi%
            \ifnum\the\catcode`\;=\active\relax\expandafter\let\tikz@activesemicolon=\tikz@origsemi\fi%
            \ifnum\the\catcode`\:=\active\relax\expandafter\let\tikz@activecolon=\tikz@origcolon\fi%
            \ifnum\the\catcode`\|=\active\relax\expandafter\let\tikz@activebar=\tikz@origbar\fi%
            \aftergroup\tikz@fig@collectresetcolor%
            \tikz@halign@check%
            \ignorespaces%
}
\def\tikz@fig@collectresetcolor{%
  % Hacks for special packages that mess with \aftergroup
  \pgfutil@ifnextchar\reset@color% hack for color package
  {\reset@color\afterassignment\tikz@fig@collectresetcolor\let\tikz@temp=}\tikz@fig@boxdone%
}
\def\tikz@fig@boxdone{%
            \tikz@atend@node%
          \ifx\tikz@text@width\pgfutil@empty%
          \else%
              \pgfutil@endminipage%
            \endgroup%
          \fi%
        \endpgfinterruptpicture%
      \egroup%
    \pgfutil@ifnextchar c{\tikz@fig@mustbenamed\tikz@fig@continue}%
    {\pgfutil@ifnextchar[{\tikz@fig@mustbenamed\tikz@fig@continue}%
      {\pgfutil@ifnextchar t{\tikz@fig@mustbenamed\tikz@fig@continue}
        {\pgfutil@ifnextchar e{\tikz@fig@mustbenamed\tikz@fig@continue}
          {\ifx\tikz@after@path\pgfutil@empty\expandafter\tikz@fig@continue\else\expandafter\tikz@fig@mustbenamed\expandafter\tikz@fig@continue\fi}}}}}%}

\def\tikz@do@matrix{%
    \tikzset{every matrix/.try}%
    \tikz@node@transformations%
    \tikz@fig@mustbenamed%
    \setbox\tikz@whichbox=\hbox\bgroup%
      \unhbox\tikz@whichbox%
      \hbox\bgroup\bgroup%
          \pgfinterruptpath%
            \pgfscope%
              \ifx\tikz@time\pgfutil@empty\let\tikz@time\tikz@time@for@matrix\fi%
              \tikz@options%
              \setbox\tikz@figbox=\box\pgfutil@voidb@x%
              \setbox\tikz@figbox@bg=\box\pgfutil@voidb@x%
              \let\tikzmatrixname=\tikz@fig@name%
              \edef\tikz@m@anchor{\ifx\tikz@matrix@anchor\pgfutil@empty\tikz@anchor\else\tikz@matrix@anchor\fi}%
              \expandafter\pgfutil@in@\expandafter{\expandafter.\expandafter}\expandafter{\tikz@m@anchor}%
              \ifpgfutil@in@%
                \expandafter\tikz@matrix@split\tikz@m@anchor\relax%
              \else%
                \def\tikz@matrix@shift{\pgfpointorigin}%  
              \fi%
              \let\tikz@transform=\relax%
              \pgfmatrix%
              {\tikz@shape}%
              {\tikz@m@anchor}%
              {\tikz@fig@name}%
              {%
                \pgfutil@tempdima=\pgflinewidth%
                {\begingroup\tikz@finish}%
                \global\pgflinewidth=\pgfutil@tempdima%
              }%
              {\tikz@matrix@shift}%
              {%
                \tikz@matrix@make@active@ampersand%
                \def\pgfmatrixbegincode{%
                  \pgfsys@beginscope%
                  \tikz@common@matrix@code%
                  \tikz@atbegin@cell%
                }%
                \def\tikz@common@matrix@code{%
                  \let\tikz@options=\pgfutil@empty%
                  \let\tikz@mode=\pgfutil@empty%
                  \tikzset{every cell/.try={\the\pgfmatrixcurrentrow}{\the\pgfmatrixcurrentcolumn}}%
                  \tikzset{column \the\pgfmatrixcurrentcolumn/.try}%
                  \ifodd\pgfmatrixcurrentcolumn%
                    \tikzset{every odd column/.try}%
                  \else%
                    \tikzset{every even column/.try}%
                  \fi%
                  \tikzset{row \the\pgfmatrixcurrentrow/.try}%
                  \ifodd\pgfmatrixcurrentrow%
                    \tikzset{every odd row/.try}%
                  \else%
                    \tikzset{every even row/.try}%
                  \fi%
                  \tikzset{row \the\pgfmatrixcurrentrow\space column \the\pgfmatrixcurrentcolumn/.try}%
                  \tikz@options%
                }%
                \def\pgfmatrixendcode{%
                  \tikz@atend@cell%
                  \pgfsys@endscope%
                }%
                \def\pgfmatrixemptycode{%
                  \pgfsys@beginscope%
                  \tikz@common@matrix@code%
                  \tikz@at@emptycell%
                  \pgfsys@endscope%
                }%
                \tikz@atbegin@matrix%
                \aftergroup\tikz@do@matrix@cont}%
              \bgroup%
}
\def\tikz@do@matrix@cont{%
              \tikz@atend@matrix%
            \endpgfscope
          \endpgfinterruptpath%
      \egroup\egroup%
    \egroup%
    %
    \tikz@node@finish%
}

{%
  \catcode`\&=13
  \gdef\tikz@matrix@make@active@ampersand{%
    \ifx\tikz@ampersand@replacement\pgfutil@empty%
      \catcode`\&=13%
      \let&=\pgfmatrixnextcell%
    \else%
      \expandafter\let\tikz@ampersand@replacement=\pgfmatrixnextcell%
    \fi%
  }%
}%


\def\tikz@matrix@split#1.#2\relax{%
  \def\tikz@m@anchor{text}%
  \def\tikz@matrix@shift{\pgfpointanchor{#1}{#2}}%
}
  
\def\tikz@fig@continue{%
    \ifx\tikz@text@width\pgfutil@empty%
    \else%
      \pgfmathsetlength{\pgf@x}{\tikz@text@width}%
      \wd\pgfnodeparttextbox=\pgf@x%
    \fi%
    \ifx\tikz@text@height\pgfutil@empty%
    \else%
      \pgfmathsetlength{\pgf@x}{\tikz@text@height}%
      \ht\pgfnodeparttextbox=\pgf@x%
    \fi%
    \ifx\tikz@text@depth\pgfutil@empty%
    \else%
      \pgfmathsetlength{\pgf@x}{\tikz@text@depth}%
      \dp\pgfnodeparttextbox=\pgf@x%
    \fi%
    %
    % Node transformation
    %
    \tikz@node@transformations%
    \tikz@nlt%
    % 
    \setbox\tikz@whichbox=\hbox{%
      \unhbox\tikz@whichbox%
      \hbox{{%
          \pgfinterruptpath%
            \pgfscope%
              \tikz@options%
              \setbox\tikz@figbox=\box\pgfutil@voidb@x%
              \setbox\tikz@figbox@bg=\box\pgfutil@voidb@x%
              \pgfmultipartnode{\tikz@shape}{\tikz@anchor}{\tikz@fig@name}{%
                \pgfutil@tempdima=\pgflinewidth%
                {\begingroup\tikz@finish}%
                \global\pgflinewidth=\pgfutil@tempdima%
              }%
            \endpgfscope
          \endpgfinterruptpath%
      }}%
    }%
    %
    \tikz@alias%
    \tikz@node@finish%
}


\def\tikz@fig@mustbenamed{%
  \ifx\tikz@fig@name\pgfutil@empty%
    % Assign a dummy name
    \global\advance\tikz@fig@count by1\relax
    \edef\tikz@fig@name{tikz@f@\the\tikz@fig@count}%
  \fi%
}

\def\tikz@node@transformations{%
  % 
  % Possibly, we are ``online''
  % 
  \ifx\tikz@time\pgfutil@empty%
    \pgftransformshift{\tikz@node@at}%
    \iftikz@fullytransformed%
    \else%
      \pgftransformresetnontranslations%
    \fi%
  \else%
    \tikz@do@auto@anchor%
    \tikz@timer%
  \fi%
  % Invoke local transformations
  \tikz@transform%
}

\def\tikz@node@finish{%  
    \global\let\tikz@last@fig@name=\tikz@fig@name%
    \global\let\tikz@after@path@smuggle=\tikz@after@path%
    % shift box outside group
    \global\setbox\tikz@tempbox=\box\tikz@figbox%
    \global\setbox\tikz@tempbox@bg=\box\tikz@figbox@bg%
  \endgroup\endgroup%
  \setbox\tikz@figbox=\box\tikz@tempbox%
  \setbox\tikz@figbox@bg=\box\tikz@tempbox@bg%
  \global\pgflinewidth=\tikz@save@line@width%
  \tikz@do@after@path@smuggle%
  \tikz@do@after@node%
}
\let\tikz@fig@continue@orig=\tikz@fig@continue

\def\tikz@do@after@node{\tikz@scan@next@command}

\def\tikz@do@after@path@smuggle{%
  \let\tikz@to@last@fig@name=\tikz@last@fig@name%
  \let\tikz@to@use@whom=\tikz@to@use@last@fig@name%
  \let\tikzlastnode=\tikz@last@fig@name%
  \ifx\tikz@after@path@smuggle\pgfutil@empty%
  \else%
    \ifpgflatenodepositioning%
      \expandafter\expandafter\expandafter\tikz@call@late%
      \expandafter\expandafter\expandafter{\expandafter\tikz@last@fig@name\expandafter}\expandafter{\tikz@after@path@smuggle}%
    \else%
      \tikz@scan@next@command{\tikz@after@path@smuggle}\pgf@stop%
    \fi%
  \fi%
}

\def\tikz@call@late#1#2{\pgfnodepostsetupcode{#1}{\path[late options={name={#1},append after command={#2}}];}}

\newif\iftikz@do@align

% Alignment handling
\def\tikz@halign@check{%
  \tikz@do@alignfalse
  \ifx\tikz@text@width\pgfutil@empty%
    \pgfkeysgetvalue{/tikz/node halign header}\tikz@align@header%
    \ifx\tikz@align@header\pgfutil@empty%
    \else%
      \tikz@do@aligntrue%
    \fi%
  \fi%
  \iftikz@do@align%
    % Bingo
    \setbox\tikz@align@aligned@box=\box\pgfutil@voidb@x% void
    \let\\=\tikz@align@newline%
    \expandafter\tikz@start@align%
  \fi%    
}
\def\tikz@align@newline{\pgfutil@protect\tikz@align@newline@}
\def\tikz@align@newline@{\unskip\pgfutil@ifnextchar[\tikz@@align@newline{\tikz@@align@newline[0pt]}}%}
\def\tikz@@align@newline[#1]{\egroup\tikz@align@continue\pgfmathparse{#1}\let\tikz@align@temp=\pgfmathresult\tikz@start@align}%
% Two safe boxes for alignment:
\let\tikz@align@aligned@box=\pgfnodeparttextbox
\let\tikz@align@line@box=\tikz@figbox

\def\tikz@start@align{%
  % Start collecting text:
  \setbox\tikz@align@line@box=\hbox\bgroup\bgroup%
    \aftergroup\tikz@align@collectresetcolor\ignorespaces%
}
\def\tikz@align@collectresetcolor{%
  \pgfutil@ifnextchar\reset@color%
  {\reset@color\afterassignment\tikz@align@collectresetcolor\let\tikz@temp=}%
  {\tikz@align@end@check}%
}
\def\tikz@align@end@check{%
  \egroup%
  \ifvoid\tikz@align@aligned@box%
    \setbox\tikz@align@aligned@box=\box\tikz@align@line@box%
  \else%
    \setbox\tikz@align@aligned@box=\vbox{%
      \expandafter\expandafter\expandafter\halign\expandafter\expandafter\expandafter{\tikz@align@header%
        \box\tikz@align@aligned@box\cr%
        \noalign{\vskip\tikz@align@temp pt}%
        \unhbox\tikz@align@line@box\unskip\cr}}%
  \fi%
  \pgfutil@ifnextchar\tikz@align@continue{}
  {%
    % Main continue
      \box\tikz@align@aligned@box%
    \egroup%
  }%
}
\def\tikz@align@continue{\tikz@@align@continue}
\let\tikz@@align@continue=\pgfutil@empty


\def\tikz@node@also lso{\pgfutil@ifnextchar[\tikz@node@also@opt{\tikz@node@also@opt[]}}
\def\tikz@node@also@opt[#1]{
  \pgfutil@ifnextchar(%)
  {\tikz@node@also@opt@cont[#1]}%
  {\tikzerror{Syntax error in node also: ``('' expected.}%
    \tikz@scan@next@command}%
}
\def\tikz@node@also@opt@cont[#1](#2){\tikzset{late options={name=#2,#1}}\tikz@scan@next@command}
    


% Syntax for parts of  nodes:
% node ... {... \nodepart[options]{name} ... \nodepart{name} ...}

\def\tikz@nodepart{\pgfutil@ifnextchar[\tikz@@nodepart{\tikz@@nodepart[]}}%}
\def\tikz@@nodepart[#1]#2{%
  \tikz@atend@node%
  \unskip%
  \gdef\tikz@nodepart@options{#1}%
  \gdef\tikz@nodepart@name{#2}%
  \global\let\tikz@fig@continue=\tikz@nodepart@continue%
  \pgfutil@ifnextchar x{\egroup\relax}{\egroup\relax}% gobble spaces
}
\def\tikz@nodepart@continue{%
  \global\let\tikz@fig@continue=\tikz@fig@continue@orig%
  \ifx\tikz@nodepart@list\pgfutil@empty%
    \let\tikz@nodepart@list\tikz@nodepart@name%
  \else%
    \edef\tikz@nodepart@list{\tikz@nodepart@list,\tikz@nodepart@name}%
  \fi%
  % Now start new box:
   \expandafter\setbox\csname pgfnodepart\tikz@nodepart@name box\endcsname=\hbox%
      \bgroup%
        \tikzset{every \tikz@nodepart@name\space node part/.try}%
        \expandafter\tikzset\expandafter{\tikz@nodepart@options}%
        \ifx\tikz@textopacity\pgfutil@empty%
        \else%
          \pgfsetfillopacity{\tikz@textopacity}%
          \pgfsetstrokeopacity{\tikz@textopacity}%
        \fi%
        \pgfinterruptpicture%
          \ifx\tikz@text@width\pgfutil@empty%
            \tikz@textfont%  
          \else%
            \begingroup%
              \pgfmathsetlength{\pgf@x}{\tikz@text@width}%
              \pgfutil@minipage[t]{\pgf@x}\leavevmode\hbox{}%
                \tikz@textfont%  
                \tikz@text@action%
          \fi%
          \bgroup%
            \aftergroup\unskip%
            \ifx\tikz@textcolor\pgfutil@empty%
            \else%
              \pgfutil@colorlet{.}{\tikz@textcolor}%
            \fi%
            \pgfsetcolor{.}%
            \setbox\tikz@figbox=\box\pgfutil@voidb@x%
            \setbox\tikz@figbox@bg=\box\pgfutil@voidb@x%
            \tikz@uninstallcommands%
            \iftikz@handle@active@code%  
              \tikz@orig@shorthands%
              \let\tikz@orig@shorthands\pgfutil@empty%
            \fi%
            \ifnum\the\catcode`\;=\active\relax\expandafter\let\tikz@activesemicolon=\tikz@origsemi\fi%
            \ifnum\the\catcode`\:=\active\relax\expandafter\let\tikz@activecolon=\tikz@origcolon\fi%
            \ifnum\the\catcode`\|=\active\relax\expandafter\let\tikz@activebar=\tikz@origbar\fi%
            \tikz@atbegin@node%
            \aftergroup\tikz@fig@collectresetcolor%
            \tikz@halign@check%
            \ignorespaces%
}


% 
% Node foreach
% 

\def\tikz@nodes@start{%
  \let\tikz@nodes@list\pgfutil@empty%
  \iftikz@node@is@pic%
    \def\tikz@nodes@collect{pic }%
  \else%
    \def\tikz@nodes@collect{node }%
  \fi%
  \tikz@nodes%
}
\def\tikz@nodes foreach{\pgfutil@ifnextchar x\tikz@nodes@\tikz@nodes@}% get rid of spaces
\def\tikz@nodes@#1in{%
  \expandafter\def\expandafter\tikz@nodes@list\expandafter{\tikz@nodes@list\foreach#1in}%
  \pgfutil@ifnextchar\bgroup\tikz@nodes@group\tikz@nodes@one%
}
\def\tikz@nodes@one#1{%
  \expandafter\def\expandafter\tikz@nodes@list\expandafter{\tikz@nodes@list#1}%
  \pgfutil@ifnextchar f\tikz@nodes\tikz@nodes@scan%
}
\def\tikz@nodes@group#1{%
  \expandafter\def\expandafter\tikz@nodes@list\expandafter{\tikz@nodes@list{#1}}%
  \pgfutil@ifnextchar f\tikz@nodes\tikz@nodes@scan%
}
\def\tikz@nodes@scan{%
  \pgfutil@ifnextchar a{\tikz@nodes@at}%
  {\pgfutil@ifnextchar({\tikz@nodes@name}%
    {\pgfutil@ifnextchar[{\tikz@nodes@opt}%
      {\pgfutil@ifnextchar\bgroup{\tikz@nodes@main}%
      {\tikzerror{Nodes must have a (possibly empty) label text}%
        \tikz@fig@main{}}}}}}%}}
\def\tikz@nodes@at at#1){%
  \expandafter\def\expandafter\tikz@nodes@collect\expandafter{\tikz@nodes@collect at#1)}%
  \tikz@nodes@scan}%
\def\tikz@nodes@name#1){%
  \expandafter\def\expandafter\tikz@nodes@collect\expandafter{\tikz@nodes@collect#1)}%
  \tikz@nodes@scan}%
\def\tikz@nodes@opt#1]{%
  \expandafter\def\expandafter\tikz@nodes@collect\expandafter{\tikz@nodes@collect#1]}%
  \tikz@nodes@scan}%
\def\tikz@nodes@main#1{%
  \iftikz@handle@active@nodes%
    \iftikz@node@is@pic%
      \expandafter\def\expandafter\tikz@nodes@collect\expandafter{\tikz@nodes@collect{#1}}%
    \else%
      \expandafter\def\expandafter\tikz@nodes@collect\expandafter{\tikz@nodes@collect{\scantokens{#1}}}%
    \fi%
  \else%
    \expandafter\def\expandafter\tikz@nodes@collect\expandafter{\tikz@nodes@collect{#1}}%
  \fi%
  % Ok, got everything.
  % Now, start building parse text.
  \global\setbox\tikz@tempbox=\box\tikz@figbox%
  \global\setbox\tikz@tempbox@bg=\box\tikz@figbox@bg%
  \tikz@nodes@list{%
    \setbox\tikz@figbox=\box\tikz@tempbox%
    \setbox\tikz@figbox@bg=\box\tikz@tempbox@bg%
    \expandafter\tikz@scan@next@command\tikz@nodes@collect\pgfextra\relax%
    \global\setbox\tikz@tempbox=\box\tikz@figbox%
    \global\setbox\tikz@tempbox@bg=\box\tikz@figbox@bg%
  }%
  \setbox\tikz@figbox=\box\tikz@tempbox%
  \setbox\tikz@figbox@bg=\box\tikz@tempbox@bg%
  \tikz@scan@next@command%
}



%
% "late" options can be used to "redo" a node
%
\tikzset{late options/.code=\tikz@late@options{#1}}
\def\tikz@late@options#1{%
  % Do a "virtual" node:
  \begingroup%
    \iftikz@shapeborder%
      \let\tikz@fig@name=\tikz@shapeborder@name%
    \else%
      \let\tikz@fig@name=\pgfutil@empty%
    \fi%
    \tikz@is@matrixfalse%
    \let\tikz@options=\pgfutil@empty%
    \let\tikz@after@path=\pgfutil@empty%
    \let\tikz@afternodepathoptions=\pgfutil@empty%
    \let\tikz@alias=\pgfutil@empty%
    \let\tikz@transform=\pgfutil@empty%
    \tikz@decoratepathfalse%
    \tikz@node@reset@hook%
    \tikz@enable@node@quotes%
    \tikzset{every node/.try,#1}% 
    \ifx\tikz@fig@name\pgfutil@empty%
      \tikzerror{Late options must reference some existing node}%
    \fi%
    \tikz@node@begin@hook%
    \tikz@alias%
    \tikzgdlatenodeoptionacallback{\tikz@fig@name}%
    \global\let\tikz@last@fig@name=\tikz@fig@name%
    \global\let\tikz@after@path@smuggle=\tikz@after@path%
  \endgroup%
  \tikz@do@after@path@smuggle%
}


% Auto placement

\def\tikz@auto@pre{%
  \begingroup
    \pgfresetnontranslationattimefalse
    \pgfslopedattimetrue%
    \pgfallowupsidedownattimetrue%
    \tikz@timer%
    \pgf@x=\pgf@pt@aa pt% 
    \pgf@y=\pgf@pt@ab pt%
    \pgfpointnormalised{}%
}

\def\tikz@auto@post{%
    \global\let\tikz@anchor@smuggle=\tikz@anchor%
  \endgroup%
  \let\tikz@anchor=\tikz@anchor@smuggle%
}

\def\tikz@auto@anchor{%
    \ifdim\pgf@x>0.05pt%
      \ifdim\pgf@y>0.05pt%
        \def\tikz@anchor{south east}%
      \else\ifdim\pgf@y<-0.05pt%
        \def\tikz@anchor{south west}%
      \else
        \def\tikz@anchor{south}%
      \fi\fi%
    \else\ifdim\pgf@x<-0.05pt%
      \ifdim\pgf@y>0.05pt%
        \def\tikz@anchor{north east}%
      \else\ifdim\pgf@y<-0.05pt%
        \def\tikz@anchor{north west}%
      \else
        \def\tikz@anchor{north}%
      \fi\fi%
    \else%
      \ifdim\pgf@y>0pt%
        \def\tikz@anchor{east}%
      \else%
        \def\tikz@anchor{west}%
      \fi%
    \fi\fi%
}

\def\tikz@auto@anchor@prime{%
    \ifdim\pgf@x>0.05pt%
      \ifdim\pgf@y>0.05pt%
        \def\tikz@anchor{north west}%
      \else\ifdim\pgf@y<-0.05pt%
        \def\tikz@anchor{north east}%
      \else
        \def\tikz@anchor{north}%
      \fi\fi%
    \else\ifdim\pgf@x<-0.05pt%
      \ifdim\pgf@y>0.05pt%
        \def\tikz@anchor{south west}%
      \else\ifdim\pgf@y<-0.05pt%
        \def\tikz@anchor{south east}%
      \else
        \def\tikz@anchor{south}%
      \fi\fi%
    \else%
      \ifdim\pgf@y>0pt%
        \def\tikz@anchor{west}%
      \else%
        \def\tikz@anchor{east}%
      \fi%
    \fi\fi%
}


%
% Callbacks: Please see the documentation of the graph drawing
% lib for info on these callbacks
%
\def\tikzgdeventcallback#1#2{}
\def\tikzgdeventgroupcallback#1{}
\def\tikzgdlatenodeoptionacallback#1{}

% Syntax for trees:
% node {...} child [options] {...} child [options] {...} ...
% node {...} child [options] foreach \var in {list} [options] {...} ...

\def\tikz@children{%
  % Start collecting the children:
  \let\tikz@children@list=\pgfutil@empty%
  \tikznumberofchildren=0\relax%
  \tikz@collect@children c}

\def\tikz@collect@children{\pgfutil@ifnextchar c{\tikz@collect@children@cchar}{\tikz@children@collected}}
\def\tikz@collect@children@cchar c{\pgfutil@ifnextchar h{\tikz@collect@child}{\tikz@children@collected c}}
\def\tikz@collect@child hild{\pgfutil@ifnextchar[{\tikz@collect@childA}{\tikz@collect@childA[]}}%}
\def\tikz@collect@childA[#1]{\pgfutil@ifnextchar f{\tikz@collect@children@foreach[#1]}{\tikz@collect@childB[#1]}}
\def\tikz@collect@childB[#1]{%
  \advance\tikznumberofchildren by1\relax
  \expandafter\def\expandafter\tikz@children@list\expandafter{\tikz@children@list \tikz@childnode[#1]}%
  \pgfutil@ifnextchar\bgroup{\tikz@collect@child@code}{\tikz@collect@child@code{}}}
\def\tikz@collect@child@code#1{%
  \expandafter\def\expandafter\tikz@children@list\expandafter{\tikz@children@list{#1}}%
  \tikz@collect@children%
}
\def\tikz@collect@children@foreach[#1]foreach#2in#3{%
  \pgfutil@ifnextchar\bgroup{\tikz@collect@children@foreachA{#1}{#2}{#3}}{\tikz@collect@children@foreachA{#1}{#2}{#3}{}}}
\def\tikz@collect@children@foreachA#1#2#3#4{%
  \expandafter\def\expandafter\tikz@children@list\expandafter
    {\tikz@children@list\tikz@childrennodes[#1]{#2}{#3}{#4}}%
  \c@pgf@counta=\tikznumberofchildren%
  \foreach#2in{#3}%
  {%
    \global\advance\c@pgf@counta by1\relax%
  }%
  \tikznumberofchildren=\c@pgf@counta%
  \tikz@collect@children%
}
\long\def\tikz@children@collected{%
  \begingroup%
    \advance\tikztreelevel by 1\relax%
    \tikzgdeventgroupcallback{descendants}%
    \let\tikz@options=\pgfutil@empty%
    \let\tikz@transform=\pgfutil@empty%
    \tikzset{level/.try=\the\tikztreelevel,level \the\tikztreelevel/.try}%
    \tikz@transform%            
    \let\tikz@transform=\relax%
    \let\tikzparentnode=\tikz@last@fig@name%
    \ifx\tikz@grow\relax\else%
      % Transform to center of node
      \pgftransformshift{\pgfpointanchor{\tikzparentnode}{\tikz@growth@anchor}}%
    \fi%
    \tikznumberofcurrentchild=0\relax%
    \tikz@children@list%
    \global\setbox\tikz@tempbox=\box\tikz@figbox%
    \global\setbox\tikz@tempbox@bg=\box\tikz@figbox@bg%
  \endgroup%
  \setbox\tikz@figbox=\box\tikz@tempbox%  
  \setbox\tikz@figbox@bg=\box\tikz@tempbox@bg%  
  \tikz@scan@next@command%
}

% Syntax for children:
%
% child [all children options] foreach \var in {values} [child options] {...}
\def\tikz@childrennodes[#1]#2#3#4{%
  \c@pgf@counta=\tikznumberofcurrentchild\relax%
  \setbox\tikz@tempbox=\box\tikz@figbox%
  \setbox\tikz@tempbox@bg=\box\tikz@figbox@bg%
  \foreach#2in{#3}{%
    \tikznumberofcurrentchild=\c@pgf@counta\relax%
    \setbox\tikz@figbox=\box\tikz@tempbox%
    \setbox\tikz@figbox@bg=\box\tikz@tempbox@bg%
    \tikz@childnode[#1]{#4}%
    % we must now make the current child number and the figbox survive
    % the group
    \global\c@pgf@counta=\tikznumberofcurrentchild\relax%
    \global\setbox\tikz@tempbox=\box\tikz@figbox%
    \global\setbox\tikz@tempbox@bg=\box\tikz@figbox@bg%
  }%
  \tikznumberofcurrentchild=\c@pgf@counta\relax%
  \setbox\tikz@figbox=\box\tikz@tempbox%
  \setbox\tikz@figbox@bg=\box\tikz@tempbox@bg%
}


% Syntax for child:
%
% child
%
% child[options]
%
% child[options] {node (name) {child node text} ...
%   edge from parent[options] node {label text} node {label text}}

\def\tikz@childnode[#1]#2{%
  \advance\tikznumberofcurrentchild by1\relax%
  {\tikzset{every child/.try,#1}\expandafter}%
  \iftikz@child@missing%
    \tikzgdeventcallback{node}{}%
  \else%
  \setbox\tikz@whichbox=\hbox\bgroup%
    \unhbox\tikz@whichbox%
    \hbox\bgroup\bgroup%
        \pgfinterruptpath%
          \pgfscope%
            \let\tikz@transform=\pgfutil@empty%
            \tikzset{every child/.try,#1}%
            \tikz@options%
            \tikz@transform%            
            \let\tikz@transform=\relax%
            \tikz@grow%
            % Typeset node:
            \edef\tikz@parent@node@name{[name=\tikzparentnode-\the\tikznumberofcurrentchild,style=every child node]}%
            \def\tikz@child@node@text{[shape=coordinate]{}}
            \tikz@parse@child@node#2\pgf@stop%
            \expandafter\expandafter\expandafter\node
            \expandafter\tikz@parent@node@name
              \tikz@child@node@text
              \pgfextra{\global\let\tikz@childnode@name=\tikz@last@fig@name};%
            \let\tikzchildnode=\tikz@childnode@name%
            {%
              \def\tikz@edge@to@parent@needed{edge from parent}
              \ifx\tikz@child@node@rest\pgfutil@empty%
                \path edge from parent;%
              \else%
                \path \tikz@child@node@rest \tikz@edge@to@parent@needed;%
              \fi%
            }%
        \endpgfscope%
      \endpgfinterruptpath%
    \egroup\egroup%
  \egroup%
  \fi%
}

\def\tikz@parse@child@node{%
  \pgfutil@ifnextchar n{\tikz@parse@child@node@n}%
  {\pgfutil@ifnextchar c{\tikz@parse@child@node@c}%
    {\pgfutil@ifnextchar\pgf@stop\tikz@parse@child@node@rest\tikz@parse@child@node@expand}}}
\def\tikz@parse@child@node@expand{%
  \advance\tikz@expandcount by-1\relax%
  \ifnum\tikz@expandcount<0\relax%
    \expandafter\tikz@parse@child@node@rest%
  \else%
    \expandafter\expandafter\expandafter\tikz@parse@child@node%
  \fi%
}
\def\tikz@parse@child@node@rest#1\pgf@stop{\tikz@expandcount=100\relax\def\tikz@child@node@rest{#1}}
\def\tikz@parse@child@node@c c{\tikz@expandcount=100\pgfutil@ifnextchar o{\tikz@parse@child@node@co}{\tikz@parse@child@node@rest c}}
\def\tikz@parse@child@node@co o{\pgfutil@ifnextchar o{\tikz@parse@child@node@coordinate}{\tikz@parse@child@node@rest co}}
\def\tikz@parse@child@node@coordinate ordinate{%
  \pgfutil@ifnextchar ({\tikz@@parse@child@node@coordinate}{%
    \def\tikz@child@node@text{[shape=coordinate]{}}%
    \tikz@parse@child@node@rest}}%}
\def\tikz@@parse@child@node@coordinate(#1){%
  \pgfutil@ifnextchar a{\tikz@p@c@n@c@at(#1)}{%
    \def\tikz@child@node@text{[shape=coordinate,name=#1]{}}%
    \tikz@parse@child@node@rest}}
\def\tikz@p@c@n@c@at(#1)at#2({%
  \def\tikz@child@node@text@pre{[shape=coordinate,name=#1]at}%
  \tikz@scan@one@point\tikz@p@c@n@c@at@math(%
}
\def\tikz@p@c@n@c@at@math#1{%
  \pgf@process{#1}%
  \edef\tikz@marshal{(\the\pgf@x,\the\pgf@y){}}%
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\tikz@child@node@text%
  \expandafter\expandafter\expandafter{\expandafter\tikz@child@node@text@pre\tikz@marshal}%
  \tikz@parse@child@node@rest%
}
\def\tikz@parse@child@node@n node{\tikz@expandcount=100%
  \let\tikz@child@node@text=\pgfutil@empty%
  \tikz@p@c@s}%
\def\tikz@p@c@s{%
  \pgfutil@ifnextchar a{\tikz@p@c@s@at}
  {\pgfutil@ifnextchar ({\tikz@p@c@s@paran}
    {\pgfutil@ifnextchar [{\tikz@p@c@s@bra}
      {\pgfutil@ifnextchar \bgroup{\tikz@p@c@s@group}
        {\tikzerror{Cannot parse this node}}}}}}%}}
\def\tikz@p@c@s@at at#1({%
  \tikz@scan@one@point\tikz@p@c@s@at@math(%
}
\def\tikz@p@c@s@at@math#1{%
  \pgf@process{#1}%
  \edef\tikz@marshal{ at(\the\pgf@x,\the\pgf@y)}%
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\tikz@child@node@text%
  \expandafter\expandafter\expandafter{\expandafter\tikz@child@node@text\tikz@marshal}
  \tikz@p@c@s}
\def\tikz@p@c@s@paran(#1){%
  \expandafter\def\expandafter\tikz@child@node@text\expandafter{\tikz@child@node@text(#1)}
  \tikz@p@c@s}
\def\tikz@p@c@s@bra[#1]{%
  \expandafter\def\expandafter\tikz@child@node@text\expandafter{\tikz@child@node@text[#1]}
  \tikz@p@c@s}
\def\tikz@p@c@s@group#1{%
  \iftikz@handle@active@nodes% 
    \expandafter\def\expandafter\tikz@child@node@text\expandafter{\tikz@child@node@text{\scantokens{#1}}}%
  \else%
    \expandafter\def\expandafter\tikz@child@node@text\expandafter{\tikz@child@node@text{#1}}
  \fi%
  \tikz@parse@child@node@rest%
}



% 
% Syntax for decorated subpaths:
%
% decorate [option] { subpath }
%
\def\tikz@decoration ecorate{%
  \pgfutil@ifnextchar[{\tikz@lib@decoration}{\tikz@lib@decoration[]}%]
}

\def\tikz@lib@decoration[#1]#2{\tikzerror{You need to load a decoration library}}

% The decorate path command:
\def\tikz@lib@dec@decorate@path{\tikzerror{You need to load a decoration library}}



% 
% Syntax for let :
%
% let \p1 = (coordinate), \p2 = (coordinate),... in 
%
\def\tikz@let@command et#1in{%
  \tikzerror{You need to say \string\usetikzlibrary{calc} to use the let command}%
}


%
% Syntax for pictures:
% 
% as for nodes, but with "pic" instead of "node"
% 
\newif\iftikz@node@is@pic
\def\tikz@subpicture ic{\tikz@node@is@pictrue\tikz@scan@next@command node}
\def\tikz@subpicture@handle#1{%
  \pgfkeys@spdef\tikz@temp{#1}%
  \expandafter\tikz@subpicture@handle@\expandafter{\tikz@temp}%
}
\def\tikz@subpicture@handle@#1{
  \pgfkeys{/tikz/pics/.cd,#1}
  \tikz@node@transformations%
  \let\tikz@transform=\relax%
  \let\tikz@picmode\tikz@mode%
  \tikzset{name prefix ../.style/.expanded={/tikz/name prefix=\pgfkeysvalueof{/tikz/name prefix}}}%
  \ifx\tikz@fig@name\pgfutil@empty\else%
    \tikzset{name prefix/.prefix/.expanded=\tikz@fig@name}%
  \fi%
  \pgfkeysvalueof{/tikz/pics/setup code}%
  \pgfkeysgetvalue{/tikz/pics/code}{\tikz@pic@code}
  \ifx\tikz@pic@code\pgfutil@empty\else%
  \setbox\tikz@whichbox=\hbox\bgroup%
    \unhbox\tikz@whichbox%
      \hbox\bgroup
        \bgroup%
          \pgfinterruptpath%
            \pgfscope%
              \tikz@options%
              \setbox\tikz@figbox=\box\pgfutil@voidb@x%
              \setbox\tikz@figbox@bg=\box\pgfutil@voidb@x%
              \tikz@atbegin@scope%
              \scope[every pic/.try]%
                \tikz@pic@code%
              \endscope%
              \tikz@atend@scope%
            \endpgfscope%
          \endpgfinterruptpath%
        \egroup
      \egroup%
    \egroup%
  \fi%  
  \pgfkeysgetvalue{/tikz/pics/foreground code}{\tikz@pic@code}
  \ifx\tikz@pic@code\pgfutil@empty\else%
  \setbox\tikz@figbox=\hbox\bgroup%
    \unhbox\tikz@figbox%
      \hbox\bgroup
        \bgroup%
          \pgfinterruptpath%
            \pgfscope%
              \tikz@options%
              \setbox\tikz@figbox=\box\pgfutil@voidb@x%
              \setbox\tikz@figbox@bg=\box\pgfutil@voidb@x%
              \tikz@atbegin@scope%
              \scope[every front pic/.try]%
                \tikz@pic@code%
              \endscope%
              \tikz@atend@scope%
            \endpgfscope%
          \endpgfinterruptpath%
        \egroup
      \egroup%
    \egroup%
  \fi%  
  \pgfkeysgetvalue{/tikz/pics/background code}{\tikz@pic@code}
  \ifx\tikz@pic@code\pgfutil@empty\else%
  \setbox\tikz@figbox@bg=\hbox\bgroup%
    \unhbox\tikz@figbox@bg%
      \hbox\bgroup
        \bgroup%
          \pgfinterruptpath%
            \pgfscope%
              \tikz@options%
              \setbox\tikz@figbox=\box\pgfutil@voidb@x%
              \setbox\tikz@figbox@bg=\box\pgfutil@voidb@x%
              \tikz@atbegin@scope%
              \scope[every behind pic/.try]%
                \tikz@pic@code%
              \endscope%
              \tikz@atend@scope%
            \endpgfscope%
          \endpgfinterruptpath%
        \egroup
      \egroup%
    \egroup%
  \fi%  
  \tikz@node@finish%
}
\tikzset{
  pic actions/.code=\tikz@addmode{\tikz@picmode}
}

% Setting up the picture codes:
\tikzset{
  pics/setup code/.initial=,
  pics/code/.initial=,
  pics/background code/.initial=,
  pics/foreground code/.initial=
}

% Defining pictures:

\def\tikzdeclarepic#1#2{\pgfkeys{/tikz/#1/.cd,#2}}

\pgfkeysdef{/handlers/.pic}{%
  \edef\pgf@temp{\pgfkeyscurrentpath}%
  \edef\pgf@temp{\expandafter\tikz@smuggle@pics@in\pgf@temp\pgf@stop}%
  \expandafter\pgfkeys\expandafter{\pgf@temp/.style={code={#1}}}
}
\def\tikz@smuggle@pics@in/tikz/#1\pgf@stop{/tikz/pics/#1}

%
% Timers
% 

\def\tikz@timer@line{%
  \pgftransformlineattime{\tikz@time}{\tikz@timer@start}{\tikz@timer@end}%
}

\def\tikz@timer@vhline{%
  \ifdim\tikz@time pt<0.5pt% first half
    \pgf@process{\tikz@timer@start}%
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgf@process{\tikz@timer@end}%
    \pgf@xb=\tikz@time pt%
    \pgf@xb=2\pgf@xb%    
    \edef\tikz@marshal{\noexpand\pgftransformlineattime{\pgf@sys@tonumber{\pgf@xb}}{\noexpand\tikz@timer@start}{%
        \noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@y}}}%
    \tikz@marshal%
  \else% second half
    \pgf@process{\tikz@timer@start}%
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgf@process{\tikz@timer@end}%
    \pgf@xb=\tikz@time pt%
    \pgf@xb=2\pgf@xb%
    \advance\pgf@xb by-1pt%
    \edef\tikz@marshal{\noexpand\pgftransformlineattime{\pgf@sys@tonumber{\pgf@xb}}%
      {\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@y}}{\noexpand\tikz@timer@end}}%
    \tikz@marshal%
  \fi%
}

\def\tikz@timer@hvline{%
  \ifdim\tikz@time pt<0.5pt% first half
    \pgf@process{\tikz@timer@start}%
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgf@process{\tikz@timer@end}%
    \pgf@xb=\tikz@time pt%
    \pgf@xb=2\pgf@xb%    
    \edef\tikz@marshal{\noexpand\pgftransformlineattime{\pgf@sys@tonumber{\pgf@xb}}{\noexpand\tikz@timer@start}{%
        \noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@ya}}}%
    \tikz@marshal%
  \else% second half
    \pgf@process{\tikz@timer@start}%
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgf@process{\tikz@timer@end}%
    \pgf@xb=\tikz@time pt%
    \pgf@xb=2\pgf@xb%
    \advance\pgf@xb by-1pt%
    \edef\tikz@marshal{\noexpand\pgftransformlineattime{\pgf@sys@tonumber{\pgf@xb}}%
      {\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@ya}}{\noexpand\tikz@timer@end}}%
    \tikz@marshal%
  \fi%
}

\def\tikz@timer@curve{%
  \pgftransformcurveattime{\tikz@time}{\tikz@timer@start}{\tikz@timer@cont@one}{\tikz@timer@cont@two}{\tikz@timer@end}%
}


\def\tikz@timer@arc{%
  \pgfmathcos@{\tikz@timer@start@angle}%
  \let\tikz@angle@cos\pgfmathresult%
  \pgfmathsin@{\tikz@timer@start@angle}%
  \let\tikz@angle@sin\pgfmathresult%
  \pgftransformarcaxesattime{\tikz@time}{%
    \pgfpointdiff{%
      \pgfpointadd{%
        \pgfpointscale{\tikz@angle@cos}{\tikz@timer@zero@axis}%
      }{%
        \pgfpointscale{\tikz@angle@sin}{\tikz@timer@ninety@axis}%
      }%
    }%
    {\tikz@timer@start}%
  }%
  {\tikz@timer@zero@axis}%
  {\tikz@timer@ninety@axis}%
  {\tikz@timer@start@angle}{\tikz@timer@end@angle}%
}



%
% Coordinate systems
% 

\def\tikzdeclarecoordinatesystem#1#2{%
  \expandafter\def\csname tikz@parse@cs@#1\endcsname(##1){%
    \pgf@process{%
      #2%
      \global\let\tikz@smubble@b=\tikz@shapeborder@name%
    }%
    \let\tikz@shapeborder@name=\tikz@smubble@b%
    \edef\tikz@return@coordinate{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}}%
}
\def\tikzaliascoordinatesystem#1#2{%
  \edef\pgf@marshal{\noexpand\let\expandafter\noexpand\csname
    tikz@parse@cs@#1\endcsname=\expandafter\noexpand\csname
    tikz@parse@cs@#2\endcsname}%
  \pgf@marshal%
}


% Default coodinate systems:

\tikzdeclarecoordinatesystem{canvas}
{%
  \tikzset{cs/.cd,x=0pt,y=0pt,#1}%
  \pgfpoint{\tikz@cs@x}{\tikz@cs@y}%
}

\tikzdeclarecoordinatesystem{canvas polar}
{%
  \tikzset{cs/.cd,angle=0,radius=0cm,#1}%
  \pgfpointpolar{\tikz@cs@angle}{\tikz@cs@xradius and \tikz@cs@yradius}%
}

\tikzdeclarecoordinatesystem{xyz}
{%
  \tikzset{cs/.cd,x=0,y=0,z=0,#1}%
  \pgfpointxyz{\tikz@cs@x}{\tikz@cs@y}{\tikz@cs@z}%
}

\tikzdeclarecoordinatesystem{xyz polar}
{%
  \tikzset{cs/.cd,angle=0,radius=0,#1}%
  \pgfpointpolarxy{\tikz@cs@angle}{\tikz@cs@xradius and \tikz@cs@yradius}%
}
\tikzaliascoordinatesystem{xy polar}{xyz polar}


\tikzdeclarecoordinatesystem{node}
{%
  \tikzset{cs/.cd,name=,anchor=none,angle=none,#1}%
  \ifx\tikz@cs@anchor\tikz@nonetext%
    \ifx\tikz@cs@angle\tikz@nonetext%
      \expandafter\ifx\csname pgf@sh@ns@\tikz@cs@node\endcsname\tikz@coordinate@text%
      \else
        \aftergroup\tikz@shapebordertrue%
        \edef\tikz@shapeborder@name{\tikz@pp@name{\tikz@cs@node}}%
      \fi%
      \pgfpointanchor{\tikz@pp@name{\tikz@cs@node}}{center}%
    \else%
      \pgfpointanchor{\tikz@pp@name{\tikz@cs@node}}{\tikz@cs@angle}%
    \fi%
  \else%
    \pgfpointanchor{\tikz@pp@name{\tikz@cs@node}}{\tikz@cs@anchor}%
  \fi%
}

% Intersection coordinates
\tikzset{cs/first line/.code=\def\tikz@cs@line@a{#1}\def\tikz@cs@type@a{line}}
\tikzset{cs/second line/.code=\def\tikz@cs@line@b{#1}\def\tikz@cs@type@b{line}}

\tikzset{cs/first node/.code=\tikz@cs@unpack{\tikz@cs@node@a}{\tikz@cs@type@a}{#1}}
\tikzset{cs/second node/.code=\tikz@cs@unpack{\tikz@cs@node@b}{\tikz@cs@type@b}{#1}}

\def\tikz@cs@unpack#1#2#3{%
  \expandafter\ifx\csname pgf@sh@ns@#3\endcsname\relax%
    \tikzerror{Undefined node ``#3''}%
  \else%
    \def#1{#3}%
    \edef#2{\csname pgf@sh@ns@#3\endcsname}%
  \fi%
}

\tikzset{cs/solution/.initial=1}

\tikzset{cs/horizontal line through/.store in=\tikz@cs@hori@line}
\tikzset{cs/vertical line through/.store in=\tikz@cs@vert@line}

\tikzdeclarecoordinatesystem{intersection}
{%
  \tikzset{cs/.cd,#1}%
  \expandafter\ifx\csname tikz@intersect@\tikz@cs@type@a @and@\tikz@cs@type@b\endcsname\relax%
    \tikzerror{I do not know how to compute the intersection
    of a \tikz@cs@type@a and a \tikz@cs@type@b. Try saying
    \string\usetikzlibrary{calc}}%
    \pgfpointorigin%
  \else%
    \csname tikz@intersect@\tikz@cs@type@a @and@\tikz@cs@type@b\endcsname%
  \fi%
}

\def\tikz@intersect@line@and@line{%
  \expandafter\tikz@scan@one@point\expandafter\tikz@parse@line\tikz@cs@line@a%
  \pgf@xa=\pgf@xc%
  \pgf@ya=\pgf@yc%
  \pgf@xb=\pgf@x%
  \pgf@yb=\pgf@y%
  \expandafter\tikz@scan@one@point\expandafter\tikz@parse@line\tikz@cs@line@b%
  \edef\pgf@marshal{%
    {\noexpand\pgfpointintersectionoflines%
      {\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}%
      {\noexpand\pgfqpoint{\the\pgf@xb}{\the\pgf@yb}}%
      {\noexpand\pgfqpoint{\the\pgf@xc}{\the\pgf@yc}}%
      {\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}}}%
  \pgf@marshal%
}

\def\tikz@parse@line#1--{%
  \pgf@process{#1}%
  \pgf@xc=\pgf@x%
  \pgf@yc=\pgf@y%
  \tikz@scan@one@point\pgf@process%
}


\tikzdeclarecoordinatesystem{perpendicular}
{%
  \tikzset{cs/.cd,#1}%
  \expandafter\tikz@scan@one@point\expandafter\tikz@parse@intersection@a\tikz@cs@hori@line%
  \expandafter\tikz@scan@one@point\expandafter\tikz@parse@intersection@b\tikz@cs@vert@line%
  \pgfqpoint{\the\pgf@xb}{\the\pgf@ya}
}

\tikzdeclarecoordinatesystem{barycentric}
{%
  {%
    \pgf@xa=0pt% point
    \pgf@ya=0pt%
    \pgf@xb=0pt% sum
    \tikz@bary@dolist#1,=,%
    \pgfmathparse{1/\the\pgf@xb}%
    \global\pgf@x=\pgfmathresult\pgf@xa%
    \global\pgf@y=\pgfmathresult\pgf@ya%
  }%
}

\def\tikz@bary@dolist#1=#2,{%
  \def\tikz@temp{#1}%
  \ifx\tikz@temp\pgfutil@empty%
  \else
    \pgf@process{\pgfpointanchor{#1}{center}}%
    \pgfmathparse{#2}%
    \advance\pgf@xa by\pgfmathresult\pgf@x%
    \advance\pgf@ya by\pgfmathresult\pgf@y%
    \advance\pgf@xb by\pgfmathresult pt%
    \expandafter\tikz@bary@dolist%
  \fi%
}

\tikzset{cs/x/.store in=\tikz@cs@x}
\tikzset{cs/y/.store in=\tikz@cs@y}
\tikzset{cs/z/.store in=\tikz@cs@z}
\tikzset{cs/angle/.store in=\tikz@cs@angle}
\tikzset{cs/x radius/.store in=\tikz@cs@xradius}
\tikzset{cs/y radius/.store in=\tikz@cs@yradius}
\tikzset{cs/radius/.style={/tikz/cs/x radius=#1,/tikz/cs/y radius=#1}}
\tikzset{cs/name/.store in=\tikz@cs@node}
\tikzset{cs/anchor/.store in=\tikz@cs@anchor}



%
% Coordinate management
%


% Last position visited
\def\tikz@last@position{\pgfqpoint{\tikz@lastx}{\tikz@lasty}}
\def\tikz@last@position@saved{\pgfqpoint{\tikz@lastxsaved}{\tikz@lastysaved}}

% Make given point the last position visited
\def\tikz@make@last@position#1{%
  \pgf@process{#1}%
  \tikz@lastx=\pgf@x\relax%
  \tikz@lasty=\pgf@y\relax%
  \iftikz@updatecurrent%
    \tikz@lastxsaved=\pgf@x\relax%
    \tikz@lastysaved=\pgf@y\relax%
  \fi%
  \tikz@updatecurrenttrue%
}

\newif\iftikz@updatecurrent
\tikz@updatecurrenttrue



% Scanner: Scans a point or a relative point. 
% It then calls the first parameter with the argument set to an
% appropriate pgf command representing that point.

\def\tikz@scan@one@point#1{%
  \let\tikz@to@use@whom=\tikz@to@use@last@coordinate%
  \tikz@shapeborderfalse%
  \pgfutil@ifnextchar+{\tikz@scan@relative#1}{\tikz@scan@absolute#1}}
\def\tikz@scan@absolute#1{%
  \pgfutil@ifnextchar({\tikz@scan@@absolute#1}%)
  {%
    \advance\tikz@expandcount by -1%
    \ifnum\tikz@expandcount<0\relax%
      \let\@next=\tikz@@scangiveup%
    \else%
      \let\@next=\tikz@@scanexpand%
    \fi%
    \@next{#1}%
  }%
}
\def\tikz@@scanexpand#1{\expandafter\tikz@scan@one@point\expandafter#1}
\def\tikz@@scangiveup#1{\tikzerror{Cannot parse this coordinate}#1{\pgfpointorigin}}
\def\tikz@scan@@absolute#1({%
  \pgfutil@ifnextchar[% uhoh... options!
  {\def\tikz@scan@point@recall{#1}\tikz@scan@options}%
  {\tikz@@@scan@@absolute#1(}%
}

\def\tikz@scan@options[#1]#2{%
  \def\tikz@scan@point@options{#1}%
  \tikz@@@scan@@absolute\tikz@scan@handle@options(#2%
}

\def\tikz@scan@handle@options#1{%
  {%
    % Ok, compute point with options set and zero transformation
    % matrix:
    \pgftransformreset%
    \let\tikz@transform=\pgfutil@empty%
    \expandafter\tikzset\expandafter{\tikz@scan@point@options}%
    \tikz@transform%
    \pgf@process{\pgfpointtransformed{#1}}%
    \xdef\tikz@marshal{\expandafter\noexpand\tikz@scan@point@recall{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}}%
  }%
  \tikz@marshal%  
}

\def\tikz@ensure@dollar@catcode{%
  \ifnum\catcode`\$=3 %
  \else
    \tikzerror{Sorry, some package has redefined the meaning of the
      math-mode dollar sign. This is incompatible with tikz and its calc
      library and might cause unrecoverable errors}% 
    % only show error once:
    \global\let\tikz@ensure@dollar@catcode=\relax
  \fi
}%

\def\tikz@@@scan@@absolute#1({%
  \tikz@ensure@dollar@catcode
  \pgfutil@ifnextchar{$}%$
  {\tikz@parse@calculator#1(}
  {\tikz@scan@no@calculator#1(}%
}
\def\tikz@scan@no@calculator#1(#2){%
  \edef\tikz@temp{(#2)}%
  \expandafter\tikz@@scan@@no@calculator\expandafter#1\tikz@temp%
}
\def\tikz@@scan@@no@calculator#1(#2){%
  \pgfutil@in@{cs:}{#2}%
  \ifpgfutil@in@%
    \let\@next\tikz@parse@coordinatesystem%
  \else%
    \pgfutil@in@{intersection }{#2}%
    \ifpgfutil@in@%
      \let\@next\tikz@parse@intersection%
    \else%
      \pgfutil@in@|{#2}%
      \ifpgfutil@in@
        \pgfutil@in@{-|}{#2}%
        \ifpgfutil@in@
          \let\@next\tikz@parse@hv%
        \else%
          \let\@next\tikz@parse@vh%
        \fi%
      \else%
        \pgfutil@in@:{#2}%
        \ifpgfutil@in@
          \let\@next\tikz@parse@polar%
        \else%
          \pgfutil@in@,{#2}%
          \ifpgfutil@in@%      
            \let\@next\tikz@parse@regular%
          \else%
            \let\@next\tikz@parse@node%
          \fi%
        \fi%
      \fi%
    \fi%
  \fi%
  \@next#1(#2)%
}

\def\tikz@parse@calculator#1($#2$){%
  \tikzerror{You need to say \string\usetikzlibrary{calc} for coordinate calculation}%
  #1{\pgfpointorigin}%
}

\def\tikz@parse@coordinatesystem#1(#2 cs:#3){%
  \let\tikz@return@coordinate=\pgfpointorigin%
  \pgfutil@ifundefined{tikz@parse@cs@#2}
  {\tikzerror{Unknown coordinate system '#2'}}
  {\csname tikz@parse@cs@#2\endcsname(#3)}%
  \expandafter#1\expandafter{\tikz@return@coordinate}%
}


\newif\iftikz@isdimension
\def\tikz@checkunit#1{%
  \pgfmathparse{#1}%
  \let\iftikz@isdimension=\ifpgfmathunitsdeclared%
}

\def\tikz@parse@polar#1(#2:#3){%
  \pgfutil@ifundefined{tikz@polar@dir@#2}
  {\tikz@@parse@polar#1({#2}:{#3})}
  {\tikz@@parse@polar#1(\csname tikz@polar@dir@#2\endcsname:{#3})}%
}
\def\tikz@@parse@polar#1(#2:#3){%
  \pgfutil@in@{ and }{#3}%
  \ifpgfutil@in@%
    \edef\tikz@args{({#2}:#3)}%
  \else%
    \edef\tikz@args{({#2}:{#3} and {#3})}%
  \fi%
  \expandafter\tikz@@@parse@polar\expandafter#1\tikz@args%
}
\def\tikz@@@parse@polar#1(#2:#3 and #4){%
  \tikz@checkunit{#3}%
  \iftikz@isdimension%
    \tikz@checkunit{#4}%
    \iftikz@isdimension%
      \def\tikz@next{#1{\pgfpointpolar{#2}{#3 and #4}}}%
    \else%
      \tikzerror{You cannot mix dimension and dimensionless values for polar coordinates}
      \def\tikz@next{#1{\pgfpointorigin}}%
    \fi%
  \else%
    \tikz@checkunit{#4}%
    \iftikz@isdimension%
      \tikzerror{You cannot mix dimension and dimensionless values for polar coordinates}
      \def\tikz@next{#1{\pgfpointorigin}}%
    \else%
      \def\tikz@next{#1{\pgfpointpolarxy{#2}{#3 and #4}}}%
    \fi%
  \fi%
  \tikz@next%
}
\def\tikz@polar@dir@up{90}
\def\tikz@polar@dir@down{-90}
\def\tikz@polar@dir@left{180}
\def\tikz@polar@dir@right{0}
\def\tikz@polar@dir@north{90}
\def\tikz@polar@dir@south{-90}
\def\tikz@polar@dir@east{0}
\def\tikz@polar@dir@west{180}
\expandafter\def\csname tikz@polar@dir@north east\endcsname{45}
\expandafter\def\csname tikz@polar@dir@north west\endcsname{135}
\expandafter\def\csname tikz@polar@dir@south east\endcsname{-45}
\expandafter\def\csname tikz@polar@dir@south west\endcsname{-135}


% MW: 
% Check to see if the y-coordinate is inside {}. If it is, scan it and
% reinsert it into the stream inside an extra group. 
%
% MW: 
% Check to see if the y-coordinate is inside {}. If it is, scan it and
% reinsert it into the stream inside an extra group. 
%
\def\tikz@parse@regular#1(#2,{%
	\pgfutil@ifnextchar\bgroup{\tikz@@parse@regular#1{#2}}{\tikz@@@parse@regular#1{#2}}%
}
\def\tikz@@parse@regular#1#2#3{%
	\pgfutil@ifnextchar[{% Uh oh! An array index.
		\tikz@@@parse@regular#1{#2}{#3}}%
	  {\tikz@@@parse@regular#1{#2}{{#3}}}}
	  
% Originally \def\tikz@parse@regular#1(#2,#3){%
%
\def\tikz@@@parse@regular#1#2#3){%
  \pgfutil@in@,{#3}%
  \ifpgfutil@in@%  
    \tikz@parse@splitxyz{#1}{#2}#3,%
  \else%
    \tikz@checkunit{#2}%
    \iftikz@isdimension%
      \tikz@checkunit{#3}%
      \iftikz@isdimension%
        \def\@next{#1{\pgfpoint{#2}{#3}}}%
      \else%
        \def\@next{#1{\pgfpointadd{\pgfpoint{#2}{0pt}}{\pgfpointxy{0}{#3}}}}%
      \fi%
    \else%
      \tikz@checkunit{#3}%
      \iftikz@isdimension%
        \def\@next{#1{\pgfpointadd{\pgfpoint{0pt}{#3}}{\pgfpointxy{#2}{0}}}}%
      \else%
        \def\@next{#1{\pgfpointxy{#2}{#3}}}%
      \fi%
    \fi%
  \fi%
  \@next%
}

\def\tikz@parse@splitxyz#1#2#3,#4,{%
  \def\@next{#1{\pgfpointxyz{#2}{#3}{#4}}}%
}

\def\tikz@coordinate@text{coordinate}

\def\tikz@parse@node#1(#2){%
  \pgfutil@in@.{#2}% Ok, flag this
  \ifpgfutil@in@
    \tikz@calc@anchor#2\tikz@stop%
  \else%
    \tikz@calc@anchor#2.center\tikz@stop% to be on the save side, in
                                % case iftikz@shapeborder is ignored...
    \expandafter\ifx\csname pgf@sh@ns@#2\endcsname\tikz@coordinate@text%
    \else
      \tikz@shapebordertrue%
      \def\tikz@shapeborder@name{\tikz@pp@name{#2}}%
    \fi%
  \fi%
  \edef\tikz@marshal{\noexpand#1{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}}%
  \tikz@marshal%
}

\def\tikz@calc@anchor#1.#2\tikz@stop{%
  \pgfpointanchor{\tikz@pp@name{#1}}{#2}%
}


\def\tikz@parse@hv#1(#2){%
  \pgfutil@in@{ -| }{#2}%
  \ifpgfutil@in@%
    \let\tikz@next=\tikz@parse@hvboth%
  \else%
    \pgfutil@in@{ -|}{#2}%
    \ifpgfutil@in@%
      \let\tikz@next=\tikz@parse@hvleft%
    \else%
      \pgfutil@in@{-| }{#2}%
      \ifpgfutil@in@%
        \let\tikz@next=\tikz@parse@hvright%
      \else%
        \let\tikz@next=\tikz@parse@hvdone%
      \fi%
    \fi%
  \fi%
  \tikz@next#1(#2)}
\def\tikz@parse@hvboth#1(#2 -| #3){\tikz@parse@vhdone#1({#3}|-{#2})}
\def\tikz@parse@hvleft#1(#2 -|#3){\tikz@parse@vhdone#1({#3}|-{#2})}
\def\tikz@parse@hvright#1(#2-| #3){\tikz@parse@vhdone#1({#3}|-{#2})}
\def\tikz@parse@hvdone#1(#2-|#3){\tikz@parse@vhdone#1({#3}|-{#2})}

\def\tikz@parse@vh#1(#2){%
  \pgfutil@in@{ |- }{#2}%
  \ifpgfutil@in@%
    \let\tikz@next=\tikz@parse@vhboth%
  \else%
    \pgfutil@in@{ |-}{#2}%
    \ifpgfutil@in@%
      \let\tikz@next=\tikz@parse@vhleft%
    \else%
      \pgfutil@in@{|- }{#2}%
      \ifpgfutil@in@%
        \let\tikz@next=\tikz@parse@vhright%
      \else%
        \let\tikz@next=\tikz@parse@vhdone%
      \fi%
    \fi%
  \fi%
  \tikz@next#1(#2)}
\def\tikz@parse@vhboth#1(#2 |- #3){\tikz@parse@vhdone#1({#2}|-{#3})}
\def\tikz@parse@vhleft#1(#2 |-#3){\tikz@parse@vhdone#1({#2}|-{#3})}
\def\tikz@parse@vhright#1(#2|- #3){\tikz@parse@vhdone#1({#2}|-{#3})}
\def\tikz@parse@vhdone#1(#2|-#3){%
  {%
    \tikz@@@scan@@absolute\tikz@parse@vh@mid(#2)%
    \tikz@@@scan@@absolute\tikz@parse@vh@end(#3)%
    \xdef\tikz@marshal{\noexpand#1{\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}}%
  }%
  \tikz@marshal%
}
\def\tikz@parse@vh@mid#1{\pgf@process{#1}\pgf@xa=\pgf@x}
\def\tikz@parse@vh@end#1{\pgf@process{#1}\pgf@ya=\pgf@y}

\def\tikz@parse@intersection#1(intersection{%
  \pgfutil@ifnextchar o{%
    \tikz@parse@main@intersection#1 1%
  }{%
    \tikz@parse@main@intersection#1%
  }%
}
\def\tikz@parse@main@intersection#1#2of #3 and #4){%
  \tikzset{cs/solution=#2}%
  \pgfutil@in@{--}{#3}%
  \ifpgfutil@in@%
    \tikz@reparse@line{first}#3\pgf@stop%
  \else%
    \tikzset{cs/first node=#3}%
  \fi%
  \pgfutil@in@{--}{#4}%
  \ifpgfutil@in@%
    \tikz@reparse@line{second}#4\pgf@stop%
  \else%
    \tikzset{cs/second node=#4}%
  \fi%
  \tikz@parse@cs@intersection()% advanced hackery...
  \edef\pgf@marshal{\noexpand#1{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}}%
  \pgf@marshal%
}
\def\tikz@reparse@line#1#2--#3\pgf@stop{%
  \tikzset{cs/#1 line={(#2)--(#3)}}%
}


\def\tikz@parse@intersection@a#1{\pgf@process{#1}\pgf@xa=\pgf@x\pgf@ya=\pgf@y}
\def\tikz@parse@intersection@b#1{\pgf@process{#1}\pgf@xb=\pgf@x\pgf@yb=\pgf@y}

\def\tikz@scan@relative#1+{%
  \pgfutil@ifnextchar+{\tikz@scan@plusplus#1}{\tikz@scan@oneplus#1}}

\def\tikz@scan@plusplus#1+{%
  \def\tikz@doafter{#1}%
  \tikz@scan@absolute\tikz@add%
}
\def\tikz@add#1{%
  \tikz@doafter{\pgfpointadd{#1}{\tikz@last@position@saved}}%
}
\def\tikz@scan@oneplus#1{%
  \def\tikz@doafter{#1}%
  \tikz@updatecurrentfalse%
  \tikz@scan@absolute\tikz@add%
} 



% 
% Quote handling
% 

\let\tikz@enable@node@quotes\relax
\let\tikz@enable@edge@quotes\relax
\let\tikz@enable@pic@quotes\relax



% Loading further libraries

% Include a library file.
%
% #1 = List of names of library file.
%  
% Description:
%
% This command includes a list of TikZ library files. For each file X in the
% list, the file tikzlibraryX.code.tex is included, provided this has
% not been done earlier. 
%
% For the convenience of Context users, both round and square brackets
% are possible for the argument.
% 
% If no file tikzlibraryX.code.tex exists, the file
% pgflibraryX.code.tex is tried instead. If this file, also, does not
% exist, an error message is printed.
%
% Example:
%
% \usetikzlibrary{arrows}
% \usetikzlibrary[patterns,topaths]

\def\usetikzlibrary{\pgfutil@ifnextchar[{\use@tikzlibrary}{\use@@tikzlibrary}}%}
\def\use@tikzlibrary[#1]{\use@@tikzlibrary{#1}}
\def\use@@tikzlibrary#1{%
  \edef\pgf@list{#1}%
  \pgfutil@for\pgf@temp:=\pgf@list\do{%
    \expandafter\pgfkeys@spdef\expandafter\pgf@temp\expandafter{\pgf@temp}%
    \ifx\pgf@temp\pgfutil@empty
    \else
      \expandafter\ifx\csname tikz@library@\pgf@temp @loaded\endcsname\relax%
      \expandafter\global\expandafter\let\csname tikz@library@\pgf@temp @loaded\endcsname=\pgfutil@empty%
      \expandafter\edef\csname tikz@library@#1@atcode\endcsname{\the\catcode`\@}
      \expandafter\edef\csname tikz@library@#1@barcode\endcsname{\the\catcode`\|}
      \expandafter\edef\csname tikz@library@#1@dollarcode\endcsname{\the\catcode`\$}
      \catcode`\@=11
      \catcode`\|=12
      \catcode`\$=3
      \pgfutil@InputIfFileExists{tikzlibrary\pgf@temp.code.tex}{}{
        \pgfutil@IfFileExists{pgflibrary\pgf@temp.code.tex}{%
          \expandafter\usepgflibrary\expandafter{\pgf@temp}%
        }{%
          \tikzerror{I did not find the tikz library
            '\pgf@temp'. I looked for files named
            tikzlibrary\pgf@temp.code.tex and
            pgflibrary\pgf@temp.code.tex, but neither
            could be found in the current texmf trees.}
        }}%
      \catcode`\@=\csname tikz@library@#1@atcode\endcsname
      \catcode`\|=\csname tikz@library@#1@barcode\endcsname
      \catcode`\$=\csname tikz@library@#1@dollarcode\endcsname
      \fi%
    \fi
  }%
}


% Always-present libraries:

\usetikzlibrary{topaths}




\endinput

tikzlibrarycalc.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/frontendlayer/tikz/libraries/tikzlibrarycalc.code.tex,v 1.9 2013/07/15 12:05:31 tantau Exp $

%
%
% Part I: The let path command
% 
%


%
% Syntax: let \p{name1} = (coord), \p{name2} = (coord), ... in ...
%
% Currently (this may get more fancy in the future), the (coord)s are
% evaluated one by one. If the first evaluates to, say, (10pt,20pt),
% the macro \p{name1} is set to "10pt,20pt" (without parantheses), the
% macro \x{name1} is set to "10pt" and the macro \y{name1} is set to
% "20pt". 
%
% If you use a number for {name}, you need no parantheses, so you
% could write:
%
% \draw let
%         \p1 = (1,1),
%         \p2 = ($ 2.5*(3,2) $)
%       in
%         (\x1,\x2) -- (\y1,\y2);

\def\tikz@let@command et{%
  \let\p=\tikz@cc@dop%
  \let\x=\tikz@cc@dox%
  \let\y=\tikz@cc@doy%
  \let\n=\tikz@cc@don%
  \pgfutil@ifnextchar i{\tikz@cc@stop@let}{\tikz@cc@handle@line}%
}
\def\tikz@cc@handle@line{%
  \pgfutil@ifnextchar\p{%
    \tikz@cc@handle@coor%
  }{%
    \pgfutil@ifnextchar\n{%
      \tikz@cc@handle@num%
    }{%
      \tikzerror{``\string\p'' or ``\string\n'' expected}%
    }%
  }%
}
\def\tikz@cc@handle@num\n#1#2=#3{%
  \pgfmathparse{#3}%
  \expandafter\edef\csname tikz@cc@n@#1\endcsname{\pgfmathresult\ifpgfmathunitsdeclared pt\fi}
  \pgfutil@ifnextchar,{\tikz@cc@handle@nextline}{\tikz@cc@stop@let}%
}
\def\tikz@cc@handle@coor\p#1#2={%
  \def\tikz@cc@coord@name{#1}%
  \tikz@scan@one@point\tikz@cc@dolet%
}
\def\tikz@cc@dolet#1{%
  \pgf@process{#1}%
  \expandafter\edef\csname tikz@cc@p@\tikz@cc@coord@name\endcsname{\the\pgf@x,\the\pgf@y}%
  \expandafter\edef\csname tikz@cc@x@\tikz@cc@coord@name\endcsname{\the\pgf@x}%
  \expandafter\edef\csname tikz@cc@y@\tikz@cc@coord@name\endcsname{\the\pgf@y}%
  \pgfutil@ifnextchar,{\tikz@cc@handle@nextline}{\tikz@cc@stop@let}%
}
\def\tikz@cc@handle@nextline,{%
  \tikz@cc@handle@line%
}
\def\tikz@cc@stop@let in{%
  \tikz@scan@next@command%
}%

\def\tikz@cc@dop#1{\csname tikz@cc@p@#1\endcsname}
\def\tikz@cc@dox#1{\csname tikz@cc@x@#1\endcsname}
\def\tikz@cc@doy#1{\csname tikz@cc@y@#1\endcsname}
\def\tikz@cc@don#1{\csname tikz@cc@n@#1\endcsname}



%
%
% Part II: The ($...$) parser
%
%

\def\tikz@parse@calculator#1(${%$
  \def\tikz@cc@command{#1}%
  \begingroup%
    %
    % Parse main computation. It's a series of optional factors in front
    % of coordiantes.
    % 
    \pgf@xa=0pt% We accumulate the result in here.
    \pgf@ya=0pt%
    \tikz@cc@parse+% 
}

\def\tikz@cc@parse{%
  \pgfutil@ifnextchar${%$
    % Ok, we found the end...
    \tikz@cc@end%
  }
  {\pgfutil@ifnextchar+{%
      % Ok, we found a coordinate...
      \tikz@cc@add%
    }{%
      \pgfutil@ifnextchar-{%
        \tikz@cc@sub%
      }{%
        \tikzerror{+ or - expected}%
        \tikz@cc@end$%$
      }%
    }%
  }%
}

%
% The end is reached with $
%
\def\tikz@cc@end$#1){%$
    \xdef\tikz@marshal{\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}%
  \endgroup%
  \expandafter\tikz@cc@command\expandafter{\tikz@marshal}%
}


%
% Another coordinate with +/-, possibly with a factor
%
\def\tikz@cc@add+{%
  \def\tikz@cc@factor{1}%
  \tikz@cc@factororcoordinate%
}
\def\tikz@cc@sub-{%
  \def\tikz@cc@factor{-1}%
  \tikz@cc@factororcoordinate%
}

%
% Check for a factor: If we see a (, its a coordinate...
% 
\def\tikz@cc@factororcoordinate{%
  \pgfutil@ifnextchar({%)
    % Ok, found coordinate
    \tikz@cc@coordinate%
  }{%
    \tikz@cc@parse@factor%
  }%
}

%
% ... otherwise it's a factor. It ends at ...*(
%
\def\tikz@cc@parse@factor#1*({%
  \pgfmathparse{#1*\tikz@cc@factor}%
  \let\tikz@cc@factor=\pgfmathresult%
  \tikz@cc@coordinate(%)
}

\def\tikz@cc@coordinate{%
  \tikz@scan@absolute\tikz@cc@after@coordinate%
}
\def\tikz@cc@after@coordinate#1{%
  \pgf@process{#1}%
  \pgf@xb=\pgf@x%
  \pgf@yb=\pgf@y%
  \tikz@cc@mid@checks%
}


%
% A coordinate can be followed by !...!(...)
%

\def\tikz@cc@mid@checks{%
  \ifnum\the\catcode`\!=\active\relax
    \expandafter\tikz@cc@mid@checks@active
  \else
    \expandafter\tikz@cc@mid@checks@nonactive
  \fi}

\def\tikz@cc@mid@checks@nonactive{%
  \pgfutil@ifnextchar!{%
    \tikz@cc@mid@nonactive%
  }{%
    \advance\pgf@xa by\tikz@cc@factor\pgf@xb
    \advance\pgf@ya by\tikz@cc@factor\pgf@yb
    \tikz@cc@parse%
  }%
}

\def\tikz@cc@mid@nonactive!{%
  \pgfutil@ifnextchar({%
    \tikz@scan@one@point\tikz@cc@project%
  }{%
    \tikz@cc@mid@num@nonactive%
  }%
}

\begingroup
  \catcode`\!=\active
  \gdef\tikz@cc@mid@checks@active{%
    \pgfutil@ifnextchar!{%
      \tikz@cc@mid@active%
    }{%
      \advance\pgf@xa by\tikz@cc@factor\pgf@xb
      \advance\pgf@ya by\tikz@cc@factor\pgf@yb
      \tikz@cc@parse%
    }%
  }

  \gdef\tikz@cc@mid@active!{%
    \pgfutil@ifnextchar({%
      \tikz@scan@one@point\tikz@cc@project%
    }{%
      \tikz@cc@mid@num@active%
    }%
  }
\endgroup

%
% Partway case: (coord a)!number!(coord b)
%
% Returns the position that is at <number> fraction on the way from a
% to b. This, (a)!0!(b) is (a), (a)!.5!(b) is the middle and (a)!1!(b)
% is (b)
%

\def\tikz@cc@mid@num@nonactive#1!{\tikz@cc@mid@num{#1}}

\begingroup
  \catcode`\!=\active
  \gdef\tikz@cc@mid@num@active#1!{\tikz@cc@mid@num{#1}}
\endgroup

\def\tikz@cc@mid@num#1{%
  \pgfmathparse{#1}%
  \ifpgfmathunitsdeclared%
    \let\tikz@cc@mid@unit=\pgfmathresult%
    \expandafter\tikz@cc@scan@rot\expandafter\tikz@cc@after@unit%
  \else%
    \let\tikz@cc@mid@factor=\pgfmathresult%
    \pgfmathparse{1-\tikz@cc@mid@factor}%
    \let\tikz@cc@mid@factor@one=\pgfmathresult%
    \expandafter\tikz@cc@scan@rot\expandafter\tikz@cc@after@num%
  \fi%
}

\def\tikz@cc@after@num#1{%
  \pgf@process{#1}%
  \pgf@xb=\tikz@cc@mid@factor@one\pgf@xb%
  \pgf@yb=\tikz@cc@mid@factor@one\pgf@yb%
  \advance\pgf@xb by\tikz@cc@mid@factor\pgf@x%
  \advance\pgf@yb by\tikz@cc@mid@factor\pgf@y%
  \tikz@cc@mid@checks%
}



%
% Distance case: (coord a)!dimension!(coord b)
%
% Returns the position that is at <dimension> removed from (coord a)
% in the direction of (coord b).
%

\def\tikz@cc@after@unit#1{%
  \pgf@process{#1}%
  \advance\pgf@x by-\pgf@xb%
  \advance\pgf@y by-\pgf@yb%
  \pgf@process{\pgfpointnormalised{}}%
  \advance\pgf@xb by\tikz@cc@mid@unit\pgf@x%
  \advance\pgf@yb by\tikz@cc@mid@unit\pgf@y%
  \tikz@cc@mid@checks%
}

%
% Projection case: (a)!(p)!(b)
%
% Projection of p on line from a to b
%
\def\tikz@cc@project#1{%
  \pgf@process{#1}%
  % Save in c
  \pgf@xc=\pgf@x%
  \pgf@yc=\pgf@y%
  \begingroup
    \ifnum\the\catcode`\!=\active
      \def\tikz@next{%
        \endgroup
        \expandafter\tikz@cc@scan@rot\expandafter\tikz@cc@after@project
        \tikz@cc@scan@ex@active}%
    \else
      \def\tikz@next{%
        \endgroup
        \expandafter\tikz@cc@scan@rot\expandafter\tikz@cc@after@project
        \tikz@cc@scan@ex@nonactive}%
    \fi
    \tikz@next%
}

\def\tikz@cc@scan@ex@nonactive!{}

\begingroup
  \catcode`\!=\active
  \gdef\tikz@cc@scan@ex@active!{}
\endgroup

\def\tikz@cc@after@project#1{%
  \pgf@process{#1}%
  % Ok, now we need to project (xc,yc) on the line (xb,xc) to (x,y)
  \advance\pgf@x by-\pgf@xb%
  \advance\pgf@y by-\pgf@yb%
  \advance\pgf@xc by-\pgf@xb%
  \advance\pgf@yc by-\pgf@yb%
  \pgf@process{\pgfpointnormalised{}}%
  % Scalar product
  \pgf@xc=\pgf@sys@tonumber{\pgf@xc}\pgf@x%
  \advance\pgf@xc by\pgf@sys@tonumber{\pgf@yc}\pgf@y%
  % and add
  \advance\pgf@xb by\pgf@sys@tonumber{\pgf@xc}\pgf@x%
  \advance\pgf@yb by\pgf@sys@tonumber{\pgf@xc}\pgf@y%
  \tikz@cc@mid@checks%
}

%
% Rotational scanner: radius:(x)
%

\def\tikz@cc@scan@rot#1{%
  \pgfutil@ifnextchar({%)
    \tikz@scan@one@point#1% normal
  }%
  {
    \def\tikz@cc@scan@rot@cmd{#1}%
    \ifnum\the\catcode`\:=\active\relax
      \expandafter\tikz@cc@scan@one@rot@active%
    \else
      \expandafter\tikz@cc@scan@one@rot@nonactive%
    \fi
  }%
}

\def\tikz@cc@scan@one@rot@nonactive#1:{%
  \def\tikz@cc@scan@rot@angle{#1}%
  \tikz@scan@one@point\tikz@cc@handle@rot%
}

\begingroup
  \catcode`\:=\active
  \gdef\tikz@cc@scan@one@rot@active#1:{%
    \def\tikz@cc@scan@rot@angle{#1}%
    \tikz@scan@one@point\tikz@cc@handle@rot%
  }
\endgroup

\def\tikz@cc@handle@rot#1{%
  \pgf@process{#1}%
  % Ok, now we need to rotate x/y around xb/xb by ...rot@angle
  {%
    \pgftransformreset%
    % Save them...
    \pgf@xc=\pgf@x%
    \pgf@yc=\pgf@y%
    \pgftransformshift{\pgfqpoint{\pgf@xb}{\pgf@yb}}%
    \pgftransformrotate{\tikz@cc@scan@rot@angle}%
    \pgftransformshift{\pgfqpoint{-\pgf@xb}{-\pgf@yb}}%
    \pgfpointtransformed{\pgfqpoint{\pgf@xc}{\pgf@yc}}%
    \expandafter
  }%
  \edef\tikz@marshal{\noexpand\tikz@cc@scan@rot@cmd{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}}%
  \tikz@marshal%
}




%
%
% Part III: Calculation coordinate systems
% 
%

% Tangent cs: Keys are a node and a point. Depending on the type of
% node, the appropriate tanent computation should be done.

\tikzdeclarecoordinatesystem{tangent}
{%
  \tikzset{cs/.cd,#1}%
  \expandafter\ifx\csname tikz@tangent@\tikz@cs@type\endcsname\relax%
    \tikzerror{I do not know how to compute the tangent to 
    a \tikz@cs@type}%
    \pgfpointorigin%
  \else%
    \expandafter\tikz@scan@one@point\expandafter\tikz@lib@do@tangent\tikz@cs@point%  
  \fi%
}

\tikzset{cs/node/.code=\tikz@cs@unpack{\tikz@cs@node}{\tikz@cs@type}{#1}}
\tikzset{cs/point/.store in=\tikz@cs@point}

\def\tikz@lib@do@tangent{\csname tikz@tangent@\tikz@cs@type\endcsname}

\def\tikz@tangent@coordinate#1{%
  \pgfpointanchor{\tikz@cs@node}{center}%
}

\def\tikz@tangent@circle#1{%
  {%
    % Step 1: Compute the transformed position of the input:
    \pgf@process{\pgfpointtransformed{#1}}%
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    %
    % Step 2: Compute vector from center of circle to transformed #1
    %
    \pgf@process{\pgfpointtransformed{\pgfpointanchor{\tikz@cs@node}{center}}}%
    \advance\pgf@xa by-\pgf@x%
    \advance\pgf@ya by-\pgf@y%
    %
    % Step 2: Reset transformations, they distract...
    %
    \pgftransformreset%
    %
    % Step 3: Transform to the center of the circle.
    %
    \pgftransformshift{\pgfpointanchor{\tikz@cs@node}{center}}%
    %
    % Step 4: Compute the radius
    %
    \pgf@process{\pgfpointanchor{\tikz@cs@node}{east}}%
    \pgf@xc=\pgf@x%
    %
    % Now, (xa,ya) is a point. Compute the tangent from this point to
    % a circle around the origin of radius xc.
    %
    % acos(radius/veclen(xa,ya)) is the angle of the tangent.
    \pgfmathparse{veclen(\the\pgf@xa,\the\pgf@ya)}
    \pgfmathparse{acos(\the\pgf@xc/\pgfmathresult)}
    \ifnum\pgfkeysvalueof{/tikz/cs/solution}>1\relax%
      \pgfmathparse{0-\pgfmathresult}%
    \fi%
    \let\tikz@lib@temp=\pgfmathresult%
    %
    % Now \pgfmathparse contains the desired angle. Use this to
    % compute the correct position on the circle...
    %
    % But, first, rotate to the point.
    \pgf@process{\pgfpointnormalised{\pgfqpoint{\pgf@xa}{\pgf@ya}}}%
    \pgf@ya=-\pgf@y%
    \pgftransformcm{\pgf@sys@tonumber{\pgf@x}}{\pgf@sys@tonumber{\pgf@y}}{\pgf@sys@tonumber{\pgf@ya}}{\pgf@sys@tonumber{\pgf@x}}{\pgfpointorigin}%
    % Finally, rotate...
    \pgf@process{\pgfpointtransformed{\pgfpointpolar{\tikz@lib@temp}{\the\pgf@xc}}}%
    %
    % Ok, undo transformations...
  }%
  % \pgf@x, \pgf@y have been smuggled outside by \pgf@process
  {%
    \pgftransforminvert%
    \pgf@process{\pgfpointtransformed{}}%
  }%
}


% Implementation of intersections


\def\tikz@intersect@circle@and@circle{%
  {%
    \pgftransformreset% transformations only confuse us, here...
    %
    % Compute origin and radius of first circle
    %
    \pgf@process{\pgfpointanchor{\tikz@cs@node@a}{center}}%
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgf@process{\pgfpointanchor{\tikz@cs@node@a}{east}}%
    \advance\pgf@x by-\pgf@xa%
    \pgf@xc=\pgf@x% ok, pgf@xc is first radius, (xa,ya) is center
    %
    % Compute origin and radius of second circle
    %
    \pgf@process{\pgfpointanchor{\tikz@cs@node@b}{center}}%
    \pgf@xb=\pgf@x%
    \pgf@yb=\pgf@y%
    \pgf@process{\pgfpointanchor{\tikz@cs@node@b}{east}}%
    \advance\pgf@x by-\pgf@xb%
    \pgf@yc=\pgf@x% \pgf@yc is second radius, (xb,yb) is center
    %
    \pgf@process{%
      \pgfpointintersectionofcircles{\pgfqpoint{\pgf@xa}{\pgf@ya}}{\pgfqpoint{\pgf@xb}{\pgf@yb}}{\pgf@xc}{\pgf@yc}{\pgfkeysvalueof{/tikz/cs/solution}}%
    }%
  }%
  % \pgf@x, \pgf@y have been smuggled outside by \pgf@process,
  % reinstall transformations...
  {%
    \pgftransforminvert%
    \pgf@process{\pgfpointtransformed{}}%
  }%
}


\def\tikz@intersect@line@and@circle{%
  {%
    %
    % Step 1: Get line
    %
    \expandafter\tikz@scan@one@point\expandafter\tikz@parse@line\tikz@cs@line@a%
    \pgf@process{\pgfpointtransformed{}}%
    \pgf@xb=\pgf@x%
    \pgf@yb=\pgf@y%
    \pgf@process{\pgfpointtransformed{\pgfqpoint{\pgf@xc}{\pgf@yc}}}%
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    %
    % Step 2: Subtract center of circle
    %
    \pgf@process{\pgfpointtransformed{\pgfpointanchor{\tikz@cs@node@b}{center}}}%
    \advance\pgf@xa by-\pgf@x%
    \advance\pgf@ya by-\pgf@y%
    \advance\pgf@xb by-\pgf@x%
    \advance\pgf@yb by-\pgf@y%
    %
    % Step 3: Reset transformations, they distract...
    %
    \pgftransformreset%
    %
    % Step 4: Transform to the center of the circle.
    %
    \pgftransformshift{\pgfpointanchor{\tikz@cs@node@b}{center}}%
    %
    % Step 5: Compute the radius
    %
    \pgf@process{\pgfpointanchor{\tikz@cs@node@b}{east}}%
    \edef\tikz@lib@saved@radius{\pgf@sys@tonumber{\pgf@x}}%
    %
    % Step 6: Compute projection of origin on line (xa,ya) -- (xb,yb),
    % store in (xa,ya)
    \pgf@x=\pgf@xb%
    \pgf@y=\pgf@yb%
    \advance\pgf@x by-\pgf@xa%
    \advance\pgf@y by-\pgf@ya%
    \pgf@process{\pgfpointnormalised{}}%
    % Scalar product
    \pgf@xc=\pgf@sys@tonumber{\pgf@xa}\pgf@x%
    \advance\pgf@xc by\pgf@sys@tonumber{\pgf@ya}\pgf@y%
    \pgf@xc=-\pgf@xc%
    % and add
    \advance\pgf@xa by\pgf@sys@tonumber{\pgf@xc}\pgf@x%
    \advance\pgf@ya by\pgf@sys@tonumber{\pgf@xc}\pgf@y%
    % 
    % Now, we have a triangle with a right angle at (xa,ya). The
    % second point of the triangle is the origin. The third point is
    % sought. 
    % Save x/y
    \pgf@xc=\pgf@x%
    \pgf@yc=\pgf@y%
    % Square radius
    \pgf@xb=\tikz@lib@saved@radius pt%
    %
    % First, make numbers smaller, in case they are too large
    %
    \c@pgf@counta=1\relax%
    \loop%
    \ifdim\pgf@xb>50pt%
      \multiply\c@pgf@counta by2\relax%
      \divide\pgf@xa by2\relax%
      \divide\pgf@ya by2\relax%
      \divide\pgf@xb by2\relax%
    \repeat%
    \pgf@xb=\pgf@sys@tonumber{\pgf@xb}\pgf@xb%
    % Subtract xa^2 + ya^2
    \pgf@yb=\pgf@sys@tonumber{\pgf@xa}\pgf@xa%
    \advance\pgf@xb by-\pgf@yb%
    \pgf@yb=\pgf@sys@tonumber{\pgf@ya}\pgf@ya%
    \advance\pgf@xb by-\pgf@yb%
    % Square root
    \ifdim\pgf@xb<0pt%
      \pgf@xb=0pt%
    \fi%
    \pgfmathsqrt@{\pgf@sys@tonumber{\pgf@xb}}%
    \pgfmathmultiply@{\pgfmathresult}{\the\c@pgf@counta}%
    \multiply\pgf@xa by\c@pgf@counta\relax%
    \multiply\pgf@ya by\c@pgf@counta\relax%
    \ifnum\pgfkeysvalueof{/tikz/cs/solution}>1\relax%
      \pgfmathsubtract{0}{\pgfmathresult}%
    \fi%
    % Ok, now add things...
    \advance\pgf@xa by \pgfmathresult\pgf@xc%
    \advance\pgf@ya by \pgfmathresult\pgf@yc%
    \pgf@process{\pgfpointtransformed{\pgfqpoint{\pgf@xa}{\pgf@ya}}}%
    % Ok, undo transformations...
  }%
  % \pgf@x, \pgf@y have been smuggled outside by \pgf@process
  {%
    \pgftransforminvert%
    \pgf@process{\pgfpointtransformed{}}%
  }%
}

\def\tikz@intersect@circle@and@line{%
  % Swap
  {%
    \let\tikz@cs@node@b=\tikz@cs@node@a%
    \let\tikz@cs@line@a=\tikz@cs@line@b%
    \tikz@intersect@line@and@circle%
  }%
}


tikzlibrarydecorations.code.tex
% Copyright 2008 by Mark Wibrow
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\usepgfmodule{decorations}

% Define the basic decoration stuff for tikz. Load more libraries to
% "actually use" decorations

\tikzset{decorate/.is if=tikz@decoratepath,
  /pgf/decoration/name/.store in=\tikz@decoration@name,
  /pgf/decoration/.unknown/.code=%
    \pgfifdecoration{\pgfkeyscurrentname}{\edef\tikz@decoration@name{\pgfkeyscurrentname}}
    {\pgfifmetadecoration{\pgfkeyscurrentname}{\edef\tikz@decoration@name{\pgfkeyscurrentname}}
    {\pgfkeys{/errors/unknown
        key={/pgf/decoration/\pgfkeyscurrentname}{#1}}}},%
  /pgf/decoration/raise/.code={\def\tikz@dec@shift{\pgftransformyshift{#1}}\tikz@dec@trans},
  /pgf/decoration/mirror/.code={%
    \csname if#1\endcsname
      \def\tikz@dec@mirror{\pgftransformyscale{-1}}%
    \else%
      \let\tikz@dec@mirror=\relax%
    \fi%
    \tikz@dec@trans%  
  },
  /pgf/decoration/mirror/.default=true,  
  /pgf/decoration/transform/.code={%
    {%
      \pgftransformreset%
      \def\tikz@transform{}%
      \pgfkeysalso{/tikz/.cd, #1}%
      \expandafter\gdef\expandafter\tikz@g@temptransform\expandafter{\tikz@transform}%
    }%
    \let\tikz@dec@user@transform=\tikz@g@temptransform%
    \tikz@dec@trans%
  },%
  /pgf/decoration/pre/.initial=lineto,
  /pgf/decoration/post/.initial=lineto,
  /pgf/decoration/pre length/.initial=0pt,
  /pgf/decoration/post length/.initial=0pt,
}

\let\tikz@decoration@name=\tikz@nonetext

\def\tikz@dec@trans{\pgfsetdecorationsegmenttransformation{\tikz@dec@user@transform\tikz@dec@mirror\tikz@dec@shift}}
\let\tikz@dec@user@transform=\relax
\let\tikz@dec@shift=\relax
\let\tikz@dec@mirror=\relax

\pgfdeclaremetadecoration{tikz@internal}{pre}{
  \state{pre}[width=\pgfkeysvalueof{/pgf/decoration/pre length}, next state=main]
  {
    \tikz@dec@trans
    \decoration{\pgfkeysvalueof{/pgf/decoration/pre}}
  }
  \state{main}[width=\pgfmetadecoratedremainingdistance-\pgfkeysvalueof{/pgf/decoration/post length}, next state=final]
  {
    \tikz@dec@trans
    \decoration{\tikz@decoration@name}
  }
  \state{final}
  {
    \tikz@dec@trans
    \decoration{\pgfkeysvalueof{/pgf/decoration/post}}
  }
}


\newif\iftikz@metadecoration

\def\tikz@lib@dec@addtomacro#1#2{\expandafter\def\expandafter#1\expandafter{#1#2}}

\def\tikz@lib@decoration[#1]{%
  \begingroup%
    % Just to be on the save side...
    %
    % Now, let's parse the options:
    \tikzset{#1}%
    %
    \ifx\tikz@decoration@name\tikz@nonetext%
    % Ok, let's forget about this decoration stuff...
    \else
      \expandafter\tikz@lib@do@dec%
    \fi%
      % Now, we expect a brace.
      \pgfutil@ifnextchar\bgroup{%
        \begingroup%
          \tikz@auto@end@pathfalse%
          \aftergroup\tikz@enddecoration%
          \afterassignment\tikz@scan@next@command%
          \let\tikz@lib@next% gobble \bgroup%
      }%
      {%
        \tikzerror{A decoration must begin with a brace}%
        \tikz@enddecoration%
      }%
}
\def\tikz@lib@do@dec{%
  % Ok, now what?
  \pgfifmetadecoration{\tikz@decoration@name}%
  {\expandafter\pgfmetadecoration\expandafter{\tikz@decoration@name}}%
  {%
    \pgfifdecoration{\tikz@decoration@name}%
    {\tikz@lib@dec@startdecoration}%
    {\tikzerror{Unknown (meta-)decoration '\tikz@decoration@name'. Perhaps you
        misspelled it?}}%
  }%
  \ifx\pgfdecorateexistingpath\pgfutil@empty%
    \pgfpathmoveto{\pgfqpoint{\the\tikz@lastxsaved}{\the\tikz@lastysaved}}%
  \fi%
}
\newbox\tikz@lib@dec@box
\def\tikz@enddecoration{%
    \global\setbox\tikz@lib@dec@box=\box\tikz@tempbox%
    \ifx\tikz@decoration@name\tikz@nonetext%
    % ignore this.
    \else
      % Ok, now what?
      \iftikz@metadecoration%
        \endpgfmetadecoration%
      \else%
        \tikz@lib@dec@stopdecoration%
      \fi%
    \fi
  \endgroup%
  \setbox\tikz@tempbox=\box\tikz@lib@dec@box%
}


\def\tikz@lib@dec@decorate@path{%
  \ifx\tikz@decoration@name\tikz@nonetext%
  \else%
    \pgfgetpath\tikz@lib@dec@currentpath%
    \pgfsetpath\pgfutil@empty%
    \pgfifmetadecoration{\tikz@decoration@name}
    {   
      \expandafter\pgfmetadecoration\expandafter{\tikz@decoration@name}%
        \pgfsetpath\tikz@lib@dec@currentpath%
      \endpgfmetadecoration%
    }
    {
      \pgfifdecoration{\tikz@decoration@name}
      {
        \tikz@lib@dec@startdecoration%
          \pgfsetpath\tikz@lib@dec@currentpath%
        \tikz@lib@dec@stopdecoration%
      }
      {
        \tikzerror{Unknown (meta-)decoration '\tikz@decoration@name'. Perhaps
          you misspelled it?}
      }
    }
  \fi%
}

\def\tikz@lib@dec@zpttext{0pt}

\newif\iftikz@lib@dec@temp
\def\tikz@lib@dec@startdecoration{%
  \pgfkeysgetvalue{/pgf/decoration/pre length}{\tikz@lib@pre}%
  \pgfkeysgetvalue{/pgf/decoration/post length}{\tikz@lib@post}%
  \tikz@lib@dec@tempfalse%
  \ifx\tikz@lib@pre\tikz@lib@dec@zpttext%
    \ifx\tikz@lib@post\tikz@lib@dec@zpttext%
    \else%
      \tikz@lib@dec@temptrue%
    \fi%
  \else%
    \tikz@lib@dec@temptrue%
  \fi%
  \iftikz@lib@dec@temp%
    \pgfmetadecoration{tikz@internal}%
  \else%
    \expandafter\pgfdecoration\expandafter{\expandafter{\tikz@decoration@name}{\pgfdecoratedpathlength}{}{}}%
  \fi%
}

\def\tikz@lib@dec@stopdecoration{%
  \iftikz@lib@dec@temp%
    \endpgfmetadecoration%
  \else%
    \endpgfdecoration%
  \fi%
}


\endinput

tikzlibrarydecorations.pathmorphing.code.tex
% Copyright 2008 by Mark Wibrow
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\usetikzlibrary{decorations}
\usepgflibrary{decorations.pathmorphing}

\endinput

tikzlibrarydecorations.pathreplacing.code.tex
% Copyright 2008 by Mark Wibrow
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\usetikzlibrary{decorations}
\usepgflibrary{decorations.pathreplacing}


\def\tikz@lib@dec@installinputsegmentpoints{%
	\pgf@process{\pgf@decorate@inputsegment@first}%
	\edef\tikzinputsegmentfirst{\the\pgf@x,\the\pgf@y}%
	%
	\pgf@process{\pgf@decorate@inputsegment@last}%
	\edef\tikzinputsegmentlast{\the\pgf@x,\the\pgf@y}%
	%
	\pgf@process{\pgf@decorate@inputsegment@supporta}%
	\edef\tikzinputsegmentsupporta{\the\pgf@x,\the\pgf@y}%
	%
	\pgf@process{\pgf@decorate@inputsegment@supportb}%
	\edef\tikzinputsegmentsupportb{\the\pgf@x,\the\pgf@y}%
}

\pgfkeys{
	/pgf/decoration/.cd,
		moveto code/.code=\def\pgfdecoratedinputsegmentmovetocode{\tikz@lib@dec@installinputsegmentpoints#1},
		lineto code/.code=\def\pgfdecoratedinputsegmentlinetocode{\tikz@lib@dec@installinputsegmentpoints#1},
		curveto code/.code=\def\pgfdecoratedinputsegmentcurvetocode{\tikz@lib@dec@installinputsegmentpoints#1},
		closepath code/.code=\def\pgfdecoratedinputsegmentclosepathcode{\tikz@lib@dec@installinputsegmentpoints#1}
}

\endinput

tikzlibrarydecorations.softclip.code.tex
%--------------------------------------------
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2013 by Christian Feuersaenger
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------
%
% This library adds support for a "soft clip" decoration. It applies
% clipping to an input path, but rather than simply instructing the
% display driver to clip the path, it computes a new clip path from
% the input.
%
% This library is (currently) on top of tikz.

\pgfutil@IfUndefined{pgfplotsset}{%
	\pgferror{Please load pgfplots before pgfplots.fillbetween.}%
	\endinput
}{}%

\usetikzlibrary{intersections}

\pgfplots@iffileexists{pgflibraryfillbetween.code.tex}{%
	\usepgflibrary{fillbetween}
}{%
	\pgfplotsusecompatibilityfile{pgflibraryfillbetween.code.tex}%
}%

\pgfutil@IfUndefined{pgfintersectiongetsolutiontimes}{%
	\pgfplotsusecompatibilityfile{pgflibraryintersections.code.tex}%
}{}%


\pgfkeys{
	% soft clip={(axis cs:0,0) rectangle (axis cs:1,1)}
	% or
	% soft clip={A}
	% where 'A' is defined using 'name path=A' somewhere
	/pgf/decoration/soft clip path/.code={%
		% FIXME : I would rather NOT evaluate path arguments in this
		% context! Who knows how people set keys!? But alas, we cannot
		% evaluate late because the CM is reset while working on
		% decorations ... (see below)
		\tikzlibsoftclip@setkey{\tikzlibsoftclip@setkey@assign}#1\pgf@stop
	},
	/pgf/decoration/every soft clipped path/.style={},%
}

% #1 a macro containing a soft path
\def\tikzlibsoftclip@setkey@assign#1{%
	\let\pgf@decoration@soft@clip=#1%
}%

\tikzlibsoftclip@setkey@assign{\pgfutil@empty}%

\pgfdeclaredecoration{soft clip}{replace}{

	\state{replace}[width=\pgfdecoratedpathlength,
		persistent precomputation={%
			% This here is an earlier draft... but alas, the
			% transformation matrix has been reset in this context,
			% and we cannot define the clip path dynamically here.
			% I left it to document that.
			%
			%\pgfkeysgetvalue{/pgf/decoration/soft clip path}\pgf@temp
			%\def\tikz@marshal{\tikzlibsoftclip@setkey{\tikzlibsoftclip@setkey@assign}}%
			%\expandafter\tikz@marshal\pgf@temp\pgf@stop
		}
	]{%
		\ifx\pgf@decoration@soft@clip\pgfutil@empty
			\pgfplotsthrow{invalid argument}
				{\pgf@decoration@soft@clip}%
				{The mandatory argument 'soft clip path=(A) rectangle (B)' has not been set}%
				\pgfeov
		\else
			\tikzset{/pgf/decoration/every soft clipped path}%
			\pgfpathcomputesoftclippath{\pgfdecoratedpath}{\pgf@decoration@soft@clip}%
			\pgfsetpathandBB{\pgfretval}%
		\fi
	}
}

% ---------------------------------------------------------------------------------
%
%  SOFT-CLIPPING.
%
%  "softclip" means to get rid of those parts of a path which are
%  outside of a clip path. 
%
%  An example is to trim at the beginning and/or end of a
%  path as part of fill-between ("poor-mans-clipping").
%
%  The difference to "real" clipping is that it is applied to the
%  path, not to the viewer -- the path can still be drawn with any
%  decorations, line widths, etc.
%
%  Another difference is that this feature is (considerably) less sophisticated.
%
%  #1: the input path
%  #2: the clip path (if it is empty, no clipping will be applied)
% OUTPUT:
%  \pgfretval is #1 with modifications
\def\pgfpathcomputesoftclippath#1#2{%
	\ifx#2\pgfutil@empty
		\let\pgfretval=#1%
	\else
		\ifx#1\pgfutil@empty
			\let\pgfretval=#1%
		\else
			\pgfpathcomputesoftclippath@{#1}{#2}%
		\fi
	\fi
}

\def\pgfpathcomputesoftclippath@#1#2{%
	\begingroup
		\pgfprocessround{#1}{#1}%
		\pgfprocessround{#2}{#2}%
		%
		%
		\pgfpathcomputesoftclippath@is@first@outside@of@path{#1}{#2}%
		\let\b@pgffill@is@outside@clip=\pgfretval
		%
%\message{computing soft clip path for ^^J\meaning#1 and ^^J\meaning#2^^J  first point of input is outside of clip path=\b@pgffill@is@outside@clip^^J}%
		%
		% FIXME : it might be that I need to sort them ... !? but
		% other tests indicate that I should not!?
		%\pgfintersectionsortbyfirstpath
		\pgf@intersect@sortfalse
		\pgfintersectionofpaths%
			{%
				\pgfsetpath#1%
			}%
			{%
				\pgfsetpath#2%
			}%
		%
%\message{... num intersections = \pgfintersectionsolutions^^J}%
		%
		\ifnum\pgfintersectionsolutions=0 %
			\if1\b@pgffill@is@outside@clip
				% entire path is outside of the clipped area.
				\let\pgfretval=\pgfutil@empty
			\else
				\let\pgfretval=#1%
			\fi
		\else
			% split the first involved path into the
			% segments induced by the intersection points:
			\pgfcomputeintersectionsegments{1}%
			\let\pgfpathfilled@a@segments=\pgfretval
			%
			% Now, create a new path which contains only those
			% segments which are INSIDE of the clip path.
			%
			% I assume that I can rely on "even/odd" matching: if the
			% first is inside, the second is outside, the third
			% inside, etc.
			\pgfapplistnewempty{pgfretval@tmp}%
			\def\c@pgfpathfilled@counter{0}%
			\pgfmathloop
			\ifnum\c@pgfpathfilled@counter<\pgfpathfilled@a@segments\relax
				\if0\b@pgffill@is@outside@clip
					\expandafter\let\expandafter\pgf@loc@path@a\csname pgf@intersect@path@split@a@\c@pgfpathfilled@counter\endcsname
					\expandafter\pgfapplistpushback\pgf@loc@path@a\to{pgfretval@tmp}%
				\fi
				\pgfpathfillbetween@negate\b@pgffill@is@outside@clip
				%
				\pgfutil@advancestringcounter\c@pgfpathfilled@counter
			\repeatpgfmathloop
			\pgfapplistlet\pgfretval={pgfretval@tmp}%
		\fi
		%
		\global\let\pgf@glob@TMPa=\pgfretval%
	\endgroup
	\let\pgfretval=\pgf@glob@TMPa
}

% #1: input path (non-empty)
% #2: soft clip path
% Defines "\def\pgfretval{1}" if (the first point of #1 is outside or on the path #2)
% Defines "\def\pgfretval{0}" if (the first point of #1 is inside of the path #2)
\def\pgfpathcomputesoftclippath@is@first@outside@of@path#1#2{%
	% APPROACH: shoot a line starting at the first coordinate of the
	% first path through "the middle of #2". Then make an even/odd
	% check on the number of intersections.
	%
	% FIXME : for now, I only support (x,y) rectangle (X,Y) anyway --
	% optimize for that case!? This here might be too complex...
	\begingroup
	\expandafter\pgfpathfillbetween@get@first@coord#1\pgf@stop
	\let\pgfpathfilled@a@firstcoord=\pgfretval%
	%
	% Get some point "in the middle of #2":
	\pgfpathcomputesoftclippath@accum@pseudo@mean#2%
	\edef\pgfpathfilled@b@center{\noexpand\pgfqpoint\pgfretval}%
	%
	% We have to shoot *through* #2, not just into the middle of #2.
	% Consequently, we need to know how big #2 is:
	\pgfpathcomputesoftclippath@is@first@outside@of@path@getBB#2%
	\let\pgf@size@hint=\pgfretval
	%
	% Now, compute a target point such that our shot goes through it:
	\pgfqpointscale{%
		\pgf@size@hint
	}{%
		\pgfpointnormalised{%
			\pgfpointdiff%
				{\expandafter\pgfqpoint\pgfpathfilled@a@firstcoord}%
				{\pgfpathfilled@b@center}%
		}%
	}%
	% collect intermediate results as \pgf@xa/\pgf@ya are overwritten:
	\edef\pgf@direction@vector{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
	\pgfpointadd{\pgfpathfilled@b@center}{\pgf@direction@vector}%
	\edef\pgfpathfilled@shoot@line@trg{{\the\pgf@x}{\the\pgf@y}}%
	%
	% this here is our path!
	\edef\pgf@direction@path{%
		\noexpand\pgfsyssoftpath@movetotoken\pgfpathfilled@a@firstcoord
		\noexpand\pgfsyssoftpath@linetotoken\pgfpathfilled@shoot@line@trg
	}%
	%
	% ... ok, compute intersections. This should be fairly fast as
	% our second path has just 1 segment, i.e. it will be O(N) where N
	% is the number of segments in #2.
	\pgf@intersect@sortfalse
	\pgfintersectionofpaths%
		{%
			\pgfsetpath#2%
		}%
		{%
			\pgfsetpath\pgf@direction@path%
		}%
	%
	\ifnum\pgfintersectionsolutions=0 %
		% this must not happen! We have taken great care such that we
		% *have* at least 1 intersection points!
		\pgferror{Illegal state encountered: the computation of a softpath failed. The failure occurred while computing whether the first input coordinate is inside of the clip path (found no intersections)}%
	\fi
	%
	\pgfpathcomputesoftclippath@if@is@first@on@boundary{%
		% AH! The first point is ON the boundary of the clip path.
		% This is equivalent to the condition that the first
		% intersection point equals the first point.
		%
		% In this case, we say that it is OUTSIDE of the clip path!
		%
		% This is actually related to 
		%   1. the fact that the input path is splitted into segments
		%   induced by the intersection points in order to apply
		%   soft-clipping.
		%   2. the fact that the clipping is based on an even/odd
		%   matching (in/out). 
		%
		% In that setup, we want to skip the segment until the first
		% intersection point - after all, it is "empty" anyway.
		%
		% To this end, we have to say that this first (empty) segment
		% is OUTSIDE:
		\def\pgfretval{1}%
	}{%
		\ifodd\pgfintersectionsolutions\relax%
			\def\pgfretval{0}%
		\else
			\def\pgfretval{1}%
		\fi
	}%
	\pgfmath@smuggleone\pgfretval
	\endgroup
}

\def\pgfpathcomputesoftclippath@if@is@first@on@boundary#1#2{%
	\pgfpathcomputesoftclippath@compute@infty@norm{%
		\pgfpointdiff%
			{\expandafter\pgfqpoint\pgfpathfilled@a@firstcoord}%
			{\pgfpointintersectionsolution{1}}%
	}%
	\ifdim\pgf@x<\pgfintersectiontolerance\relax
		% YES: the first point IS on the boundary: the first
		% intersection solution == first point.
		#1%
	\else
		% No, it is NOT equal to the first intersection solution - and
		% thus NOT on the boundary.
		#2%
	\fi
}%

% Defines \pgf@x to be the infty norm of vector #1
\def\pgfpathcomputesoftclippath@compute@infty@norm#1{%
	\pgf@process{#1}%
	\ifdim\pgf@x<0sp \global\pgf@x=-\pgf@x\fi
	\ifdim\pgf@y<0sp \global\pgf@y=-\pgf@y\fi
	\ifdim\pgf@x<\pgf@y 
		\global\pgf@x=\pgf@y
	\fi
}

% Defines \pgfretval to be a *scalar* "size indicator" (1-norm) of the bounding
% box of #1.
%
% #1: a macro containing a softpath.
\def\pgfpathcomputesoftclippath@is@first@outside@of@path@getBB#1{%
	\begingroup
	\pgf@getpathsizes\pgf@interrupt@pathsizes
	% we only need the path size here:
	\pgf@relevantforpicturesizefalse
	%
	% FIXME : CODE CLEANUP NEEDED
	\def\pgfsetpathBB@protocol@lastmoveto##1##2{}%
	\expandafter\pgfsetpath@loop#1\pgf@stop
	\pgfpointdiff
		{\pgfqpoint\pgf@pathminx\pgf@pathminy}%
		{\pgfqpoint\pgf@pathmaxx\pgf@pathmaxy}%
	% compute |v|_1 = x + y (both components are non-negative anyway):
	\pgf@xa=\pgf@x
	\advance\pgf@xa by\pgf@y
	\xdef\pgf@glob@TMPa{\pgf@sys@tonumber\pgf@xa}%
	\pgf@setpathsizes\pgf@interrupt@pathsizes
	\endgroup
	\let\pgfretval=\pgf@glob@TMPa
}%

% Defines \pgfretval to be of a "pseudo" mean of path #1.
%
% Here, "pseudo" refers to the fact that the mean will only be
% accumulated over the "first couple of coordinates" to avoid numeric
% overflows in TeX's math engine.
\def\pgfpathcomputesoftclippath@accum@pseudo@mean#1{%
	\begingroup
	\let\pgfsyssoftpath@movetotoken\pgfpathcomputesoftclippath@accum@pseudo@mean@
	\let\pgfsyssoftpath@linetotoken\pgfpathcomputesoftclippath@accum@pseudo@mean@
	\let\pgfsyssoftpath@closepathtoken\pgfpathcomputesoftclippath@accum@pseudo@mean@
	\let\pgfsyssoftpath@curvetotoken\pgfpathcomputesoftclippath@accum@pseudo@mean@
	\let\pgfsyssoftpath@curvetosupportatoken\pgfpathcomputesoftclippath@accum@pseudo@mean@relax
	\let\pgfsyssoftpath@curvetosupportbtoken\pgfpathcomputesoftclippath@accum@pseudo@mean@relax
	\c@pgf@countc=0 %
	\pgf@xa=0pt %
	\pgf@ya=0pt %
	#1%
	\divide\pgf@xa by\c@pgf@countc
	\divide\pgf@ya by\c@pgf@countc
	\edef\pgfretval{{\the\pgf@xa}{\the\pgf@ya}}%
	\pgfmath@smuggleone\pgfretval
	\endgroup
}%
\def\pgfpathcomputesoftclippath@accum@pseudo@mean@relax#1#2{}
\def\pgfpathcomputesoftclippath@accum@pseudo@mean@#1#2{%
	\ifnum\c@pgf@countc<4
		% avoid overflows. 4 must be sufficient for now.
		\advance\pgf@xa by#1\relax
		\advance\pgf@ya by#2\relax
		\advance\c@pgf@countc by1 %
	\fi
}


% #1: of the form '{<x>}{<y>}'
% #2: of the form '{<x>}{<y>}'
\def\pgfpathfillbetween@check@x@less@than#1#2{%
	\edef\pgf@temp{#1#2}%
	\expandafter\pgfpathfillbetween@check@x@less@than@\pgf@temp
}%

% #1: x1
% #2: y1
% #3: x2
% #4: y2
\def\pgfpathfillbetween@check@x@less@than@#1#2#3#4{%
	\ifdim#1>#3\relax
		% <=
		\def\pgfretval{0}%
	\else
		\def\pgfretval{1}%
	\fi
}%

\def\pgfpathfillbetween@negate#1{%
	\if0#1%
		\def#1{1}%
	\else
		\def#1{0}%
	\fi
}

\pgfkeys{
	/tikz/soft clip assign/name/.code={\tikzgetnamedpath{#1}},
	/tikz/soft clip assign/path/.code={\tikzlibsoftclip@setkey@@#1\pgf@stop},
}

% 
% \tikzlibsoftclip@setkey{<\macro>} <path name>\pgf@stop
%
% OR
%
% \tikzlibsoftclip@setkey{<\macro>} (<A>) rectangle (<B>)\pgf@stop
%
% #1: a macro which is called with the resulting clip path as argument #1.
\def\tikzlibsoftclip@setkey#1#2\pgf@stop{%
	\pgfutil@in@{=}{#2}%
	\ifpgfutil@in@
		\pgfqkeys{/tikz/soft clip assign}{#2}%
	\else
		\def\pgf@temp{#2}%
		\pgfplots@command@to@string\pgf@temp\pgf@temp
		%
		\tikzifisnamedpath{\pgf@temp}{%
			\pgfkeysalso{/tikz/soft clip assign/name={#2}}%
		}{%
			\pgfkeysalso{/tikz/soft clip assign/path={#2}}%
		}%
	\fi
	#1{\pgfretval}%
}

\def\tikzlibsoftclip@setkey@@{%
	%
	\tikz@scan@one@point\tikzlibsoftclip@setkey@bb@scan@a
}%

\def\tikzlibsoftclip@setkey@bb@scan@a#1{%
	\def\tikzlibsoftclip@setkey@bb@a{#1}%
	\pgfutil@ifnextchar r{%
		\tikzlibsoftclip@setkey@bb@scan@rectangle
	}{%
		\tikzlibsoftclip@setkey@@error
	}%
}%

\def\tikzlibsoftclip@setkey@bb@scan@rectangle rectangle{%
	\tikz@scan@one@point\tikzlibsoftclip@setkey@bb@scan@b
}%

\def\tikz@gobble@until@stop#1\pgf@stop{}%

\def\tikzlibsoftclip@setkey@bb@scan@b#1{%
	\def\tikzlibsoftclip@setkey@bb@b{#1}%
	\pgfutil@ifnextchar \pgf@stop{%
		\tikzlibsoftclip@setkey@@activate
		\tikz@gobble@until@stop
	}{%
		\tikzlibsoftclip@setkey@@error
	}%
}%

\def\tikzlibsoftclip@setkey@@error#1\pgf@stop{%
	\def\pgfplots@loc@TMPa{#1}%
	\pgfplots@command@to@string\pgfplots@loc@TMPa\pgfplots@loc@TMPb
	\pgfplotsthrow{invalid argument}
		{\pgfplots@loc@TMPa}%
		{fill between: the argument of 'soft clip' has an unexpected format near '\pgfplots@loc@TMPb'; expected '(<pt>) rectangle (<pt>)'}%
		\pgfeov
}%

% INPUT:
%  - two PGF points \tikzlibsoftclip@setkey@bb@a and \tikzlibsoftclip@setkey@bb@b.
%
% POSTCONDITION: \pgfretval contains the resulting path.
\def\tikzlibsoftclip@setkey@@activate{%
	% Expand points to {<x>}{<y>} ...
	\pgf@process{\tikzlibsoftclip@setkey@bb@a}%
	\edef\tikzlibsoftclip@setkey@bb@a{{\the\pgf@x}{\the\pgf@y}}%
	\pgf@process{\tikzlibsoftclip@setkey@bb@b}%
	\edef\tikzlibsoftclip@setkey@bb@b{{\the\pgf@x}{\the\pgf@y}}%
	%
	\pgfinterruptpath
	\pgf@relevantforpicturesizefalse%
	\expandafter\pgfqpoint\tikzlibsoftclip@setkey@bb@a
	\pgf@xa=\pgf@x
	\pgf@ya=\pgf@y
	\expandafter\pgfqpoint\tikzlibsoftclip@setkey@bb@b
	\pgf@xb=\pgf@x
	\pgf@yb=\pgf@y
	%
	\pgfpathmoveto{\pgfqpoint{\pgf@xa}{\pgf@ya}}%
	\pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@yb}}%
	\pgfpathlineto{\pgfqpoint{\pgf@xb}{\pgf@yb}}%
	\pgfpathlineto{\pgfqpoint{\pgf@xb}{\pgf@ya}}%
	\pgfpathclose
	\pgfgetpath\pgfplots@loc@TMPa
	\global\let\pgfplots@glob@TMPa=\pgfplots@loc@TMPa
	\endpgfinterruptpath
	%
	\let\pgfretval=\pgfplots@glob@TMPa
}%
% ---------------------------------------------------------------------------------

% Executes #2 if #1 is a named path and #3 otherwise.
\def\tikzifisnamedpath#1#2#3{%
	\pgfutil@IfUndefined{tikz@intersect@path@name@#1}{%
		\def\tikz@next{#3}%
	}{%
		\def\tikz@next{#2}%
	}%
	\tikz@next
}%



tikzlibraryfillbetween.code.tex
%--------------------------------------------
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2013 by Christian Feuersaenger
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------


% This library adds support for high-level instructions for "fill area
% between two arbitrary plots of functions".
%
% It activates the syntax \pgfpathfillbetween
% where A and B are two plots named by 'name path='.
%
% In fact, this here is not much more than a low-level invocation of
% \pgfpathfillbetween
% and a couple of styles. It could become a TikZ library because it
% actually works on any two named paths, but it has its restrictions
% regarding the supported input paths: both need to be plots of
% functions (non-intersecting, should have at most one function value
% for each canvas X coord)

\pgfutil@IfUndefined{pgfplotsset}{%
	\pgferror{Please load pgfplots before pgfplots.fillbetween.}%
	\endinput
}{}%

\usetikzlibrary{intersections}
\usetikzlibrary{decorations.softclip}

% COMPATIBILITY WITH PGF RELEASE:
\pgfutil@IfUndefined{pgfintersectiongetsolutiontimes}{%
	\pgfplotsusecompatibilityfile{pgflibraryintersections.code.tex}%
}{}%
\def\tikz@key@name@path@wrong#1#2{%
    \tikz@addmode{%
      \pgfsyssoftpath@getcurrentpath\tikz@intersect@temppath@round%
      \pgfprocessround\tikz@intersect@temppath@round\tikz@intersect@temppath%
      \ifx\tikz@intersect@namedpaths\pgfutil@empty%
      \else%
        \tikz@intersect@namedpaths%
        \pgfutil@ifundefined{tikz@intersect@path@name@#1}{}%
        {%
          \expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter\tikz@intersect@@temppath%
          \expandafter\expandafter\expandafter{\csname tikz@intersect@path@name@#1\endcsname}%
          \expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter\tikz@intersect@temppath%
          \expandafter\expandafter\expandafter{\expandafter\tikz@intersect@temppath\tikz@intersect@temppath}%
        }%
      \fi%
      \tikz@intersect@addto@path@names{#1}{#2}%
    }%
}%

\def\tikz@key@name@path@new#1#2{%
    \tikz@addmode{%
      \pgfsyssoftpath@getcurrentpath\tikz@intersect@temppath@round%
      \pgfprocessround\tikz@intersect@temppath@round\tikz@intersect@temppath%
      \ifx\tikz@intersect@namedpaths\pgfutil@empty%
      \else%
        \tikz@intersect@namedpaths%
      \fi%
      \tikz@intersect@addto@path@names{#1}{#2}%
    }%
}%

\ifx\tikz@key@name@path@wrong\tikz@key@name@path
	\immediate\write16{Package pgfplots: loading complementary 'name path' implementation for your pgf version...}
	\let\tikz@key@name@path=\tikz@key@name@path@new
\fi

% ------------------------------------------------------------

\newif\iftikzfillbetween@optimize@name@intersections

\pgfkeys{%
	/tikz/fill between/of/.code=\tikzlibraryfillbetween@parse#1\pgf@stop,
	%
	/tikz/fill between/on layer/.initial=pre main,
	/tikz/fill between/every segment/.style={},
	/tikz/fill between/every odd segment/.style={},
	/tikz/fill between/every even segment/.style={},
	/tikz/fill between/every last segment/.style={},
	%
	% Allows to add path instructions *after* the segment.
	% If you want to add some *before* the segment, you can rely on
	% 'every segment no 0/.style={ ... suitable tikz options ... }'
	/tikz/fill between/path after segment/.initial={},
	%
	% soft clip={(axis cs:0,0) rectangle (axis cs:1,1)}
	/tikz/fill between/soft clip/.style={
		/tikz/fill between/soft clip first={#1},%
		/tikz/fill between/soft clip second={#1},%
	},%
	/tikz/fill between/soft clip first/.initial=,%
	/tikz/fill between/soft clip second/.initial=,
	%
	% #1: drawing options.
	/tikz/fill between/@draw style/.style={
		/pgf/fill between/result stream/begin/.code={%
			\gdef\tikzsegmentindex{0}%
			\xdef\tikzsegmentindices{##1}%
			\c@pgf@countc=##1 %
			\advance\c@pgf@countc by-1 %
			\xdef\tikzsegmentlastindex{\the\c@pgf@countc}%
		},%
		/pgf/fill between/result stream/next ready/.code={%
			\let\pgflibraryfill@path=\pgfretval
			\def\pgfplots@loc@TMPa{%
				/tikz/fill between/every segment,
				#1,%
				/tikz/fill between/every segment no \tikzsegmentindex/.try,
			}%
			\ifodd\tikzsegmentindex\relax
				\expandafter\def\expandafter\pgfplots@loc@TMPa\expandafter{\pgfplots@loc@TMPa
					/tikz/fill between/every odd segment,
				}%
			\else
				\expandafter\def\expandafter\pgfplots@loc@TMPa\expandafter{\pgfplots@loc@TMPa
					/tikz/fill between/every even segment,
				}%
			\fi
			%
			\ifnum\tikzsegmentindex=\tikzsegmentlastindex\relax
				\expandafter\def\expandafter\pgfplots@loc@TMPa\expandafter{\pgfplots@loc@TMPa
					/tikz/fill between/every last segment,
				}%
			\fi
			%
			\expandafter\fill\expandafter[\pgfplots@loc@TMPa]
				\pgfextra 
				\pgfsetpathandBB{\pgflibraryfill@path}%
				\pgfkeysgetvalue{/tikz/fill between/path after segment}\tikz@fillbetween@post@segment
				\expandafter
				\endpgfextra
				\tikz@fillbetween@post@segment
			;%
			\pgfplotsutil@advancestringcounter@global\tikzsegmentindex
		},%
		/pgf/fill between/result stream/end/.code=,%
	},
	/tikz/fill between/.search also={/pgf/fill between,/pgfplots},
	/tikz/fill between/optimize name intersections/.is if=tikzfillbetween@optimize@name@intersections,
	% 
	% FIXME : this optimization needs much more work... I believe it
	% would be stable enough, but it covers too few cases.
	%/tikz/fill between/optimize name intersections=true,
	%
	%
	%
	%--------------------------------------------------
	% /pgfplots/execute at begin axis@@/.add={%
	% 	\def\b@pgfplotslibraryfill@added
	% }{%
	% 	
	% },%
	%-------------------------------------------------- 
}

\def\tikzlibraryfillbetween@parse#1 and #2\pgf@stop{%
	\def\tikz@fillbetween@a{#1}%
	\def\tikz@fillbetween@b{#2}%
}%

% \tikzfillbetween[<options>]{<draw style>}
%
% <options> must contain 'of=<A> and <B>' and may configure how the
% area is computed.
%
% <draw style> affects every drawn region.
%
\def\tikzfillbetween{\pgfutil@ifnextchar[{\tikzfillbetween@opt}{\tikzfillbetween@opt[]}}
\def\tikzfillbetween@opt[#1]#2{%
	\begingroup
	\pgfqkeys{/tikz/fill between}{% 
		% prepare the low-level path generation instruction(s):
		/tikz/fill between/@draw style={#2},%
		%
		% set up input options:
		#1,%
	}%
	% automagically try to use the correct layer:
	\pgfkeysgetvalue{/tikz/fill between/on layer}\tikzlibraryfillbetween@path@layer@name
	\tikzlibraryfillbetween@determine@layer
	%
	\ifx\tikzlibraryfillbetween@path@layer@name\pgfutil@empty \else
		\pgfonlayer{\tikzlibraryfillbetween@path@layer@name}%
	\fi
	%
		\tikzlibraryfillbetween@path@generatepath
	%
	\ifx\tikzlibraryfillbetween@path@layer@name\pgfutil@empty \else
		\endpgfonlayer%
	\fi
	%
	\endgroup
}%

% Defines \tikzlibraryfillbetween@path@layer@name
\def\tikzlibraryfillbetween@determine@layer{%
	\ifx\tikzlibraryfillbetween@path@layer@name\pgfutil@empty
	\else
		\pgfutil@IfUndefined{pgf@layerlist}{%
			% hm. No layers active!? A pity...
			\tikzlibraryfillbetween@path@warn@layer
			\let\tikzlibraryfillbetween@path@layer@name\pgfutil@empty%
		}{%
			\edef\pgfplots@loc@TMPa{\noexpand\pgfutil@in@{\tikzlibraryfillbetween@path@layer@name}}%
			\expandafter\pgfplots@loc@TMPa\expandafter{\pgf@layerlist}%
			\ifpgfutil@in@
			\else
				\tikzlibraryfillbetween@path@warn@layer
				\let\tikzlibraryfillbetween@path@layer@name\pgfutil@empty%
			\fi
		}%
	\fi
}%

\def\tikzlibraryfillbetween@path@warn@layer{%
	\pgfplots@warning{'fill between': Could not activate graphics layer '\tikzlibraryfillbetween@path@layer@name'. Filled path will be on top of the other ones. Please ensure that '\tikzlibraryfillbetween@path@layer@name' is somewhere in the layer list (or set '/tikz/fill between/on layer=').}%
}%

\def\tikzlibraryfillbetween@parse@softclip{%
	\pgfkeysgetvalue{/tikz/fill between/soft clip first}\pgf@temp
	\pgfkeysgetvalue{/tikz/fill between/soft clip second}\pgf@tempb
	\ifx\pgf@temp\pgf@tempb
		% Ah - both have the same value!
		\ifx\pgf@temp\pgfutil@empty
			% ... and both are empty.
			\pgffillbetweensetsoftclippath{\pgfutil@empty}%
		\else
			% ... and both contain some path! Process it (once):
			\def\tikz@marshal{\tikzlibsoftclip@setkey{\pgffillbetweensetsoftclippath}}%
			\expandafter\tikz@marshal\pgf@temp\pgf@stop
		\fi
	\else
		% handle 'soft clip first':
		\ifx\pgf@temp\pgfutil@empty
			\pgffillbetweensetsoftclippathfirst{\pgfutil@empty}%
		\else
			\def\tikz@marshal{\tikzlibsoftclip@setkey{\pgffillbetweensetsoftclippathfirst}}%
			\expandafter\tikz@marshal\pgf@temp\pgf@stop
		\fi
		%
		% handle 'soft clip second':
		\pgfkeysgetvalue{/tikz/fill between/soft clip second}\pgf@tempb
		\ifx\pgf@tempb\pgfutil@empty
			\pgffillbetweensetsoftclippathsecond{\pgfutil@empty}%
		\else
			\def\tikz@marshal{\tikzlibsoftclip@setkey{\pgffillbetweensetsoftclippathsecond}}%
			\expandafter\tikz@marshal\pgf@tempb\pgf@stop
		\fi
	\fi
}%

\def\tikzlibraryfillbetween@path@generatepath{%
	%
	\tikzlibraryfillbetween@parse@softclip
	%
	\tikzlibraryfillbetween@path@check
	\expandafter\let\expandafter\tikz@fillbetween@a@path
		\csname tikz@intersect@path@name@\tikz@fillbetween@a\endcsname
	\expandafter\let\expandafter\tikz@fillbetween@b@path
		\csname tikz@intersect@path@name@\tikz@fillbetween@b\endcsname
	%
	\iftikzfillbetween@optimize@name@intersections
		\ifpgfpathfillbetween@split
			\tikzfillbetween@optimize@name@intersections\tikz@fillbetween@a\tikz@fillbetween@b
		\fi
	\fi
	%
	\pgfpathfillbetween{\tikz@fillbetween@a@path}{\tikz@fillbetween@b@path}%
}%

\def\tikzlibraryfillbetween@path@check{%
	\pgfutil@IfUndefined{tikz@intersect@path@name@\tikz@fillbetween@a}{%
		\pgferror
		{fill between: the mandatory argument 'of=<name path A> and <name path B> is missing or has empty arguments. Please ensure that the option has been set and that both path names have been assigned (perhaps you need 'name path global=\tikz@fillbetween@a' somewhere?)}%
	}{}%
	\pgfutil@IfUndefined{tikz@intersect@path@name@\tikz@fillbetween@b}{%
		\pgferror
		{fill between: the mandatory argument 'of=<name path A> and <name path B> is missing or has empty arguments. Please ensure that the option has been set and that both path names have been assigned (perhaps you need 'name path global=\tikz@fillbetween@b' somewhere?)}%
	}{}%
}


%-----------------------------------------
%
% Utilities to work with path segments
%
%-----------------------------------------

% Defines \pgfretval such that it contains the named path '#1'
\def\tikzgetnamedpath#1{%
	\pgfutil@IfUndefined{tikz@intersect@path@name@#1}{%
		\pgferror{There is no named path called '#1'. Perhaps you misspelled it?}%
	}{%
		\expandafter\let\expandafter\pgfretval
			\csname tikz@intersect@path@name@#1\endcsname
	}%
}%

\def\tikznamecurrentpath#1{%
	\pgfgetpath\pgf@temp
	\pgfprocessround\pgf@temp\pgf@tempb%
	\expandafter\global\expandafter\let\csname tikz@intersect@path@name@#1\endcsname=\pgf@tempb
}%

% ---------------------------------------------------------------------------------------

\newif\iftikzpathsegments@reverse
\def\tikzlibrarysegments@parse#1 and #2\pgf@stop{%
	\def\tikz@path@segments@a{#1}%
	\def\tikz@path@segments@b{#2}%
}%


\pgfkeys{
	% allows to append intersection segments to the current path by
	% writing
	% \path[intersection segments={of=first and second, sequence=A0 -- B1 -- B3 A3[reverse] -- A1}];
	/tikz/intersection segments/.code={%
		\tikzpathintersectionsegments[#1]%
	},
	/tikz/segments/of/.code=\tikzlibrarysegments@parse#1\pgf@stop,
	/tikz/segments/of={} and {},
	/tikz/segments/sequence/.initial=A0 -- B1,
	/tikz/segments/reverse/.is if=tikzpathsegments@reverse,
	/tikz/segments/reverse/.default=true,
}

% Programmatic method to do the same as 'intersection
% segments={<options>}
%
% #1: <options>
\def\tikzpathintersectionsegments[#1]{%
	\begingroup
	\pgfqkeys{/tikz/segments}{#1}%
	\tikzgetnamedpath{\tikz@path@segments@a}%
	\let\tikz@path@segments@A=\pgfretval
	\tikzgetnamedpath{\tikz@path@segments@b}%
	\let\tikz@path@segments@B=\pgfretval
	%
	% this macro will be called whenever we need an intersection
	% segment. Perhaps we do not need it at all
	\def\tikz@ensurehascomputedintersection{%
		% compute intersections using the PGF intersection lib...
		\pgfintersectionofpaths{\pgfsetpath\tikz@path@segments@A}{\pgfsetpath\tikz@path@segments@B}%
		%
		\ifnum\pgfintersectionsolutions=0 %
			\pgferror{The argument of 'sequence' requests an intersection segment -- but the two input paths do not intersect. Please use A* or B* to select the whole path}%
			\def\b@tikz@select@all{1}%
		\else
			%
			% ... and compute the intersection *segments* for both input
			% paths...
			\pgfcomputeintersectionsegments1%
			\pgfcomputeintersectionsegments2%
		\fi
		\let\tikz@ensurehascomputedintersection=\relax
	}%
	%
	\pgfkeysgetvalue{/tikz/segments/sequence}\tikz@sequence
	%
	\def\b@tikz@isect@nextismoveto{1}%
	\let\pgfpointlastofsetpath=\pgfutil@empty
	\expandafter\tikzpathintersectionsegments@parse@loop\tikz@sequence\pgf@stop
	\pgfmath@smuggleone\pgfpointlastofsetpath
	\endgroup
	\tikz@make@last@position{\pgfpointlastofsetpath}%
}%

\def\tikzpathintersectionsegments@parse@loop{%
	\pgfutil@ifnextchar-{%
		\tikz@isect@p@lineto
	}{%
		\pgfutil@ifnextchar A{%
			\tikz@isect@p@next
		}{%
			\pgfutil@ifnextchar B{%
				\tikz@isect@p@next
			}{%
				\pgfutil@ifnextchar L{%
					\tikz@isect@p@next
				}{%
					\pgfutil@ifnextchar R{%
						\tikz@isect@p@next
					}{%
						\pgfutil@ifnextchar\pgf@stop{%
							\tikz@isect@finish
						}{%
							\tikz@isect@p@error
						}%
					}%
				}%
			}%
		}%
	}%
}%

\def\tikz@isect@finish\pgf@stop{}%

\def\tikz@isect@p@lineto--{%
	\def\b@tikz@isect@nextismoveto{0}%
	\tikzpathintersectionsegments@parse@loop
}%

\def\tikz@isect@p@error#1\pgf@stop{%
	\pgferror{The argument of 'sequence' has an unexpected format near '#1'. Please write something like A0 -- B1 -- A1}%
}

\def\tikz@isect@p@next#1#2{%
	\def\tikz@temp{#2}%
	\def\tikz@@temp{-}%
	\ifx\tikz@@temp\tikz@temp
		% also accept minus signs without curly braces, i.e. 
		% L-2 instead of L{-2}
		\def\tikz@next{\tikz@isect@p@next@{#1}{#2}}%
	\else
		\def\tikz@next{\tikz@isect@p@next@{#1}{#2}{}}%
	\fi
	\tikz@next
}%
\def\tikz@isect@p@next@#1#2#3{%
	\pgfutil@ifnextchar[{%
		\tikz@isect@p@next@opt{#1}{#2#3}%
	}{%
		\tikz@isect@p@next@opt{#1}{#2#3}[]%
	}%
}%

\def\tikz@isect@p@next@opt#1#2[#3]{%
	\begingroup
	%
	% set keys (if any):
	\def\tikz@temp{#3}%
	\ifx\tikz@temp\pgfutil@empty
	\else
		\pgfqkeys{/tikz/segments}{#3}%
	\fi
	%
	\def\tikz@indexshift{}%
	\if A#1%
		% FIRST function (0-based index)
		\def\tikz@path{1}%
		\def\tikz@path@ab{A}%
	\else
		\if B#1%
			% SECOND function (0-based index)
			\def\tikz@path{2}%
			\def\tikz@path@ab{B}%
		\else
			\if L#1%
				% FIRST function (1-based index)
				\def\tikz@path{1}%
				\def\tikz@indexshift{-1}%
				\def\tikz@path@ab{A}%
			\else
				\if R#1%
					% SECOND function (1-based index)
					\def\tikz@path{2}%
					\def\tikz@indexshift{-1}%
					\def\tikz@path@ab{B}%
				\else
					\def\tikz@path{}%
					\pgferror{The argument of 'sequence' has an unexpected format near '#1#2': expected L#2 or R#2}%
				\fi
			\fi
		\fi
	\fi
	%
	% parse arguments:
	\def\pgfmathresult{#2}%
	\def\tikz@temp{*}%
	\ifx\pgfmathresult\tikz@temp
		\def\b@tikz@select@all{1}%
	\else
		\def\b@tikz@select@all{0}%
		\tikz@ensurehascomputedintersection
		\pgfmathparse{round(#2)}%
		\let\tikz@index=\pgfmathresult
		\ifx\tikz@indexshift\pgfutil@empty
		\else
			\afterassignment\pgfutil@gobble@until@relax
			\c@pgf@countc=\tikz@index\relax
			\ifnum\c@pgf@countc<0 \else
				% the index shift is ONLY for positive numbers: we
				% want to start indexing at 1, not at 0 -- and the
				% negative ones start at -1 anyway.
				\advance\c@pgf@countc by\tikz@indexshift\relax
				\edef\tikz@index{\the\c@pgf@countc}%
			\fi
		\fi
	\fi
	%
	%
	% PROCESS IT:
	\ifx\tikz@path\pgfutil@empty
		\let\pgfpointlastofsetpath=\pgfutil@empty
	\else
		\if1\b@tikz@select@all%
			% ok... select the *entire* path. 
			% #1 = A|B :
			\expandafter\let\expandafter\pgfretval\csname tikz@path@segments@\tikz@path@ab\endcsname
		\else
			\pgfgetintersectionsegmentpath{\tikz@path}{\tikz@index}%
		\fi
		\iftikzpathsegments@reverse
			\pgf@reverse@path\pgfretval
		\fi
		\if0\b@tikz@isect@nextismoveto
			\pgfpathreplacefirstmoveto\pgfretval
		\fi
		\pgfaddpathandBB\pgfretval
	\fi
	\pgfmath@smuggleone\pgfpointlastofsetpath
	\endgroup
	\def\b@tikz@isect@nextismoveto{1}%
	\tikzpathintersectionsegments@parse@loop
}%

\def\tikzfillbetween@optimize@name@intersections#1#2{%
	\edef\tikzfillbetween@precached@intersectionofpaths@A{#1}%
	\edef\tikzfillbetween@precached@intersectionofpaths@B{#2}%
	\pgfkeys{%
		/tikz/name intersections/.add code={%
			\let\pgfintersectionofpaths=\tikzfillbetween@precached@intersectionofpaths
		}{%
			\let\pgfintersectionofpaths=\pgfintersectionofpaths@orig
		}
	}%
}%

\let\pgfintersectionofpaths@orig=\pgfintersectionofpaths

\def\tikzfillbetween@precached@intersectionofpaths@log{%
	\immediate\write-1{fill between: outcome of 'name intersections={of=\tikz@intersect@path@a\space and \tikz@intersect@path@b}' has been computed from available information of fill between}%
}
\def\tikzfillbetween@precached@intersectionofpaths#1#2{%
	\def\pgf@loc@TMPa{0}%
	\ifx\tikz@intersect@path@a\tikzfillbetween@precached@intersectionofpaths@A
		\ifx\tikz@intersect@path@b\tikzfillbetween@precached@intersectionofpaths@B
			\def\pgf@loc@TMPa{1}%
		\fi
	\fi
	\ifx\tikz@intersect@path@b\tikzfillbetween@precached@intersectionofpaths@A
		\ifx\tikz@intersect@path@a\tikzfillbetween@precached@intersectionofpaths@B
			\def\pgf@loc@TMPa{1}%
		\fi
	\fi
	%
	\if1\pgf@loc@TMPa
		\tikzfillbetween@precached@intersectionofpaths@log
		\relax
	\else
		\pgfintersectionofpaths@orig{#1}{#2}%
	\fi
}%
\endinput

tikzlibraryintersections.code.tex
% Copyright 2008 by Mark Wibrow
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Free Documentation License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\usepgflibrary{intersections}

\pgfkeys{%
  /tikz/name path global/.code={%
  	% reset any "old" variables inheritted from some other path 
	% - we do not accidentally want to append to an old path with the
	% same name (or if someone provided the option twice)...
	\expandafter\global\expandafter\let\csname tikz@intersect@path@name@#1\endcsname=\relax
  	\tikz@key@name@path{#1}{\gdef}%
  },
  /tikz/name path local/.code={%
    \pgfkeys{/tikz/name path={#1}}%
  },
  /tikz/name path/.code={%
	% hm. Do we need this "reset old option" as in 'name path global'
	% for this case as well?
  	\tikz@key@name@path{#1}{\def}%
  },
}

% #1: the name to assign.
% #2: one of '\def' or '\gdef'.
\def\tikz@key@name@path#1#2{%
    \tikz@addmode{%
      \pgfsyssoftpath@getcurrentpath\tikz@intersect@temppath@round%
      \pgfprocessround\tikz@intersect@temppath@round\tikz@intersect@temppath%
      \ifx\tikz@intersect@namedpaths\pgfutil@empty%
      \else%
        \tikz@intersect@namedpaths%
        \pgfutil@ifundefined{tikz@intersect@path@name@#1}{}%
        {%
          \expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter\tikz@intersect@@temppath%
          \expandafter\expandafter\expandafter{\csname tikz@intersect@path@name@#1\endcsname}%
          \expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter\tikz@intersect@temppath%
          \expandafter\expandafter\expandafter{\expandafter\tikz@intersect@temppath\tikz@intersect@temppath}%
        }%
      \fi%
      \tikz@intersect@addto@path@names{#1}{#2}%
    }%
}%

% #1: the name to assign.
% #2: one of '\def' or '\gdef'.
\def\tikz@intersect@addto@path@names#1#2{%
  \edef\tikz@marshal{#2\expandafter\noexpand\csname tikz@intersect@path@name@#1\endcsname}%
  \expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter\tikz@marshal%
    \expandafter\expandafter\expandafter{\expandafter\tikz@marshal\expandafter{\tikz@intersect@temppath}}%
  \expandafter\pgfutil@g@addto@macro\expandafter\tikz@intersect@namedpaths\expandafter{\tikz@marshal}%
}


\let\tikz@finish@orig=\tikz@finish
\def\tikz@finish{%
	\tikz@finish@orig%
	\tikz@intersect@finish%
}

\def\tikz@intersect@finish{%	
	\ifx\tikz@intersect@namedpaths\pgfutil@empty%
	\else%
		\tikz@intersect@namedpaths%
		\let\tikz@intersect@namedpaths=\pgfutil@empty%
	\fi%
}
	
\let\tikz@intersect@namedpaths=\pgfutil@empty
\let\tikz@intersect@path@a=\pgfutil@empty
\let\tikz@intersect@path@b=\pgfutil@empty
\let\tikz@intersect@name=\pgfutil@empty
\let\tikz@intersect@total=\pgfutil@empty

\tikzset{
  name intersections/.code={%
    \tikzset{/tikz/intersection/.cd,
      by=,
      #1}%
    \pgfutil@ifundefined{tikz@intersect@path@name@\tikz@intersect@path@a}{%
      \tikzerror{I do not know the path named `\tikz@intersect@path@a'. Perhaps you misspelt it}}%
    {\pgfutil@ifundefined{tikz@intersect@path@name@\tikz@intersect@path@b}{%
        \tikzerror{I do not know the path named `\tikz@intersect@path@b'. Perhaps you misspelt it}}%
      {%
        \pgfintersectionofpaths%
        {%
          \expandafter\pgfsetpath\csname tikz@intersect@path@name@\tikz@intersect@path@a\endcsname%
        }%
        {%
          \expandafter\pgfsetpath\csname tikz@intersect@path@name@\tikz@intersect@path@b\endcsname%
        }%
        \ifx\tikz@intersect@total\pgfutil@empty%
        \else%
          \expandafter\let\tikz@intersect@total=\pgfintersectionsolutions%
        \fi%
        \ifx\tikz@intersect@name\pgfutil@empty%
          \def\tikz@intersect@@name{intersection}%
        \else%
          \let\tikz@intersect@@name=\tikz@intersect@name%
        \fi%
        \pgfmathloop%
        \ifnum\pgfmathcounter>\pgfintersectionsolutions\relax%
        \else%
          \path[reset cm]\pgfextra{\pgftransformshift{\pgfpointintersectionsolution{\pgfmathcounter}}}%
            coordinate (\tikz@intersect@@name-\pgfmathcounter);
        \repeatpgfmathloop%
        \ifx\tikz@intersect@by\pgfutil@empty%
        \else%
          \foreach\tikz@intersect@name[count=\tikz@intersection@count] in \tikz@intersect@by%
          {\expandafter\tikz@intersect@name@parse\tikz@intersect@name\pgf@stop}%
        \fi%
      }%
    }%
  },%
  intersection/.cd,
  of/.code=\tikz@intersect@path@names@parse#1\tikz@stop,%
  name/.store in=\tikz@intersect@name,
  total/.store in=\tikz@intersect@total,
  by/.store in=\tikz@intersect@by,
  sort by/.code=\edef\tikz@intersect@sort@by{#1}\tikz@intersect@check@sort@by%
}


\def\tikz@intersect@check@sort@by{%
	\ifx\tikz@intersect@sort@by\tikz@intersect@path@a%
		\pgfintersectionsortbyfirstpath%
	\else%
		\ifx\tikz@intersect@sort@by\tikz@intersect@path@b%
			\pgfintersectionsortbysecondpath%
		\else%
			\pgf@intersect@sortfalse%
		\fi%
	\fi%
}
\def\tikz@intersect@path@names@parse#1 and #2\tikz@stop{%
  \def\tikz@intersect@path@a{#1}%
  \def\tikz@intersect@path@b{#2}%
}

\def\tikz@intersect@name@parse{\pgfutil@ifnextchar[\tikz@intersect@name@parse@opt{\tikz@intersect@name@parse@opt[]}}%}
\def\tikz@intersect@name@parse@opt[#1]#2\pgf@stop{%
  \coordinate [#1] (#2) at (\tikz@intersect@@name-\tikz@intersection@count);
}%

\endinput

tikzlibrarypgfplots.decorations.softclip.code.tex
%--------------------------------------------
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2013 by Christian Feuersaenger
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------
%
% This library adds support for a "soft clip" decoration. It applies
% clipping to an input path, but rather than simply instructing the
% display driver to clip the path, it computes a new clip path from
% the input.
%
% This library is (currently) on top of tikz.

\usetikzlibrary{decorations.softclip}

\endinput

tikzlibrarypgfplots.fillbetween.code.tex
%--------------------------------------------
%
% Package pgfplots
%
% Provides a user-friendly interface to create function plots (normal
% plots, semi-logplots and double-logplots).
% 
% It is based on Till Tantau's PGF package.
%
% Copyright 2013 by Christian Feuersaenger
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------


% This library adds support for high-level instructions for "fill area
% between two arbitrary plots of functions".
%
% It activates the syntax
%
% 	\addplot fill between[of=A and B];
%
% where A and B are two plots named by 'name path='.
%
% In fact, this here is not much more than a low-level invocation of
% \pgfpathfillbetween
% and a couple of styles. It could become a TikZ library because it
% actually works on any two named paths, but it has its restrictions
% regarding the supported input paths: both need to be plots of
% functions (non-intersecting, should have at most one function value
% for each canvas X coord)

\pgfutil@IfUndefined{pgfplotsset}{%
	\pgferror{Please load pgfplots before pgfplots.fillbetween.}%
	\endinput
}{}%

\usetikzlibrary{fillbetween}
\usepgfplotslibrary{decorations.softclip}

\pgfkeys{
	/pgfplots/every fill between plot/.style={/pgfplots/area legend,/tikz/fill},
	/tikz/soft clip assign/domain/.code args={#1:#2}{%
		\pgfplotsifisvisualizationphase{%
			\edef\pgfplots@loc@TMPa{%
				(axis cs:#1,\pgfkeysvalueof{/pgfplots/ymin}) 
				rectangle (axis cs:#2,\pgfkeysvalueof{/pgfplots/ymax})}%
			\pgfkeysalso{/tikz/soft clip assign/path/.expand once=\pgfplots@loc@TMPa}%
		}{}%
	},%
	/tikz/soft clip assign/y domain y/.style={/tikz/soft clip assign/domain y={#1}},
	/tikz/soft clip assign/domain y/.code args={#1:#2}{%
		\pgfplotsifisvisualizationphase{%
			\edef\pgfplots@loc@TMPa{%
				(axis cs:\pgfkeysvalueof{/pgfplots/xmin},#1) 
				rectangle (axis cs:\pgfkeysvalueof{/pgfplots/xmax},#2)}%
			\pgfkeysalso{/tikz/soft clip assign/path/.expand once=\pgfplots@loc@TMPa}%
		}{}%
	},%
	%
	/pgfplots/execute at begin axis@@/.add={}{%
		\gdef\pgfplotsfillbetween@list@of@layers@with@clippath{}%
		\gdef\b@pgfplotsfillbetween@list@has@set@layers{0}%
	},
}

% #1: the value of /tikz/fill between/on layer
\def\pgfplotsfillbetween@ensure@clipping@on@layer{%
	\ifpgfplots@clip
		\pgfkeysgetvalue{/tikz/fill between/on layer}\pgfplots@loc@TMPa
		\edef\pgfplots@loc@TMPa{\pgfplots@loc@TMPa}%
		%
		% check if 'pre main,' is inside of the already prepared layers:
		\def\pgfplots@loc@TMPb{\expandafter\pgfutil@in@\expandafter{\pgfplots@loc@TMPa,}}%
		\expandafter\pgfplots@loc@TMPb\expandafter{\pgfplotsfillbetween@list@of@layers@with@clippath}%
		%
		\ifpgfutil@in@
			% ah - already prepared. Good, nothing left to do.
		\else
			\pgfplots@log3{fill between: found 'clip=true'. Preparing pgfplotsextra instruction with clip path for layer '\pgfplots@loc@TMPa'...}%
			\xdef\pgfplotsfillbetween@list@of@layers@with@clippath{\pgfplots@loc@TMPa,\pgfplotsfillbetween@list@of@layers@with@clippath}%
			%
			\edef\pgfplots@loc@TMPb{%
				\noexpand\pgfplotsextra{%
					\noexpand\pgfplotsonlayer{\pgfplots@loc@TMPa}%
					\noexpand\pgfplotspathaxisoutline
					\noexpand\pgfusepath{clip}%
					\noexpand\endpgfplotsonlayer
				}%
			}%
			\pgfplots@loc@TMPb
			%
		\fi
	\fi
}%

% The options are from 
% \addplot[#1] fill between[#2] #3;
%
% This method is invoked from the global \addplot dispatching.
\def\pgfplotslibraryfillbetween@addplot#1#2#3{%
	%
	\pgfplots@start@plot@with@behavioroptions{/pgfplots/every fill between plot,#1}%
	%
	\pgfkeysvalueof{/pgfplots/execute at end survey}%
	\pgfplots@remember@survey@option@list
	%
	%
	\pgfplotslibraryfillbetweenpreparecurrentlayer
	%
	\pgfplots@addplot@enqueue@coords{%
		% precmd
	}{%
		% empty - this here is a TikZ instruction, not a "real" \addplot command
	}{%
		% the path instruction:
		\tikzfillbetween[#2]{%
			/pgfplots/.search also=/tikz,%
			/pgfplots/.cd,%
			/tikz/fill between/every last segment/.append style={/tikz/fill between/path after segment={#3}},%
			#1%
		}%
	}{%	
		% post command.
	}%
}

% ONLY TO BE USED AS LATER OPTION!
\pgfkeysdef{/pgfplots/fill between/@ensure layers}{%
	\ifpgfplots@layered@graphics
	\else
		\pgfplots@log3{fill between: activating layered graphics}%
		\pgfplotsset{set layers}%
		\pgfplots@set@options@of@layered@graphics
	\fi
}%

% SIDE-EFFECT: modifies \b@pgfplotsfillbetween@list@has@set@layers and
% \pgfplotsfillbetween@list@of@layers@with@clippath
\def\pgfplotslibraryfillbetweenpreparecurrentlayer{%
	\pgfkeysgetvalue{/tikz/fill between/on layer}\pgfplots@loc@TMPa
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
	\else
		\if0\b@pgfplotsfillbetween@list@has@set@layers
			%
			\pgfplotssetlateoptions{fill between/@ensure layers}%
			\gdef\b@pgfplotsfillbetween@list@has@set@layers{1}%
		\fi
		\pgfplotsfillbetween@ensure@clipping@on@layer%
	\fi
}

\def\pgfplots@tikzfillbetween{\pgfutil@ifnextchar[{\pgfplots@tikzfillbetween@opt}{\pgfplots@tikzfillbetween@opt[]}}
\def\pgfplots@tikzfillbetween@opt[#1]#2{%
	\pgfplots@addplot@enqueue@coords{%
		% precmd
	}{%
		% empty - this here is a TikZ instruction, not a "real" \addplot command
	}{%
		% the path instruction:
		\tikzfillbetween[#1]{#2}%
	}{%	
		% post command.
	}%
}%

\expandafter\def\expandafter\pgfplots@replace@path@commands\expandafter{\pgfplots@replace@path@commands
	\let\pgfplots@orig@tikzfillbetween=\tikzfillbetween
	\let\tikzfillbetween=\pgfplots@tikzfillbetween
}%
\expandafter\def\expandafter\pgfplots@restore@path@commands\expandafter{\pgfplots@restore@path@commands
	\let\tikzfillbetween=\pgfplots@orig@tikzfillbetween
}

\endinput

tikzlibrarypgfplots.statistics.code.tex
%--------------------------------------------
%
% Package pgfplots, library for statistical plots (boxplots in the first version)
%
% Copyright 2007-2012 by Christian Feuersänger.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------

\newif\ifpgfplotsplothandlerboxplot@variable@width

\pgfplotsset{
	boxplot/.code={%
		\def\tikz@plot@handler{\pgfplotsplothandlerboxplot}%
		\pgfkeysalso{%
			/pgfplots/every boxplot,
			/pgfplots/boxplot/.cd,
			#1%
		}%
	},
	boxplot prepared/.code={%
		\def\tikz@plot@handler{\pgfplotsplothandlerboxplotprepared}%
		\pgfkeysalso{%
			/pgfplots/every boxplot,
			/pgfplots/boxplot/.cd,
			#1%
		}%
	},
	boxplot/data value/.code	=\pgfplots@set@source@for{boxplot/data}{#1}{0},%
	boxplot/data/.code			=\pgfplots@set@source@for{boxplot/data}{#1}{1},%
	boxplot/data filter/.code=,
	boxplot/data value=\pgfkeysvalueof{/data point/y},
	%
	every boxplot/.style={%
	},
	%
	% 'auto' means "if possible".
	% For boxplot prepared, this is equivalent to "disabled" (empty value).
	% For boxplot, it means "compute it".
	% Empty value means disabled.
	boxplot/median/.initial=auto,
	boxplot/lower quartile/.initial=auto,
	boxplot/upper quartile/.initial=auto,
	boxplot/lower whisker/.initial=auto,
	boxplot/upper whisker/.initial=auto,
	boxplot/average/.initial=,
	%
	boxplot/lower quartile off/.initial=0.25,
	boxplot/upper quartile off/.initial=0.75,
	boxplot/whisker range/.initial=1.5,
	%
	%
	% the size of whisker lines in axis units.
	% The default is to make it relative to 'box extend'
	boxplot/whisker extend/.initial=\pgfkeysvalueof{/pgfplots/boxplot/box extend}*0.8,
	%
	% the size of the box in axis units. Note that this has been
	% chosen to fit the initial 'draw position':
	boxplot/box extend/.initial=0.8,
	% draw direction=x|y
	boxplot/draw direction/.initial=x,	
	%
	% Activates "dynamic size" feature
	boxplot/variable width/.is if=pgfplotsplothandlerboxplot@variable@width,
	boxplot/variable width/.default=true,
	%
	boxplot/sample size/.initial=auto,
	%
	% a transformation which is applied to anything related to
	% sample size.
	boxplot/variable width expr/.code=\pgfmathparse{sqrt(#1)},
	%
	% will be computed automatically if needed. If it is present, it
	% will not contribute to the axis-wide limit unless it has been
	% given axis-wide.
	boxplot/sample size min/.initial=,
	boxplot/sample size max/.initial=,
	%
	% this factor times 'box extend' is the size for 
	% 'sample size min'. The max value gets 'box extend'.
	boxplot/variable width min target/.initial=0.2,
	%
	%
	% defines where how the "free" position is chosen. The idea is to
	% place one box at each "y" position and to number these
	% 1,2,3,4,... . This should probably simplify tick (label) generation.
	boxplot/draw position/.initial=1+\plotnumofactualtype,
	%
	% draw relative anchor=0:  
	%     |    |---|  |
	%     |    |   |  |
	%     |----|---|--|
	%
	% draw relative anchor=0.5:
	%     |    |---|  |
	%     |----|   |--|
	%     |    |---|  |
	%
	% draw relative anchor=1:  
	%     |----|---|--|
	%     |    |   |  |
	%     |    |---|  |
	boxplot/draw relative anchor/.initial=0.5,
	%
	boxplot/every whisker/.style={%
	},
	boxplot/every box/.style={%
	},
	boxplot/every median/.style={%
	},
	boxplot/every average/.style={%
		/tikz/mark=diamond*,
	},
	boxplot/draw/lower whisker/.style={%
		/pgfplots/boxplot/draw/whisker=%
			{\pgfplotsboxplotvalue{lower quartile}}
			{\pgfplotsboxplotvalue{lower whisker}}
	},
	boxplot/draw/upper whisker/.style={%
		/pgfplots/boxplot/draw/whisker=%
			{\pgfplotsboxplotvalue{upper quartile}}
			{\pgfplotsboxplotvalue{upper whisker}}%
	},
	boxplot/draw/whisker/.code 2 args={%
		\draw[/pgfplots/boxplot/every whisker/.try]
			(boxplot cs:#1) -- (boxplot cs:#2)
			(boxplot whisker cs:#2,0)
			--
			(boxplot whisker cs:#2,1)
		;
	},%
	%
	boxplot/draw/box/.code={%
		\draw[/pgfplots/boxplot/every box/.try]
			(boxplot box cs:\pgfplotsboxplotvalue{lower quartile},0)
			rectangle
			(boxplot box cs:\pgfplotsboxplotvalue{upper quartile},1)
		;
	},%
	%
	boxplot/draw/average/.code={%
		\draw[/pgfplots/boxplot/every average/.try]
			\pgfextra
			% do NOT use \draw[mark=*] plot coordinates because
			% boxplots uses the same plot handler to draw its
			% outliers.
			\pgftransformshift{%
				\pgfplotsboxplotpointabbox
					{\pgfplotsboxplotvalue{average}}
					{0.5}%
			}%
			\pgfuseplotmark{\tikz@plot@mark}%
			\endpgfextra
		;
	},
	%
	boxplot/draw/median/.code={%
		\draw[/pgfplots/boxplot/every median/.try]
			(boxplot box cs:\pgfplotsboxplotvalue{median},0)
			--
			(boxplot box cs:\pgfplotsboxplotvalue{median},1)
		;
	},%
}


\def\pgfplotsplothandlerboxplot{%
	\pgfplotsresetplothandler
	\def\pgf@plotstreamstart{%
		\pgfplotsset{/pgfplots/boxplot prepared}%
		\pgfplotsresetplothandler
		\tikz@plot@handler
		\pgf@plotstreamstart
	}%
	\def\pgfplotsplothandlername{boxplot}%
	\let\pgfplotsplothandlersurveypoint=\pgfplotsplothandlersurveypoint@boxplot
	\let\pgfplotsplothandlersurveystart=\pgfplotsplothandlersurveystart@boxplot
	\let\pgfplotsplothandlersurveyend=\pgfplotsplothandlersurveyend@boxplot
}


\def\pgfplotsplothandlersurveystart@boxplot{%
	\pgfplots@prepare@source@parser@for{boxplot/}{data}{\pgfplotsplothandlerboxplot@parse}%
	%
	\pgfplotscoordmath{float}{zero}%
	\let\pgfplotsplothandlerboxplot@sum=\pgfmathresult
	%
	\pgfplotscoordmath{float}{min limit}%
	\let\pgfplotsplothandlerboxplot@last=\pgfmathresult
	%
	\def\b@pgfplotsplothandlerboxplot@issorted{1}%
	%
	% FIXME : the decision to store the input points into a SINGLY
	% LINKED LIST is based on the observation that huge TeX arrays
	% (with one macro per index) run into out-of-memory easily.
	% The list does not: it does not need that many macros and uses a
	% different memory limit...
	%
	% However, the linked-list is bought off for a high price... the
	% statistics computation takes linear time instead of constant.
	% But we have linear time anyway, so it does not destroy the
	% asymptotics... and it appears to be better to get it into main
	% memory (?)
	\pgfplotsapplistXnewempty\pgfp@boxplot@@
	\def\c@pgfplotsplothandlerboxplot@num{0}%
	\c@pgfplots@coordindex=0
}%

\def\pgfplotsplothandlersurveyend@boxplot{%
	\pgfplots@curplot@threedimfalse
	%
	\pgfplotsapplistXlet\pgfplots@boxplot@data=\pgfp@boxplot@@
	\pgfplotsapplistXnewempty\pgfp@boxplot@@
	%
	\if0\b@pgfplotsplothandlerboxplot@issorted
		\pgfplotsplothandlersurveyend@boxplot@sort
	\fi
	%
	%
	\edef\numcoords{\pgfplots@current@point@coordindex}%
	%
	%%
	\pgfplotsset{%
		/pgfplots/boxplot prepared={%
			data value=\pgfplots@current@point@data,
		},%
	}%
	\pgfplotsresetplothandler
	%
	\let\pgfplotsplothandlerboxplotprepared@normalize@values@@=\pgfplotsplothandlerboxplotprepared@normalize@values
	\def\pgfplotsplothandlerboxplotprepared@normalize@values{\relax}%
	%
	\tikz@plot@handler
	%
	\pgfplotsplothandlersurveystart
	%
	% this will report outliers as point stream:
	\pgfplotsplothandlersurveyend@boxplot@computestats
	\let\pgfplots@boxplot@data=\relax
	%
	\let\pgfplotsplothandlerboxplotprepared@normalize@values=\pgfplotsplothandlerboxplotprepared@normalize@values@@
	\pgfplotsplothandlerboxplotprepared@normalize@values
	%
	%
	\pgfplotsplothandlersurveyend
}%

\def\pgfplotsplothandlersurveyend@boxplot@sort{%
	% how bad. we have to convert to array, sort, convert back to
	% list... it would have been better if we had worked with arrays
	% right away! But see the docs in front of the line
	% '\pgfplotsapplistXnewempty\pgfp@boxplot@@' somewhere in this
	% file...
	%
	\begingroup
	\pgfplotsarraynewempty{P}%
	\pgfplotsarrayresize{P}{\c@pgfplots@coordindex}%
	%
	\c@pgfplots@coordindex=0
	\let\pgfplotsplothandlersurveyend@boxplot@computestats@=\pgfplots@boxplot@fillarray
	\expandafter\pgfplotsplothandlersurveyend@boxplot@computestats@loop\pgfplots@boxplot@data\pgfplots@EOI
	%
	\pgfkeysdef{/pgfplots/array/unscope pre}{%
		\pgfplotsapplistXnewempty\pgfp@boxplot@@
		\pgfplotsarrayforeachungrouped{##1}\as\elem{%
			\edef\elem{{\elem}}%
			\expandafter\pgfplotsapplistXpushback\expandafter{\elem}\to\pgfp@boxplot@@
		}%
		\pgfplotsapplistXlet\pgfplots@boxplot@data=\pgfp@boxplot@@
		\global\let\pgfplots@glob@boxplot@TMPd=\pgfplots@boxplot@data
	}%
	\pgfkeysdef{/pgfplots/array/unscope post}{%
	}%
	%
	%\message{[}\pgfplotsarrayforeach{P}\as\elem{\message{\elem,}}\message{]^^J}%
	%
	\pgfkeys{/pgfplots/float <}%
	\pgfplotsarraysort{P}%
	%
	\endgroup
	\let\pgfplots@boxplot@data=\pgfplots@glob@boxplot@TMPd
	%\message{-> \meaning\pgfplots@boxplot@data^^J}%
}%

\def\pgfplots@boxplot@fillarray{%
	\def\pgfplots@loc@TMPa{\pgfplotsarrayset\c@pgfplots@coordindex\of{P}\to}%
	\expandafter\pgfplots@loc@TMPa\expandafter{\pgfplots@current@point@data}%
}

%%%%

% 
% OUTPUT:
% \pgfplotsretval: the result of #1 * #2 as integer
% \pgfplotsretvalb = 1 iff #1 * #2 is an integer (without loss)
\def\pgfplots@boxplot@get@quantile@offset#1#2{%
	\pgfplotscoordmath{float}{parsenumber}{#2}%
	\pgfplotscoordmath{float}{op}{multiply}{{\pgfmathresult}{#1}}%
	\pgfplotscoordmath{float}{tofixed}{\pgfmathresult}%
	\afterassignment\pgfplots@boxplot@get@quantile@remainder
	\c@pgf@countd=\pgfmathresult\relax
	\edef\pgfplotsretval{\the\c@pgf@countd}%
}%

\def\pgfplots@boxplot@get@quantile@remainder#1\relax{%
	\ifdim #1pt>0.001pt
		\def\pgfplotsretvalb{0}%
	\else
		\def\pgfplotsretvalb{1}%
	\fi
}%

\def\pgfplotsplothandlersurveyend@boxplot@computestats{ 
	%
	% compute TMPa := float(\numcoords - 1)
	\pgfplotscoordmath{float}{one}%
	\let\pgfplots@loc@TMPa=\pgfmathresult
	\pgfplotscoordmath{float}{parsenumber}{\numcoords}%
	\let\pgfplots@boxplot@numcoords=\pgfmathresult
	\pgfplotscoordmath{float}{op}{subtract}{{\pgfmathresult}{\pgfplots@loc@TMPa}}%
	\let\pgfplots@boxplot@numcoords@minus@one=\pgfmathresult
	%
	% compute the indices into the coordinate arrays:
	\pgfplots@boxplot@get@quantile@offset{\pgfplots@boxplot@numcoords@minus@one}{\pgfplotsboxplotvalue{lower quartile off}}%
	\let\c@pgfplotsplothandlerboxplot@lowerquartile=\pgfplotsretval
	\let\b@pgfplotsplothandlerboxplot@lowerquartile@isint=\pgfplotsretvalb
	\pgfplots@boxplot@get@quantile@offset{\pgfplots@boxplot@numcoords@minus@one}{0.5}%
	\let\c@pgfplotsplothandlerboxplot@median=\pgfplotsretval
	\let\b@pgfplotsplothandlerboxplot@median@isint=\pgfplotsretvalb
	\pgfplots@boxplot@get@quantile@offset{\pgfplots@boxplot@numcoords@minus@one}{\pgfplotsboxplotvalue{upper quartile off}}%
	\let\c@pgfplotsplothandlerboxplot@upperquartile=\pgfplotsretval
	\let\b@pgfplotsplothandlerboxplot@upperquartile@isint=\pgfplotsretvalb
	%
	% hm. I once had the idea to support quartile-based whisker
	% definitions... but I did not implement them.
	\let\c@pgfplotsplothandlerboxplot@lowerwhisker=\pgfutil@empty
	\let\c@pgfplotsplothandlerboxplot@upperwhisker=\pgfutil@empty
	%
	%
	% These here are the VALUES that will be communicated to 'boxplot prepared'
	% They need to be computed below.
	\let\pgfplotsplothandlerboxplot@lowerwhisker=\pgfutil@empty
	\let\pgfplotsplothandlerboxplot@lowerquartile=\pgfutil@empty
	\let\pgfplotsplothandlerboxplot@median=\pgfutil@empty
	\let\pgfplotsplothandlerboxplot@upperquartile=\pgfutil@empty
	\let\pgfplotsplothandlerboxplot@upperwhisker=\pgfutil@empty
	%
	\c@pgfplots@coordindex=0 %
	\def\pgfplots@boxplot@@next@target{lowerquartile}%
	\def\pgfplots@boxplot@next@@lowerquartile{median}%
	\def\pgfplots@boxplot@next@@median{upperquartile}%
	\def\pgfplots@boxplot@next@@upperquartile{}%
	\let\pgfplotsplothandlersurveyend@boxplot@computestats@=\pgfplotsplothandlersurveyend@boxplot@computestats@quantile
	\expandafter\pgfplotsplothandlersurveyend@boxplot@computestats@loop\pgfplots@boxplot@data\pgfplots@EOI
	%
	%
	\pgfplotscoordmath{float}{op}{divide}{{\pgfplotsplothandlerboxplot@sum}{\pgfplots@boxplot@numcoords}}%
	\let\pgfplotsplothandlerboxplot@average=\pgfmathresult
	%
	% communicate and set results to pgfkeys - and to the plot
	% specification option list:
	\pgfplotsplothandlersurveyend@boxplot@set{lower whisker}{\pgfplotsplothandlerboxplot@lowerwhisker}%
	\pgfplotsplothandlersurveyend@boxplot@set{lower quartile}{\pgfplotsplothandlerboxplot@lowerquartile}%
	\pgfplotsplothandlersurveyend@boxplot@set{median}{\pgfplotsplothandlerboxplot@median}%
	\pgfplotsplothandlersurveyend@boxplot@set{average}{\pgfplotsplothandlerboxplot@average}%
	\pgfplotsplothandlersurveyend@boxplot@set{upper quartile}{\pgfplotsplothandlerboxplot@upperquartile}%
	\pgfplotsplothandlersurveyend@boxplot@set{upper whisker}{\pgfplotsplothandlerboxplot@upperwhisker}%
	\pgfplotsplothandlersurveyend@boxplot@set{sample size}{\pgfplots@boxplot@numcoords}%
	%
	% Ok, now make sure that we use the FINAL variables from the user,
	% i.e. that we respect manual overrides. This is only necessary
	% for quartiles from what I see here.
	\pgfplotsplothandlersurveyend@boxplot@get{\pgfplotsplothandlerboxplot@lowerquartile}{lower quartile}%
	\pgfplotsplothandlersurveyend@boxplot@get{\pgfplotsplothandlerboxplot@upperquartile}{upper quartile}%
	%
	\pgfplotscoordmath{float}{parsenumber}{\pgfplotsboxplotvalue{whisker range}}%
	\let\pgfplots@loc@TMPa=\pgfmathresult
	\pgfplotscoordmath{float}{op}{subtract}{{\pgfplotsplothandlerboxplot@upperquartile}{\pgfplotsplothandlerboxplot@lowerquartile}}%
	\pgfplotscoordmath{float}{op}{multiply}{{\pgfmathresult}{\pgfplots@loc@TMPa}}%
	\let\pgfplots@boxplot@whisker@width=\pgfmathresult
	\pgfplotscoordmath{float}{op}{add}{{\pgfplotsplothandlerboxplot@upperquartile}{\pgfplots@boxplot@whisker@width}}%
	\let\pgfplotsplothandlerboxplot@upperwhisker@value=\pgfmathresult
	\pgfplotscoordmath{float}{op}{subtract}{{\pgfplotsplothandlerboxplot@lowerquartile}{\pgfplots@boxplot@whisker@width}}%
	\let\pgfplotsplothandlerboxplot@lowerwhisker@value=\pgfmathresult
	%
	\c@pgfplots@coordindex=0 %
	\let\pgfplotsplothandlersurveyend@boxplot@computestats@=\pgfplotsplothandlersurveyend@boxplot@computestats@valuebased
	\expandafter\pgfplotsplothandlersurveyend@boxplot@computestats@loop\pgfplots@boxplot@data\pgfplots@EOI
	%
	\pgfplotsplothandlersurveyend@boxplot@set{lower whisker}{\pgfplotsplothandlerboxplot@lowerwhisker}%
	\pgfplotsplothandlersurveyend@boxplot@set{upper whisker}{\pgfplotsplothandlerboxplot@upperwhisker}%
	%
}%

% takes a key #1 which is expected in /pgfplots/boxplot/#1,
% and overwrites its value with #2 if that is allowed.
%
% More specifically, if the current value of '#1' is 'auto', it is
% replaced by #2. In all other cases, it will not be modified.
%
% The "replaced by #2" means to set the value right away and to modify
% the plot's option list to reflect the new value.
\def\pgfplotsplothandlersurveyend@boxplot@set#1#2{%
	\pgfkeysgetvalue{/pgfplots/boxplot/#1}\pgfplots@loc@TMPa
	\edef\pgfplots@loc@TMPa{\pgfplots@loc@TMPa}%
	\def\pgfplots@loc@TMPc{auto}%
	\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPc
		\edef\pgfmathresult{#2}%
		\ifx\pgfmathresult\pgfutil@empty
		\else
			\pgfplotscoordmath{float}{tostring}{#2}%
			\edef\pgfplots@loc@TMPb{\noexpand\pgfplotsplothandlersurveyaddoptions{/pgfplots/boxplot/#1={\pgfmathresult}}}%
			\pgfplots@loc@TMPb
		\fi
	\fi
}%

\def\pgfplotsplothandlersurveyend@boxplot@get#1#2{%
	\pgfkeysgetvalue{/pgfplots/boxplot/#2}\pgfplots@loc@TMPa
	\edef\pgfplots@loc@TMPa{\pgfplots@loc@TMPa}%
	\def\pgfplots@loc@TMPc{auto}%
	\ifx\pgfplots@loc@TMPa\pgfplots@loc@TMPc
	\else
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			\pgfmathparse{\pgfplots@loc@TMPa}%
			\let#1=\pgfmathresult
		\fi
	\fi
}


% Assuming that the input coordinates are in a LIST, we have to loop
% over that list.
\def\pgfplotsplothandlersurveyend@boxplot@computestats@loop#1{%
	\def\pgfplots@loc@TMPa{#1}%
	\ifx\pgfplots@loc@TMPa\pgfplots@EOI
	\else
		%
		\let\pgfplots@current@point@data=\pgfplots@loc@TMPa
		\pgfplotsplothandlersurveyend@boxplot@computestats@
		%
		\advance\c@pgfplots@coordindex by1 %
		\expandafter\pgfplotsplothandlersurveyend@boxplot@computestats@loop
	\fi
}%

% Really computes stats.
% 
% This method computes ALL quantiles (one after the other). These are 0.25,
% 0.5, and 0.75. Perhaps I add quantile-based whiskers eventually.
%
% XXX : this method is quite inefficient because it iterates through a
% loop for what would be 3 arrays lookups otherwise. If I would have enough
% courage to store the points into an array, both this and the
% whisker-loop would be more efficient. But in TeX, arrays are not
% necessarily that efficient ... they run out of memory easily!
%
% The data is in \pgfplots@current@point@data.
\def\pgfplotsplothandlersurveyend@boxplot@computestats@quantile{%
	%
	\c@pgf@countd=\csname c@pgfplotsplothandlerboxplot@\pgfplots@boxplot@@next@target\endcsname\relax
	\expandafter\let\expandafter\pgfplots@loc@TMPa\csname pgfplotsplothandlerboxplot@\pgfplots@boxplot@@next@target\endcsname
	%
	\ifnum\c@pgf@countd=\c@pgfplots@coordindex\relax
		% Ah - we found the occurence of the current search target! 
		\expandafter\let\csname pgfplotsplothandlerboxplot@\pgfplots@boxplot@@next@target\endcsname=\pgfplots@current@point@data
		%
		\expandafter\let\expandafter\pgfplots@loc@TMPb\csname b@pgfplotsplothandlerboxplot@\pgfplots@boxplot@@next@target @isint\endcsname
		\if 1\pgfplots@loc@TMPb
			% accept the match!
			% ... and search for the next search target.
			\expandafter\let\expandafter\pgfplots@boxplot@@next@target\csname pgfplots@boxplot@next@@\pgfplots@boxplot@@next@target\endcsname
		\else
			% ... continue searching for the same target in order to
			% compute the mean.
		\fi
	\else
		\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\else
			% Ah! this can *only* happen if we have to compute a
			% mean between the previous and this data point.
			%
			% The current search target is 0.5 * (value + next):
			\pgfplotscoordmath{float}{op}{add}{{\pgfplots@current@point@data}{\pgfplots@loc@TMPa}}%
			\let\pgfplots@loc@TMPb=\pgfmathresult
			\pgfplotscoordmath{float}{parsenumber}{0.5}%
			\pgfplotscoordmath{float}{op}{multiply}{{\pgfmathresult}{\pgfplots@loc@TMPb}}%
			%
			\expandafter\let\csname pgfplotsplothandlerboxplot@\pgfplots@boxplot@@next@target\endcsname
				=\pgfmathresult
			%
			% ... and search for the next search target.
			\expandafter\let\expandafter\pgfplots@boxplot@@next@target\csname pgfplots@boxplot@next@@\pgfplots@boxplot@@next@target\endcsname
			%
		\fi
	\fi
	%
	\ifx\pgfplots@boxplot@@next@target\pgfutil@empty
		% stop searching.
		\let\pgfplotsplothandlersurveyend@boxplot@computestats@=\relax
	\fi
}

\def\pgfplotsplothandlersurveyend@boxplot@computestats@valuebased{%
	\ifx\pgfplotsplothandlerboxplot@lowerwhisker\pgfutil@empty
		\pgfplotscoordmath{float}{if less than}{\pgfplots@current@point@data}{\pgfplotsplothandlerboxplot@lowerwhisker@value}{%
			% Ah. an outlier.
			\pgfplotsplothandlerboxplot@outlier
		}{%
			\let\pgfplotsplothandlerboxplot@lowerwhisker=\pgfplots@current@point@data
		}%
	\fi
	%
	% it would be so cool if we could simply check the list in reverse
	% order. but not if it really is a singly-linked list...
	\pgfplotscoordmath{float}{if less than}{\pgfplotsplothandlerboxplot@upperwhisker@value}{\pgfplots@current@point@data}{%
		% Ah. an outlier.
		\pgfplotsplothandlerboxplot@outlier
	}{%
		\ifx\pgfplotsplothandlerboxplot@upperwhisker\pgfutil@empty
			\let\pgfplotsplothandlerboxplot@upperwhisker=\pgfplots@current@point@data
		\else
			\pgfplotscoordmath{float}{max}{\pgfplotsplothandlerboxplot@upperwhisker}{\pgfplots@current@point@data}%
			\let\pgfplotsplothandlerboxplot@upperwhisker=\pgfmathresult
		\fi
	}%
}

\def\pgfplotsplothandlerboxplot@outlier{%
	\def\pgfplots@current@point@x{0}%
	\def\pgfplots@current@point@y{0}%
	\def\pgfplots@current@point@z{0}%
	\pgfplotsplothandlersurveypoint
}%

%%%

\def\pgfplotsplothandlersurveypoint@boxplot{%
	\pgfplotsplothandlerboxplot@parse
	\let\pgfplots@current@point@data=\pgfmathresult
	%
	\ifx\pgfplots@current@point@data\pgfutil@empty
	\else
		\pgfplotscoordmath{float}{if is bounded}{\pgfplots@current@point@data}{%
			%
			\pgfplotsplothandlersurveypoint@boxplot@
		}{%
		}%
	\fi
}%

\def\pgfplotsplothandlersurveypoint@boxplot@{%
	\pgfplotsutil@advancestringcounter\c@pgfplotsplothandlerboxplot@num
	%
	\if1\b@pgfplotsplothandlerboxplot@issorted
		\pgfplotscoordmath{float}{if less than}{\pgfplots@current@point@data}{\pgfplotsplothandlerboxplot@last}{%
			\def\b@pgfplotsplothandlerboxplot@issorted{0}%
		}{%
		}%
	\fi
	%
	%
	\pgfplotscoordmath{float}{op}{add}{{\pgfplots@current@point@data}{\pgfplotsplothandlerboxplot@sum}}%
	\let\pgfplotsplothandlerboxplot@sum=\pgfmathresult
	%
	% store parsed result.
	\edef\pgfmathresult{{\pgfplots@current@point@data}}%
	\expandafter\pgfplotsapplistXpushback\expandafter{\pgfmathresult}\to\pgfp@boxplot@@
	%
	\let\pgfplotsplothandlerboxplot@last=\pgfplots@current@point@data
	%
	\advance\c@pgfplots@coordindex by1
}
% =============================================================

\def\pgfplotsplothandlerboxplotprepared{%
	\ifpgfplots@stackedmode
		\pgfplotsthrow{unsupported operation}{Sorry, 'stacked plots' are currently unsupported for box plots. See the manual for 'boxplot/draw position' for how to achieve the effect (using \string\plotnumofactualtype)}\pgfeov
	\else
		\pgfplotsplothandlerboxplotprepared@
	\fi
}
\def\pgfplotsplothandlerboxplotprepared@{%
	\pgfplotsresetplothandler
	%
	\def\pgfplotsplothandlername{boxplot prepared}%
	%
	\let\pgf@plotstreamstart=\pgfplotsplothandlervisstart@boxplot@prepared
	\let\pgfplotsplothandlersurveystart=\pgfplotsplothandlersurveystart@boxplot@prepared
	\let\pgfplotsplothandlersurveypoint=\pgfplotsplothandlersurveypoint@boxplot@prepared
	\let\pgfplotsplothandlersurveyend=\pgfplotsplothandlersurveyend@boxplot@prepared
	%
	\pgfplotsplothandlerboxplotprepared@normalize@values
	%
	\pgfkeysgetvalue{/pgfplots/boxplot/draw direction}\pgfplots@loc@TMPa
	\if x\pgfplotsboxplotvalue{draw direction}%
	\else
		\if y\pgfplotsboxplotvalue{draw direction}%
		\else
			\pgfplotsthrow{invalid argument}{\pgfplots@loc@TMPa}{Invalid choice boxplot/draw direction=\pgfplots@loc@TMPa}\pgfeov%
			\def\pgfplots@loc@TMPa{x}%
		\fi
	\fi
	\csname pgfplotsplothandlerboxplotprepared@setxy@\pgfplots@loc@TMPa\endcsname
	%
	\def\pgfplotsboxplotpointab##1##2{%
		\begingroup
			\pgfkeys{/pgf/fpu}%
			\pgfmathparse{##1}%
			\let\pgfplotsplothandlerboxplot@@=\pgfmathresult
			\pgfmathparse{\pgfplotsboxplotvalue{draw position} + ##2}%
			\xdef\pgfplots@glob@TMPa{{\pgfplotsplothandlerboxplot@@}{\pgfmathresult}}%
			\expandafter\pgfplotsboxplotpointab@\pgfplots@glob@TMPa{\pgfplotspointaxisxy}%
			\pgf@process{}%
		\endgroup
	}%
	\def\pgfplotsboxplotpointab@survey##1##2{%
		\edef\pgfmathresult{##1}%
		\ifx\pgfmathresult\pgfutil@empty
		\else
			\pgfmathparse{\pgfmathresult}%
		\fi
		\let\pgfplotsplothandlerboxplot@@=\pgfmathresult
		\pgfmathparse{\pgfplotsboxplotvalue{draw position} + ##2}%
		\xdef\pgfplots@glob@TMPa{{\pgfplotsplothandlerboxplot@@}{\pgfmathresult}}%
		\let\pgfplotsplothandlerboxplot@modified@draw@position=\pgfmathresult%
		\expandafter\pgfplotsboxplotpointab@\pgfplots@glob@TMPa{\pgfplotsboxplotpointab@@define@current@xy}%
	}%
}%

\def\pgfplotsplothandlerboxplotprepared@normalize@values{%
	\def\pgfplots@loc@TMPa{auto}%
	\pgfplotsforeachentryinCSV{\value}{%
		lower whisker,%
		lower quartile,%
		median,%
		average,%
		upper quartile,%
		upper whisker,%
		sample size%
	}{%
		\pgfkeysgetvalue{/pgfplots/boxplot/\value}\pgfplots@loc@TMPb
		\edef\pgfplots@loc@TMPb{\pgfplots@loc@TMPb}%
		\ifx\pgfplots@loc@TMPb\pgfplots@loc@TMPa
			\pgfkeyslet{/pgfplots/boxplot/\value}\pgfutil@empty
		\fi
	}%
}%

\def\pgfplotsboxplotpointab@@define@current@xy#1#2{%
	\edef\pgfplots@current@point@x{#1}%
	\edef\pgfplots@current@point@y{#2}%
}%

\def\pgfplotsplothandlerboxplotprepared@setxy@x{%
	\def\pgfplotsboxplotpointab@##1##2##3{%
		##3{##1}{##2}%
	}%
}%
\def\pgfplotsplothandlerboxplotprepared@setxy@y{%
	\def\pgfplotsboxplotpointab@##1##2##3{%
		##3{##2}{##1}%
	}%
}%

\def\pgfplotsplothandlersurveypoint@boxplot@collect@limits{%
	\pgfplotsaxisparsecoordinate
	\pgfplotsaxispreparecoordinate
	\ifpgfplotsaxisparsecoordinateok
		\pgfplotsaxisupdatelimitsforcoordinate\pgfplots@current@point@x\pgfplots@current@point@y\pgfplots@current@point@z
	\fi
	%
	% do NOT store the processed coordinate! the coordinate stream
	% is ONLY for outliers.
	%
	% ... but update this stuff to avoid a "plot without coordinates"
	% case
	\pgfplotscoordstream@firstlast@update
}

\def\pgfplotsplothandlersurveystart@boxplot@prepared{%
	\pgfplots@prepare@source@parser@for{boxplot/}{data}{\pgfplotsplothandlerboxplot@parse}%
	%
	\let\pgfplotsboxplotpointab=\pgfplotsboxplotpointab@survey
	%
	\pgfplotsplothandlersurveystart@default
}

\def\pgfplotsplothandlersurveypoint@boxplot@prepared{%
	% seems the "parse" routine is stupid ... the /data point/ stuff
	% is redefined although it should not. Strange...
	\pgfkeyslet{/data point/x}\pgfplots@current@point@x
	\pgfkeyslet{/data point/y}\pgfplots@current@point@y
	\pgfkeyslet{/data point/z}\pgfplots@current@point@z
	\pgfplotsplothandlerboxplot@parse
	%
	\pgfplotsboxplotpointab{\pgfmathresult}{0}%
	%
	\pgfplotsplothandlersurveypoint@default
}

\def\pgfplotsplothandlersurveyend@boxplot@prepared{%
	\let\pgfplots@invoke@filter@xyz@old=\pgfplots@invoke@filter@xyz
	\let\pgfplots@invoke@filter@xyz=\relax
	\let\pgfplots@invoke@filter@old=\pgfplots@invoke@filter
	\def\pgfplots@invoke@filter##1##2{}%
	\let\pgfplots@invoke@prefilter@old=\pgfplots@invoke@prefilter
	\let\pgfplots@invoke@prefilter=\relax
	%
	\pgfmathparse{\pgfplotsboxplotvalue{draw position}}%
	\let\pgfplots@loc@TMPa=\pgfmathresult
	\ifpgfplots@usefpu
		\pgfmathfloattofixed\pgfmathresult
	\fi
	% remember it for later - it might have been retrieved from some
	% table column! If you used something like 
	% 'draw position=\thisrow{position}, the position of the LAST data point
	% will be used (because we are in end survey here).
	\edef\pgfplots@loc@TMPb{\noexpand\pgfplotsplothandlersurveyaddoptions{/pgfplots/boxplot/draw position=\pgfmathresult}}%
	\pgfplots@loc@TMPb
	%
	% ... this here will make things faster if the FPU is active.
	\pgfkeyslet{/pgfplots/boxplot/draw position}\pgfplots@loc@TMPa
	%
	%
	%
	%
	\pgfplotsboxplotpointabwhisker
		{\pgfplotsboxplotvalue{lower whisker}}
		{0}%
	\pgfplotsplothandlersurveypoint@boxplot@collect@limits
	%
	\pgfplotsboxplotpointabwhisker
		{\pgfplotsboxplotvalue{lower whisker}}
		{1}%
	\pgfplotsplothandlersurveypoint@boxplot@collect@limits
	%
	%
	\pgfplotsboxplotpointabbox
		{\pgfplotsboxplotvalue{lower quartile}}%
		{0}%
	\pgfplotsplothandlersurveypoint@boxplot@collect@limits
	%
	\pgfplotsboxplotpointabbox
		{\pgfplotsboxplotvalue{lower quartile}}%
		{1}%
	\pgfplotsplothandlersurveypoint@boxplot@collect@limits
	%
	%
	\pgfplotsboxplotpointabbox
		{\pgfplotsboxplotvalue{median}}
		{0}%
	\pgfplotsplothandlersurveypoint@boxplot@collect@limits
	%
	\pgfplotsboxplotpointabbox
		{\pgfplotsboxplotvalue{median}}
		{1}%
	\pgfplotsplothandlersurveypoint@boxplot@collect@limits
	%
	%
	\pgfplotsboxplotpointabbox
		{\pgfplotsboxplotvalue{average}}
		{0}%
	\pgfplotsplothandlersurveypoint@boxplot@collect@limits
	%
	\pgfplotsboxplotpointabbox
		{\pgfplotsboxplotvalue{average}}
		{1}%
	\pgfplotsplothandlersurveypoint@boxplot@collect@limits
	%
	%
	\pgfplotsboxplotpointabbox
		{\pgfplotsboxplotvalue{upper quartile}}%
		{0}%
	\pgfplotsplothandlersurveypoint@boxplot@collect@limits
	%
	\pgfplotsboxplotpointabbox
		{\pgfplotsboxplotvalue{upper quartile}}%
		{1}%
	\pgfplotsplothandlersurveypoint@boxplot@collect@limits
	%
	%
	%
	\pgfplotsboxplotpointabwhisker
		{\pgfplotsboxplotvalue{upper whisker}}%
		{1}%
	\pgfplotsplothandlersurveypoint@boxplot@collect@limits
	%
	\pgfplotsboxplotpointabwhisker
		{\pgfplotsboxplotvalue{upper whisker}}%
		{0}%
	\pgfplotsplothandlersurveypoint@boxplot@collect@limits
	%
	\let\pgfplots@invoke@prefilter=\pgfplots@invoke@prefilter@old
	\let\pgfplots@invoke@filter=\pgfplots@invoke@filter@old
	\let\pgfplots@invoke@filter@xyz=\pgfplots@invoke@filter@xyz@old
	%
	\pgfplotsplothandlerboxplotsurvey@variable@width%
	%
	\pgfplotsplothandlersurveyend@default
}%

\def\pgfplotsplothandlerboxplotsurvey@variable@width{%
	\ifnum\plotnumofactualtype=0 %
		% Ah - the first boxplot in this axis. Init the global
		% counter:
		\pgfplotscoordmath{default}{max limit}%
		\global\let\g@pgfplotsplothandlerboxplot@widthkey@min=\pgfmathresult
		\pgfplotscoordmath{default}{min limit}%
		\global\let\g@pgfplotsplothandlerboxplot@widthkey@max=\pgfmathresult
	\fi
	%
	%
	\ifpgfplotsplothandlerboxplot@variable@width
		\pgfkeysgetvalue{/pgfplots/boxplot/sample size}\pgfmathresult
		\edef\pgfmathresult{\pgfmathresult}%
		\ifx\pgfmathresult\pgfutil@empty
		\else
			\pgfplotsplothandlerboxplot@variable@width@expr{\pgfmathresult}%
			%
			\let\pgfplots@widthkey@=\pgfmathresult
			%
			\pgfkeysgetvalue{/pgfplots/boxplot/sample size min}\pgfmathresult
			\edef\pgfplotsplothandlerboxplot@widthkey@min{\pgfmathresult}%
			%
			\pgfkeysgetvalue{/pgfplots/boxplot/sample size max}\pgfmathresult
			\edef\pgfplotsplothandlerboxplot@widthkey@max{\pgfmathresult}%
			%
			%
			\ifx\pgfplotsplothandlerboxplot@widthkey@min\pgfutil@empty
				\let\pgfplotsplothandlerboxplot@widthkey@min=\g@pgfplotsplothandlerboxplot@widthkey@min
				\def\pgfplotsplothandlerboxplot@widthkey@min@autocompute{1}%
			\else
				\pgfplotsplothandlerboxplot@variable@width@expr{\pgfplotsplothandlerboxplot@widthkey@min}%
				\let\pgfplotsplothandlerboxplot@widthkey@min=\pgfmathresult
				\def\pgfplotsplothandlerboxplot@widthkey@min@autocompute{0}%
			\fi
			\ifx\pgfplotsplothandlerboxplot@widthkey@max\pgfutil@empty
				\let\pgfplotsplothandlerboxplot@widthkey@max=\g@pgfplotsplothandlerboxplot@widthkey@max
				\def\pgfplotsplothandlerboxplot@widthkey@max@autocompute{1}%
			\else
				\pgfplotsplothandlerboxplot@variable@width@expr{\pgfplotsplothandlerboxplot@widthkey@max}%
				\def\pgfplotsplothandlerboxplot@widthkey@max@autocompute{0}%
			\fi
			%
			\if1\pgfplotsplothandlerboxplot@widthkey@max@autocompute
				\pgfmathparse{max(\pgfplotsplothandlerboxplot@widthkey@max,\pgfplots@widthkey@)}%
				\global\let\g@pgfplotsplothandlerboxplot@widthkey@max=\pgfmathresult
				\let\pgfplotsplothandlerboxplot@widthkey@max=\pgfmathresult
				%
				\pgfmathparse{min(\pgfplotsplothandlerboxplot@widthkey@min,\pgfplots@widthkey@)}%
				\global\let\g@pgfplotsplothandlerboxplot@widthkey@min=\pgfmathresult
				\let\pgfplotsplothandlerboxplot@widthkey@min=\pgfmathresult
			\fi
			%
			%
		\fi
	\fi
	%
%\message{sample size=\pgfplots@widthkey@. interval = \pgfplotsplothandlerboxplot@widthkey@min:\pgfplotsplothandlerboxplot@widthkey@max^^J}%
}%

\def\pgfplotsplothandlerboxplot@variable@width@expr#1{%
	\begingroup
	\pgfkeys{/pgf/fpu}%
	\let\pgfmathresult=#1%
	\pgfplotsboxplotvalue{variable width expr/.@cmd}#1\pgfeov
	\pgfmath@smuggleone\pgfmathresult
	\endgroup
	\let#1=\pgfmathresult
}%

\def\pgfplotsplothandlerboxplotvisualization@variable@width{%
	\ifpgfplotsplothandlerboxplot@variable@width
		\pgfkeysgetvalue{/pgfplots/boxplot/sample size}\pgfmathresult
		\edef\pgfmathresult{\pgfmathresult}%
		\ifx\pgfmathresult\pgfutil@empty
		\else
			\pgfplotsplothandlerboxplot@variable@width@expr{\pgfmathresult}%
			\let\pgfplots@widthkey@=\pgfmathresult
			%
			\pgfkeysgetvalue{/pgfplots/boxplot/sample size min}\pgfmathresult
			\edef\pgfplotsplothandlerboxplot@widthkey@min{\pgfmathresult}%
			%
			\pgfkeysgetvalue{/pgfplots/boxplot/sample size max}\pgfmathresult
			\edef\pgfplotsplothandlerboxplot@widthkey@max{\pgfmathresult}%
			%
			%
			\ifx\pgfplotsplothandlerboxplot@widthkey@min\pgfutil@empty
				\let\pgfplotsplothandlerboxplot@widthkey@min=\g@pgfplotsplothandlerboxplot@widthkey@min
			\else
				\pgfplotsplothandlerboxplot@variable@width@expr{\pgfplotsplothandlerboxplot@widthkey@min}%
			\fi
			\ifx\pgfplotsplothandlerboxplot@widthkey@max\pgfutil@empty
				\let\pgfplotsplothandlerboxplot@widthkey@max=\g@pgfplotsplothandlerboxplot@widthkey@max
			\else
				\pgfplotsplothandlerboxplot@variable@width@expr{\pgfplotsplothandlerboxplot@widthkey@max}%
			\fi
			%
			\pgfkeysgetvalue{/pgfplots/boxplot/variable width min target}\pgfplots@widthkey@mintrg
			\pgfkeysgetvalue{/pgfplots/boxplot/box extend}\pgfplots@loc@TMPa
	%\message{sample size=\pgfplots@widthkey@. interval = \pgfplotsplothandlerboxplot@widthkey@min:\pgfplotsplothandlerboxplot@widthkey@max. Target = [\pgfplots@widthkey@mintrg:1]^^J}%
			\begingroup
			\pgfkeys{/pgf/fpu}%
			\pgfmathparse{
				(\pgfplots@widthkey@mintrg + 
				max(0,min(1,(\pgfplots@widthkey@ - \pgfplotsplothandlerboxplot@widthkey@min) / 
				(\pgfplotsplothandlerboxplot@widthkey@max - \pgfplotsplothandlerboxplot@widthkey@min))) 
				  * (1-\pgfplots@widthkey@mintrg)) * \pgfplots@loc@TMPa}%
			\pgfmathfloattofixed\pgfmathresult
			\pgfmath@smuggleone\pgfmathresult
			\endgroup
			\pgfkeyslet{/pgfplots/boxplot/box extend}\pgfmathresult
		\fi
	\fi
}%

\def\pgfplotsplothandlervisstart@boxplot@prepared{%
	%
	\pgfplotsplothandlerboxplotvisualization@variable@width
	%
	\global\let\pgf@plotstreampoint=\pgfutil@gobble
	\global\let\pgf@plotstreamspecial=\pgfutil@gobble%
	\global\let\pgf@plotstreamend=\relax
	%
	\pgfplotsplothandlervisstart@boxplot@prepared@draw
}%

\def\pgfplotsplothandlervisstart@boxplot@prepared@draw{%
	\def\b@pgfplots@boxplot@hasbox{1}%
	\edef\pgfplots@loc@TMPa{\pgfplotsboxplotvalue{lower quartile}}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\def\b@pgfplots@boxplot@hasbox{0}%
	\fi
	\edef\pgfplots@loc@TMPa{\pgfplotsboxplotvalue{upper quartile}}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
		\def\b@pgfplots@boxplot@hasbox{0}%
	\fi
	%
	\if0\b@pgfplots@boxplot@hasbox
		% hm. we have no box. Very strange boxplot, I'd say.
		%
		% But anyway: if someone has whiskers without box,
		% short-circuit the whiskers:
		\edef\pgfplots@loc@TMPa{\pgfplotsboxplotvalue{lower whisker}}%
		\edef\pgfplots@loc@TMPb{\pgfplotsboxplotvalue{upper whisker}}%
		\pgfkeyslet{/pgfplots/boxplot/lower quartile}\pgfplots@loc@TMPb
		\pgfkeyslet{/pgfplots/boxplot/upper quartile}\pgfplots@loc@TMPa
	\fi
	%
	%
	\edef\pgfplots@loc@TMPa{\pgfplotsboxplotvalue{lower whisker}}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
	\else
		\pgfplotsboxplotvalue{draw/lower whisker/.@cmd}\pgfeov
	\fi
	%
	\edef\pgfplots@loc@TMPa{\pgfplotsboxplotvalue{upper whisker}}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
	\else
		\pgfplotsboxplotvalue{draw/upper whisker/.@cmd}\pgfeov
	\fi
	%
	\if1\b@pgfplots@boxplot@hasbox
		\pgfplotsboxplotvalue{draw/box/.@cmd}\pgfeov
	\fi
	%
	\edef\pgfplots@loc@TMPa{\pgfplotsboxplotvalue{median}}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
	\else
		\pgfplotsboxplotvalue{draw/median/.@cmd}\pgfeov
	\fi
	%
	\edef\pgfplots@loc@TMPa{\pgfplotsboxplotvalue{average}}%
	\ifx\pgfplots@loc@TMPa\pgfutil@empty
	\else
		\pgfplotsboxplotvalue{draw/average/.@cmd}\pgfeov
	\fi
}%

\def\pgfplots@boxplot@cs@decompose#1{%
	\edef\pgfplots@loc@TMPa{#1}%
	\expandafter\pgfutil@in@\expandafter,\expandafter{\pgfplots@loc@TMPa}%
	\ifpgfutil@in@
		\def\pgfplots@loc@TMPb##1,##2\pgfplots@EOI{%
			\def\pgfplots@boxplotcs@a{##1}%
			\def\pgfplots@boxplotcs@b{##2}%
		}%
		\expandafter\pgfplots@loc@TMPb\pgfplots@loc@TMPa\pgfplots@EOI
	\else
		\let\pgfplots@boxplotcs@a=\pgfplots@loc@TMPa%
		\def\pgfplots@boxplotcs@b{0}%
	\fi
}%

\def\pgfplotsboxplotvalue#1{\pgfkeysvalueof{/pgfplots/boxplot/#1}}%

\tikzaddtikzonlycommandshortcutlet\boxplotvalue\pgfplotsboxplotvalue

% A helper which implements 'draw relative anchor'. It expands to a
% math expression which is suitable as second argument for 'boxplot cs';
% i.e. it needs to be added to 'boxplot/draw position'.
% 
% More precisely, this macro is to be used in a context where lines of
% 'box extend' length have to be drawn.
%
% The argument is shifted by 'draw relative anchor' and is scaled by
% 'box extend'.
%
% #1: the coordinate. 0 is the means "lower part of the construct
% which is to be drawn". 1 means the "upper part of that construct"
% and 0.5 is in the middle. 
\def\pgfplots@boxplot@anchor@value#1{%
	(#1-\pgfplotsboxplotvalue{draw relative anchor})*\pgfplotsboxplotvalue{box extend}%
}

% same as \pgfplots@boxplot@anchor@value, but for drawing constructs
% which are at most 'whisker extend' long.
\def\pgfplots@boxplot@anchor@value@whisker#1{%
	(#1-\pgfplotsboxplotvalue{draw relative anchor})*\pgfplotsboxplotvalue{whisker extend}%
}

\def\pgfplotsboxplotpointabbox#1#2{%
	\pgfplotsboxplotpointab{#1}{\pgfplots@boxplot@anchor@value{#2}}%	
}%
\def\pgfplotsboxplotpointabwhisker#1#2{%
	\pgfplotsboxplotpointab{#1}{\pgfplots@boxplot@anchor@value@whisker{#2}}%	
}%

\tikzdeclarecoordinatesystem{boxplot}{%
	\pgfplots@boxplot@cs@decompose{#1}%
	\pgfplotsboxplotpointab{\pgfplots@boxplotcs@a}{\pgfplots@boxplotcs@b}%
}%

\tikzdeclarecoordinatesystem{boxplot box}{%
	\pgfplots@boxplot@cs@decompose{#1}%
	\pgfplotsboxplotpointabbox{\pgfplots@boxplotcs@a}{\pgfplots@boxplotcs@b}%
}%

\tikzdeclarecoordinatesystem{boxplot whisker}{%
	\pgfplots@boxplot@cs@decompose{#1}%
	\pgfplotsboxplotpointabwhisker{\pgfplots@boxplotcs@a}{\pgfplots@boxplotcs@b}%
}%
\endinput

tikzlibraryplotmarks.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/frontendlayer/tikz/libraries/tikzlibraryplotmarks.code.tex,v 1.1 2008/01/09 17:57:16 tantau Exp $

\usepgflibrary{plotmarks}

\endinput

tikzlibrarytopaths.code.tex
% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Public License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\ProvidesFileRCS[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/frontendlayer/tikz/libraries/tikzlibrarytopaths.code.tex,v 1.2 2008/06/17 21:23:44 tantau Exp $


% Move to

\tikzstyle{move to}=                 [to path={(\tikztotarget) \tikztonodes}]


% Straight to

\tikzstyle{line to}=                 [to path={-- (\tikztotarget) \tikztonodes}]


% Curved to

\tikzstyle{every curve to}=          []
\tikzstyle{curve to}=                [to path=\tikz@to@curve@path]

\tikzoption{bend angle}{\def\tikz@to@bend{#1}}

\tikzoption{bend left}[]{%
  \def\pgf@temp{#1}%
  \ifx\pgf@temp\pgfutil@empty%
  \else%
    \def\tikz@to@bend{#1}%
  \fi%
  \let\tikz@to@out=\tikz@to@bend%
  \c@pgf@counta=180\relax%
  \advance\c@pgf@counta by-\tikz@to@out\relax%
  \edef\tikz@to@in{\the\c@pgf@counta}%
  \tikz@to@switch@on%
  \tikz@to@relativetrue%
}

\tikzoption{bend right}[]{%
  \def\pgf@temp{#1}%
  \ifx\pgf@temp\pgfutil@empty%
  \else%
    \def\tikz@to@bend{#1}%
  \fi%
  % Now, negate
  \c@pgf@counta=\tikz@to@bend\relax%
  \c@pgf@counta=-\c@pgf@counta\relax%
  \edef\tikz@to@out{\the\c@pgf@counta}%
  \c@pgf@counta=180\relax%
  \advance\c@pgf@counta by-\tikz@to@out\relax%
  \edef\tikz@to@in{\the\c@pgf@counta}%
  \tikz@to@switch@on%
  \tikz@to@relativetrue%
}

\tikzoption{relative}[true]{\csname tikz@to@relative#1\endcsname}
\newif\iftikz@to@relative
\tikz@to@relativefalse

\tikzoption{in}{\def\tikz@to@in{#1}\tikz@to@switch@on}
\tikzoption{out}{\def\tikz@to@out{#1}\tikz@to@switch@on}

\tikzoption{in looseness}{\tikz@to@set@in@looseness{#1}}
\tikzoption{out looseness}{\tikz@to@set@out@looseness{#1}}
\tikzoption{looseness}{\tikz@to@set@in@looseness{#1}\tikz@to@set@out@looseness{#1}}

\tikzoption{in control}{\tikz@to@set@in@control{#1}}
\tikzoption{out control}{\tikz@to@set@out@control{#1}}
\tikzoption{controls}{\tikz@to@parse@controls#1\pgf@stop}

\tikzoption{in min distance}{\tikz@to@set@distances{#1}{}{}{}}
\tikzoption{in max distance}{\tikz@to@set@distances{}{#1}{}{}}
\tikzoption{in distance}{\tikz@to@set@distances{#1}{#1}{}{}}
\tikzoption{out min distance}{\tikz@to@set@distances{}{}{#1}{}}
\tikzoption{out max distance}{\tikz@to@set@distances{}{}{}{#1}}
\tikzoption{out distance}{\tikz@to@set@distances{}{}{#1}{#1}}
\tikzoption{min distance}{\tikz@to@set@distances{#1}{}{#1}{}}
\tikzoption{max distance}{\tikz@to@set@distances{}{#1}{}{#1}}
\tikzoption{distance}{\tikz@to@set@distances{#1}{#1}{#1}{#1}}

\def\tikz@to@set@distances#1#2#3#4{%
  \tikz@to@setifnotempy{#1}{\tikz@to@in@min}{\let\tikz@to@end@compute=\tikz@to@end@compute@looseness}%
  \tikz@to@setifnotempy{#2}{\tikz@to@in@max}{\let\tikz@to@end@compute=\tikz@to@end@compute@looseness}%
  \tikz@to@setifnotempy{#3}{\tikz@to@out@min}{\let\tikz@to@start@compute=\tikz@to@start@compute@looseness}%
  \tikz@to@setifnotempy{#4}{\tikz@to@out@max}{\let\tikz@to@start@compute=\tikz@to@start@compute@looseness}%
  \tikz@to@switch@on%
}

\def\tikz@to@setifnotempy#1#2#3{%
  \def\pgf@temp{#1}%
  \ifx\pgf@temp\pgfutil@empty\else\def#2{#1}#3\fi%
}


\def\tikz@to@set@in@looseness#1{%
  \def\tikz@to@in@looseness{#1}%
  \let\tikz@to@end@compute=\tikz@to@end@compute@looseness%
  \tikz@to@switch@on%
}
\def\tikz@to@set@out@looseness#1{%
  \def\tikz@to@out@looseness{#1}%
  \let\tikz@to@start@compute=\tikz@to@start@compute@looseness%
  \tikz@to@switch@on%
}

\def\tikz@to@parse@controls#1and#2\pgf@stop{\tikz@to@set@in@control{#2}\tikz@to@set@out@control{#1}}

\def\tikz@to@set@in@control#1{%
  \def\tikz@to@in@control{#1}%
  \let\tikz@to@end@compute=\tikz@to@end@compute@control%
  \tikz@to@switch@on%
}
\def\tikz@to@set@out@control#1{%
  \def\tikz@to@out@control{#1}%
  \let\tikz@to@start@compute=\tikz@to@start@compute@control%
  \tikz@to@switch@on%
}


\def\tikz@to@bend{30}

\def\tikz@to@out{45}
\def\tikz@to@in{135}

\def\tikz@to@out@looseness{1}
\def\tikz@to@in@looseness{1}

\def\tikz@to@in@min{0pt}
\def\tikz@to@in@max{10000pt}
\def\tikz@to@out@min{0pt}
\def\tikz@to@out@max{10000pt}

\def\tikz@to@switch@on{\let\tikz@to@path=\tikz@to@curve@path}

\def\tikz@to@curve@path{%
  [every curve to]
  \pgfextra{\iftikz@to@relative\tikz@to@compute@relative\else\tikz@to@compute\fi}
  \tikz@computed@path
  \tikztonodes%
}

\def\tikz@to@modify#1#2{%
  \pgfutil@ifundefined{pgf@sh@ns@#1}
  {}%
  {\edef#1{#1.#2}}
}%

\def\tikz@to@compute{%
  \let\tikz@tofrom=\tikztostart%
  \let\tikz@toto=\tikztotarget%
  \tikz@to@modify\tikz@tofrom\tikz@to@out%
  \tikz@to@modify\tikz@toto\tikz@to@in%
  \ifx\tikz@to@start@compute\tikz@to@start@compute@looseness%
    \tikz@to@compute@distance%
  \else%
    \ifx\tikz@from@start@compute\tikz@to@start@compute@looseness%  
      \tikz@to@compute@distance%
    \fi%
  \fi%
  \tikz@to@start@compute%
  \tikz@to@end@compute%
  \edef\tikz@computed@path{.. controls \tikz@computed@start and \tikz@computed@end .. (\tikz@toto)}
}

\def\tikz@to@compute@distance{\tikz@scan@one@point\tikz@@to@compute@distance(\tikz@tofrom)}
\def\tikz@@to@compute@distance#1{%
  \def\tikz@first@point{#1}%
  \tikz@scan@one@point\tikz@@@to@compute@distance(\tikz@toto)}
\def\tikz@@@to@compute@distance#1{%
  \def\tikz@second@point{#1}%
  \tikz@to@compute@distance@main%
}
\def\tikz@to@compute@distance@main{%
  \pgf@process{\pgfpointdiff{\tikz@first@point}{\tikz@second@point}}%
  \ifdim\pgf@x<0pt\pgf@xa=-\pgf@x\else\pgf@xa=\pgf@x\fi%
  \ifdim\pgf@y<0pt\pgf@ya=-\pgf@y\else\pgf@ya=\pgf@y\fi%
  % 
  % Calculate length of second to first vector:
  % 
  \pgf@process{\pgfpointnormalised{\pgfqpoint{\pgf@xa}{\pgf@ya}}}%
  \ifdim\pgf@x>\pgf@y%
    \c@pgf@counta=\pgf@x%
    \ifnum\c@pgf@counta=0\relax%
    \else%
      \divide\c@pgf@counta by 255\relax%
      \pgf@xa=16\pgf@xa\relax%
      \divide\pgf@xa by\c@pgf@counta%
      \pgf@xa=16\pgf@xa\relax%
    \fi%
  \else%
    \c@pgf@counta=\pgf@y%
    \ifnum\c@pgf@counta=0\relax%
    \else%
      \divide\c@pgf@counta by 255\relax%
      \pgf@ya=16\pgf@ya\relax%
      \divide\pgf@ya by\c@pgf@counta%
      \pgf@xa=16\pgf@ya\relax%
    \fi%
  \fi%
  \pgf@x=0.3915\pgf@xa%
  \pgf@xa=\tikz@to@out@looseness\pgf@x%
  \pgf@xb=\tikz@to@in@looseness\pgf@x%
  % Adjust as necessary
  \pgfmathsetlength{\pgf@ya}{\tikz@to@out@min}
  \ifdim\pgf@xa<\pgf@ya%
    \pgf@xa=\pgf@ya%
  \fi%
  \pgfmathsetlength{\pgf@ya}{\tikz@to@out@max}
  \ifdim\pgf@xa>\pgf@ya%
    \pgf@xa=\pgf@ya%
  \fi%
  \pgfmathsetlength{\pgf@ya}{\tikz@to@in@min}
  \ifdim\pgf@xb<\pgf@ya%
    \pgf@xb=\pgf@ya%
  \fi%
  \pgfmathsetlength{\pgf@ya}{\tikz@to@in@max}
  \ifdim\pgf@xb>\pgf@ya%
    \pgf@xb=\pgf@ya%
  \fi%
}

\def\tikz@to@start@compute@looseness{%
  \edef\tikz@computed@start{([shift=(\tikz@to@out:\the\pgf@xa)]\tikz@tofrom)}%
}
\def\tikz@to@end@compute@looseness{%
  \edef\tikz@computed@end{([shift=(\tikz@to@in:\the\pgf@xb)]\tikz@toto)}%
}
\def\tikz@to@start@compute@control{%
  \let\tikz@computed@start=\tikz@to@out@control%
}
\def\tikz@to@end@compute@control{%
  \let\tikz@computed@end=\tikz@to@in@control%
}

\let\tikz@to@start@compute=\tikz@to@start@compute@looseness%
\let\tikz@to@end@compute=\tikz@to@end@compute@looseness%




% Relative curves

\def\tikz@to@compute@relative{%
  \tikz@scan@one@point\tikz@@to@compute@relative(\tikztostart)%
}
\def\tikz@@to@compute@relative#1{%
  \def\tikz@tofrom{#1}%
  \tikz@scan@one@point\tikz@@@to@compute@relative(\tikztotarget)%
}
\def\tikz@@@to@compute@relative#1{%
  \def\tikz@toto{#1}%
  \begingroup
    % 
    % Adjust start and target so that they lie on the border in the
    % rotated coordinate system.
    %  
    \pgfutil@ifundefined{pgf@sh@ns@\tikztostart}
    {%
      \let\tikz@first@point=\tikz@tofrom%
      \let\tikz@tostart@tikz=\pgfutil@empty
    }%
    {%
      % Start computation of new start.
      {%
        \tikz@tofrom%
        \pgf@xc=\pgf@x%
        \pgf@yc=\pgf@y%
        {%
          \pgftransformreset%
          \pgftransformshift{\pgfqpoint{\pgf@xc}{\pgf@yc}}%
          \pgftransformrotate{\tikz@to@out}%
          \pgftransformshift{\pgfqpoint{-\pgf@xc}{-\pgf@yc}}%
          \pgf@process{\pgfpointtransformed{\tikz@toto}}%
        }%
        \pgf@xc=\pgf@x%
        \pgf@yc=\pgf@y%
        \pgfpointshapeborder{\tikztostart}{\pgfqpoint{\pgf@xc}{\pgf@yc}}%
        \xdef\tikz@tofrom@smuggle{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}
      }%
      \let\tikz@first@point=\tikz@tofrom@smuggle%
      \tikz@first@point%
      \edef\tikz@tostart@tikz{(\the\pgf@x,\the\pgf@y)}%
    }%
    \pgfutil@ifundefined{pgf@sh@ns@\tikztotarget}
    {%
      \let\tikz@second@point=\tikz@toto%
    }%
    {%
      % Start computation of new target.
      {%
        \tikz@toto%
        \pgf@xc=\pgf@x%
        \pgf@yc=\pgf@y%
        {%
          \pgftransformreset%
          \pgftransformshift{\pgfqpoint{\pgf@xc}{\pgf@yc}}%
          \pgftransformrotate{180}%
          \pgftransformrotate{\tikz@to@in}%
          \pgftransformshift{\pgfqpoint{-\pgf@xc}{-\pgf@yc}}%
          \pgf@process{\pgfpointtransformed{\tikz@tofrom}}%
        }%
        \pgf@xc=\pgf@x%
        \pgf@yc=\pgf@y%
        \pgfpointshapeborder{\tikztotarget}{\pgfqpoint{\pgf@xc}{\pgf@yc}}%
        \xdef\tikz@toto@smuggle{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}
      }%
      \let\tikz@second@point=\tikz@toto@smuggle%
    }%
    \tikz@second@point%
    \edef\tikz@totarget@tikz{(\the\pgf@x,\the\pgf@y)}%
    %
    % Compute distances
    %
    \tikz@to@compute@distance@main%
    \edef\tikz@to@first@distance{\the\pgf@xa}%
    \edef\tikz@to@second@distance{\the\pgf@xb}%
    %
    % Next step: Establish a transformed coordinate system so that the (modified)
    % start is at the origin and the (modified) target is at (1,0)
    %
    \pgftransformreset%
    \pgf@process{\tikz@first@point}%
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgf@process{\tikz@second@point}%
    \advance\pgf@x by-\pgf@xa%
    \advance\pgf@y by-\pgf@ya%
    \pgfpointnormalised{}%
    \pgf@xc=\pgf@x%
    \pgf@yc=\pgf@y%
    \pgf@xb=-\pgf@x%
    \pgf@yb=-\pgf@y%
    %
    % Now compute the control points.
    %
    {%
      \pgftransformshift{\tikz@first@point}%
      \pgftransformcm{\pgf@sys@tonumber\pgf@xc}{\pgf@sys@tonumber\pgf@yc}{\pgf@sys@tonumber\pgf@yb}{\pgf@sys@tonumber\pgf@xc}%
                      {\pgfpointorigin}%
      \pgf@process{\pgfpointtransformed{\pgfpointpolar{\tikz@to@out}{\tikz@to@first@distance}}}%
      \xdef\tikz@computed@start{(\the\pgf@x,\the\pgf@y)}%
    }
    {%
      \pgftransformshift{\tikz@second@point}%
      \pgftransformcm{\pgf@sys@tonumber\pgf@xc}{\pgf@sys@tonumber\pgf@yc}{\pgf@sys@tonumber\pgf@yb}{\pgf@sys@tonumber\pgf@xc}%
                      {\pgfpointorigin}%
      \pgf@process{\pgfpointtransformed{\pgfpointpolar{\tikz@to@in}{\tikz@to@second@distance}}}%
      \xdef\tikz@computed@end{(\the\pgf@x,\the\pgf@y)}%
    }
    \xdef\tikz@computed@path{
      \tikz@tostart@tikz
      .. controls \tikz@computed@start and \tikz@computed@end ..
      \tikz@totarget@tikz}%
  \endgroup
}



% Loops

\tikzstyle{loop}=                    [to path={
  \pgfextra{\let\tikztotarget=\tikztostart}
  [looseness=8,min distance=5mm,every loop]
  \tikz@to@curve@path
  }]

\tikzstyle{every loop}=              [->,shorten >=1pt]

\tikzstyle{loop right}=              [right,out=15,in=-15,loop]
\tikzstyle{loop above}=              [above,out=105,in=75,loop]
\tikzstyle{loop left}=               [left,out=195,in=165,loop]
\tikzstyle{loop below}=              [below,out=285,in=255,loop]





\endinput

Paper.bbl
\begin{thebibliography}{}

\bibitem[Arroyo and Conejo, 2000]{arroyo_optimal_2000}
Arroyo, J. and Conejo, A. (2000).
\newblock Optimal response of a thermal unit to an electricity spot market.
\newblock {\em {IEEE} Transactions on Power Systems}, 15(3):1098--1104.

\bibitem[Bertsimas and Weismantel, 2005]{bertsimas_optimization_2005}
Bertsimas, D. and Weismantel, R. (2005).
\newblock {\em Optimization over integers}, volume~13.
\newblock Dynamic Ideas Belmont.

\bibitem[Carri{\'o}n and Arroyo, 2006]{carrion_computationally_2006}
Carri{\'o}n, M. and Arroyo, J. (2006).
\newblock A computationally efficient mixed-integer linear formulation for the
  thermal unit commitment problem.
\newblock {\em {IEEE} Transactions on Power Systems}, 21(3):1371--1378.

\bibitem[Dantzig and Wolfe, 1960]{dantzig_decomposition_1960}
Dantzig, G.~B. and Wolfe, P. (1960).
\newblock Decomposition principle for linear programs.
\newblock {\em Operations Research}, 8(1):101--111.

\bibitem[Egerer et~al., 2014]{egerer_electricity_2014}
Egerer, J., Gerbaulet, C., Ihlenburg, R., Kunz, F., Reinhard, B., Hirschhausen,
  C.~v., Weber, A., and Weibezahn, J. (2014).
\newblock Electricity sector data for policy-relevant modeling: Data
  documentation and applications to the german and european electricity
  markets.
\newblock Data Documentation~72, Deutsches Institut f{\"u}r
  Wirtschaftsforschung ({DIW}), Berlin.

\bibitem[{ENTSO}-E, 2007]{entsoe_hourly_2007}
{ENTSO}-E (2007).
\newblock Hourly consumption profiles.
\newblock Technical report, {ENTSO}-E, European Network of Transmission System
  Operators for Electricity.

\bibitem[{EURELECTRIC}, 2003]{eurelectric_efficiency_2003}
{EURELECTRIC} (2003).
\newblock Efficiency in electricity generation.
\newblock Technical report, {EURELECTRIC}, Brussels, Belgium.

\bibitem[Gabow et~al., 1984]{gabow_scaling_1984}
Gabow, H.~N., Bentley, J.~L., and Tarjan, R.~E. (1984).
\newblock Scaling and related techniques for geometry problems.
\newblock In {\em Proceedings of the Sixteenth Annual {ACM} Symposium on Theory
  of Computing}, {STOC} '84, pages 135--143, New York, {NY}, {USA}. {ACM}.

\bibitem[Garver, 1962]{garver_power_1962}
Garver, L. (1962).
\newblock Power generation scheduling by integer programming-development of
  theory.
\newblock {\em Power Apparatus and Systems, Part {III}. Transactions of the
  American Institute of Electrical Engineers}, 81(3):730--734.

\bibitem[{German Federal Network Agency},
  2014]{german_federal_network_agency_list_2014}
{German Federal Network Agency} (2014).
\newblock List of power plants.

\bibitem[Kumar et~al., 2012]{kumar_power_2012}
Kumar, N., Besuner, P.~M., Lefton, S.~A., Agan, D.~D., and Hileman, D.~A.
  (2012).
\newblock Power plant cycling costs.
\newblock Technical report, Intertek {APTECH}, Sunnyvale, California.

\bibitem[Morales-Espa{\~n}a et~al., 2013]{morales-espana_tight_2013}
Morales-Espa{\~n}a, G., Latorre, J., and Ramos, A. (2013).
\newblock Tight and compact {MILP} formulation for the thermal unit commitment
  problem.
\newblock {\em {IEEE} Transactions on Power Systems}, 28(4):4897--4908.

\bibitem[Nowak and R{\"o}misch, 2000]{nowak_stochastic_2000}
Nowak, M.~P. and R{\"o}misch, W. (2000).
\newblock Stochastic lagrangian relaxation applied to power scheduling in a
  hydro-thermal system under uncertainty.
\newblock {\em Annals of Operations Research}, 100(1-4):251--272.

\bibitem[Rienecker et~al., 2011]{rienecker_merra:_2011}
Rienecker, M.~M., Suarez, M.~J., Gelaro, R., Todling, R., Bacmeister, J., Liu,
  E., Bosilovich, M.~G., Schubert, S.~D., Takacs, L., Kim, G.-K., Bloom, S.,
  Chen, J., Collins, D., Conaty, A., da~Silva, A., Gu, W., Joiner, J., Koster,
  R.~D., Lucchesi, R., Molod, A., Owens, T., Pawson, S., Pegion, P., Redder,
  C.~R., Reichle, R., Robertson, F.~R., Ruddick, A.~G., Sienkiewicz, M., and
  Woollen, J. (2011).
\newblock {MERRA}: {NASA}{\textquoteright}s modern-era retrospective analysis
  for research and applications.
\newblock {\em Journal of Climate}, 24(14):3624--3648.

\bibitem[Rosen, 1999]{rosen_handbook_1999}
Rosen, K.~H., editor (1999).
\newblock {\em Handbook of discrete and combinatorial mathematics}.
\newblock Discrete Mathematics and Its Applications. {CRC} press.

\bibitem[Silbernagl, tion]{silbernagl_thesis}
Silbernagl, M. (in preparation).
\newblock {\em The Unit Commitment Problem: Start-up Costs and Market
  Interaction}.
\newblock PhD thesis, Technische Universität München.

\bibitem[Silbernagl et~al., 2014]{silbernagl_improving_2014}
Silbernagl, M., Huber, M., and Brandenberg, R. (2014).
\newblock Improving accuracy and efficiency of start-up cost formulations in
  {MIP} unit commitment by modeling power plant temperatures.
\newblock {\em {arXiv}:1408.2644 [math]}.

\bibitem[Simoglou et~al., 2010]{simoglou_optimal_2010}
Simoglou, C., Biskas, P., and Bakirtzis, A. (2010).
\newblock Optimal self-scheduling of a thermal producer in short-term
  electricity markets by {MILP}.
\newblock {\em {IEEE} Transactions on Power Systems}, 25(4):1965 --1977.

\bibitem[Vuillemin, 1980]{vuillemin_unifying_1980}
Vuillemin, J. (1980).
\newblock A unifying look at data structures.
\newblock {\em Communications of the {ACM}}, 23(4):229--239.

\bibitem[Wood and Wollenberg, 1996]{wood_power_1996}
Wood, A. and Wollenberg, B. (1996).
\newblock {\em Power generation, operation and control}.
\newblock Wiley, 2nd ed. edition.

\end{thebibliography}
