Regular formal moduli spaces and \\ arithmetic transfer conjectures
M. Rapoport
B. Smithling
W. Zhang
We define various formal moduli spaces of $p$-divisible groups which are regular, and morphisms between them. We formulate arithmetic transfer conjectures, which are variants of the arithmetic fundamental lemma conjecture of \cite{Z12 in the presence of ramification. These conjectures include the AT conjecture of \cite{RSZ. We prove these conjectures in low-dimensional cases.
atc_regular-local_arxiv_v2.tex
\documentclass[a4paper, reqno]{amsart}

\usepackage{amsthm,amsfonts,amssymb,amsmath,amsxtra}
\usepackage[all]{xy}
% force xy arrow tips in computer modern font:
\SelectTips{cm}{}
\usepackage{tikz}
\usepackage{verbatim}
% \usepackage{pdfsync}
% \usepackage{showkeys}

\usepackage[margin=1.25in]{geometry}
\usepackage{mathrsfs}

% for smart spacing after certain commands:
\RequirePackage{xspace}
% for programming features:
\RequirePackage{etoolbox}
% for text environments which are automatically the natural width of the text they contain:
\RequirePackage{varwidth}
% for easy margin adjustment in enumerate and itemize environments:
\RequirePackage{enumitem}
% for good placement of super/subscripts to the left of symbols:
\RequirePackage{tensor}
% for various extensions of amsmath:
\RequirePackage{mathtools}
% allow tables to (if needed) split over multiple pages:
\RequirePackage{longtable}
% allow cells spanning multiple rows in tables:
\RequirePackage{multirow}
% allow nice line breaks inside cells (with \makecell{}):
\RequirePackage{makecell}
% for big integral signs:
\RequirePackage{bigints}
% for upward diagonal dots:
\RequirePackage{mathdots}

\usepackage{hyperref} %[backref=page]




% put sections only (as opposed to subsections) in the table of contents
\setcounter{tocdepth}{1}


\newcommand{\sA}{\ensuremath{\mathscr{A}}\xspace}
\newcommand{\sB}{\ensuremath{\mathscr{B}}\xspace}
\newcommand{\sC}{\ensuremath{\mathscr{C}}\xspace}
\newcommand{\sD}{\ensuremath{\mathscr{D}}\xspace}
\newcommand{\sE}{\ensuremath{\mathscr{E}}\xspace}
\newcommand{\sF}{\ensuremath{\mathscr{F}}\xspace}
\newcommand{\sG}{\ensuremath{\mathscr{G}}\xspace}
\newcommand{\sH}{\ensuremath{\mathscr{H}}\xspace}
\newcommand{\sI}{\ensuremath{\mathscr{I}}\xspace}
\newcommand{\sJ}{\ensuremath{\mathscr{J}}\xspace}
\newcommand{\sK}{\ensuremath{\mathscr{K}}\xspace}
\newcommand{\sL}{\ensuremath{\mathscr{L}}\xspace}
\newcommand{\sM}{\ensuremath{\mathscr{M}}\xspace}
\newcommand{\sN}{\ensuremath{\mathscr{N}}\xspace}
\newcommand{\sO}{\ensuremath{\mathscr{O}}\xspace}
\newcommand{\sP}{\ensuremath{\mathscr{P}}\xspace}
\newcommand{\sQ}{\ensuremath{\mathscr{Q}}\xspace}
\newcommand{\sR}{\ensuremath{\mathscr{R}}\xspace}
\newcommand{\sS}{\ensuremath{\mathscr{S}}\xspace}
\newcommand{\sT}{\ensuremath{\mathscr{T}}\xspace}
\newcommand{\sU}{\ensuremath{\mathscr{U}}\xspace}
\newcommand{\sV}{\ensuremath{\mathscr{V}}\xspace}
\newcommand{\sW}{\ensuremath{\mathscr{W}}\xspace}
\newcommand{\sX}{\ensuremath{\mathscr{X}}\xspace}
\newcommand{\sY}{\ensuremath{\mathscr{Y}}\xspace}
\newcommand{\sZ}{\ensuremath{\mathscr{Z}}\xspace}


\newcommand{\fka}{\ensuremath{\mathfrak{a}}\xspace}
\newcommand{\fkb}{\ensuremath{\mathfrak{b}}\xspace}
\newcommand{\fkc}{\ensuremath{\mathfrak{c}}\xspace}
\newcommand{\fkd}{\ensuremath{\mathfrak{d}}\xspace}
\newcommand{\fke}{\ensuremath{\mathfrak{e}}\xspace}
\newcommand{\fkf}{\ensuremath{\mathfrak{f}}\xspace}
\newcommand{\fkg}{\ensuremath{\mathfrak{g}}\xspace}
\newcommand{\fkh}{\ensuremath{\mathfrak{h}}\xspace}
\newcommand{\fki}{\ensuremath{\mathfrak{i}}\xspace}
\newcommand{\fkj}{\ensuremath{\mathfrak{j}}\xspace}
\newcommand{\fkk}{\ensuremath{\mathfrak{k}}\xspace}
\newcommand{\fkl}{\ensuremath{\mathfrak{l}}\xspace}
\newcommand{\fkm}{\ensuremath{\mathfrak{m}}\xspace}
\newcommand{\fkn}{\ensuremath{\mathfrak{n}}\xspace}
\newcommand{\fko}{\ensuremath{\mathfrak{o}}\xspace}
\newcommand{\fkp}{\ensuremath{\mathfrak{p}}\xspace}
\newcommand{\fkq}{\ensuremath{\mathfrak{q}}\xspace}
\newcommand{\fkr}{\ensuremath{\mathfrak{r}}\xspace}
\newcommand{\fks}{\ensuremath{\mathfrak{s}}\xspace}
\newcommand{\fkt}{\ensuremath{\mathfrak{t}}\xspace}
\newcommand{\fku}{\ensuremath{\mathfrak{u}}\xspace}
\newcommand{\fkv}{\ensuremath{\mathfrak{v}}\xspace}
\newcommand{\fkw}{\ensuremath{\mathfrak{w}}\xspace}
\newcommand{\fkx}{\ensuremath{\mathfrak{x}}\xspace}
\newcommand{\fky}{\ensuremath{\mathfrak{y}}\xspace}
\newcommand{\fkz}{\ensuremath{\mathfrak{z}}\xspace}


\newcommand{\fkA}{\ensuremath{\mathfrak{A}}\xspace}
\newcommand{\fkB}{\ensuremath{\mathfrak{B}}\xspace}
\newcommand{\fkC}{\ensuremath{\mathfrak{C}}\xspace}
\newcommand{\fkD}{\ensuremath{\mathfrak{D}}\xspace}
\newcommand{\fkE}{\ensuremath{\mathfrak{E}}\xspace}
\newcommand{\fkF}{\ensuremath{\mathfrak{F}}\xspace}
\newcommand{\fkG}{\ensuremath{\mathfrak{G}}\xspace}
\newcommand{\fkH}{\ensuremath{\mathfrak{H}}\xspace}
\newcommand{\fkI}{\ensuremath{\mathfrak{I}}\xspace}
\newcommand{\fkJ}{\ensuremath{\mathfrak{J}}\xspace}
\newcommand{\fkK}{\ensuremath{\mathfrak{K}}\xspace}
\newcommand{\fkL}{\ensuremath{\mathfrak{L}}\xspace}
\newcommand{\fkM}{\ensuremath{\mathfrak{M}}\xspace}
\newcommand{\fkN}{\ensuremath{\mathfrak{N}}\xspace}
\newcommand{\fkO}{\ensuremath{\mathfrak{O}}\xspace}
\newcommand{\fkP}{\ensuremath{\mathfrak{P}}\xspace}
\newcommand{\fkQ}{\ensuremath{\mathfrak{Q}}\xspace}
\newcommand{\fkR}{\ensuremath{\mathfrak{R}}\xspace}
\newcommand{\fkS}{\ensuremath{\mathfrak{S}}\xspace}
\newcommand{\fkT}{\ensuremath{\mathfrak{T}}\xspace}
\newcommand{\fkU}{\ensuremath{\mathfrak{U}}\xspace}
\newcommand{\fkV}{\ensuremath{\mathfrak{V}}\xspace}
\newcommand{\fkW}{\ensuremath{\mathfrak{W}}\xspace}
\newcommand{\fkX}{\ensuremath{\mathfrak{X}}\xspace}
\newcommand{\fkY}{\ensuremath{\mathfrak{Y}}\xspace}
\newcommand{\fkZ}{\ensuremath{\mathfrak{Z}}\xspace}


\newcommand{\BA}{\ensuremath{\mathbb{A}}\xspace}
\newcommand{\BB}{\ensuremath{\mathbb{B}}\xspace}
\newcommand{\BC}{\ensuremath{\mathbb{C}}\xspace}
\newcommand{\BD}{\ensuremath{\mathbb{D}}\xspace}
\newcommand{\BE}{\ensuremath{\mathbb{E}}\xspace}
\newcommand{\BF}{\ensuremath{\mathbb{F}}\xspace}
\newcommand{\BG}{\ensuremath{\mathbb{G}}\xspace}
\newcommand{\BH}{\ensuremath{\mathbb{H}}\xspace}
\newcommand{\BI}{\ensuremath{\mathbb{I}}\xspace}
\newcommand{\BJ}{\ensuremath{\mathbb{J}}\xspace}
\newcommand{\BK}{\ensuremath{\mathbb{K}}\xspace}
\newcommand{\BL}{\ensuremath{\mathbb{L}}\xspace}
\newcommand{\BM}{\ensuremath{\mathbb{M}}\xspace}
\newcommand{\BN}{\ensuremath{\mathbb{N}}\xspace}
\newcommand{\BO}{\ensuremath{\mathbb{O}}\xspace}
\newcommand{\BP}{\ensuremath{\mathbb{P}}\xspace}
\newcommand{\BQ}{\ensuremath{\mathbb{Q}}\xspace}
\newcommand{\BR}{\ensuremath{\mathbb{R}}\xspace}
\newcommand{\BS}{\ensuremath{\mathbb{S}}\xspace}
\newcommand{\BT}{\ensuremath{\mathbb{T}}\xspace}
\newcommand{\BU}{\ensuremath{\mathbb{U}}\xspace}
\newcommand{\BV}{\ensuremath{\mathbb{V}}\xspace}
\newcommand{\BW}{\ensuremath{\mathbb{W}}\xspace}
\newcommand{\BX}{\ensuremath{\mathbb{X}}\xspace}
\newcommand{\BY}{\ensuremath{\mathbb{Y}}\xspace}
\newcommand{\BZ}{\ensuremath{\mathbb{Z}}\xspace}


\newcommand{\bA}{\ensuremath{\mathbf{A}}\xspace}
\newcommand{\bB}{\ensuremath{\mathbf{B}}\xspace}
\newcommand{\bC}{\ensuremath{\mathbf{C}}\xspace}
\newcommand{\bD}{\ensuremath{\mathbf{D}}\xspace}
\newcommand{\bE}{\ensuremath{\mathbf{E}}\xspace}
\newcommand{\bF}{\ensuremath{\mathbf{F}}\xspace}
\newcommand{\bG}{\ensuremath{\mathbf{G}}\xspace}
\newcommand{\bH}{\ensuremath{\mathbf{H}}\xspace}
\newcommand{\bI}{\ensuremath{\mathbf{I}}\xspace}
\newcommand{\bJ}{\ensuremath{\mathbf{J}}\xspace}
\newcommand{\bK}{\ensuremath{\mathbf{K}}\xspace}
\newcommand{\bL}{\ensuremath{\mathbf{L}}\xspace}
\newcommand{\bM}{\ensuremath{\mathbf{M}}\xspace}
\newcommand{\bN}{\ensuremath{\mathbf{N}}\xspace}
\newcommand{\bO}{\ensuremath{\mathbf{O}}\xspace}
\newcommand{\bP}{\ensuremath{\mathbf{P}}\xspace}
\newcommand{\bQ}{\ensuremath{\mathbf{Q}}\xspace}
\newcommand{\bR}{\ensuremath{\mathbf{R}}\xspace}
\newcommand{\bS}{\ensuremath{\mathbf{S}}\xspace}
\newcommand{\bT}{\ensuremath{\mathbf{T}}\xspace}
\newcommand{\bU}{\ensuremath{\mathbf{U}}\xspace}
\newcommand{\bV}{\ensuremath{\mathbf{V}}\xspace}
\newcommand{\bW}{\ensuremath{\mathbf{W}}\xspace}
\newcommand{\bX}{\ensuremath{\mathbf{X}}\xspace}
\newcommand{\bY}{\ensuremath{\mathbf{Y}}\xspace}
\newcommand{\bZ}{\ensuremath{\mathbf{Z}}\xspace}


\newcommand{\ba}{\ensuremath{\mathbf{a}}\xspace}
\newcommand{\bb}{\ensuremath{\mathbf{b}}\xspace}
\newcommand{\bc}{\ensuremath{\mathbf{c}}\xspace}
\newcommand{\bd}{\ensuremath{\mathbf{d}}\xspace}
\newcommand{\be}{\ensuremath{\mathbf{e}}\xspace}
\newcommand{\bbf}{\ensuremath{\mathbf{f}}\xspace}
\newcommand{\bg}{\ensuremath{\mathbf{g}}\xspace}
\newcommand{\bh}{\ensuremath{\mathbf{h}}\xspace}
\newcommand{\bi}{\ensuremath{\mathbf{i}}\xspace}
\newcommand{\bj}{\ensuremath{\mathbf{j}}\xspace}
\newcommand{\bk}{\ensuremath{\mathbf{k}}\xspace}
\newcommand{\bl}{\ensuremath{\mathbf{l}}\xspace}
\newcommand{\bm}{\ensuremath{\mathbf{m}}\xspace}
\newcommand{\bn}{\ensuremath{\mathbf{n}}\xspace}
\newcommand{\bo}{\ensuremath{\mathbf{o}}\xspace}
\newcommand{\bp}{\ensuremath{\mathbf{p}}\xspace}
\newcommand{\bq}{\ensuremath{\mathbf{q}}\xspace}
\newcommand{\br}{\ensuremath{\mathbf{r}}\xspace}
\newcommand{\bbs}{\ensuremath{\mathbf{s}}\xspace}
\newcommand{\bt}{\ensuremath{\mathbf{t}}\xspace}
\newcommand{\bu}{\ensuremath{\mathbf{u}}\xspace}
\newcommand{\bv}{\ensuremath{\mathbf{v}}\xspace}
\newcommand{\bw}{\ensuremath{\mathbf{w}}\xspace}
\newcommand{\bx}{\ensuremath{\mathbf{x}}\xspace}
\newcommand{\by}{\ensuremath{\mathbf{y}}\xspace}
\newcommand{\bz}{\ensuremath{\mathbf{z}}\xspace}


\newcommand{\CA}{\ensuremath{\mathcal{A}}\xspace}
\newcommand{\CB}{\ensuremath{\mathcal{B}}\xspace}
\newcommand{\CC}{\ensuremath{\mathcal{C}}\xspace}
\newcommand{\CD}{\ensuremath{\mathcal{D}}\xspace}
\newcommand{\CE}{\ensuremath{\mathcal{E}}\xspace}
\newcommand{\CF}{\ensuremath{\mathcal{F}}\xspace}
\newcommand{\CG}{\ensuremath{\mathcal{G}}\xspace}
\newcommand{\CH}{\ensuremath{\mathcal{H}}\xspace}
\newcommand{\CI}{\ensuremath{\mathcal{I}}\xspace}
\newcommand{\CJ}{\ensuremath{\mathcal{J}}\xspace}
\newcommand{\CK}{\ensuremath{\mathcal{K}}\xspace}
\newcommand{\CL}{\ensuremath{\mathcal{L}}\xspace}
\newcommand{\CM}{\ensuremath{\mathcal{M}}\xspace}
\newcommand{\CN}{\ensuremath{\mathcal{N}}\xspace}
\newcommand{\CO}{\ensuremath{\mathcal{O}}\xspace}
\newcommand{\CP}{\ensuremath{\mathcal{P}}\xspace}
\newcommand{\CQ}{\ensuremath{\mathcal{Q}}\xspace}
\newcommand{\CR}{\ensuremath{\mathcal{R}}\xspace}
\newcommand{\CS}{\ensuremath{\mathcal{S}}\xspace}
\newcommand{\CT}{\ensuremath{\mathcal{T}}\xspace}
\newcommand{\CU}{\ensuremath{\mathcal{U}}\xspace}
\newcommand{\CV}{\ensuremath{\mathcal{V}}\xspace}
\newcommand{\CW}{\ensuremath{\mathcal{W}}\xspace}
\newcommand{\CX}{\ensuremath{\mathcal{X}}\xspace}
\newcommand{\CY}{\ensuremath{\mathcal{Y}}\xspace}
\newcommand{\CZ}{\ensuremath{\mathcal{Z}}\xspace}


\newcommand{\RA}{\ensuremath{\mathrm{A}}\xspace}
\newcommand{\RB}{\ensuremath{\mathrm{B}}\xspace}
\newcommand{\RC}{\ensuremath{\mathrm{C}}\xspace}
\newcommand{\RD}{\ensuremath{\mathrm{D}}\xspace}
\newcommand{\RE}{\ensuremath{\mathrm{E}}\xspace}
\newcommand{\RF}{\ensuremath{\mathrm{F}}\xspace}
\newcommand{\RG}{\ensuremath{\mathrm{G}}\xspace}
\newcommand{\RH}{\ensuremath{\mathrm{H}}\xspace}
\newcommand{\RI}{\ensuremath{\mathrm{I}}\xspace}
\newcommand{\RJ}{\ensuremath{\mathrm{J}}\xspace}
\newcommand{\RK}{\ensuremath{\mathrm{K}}\xspace}
\newcommand{\RL}{\ensuremath{\mathrm{L}}\xspace}
\newcommand{\RM}{\ensuremath{\mathrm{M}}\xspace}
\newcommand{\RN}{\ensuremath{\mathrm{N}}\xspace}
\newcommand{\RO}{\ensuremath{\mathrm{O}}\xspace}
\newcommand{\RP}{\ensuremath{\mathrm{P}}\xspace}
\newcommand{\RQ}{\ensuremath{\mathrm{Q}}\xspace}
\newcommand{\RR}{\ensuremath{\mathrm{R}}\xspace}
\newcommand{\RS}{\ensuremath{\mathrm{S}}\xspace}
\newcommand{\RT}{\ensuremath{\mathrm{T}}\xspace}
\newcommand{\RU}{\ensuremath{\mathrm{U}}\xspace}
\newcommand{\RV}{\ensuremath{\mathrm{V}}\xspace}
\newcommand{\RW}{\ensuremath{\mathrm{W}}\xspace}
\newcommand{\RX}{\ensuremath{\mathrm{X}}\xspace}
\newcommand{\RY}{\ensuremath{\mathrm{Y}}\xspace}
\newcommand{\RZ}{\ensuremath{\mathrm{Z}}\xspace}


\newcommand{\uF}{\underline{F}}
\newcommand{\uV}{\underline{V}}





\newcommand{\heart}{{\heartsuit}}
\newcommand{\club}{{\clubsuit}}
\newcommand{\nat}{{\natural}}
\newcommand{\shp}{{\sharp}}
%\newcommand{\flat}{{\flat}}
\newcommand{\diam}{{\Diamond}}
\newcommand{\spade}{{\spadesuit}}






\newcommand{\ab}{\mathrm{ab}}
\newcommand{\Ad}{\mathrm{Ad}}
\newcommand{\ad}{\mathrm{ad}}
\newcommand{\alb}{\mathrm{alb}}
\newcommand{\AT}{\mathrm{AT}}
\DeclareMathOperator{\Aut}{Aut}

\newcommand{\Br}{{\mathrm{Br}}}

\newcommand{\cay}{\ensuremath{\operatorname{\fkc_\xi}}\xspace}
\newcommand{\Ch}{{\mathrm{Ch}}}
\DeclareMathOperator{\charac}{char}
\DeclareMathOperator{\Coker}{Coker}
\newcommand{\cod}{{\mathrm{cod}}}
\DeclareMathOperator{\colspan}{colspan}
\newcommand{\cont}{{\mathrm{cont}}}
\newcommand{\cl}{{\mathrm{cl}}}
\newcommand{\Cl}{{\mathrm{Cl}}}
\newcommand{\cm}{{\mathrm {cm}}}
\newcommand{\corr}{\mathrm{corr}}

\newcommand{\del}{\operatorname{\partial Orb}}
\newcommand{\delJ}{\partial J}
\DeclareMathOperator{\diag}{diag}
\newcommand{\disc}{{\mathrm{disc}}}
\DeclareMathOperator{\dist}{dist}
\newcommand{\Div}{{\mathrm{Div}}}
\renewcommand{\div}{{\mathrm{div}}}
\newcommand{\DR}{\mathrm{DR}}
\newcommand{\Dr}{\mathrm{Dr}}

\DeclareMathOperator{\End}{End}

\newcommand{\Fil}{\ensuremath{\mathrm{Fil}}\xspace}
\newcommand{\fin}{\mathrm{fin}}
\DeclareMathOperator{\Frob}{Frob}


\DeclareMathOperator{\Gal}{Gal}
\newcommand{\gen}{\mathrm{generic}}
\newcommand{\GL}{\mathrm{GL}}
\newcommand{\gl}{\frak{gl}}
\newcommand{\GO}{\mathrm{GO}}
\DeclareMathOperator{\Gr}{Gr}
\newcommand{\gr}{\mathrm{gr}}
\newcommand{\GS}{\mathrm{GS}}
\newcommand{\GSpin}{\mathrm{GSpin}}
\newcommand{\GU}{\mathrm{GU}}

\newcommand{\hg}{{\mathrm{hg}}}
\DeclareMathOperator{\Hom}{Hom}

\newcommand{\id}{\ensuremath{\mathrm{id}}\xspace}
\let\Im\relax
\DeclareMathOperator{\im}{im}
\DeclareMathOperator{\Im}{Im}
\renewcommand{\i}{^{-1}}
\newcommand{\Ind}{{\mathrm{Ind}}}
\newcommand{\inj}{\hookrightarrow}
\DeclareMathOperator{\Int}{\ensuremath{\mathrm{Int}}\xspace}
\newcommand{\inv}{{\mathrm{inv}}}
\DeclareMathOperator{\Isom}{Isom}

\DeclareMathOperator{\Jac}{Jac}

% \DeclareMathOperator{\ker}{ker}

\DeclareMathOperator{\length}{length}
\DeclareMathOperator{\Lie}{Lie}
\newcommand{\lInt}{\ensuremath{\text{$\ell$-}\mathrm{Int}}\xspace}
\newcommand{\loc}{\ensuremath{\mathrm{loc}}\xspace}

\newcommand{\Mp}{{\mathrm{Mp}}}

\newcommand{\naive}{\ensuremath{\mathrm{naive}}\xspace}
\newcommand{\new}{{\mathrm{new}}}
\newcommand{\Nilp}{\ensuremath{\mathtt{Nilp}}\xspace}
\newcommand{\ngen}{\mathrm{non\text{-}generic}}
\DeclareMathOperator{\Nm}{Nm}
\DeclareMathOperator{\NS}{NS}

\newcommand{\OGr}{\mathrm{OGr}}
\DeclareMathOperator{\Orb}{Orb}
\DeclareMathOperator{\ord}{ord}

\DeclareMathOperator{\proj}{proj}

\DeclareMathOperator{\rank}{rank}
\DeclareMathOperator{\Ros}{Ros}

\newcommand{\PGL}{{\mathrm{PGL}}}
\DeclareMathOperator{\Pic}{Pic}

\newcommand{\rc}{\ensuremath{\mathrm{rc}}\xspace}
\renewcommand{\Re}{{\mathrm{Re}}}
\newcommand{\red}{\ensuremath{\mathrm{red}}\xspace}
\newcommand{\reg}{{\mathrm{reg}}}
\DeclareMathOperator{\Res}{Res}
\newcommand{\rs}{\ensuremath{\mathrm{rs}}\xspace}

\newcommand{\Sel}{{\mathrm{Sel}}}
\newcommand{\Sh}{\mathrm{Sh}}
%\newcommand{\Sha}{{\underline{\mathrm{|||}}}}
%\newcommand{\Sha}{{\hbox{\cyr Sh}}
\newcommand{\Sim}{{\mathrm{Sim}}}
\newcommand{\SL}{{\mathrm{SL}}}
\DeclareMathOperator{\spann}{span}
\DeclareMathOperator{\Spec}{Spec}
\DeclareMathOperator{\Spf}{Spf}
\newcommand{\spin}{\ensuremath{\mathrm{spin}}\xspace}
\newcommand{\SO}{{\mathrm{SO}}}
\newcommand{\Sp}{{\mathrm{Sp}}}
\newcommand{\spl}{\mathrm{split}}
\newcommand{\SU}{{\mathrm{SU}}}
\DeclareMathOperator{\supp}{supp}
\DeclareMathOperator{\Sym}{Sym}
\DeclareMathOperator{\sgn}{sgn}

\DeclareMathOperator{\tr}{tr}
\newcommand{\triv}{\mathrm{triv}}

\newcommand{\U}{\mathrm{U}}
\DeclareMathOperator{\uAut}{\underline{Aut}}
\newcommand{\ur}{{\mathrm{ur}}}

\DeclareMathOperator{\vol}{vol}

\DeclareMathOperator{\WT}{WT}
\newcommand{\wtHG}{\ensuremath{{\widetilde{{H\! G}}}}\xspace}


\newcommand{\wt}{\widetilde}
\newcommand{\wh}{\widehat}
\newcommand{\pp}{\frac{\partial\ov\partial}{\pi i}}
\newcommand{\pair}[1]{\langle {#1} \rangle}
\newcommand{\wpair}[1]{\left\{{#1}\right\}}
\newcommand{\intn}[1]{\left( {#1} \right)}
\newcommand{\norm}[1]{\|{#1}\|}
\newcommand{\sfrac}[2]{\left( \frac {#1}{#2}\right)}
\newcommand{\ds}{\displaystyle}
\newcommand{\ov}{\overline}
\newcommand{\incl}{\hookrightarrow}
\newcommand{\lra}{\longrightarrow}
\newcommand{\imp}{\Longrightarrow}
\newcommand{\lto}{\longmapsto}
\newcommand{\bs}{\backslash}
\newcommand{\la}{\langle}
\newcommand{\ra}{\rangle}
\newcommand{\lv}{\lvert}
\newcommand{\rv}{\rvert}
\newcommand{\sidewedge}[1]{\sideset{}{#1}\bigwedge}


\newcommand{\ep}{\varepsilon}

%%% some additional macros


\newcommand{\nass}{\noalign{\smallskip}}
\newcommand{\htt}{h}
\newcommand{\cutter}{\medskip\medskip \hrule \medskip\medskip}



% Equation  \AMSname
% Theorem   \theoremname


% Theorem environments.
%
\newtheorem{theorem}{Theorem}
\newtheorem{proposition}[theorem]{Proposition}
\newtheorem{lemma}[theorem]{Lemma}
\newtheorem{conjecture}[theorem]{Conjecture}
\newtheorem{`conjecture'}[theorem]{``Conjecture''}
\newtheorem{corollary}[theorem]{Corollary}

\theoremstyle{definition}
\newtheorem{definition}[theorem]{Definition}
\newtheorem{example}[theorem]{Example}
\newtheorem{exercise}[theorem]{Exercise}
\newtheorem{situation}[theorem]{Situation}
\newtheorem{remark}[theorem]{Remark}
\newtheorem{remarks}[theorem]{Remarks}
\newtheorem{question}[theorem]{Question}

\newenvironment{altenumerate}
   {\begin{list}
      {(\theenumi) }
      {\usecounter{enumi}
       \setlength{\labelwidth}{0pt}
       \setlength{\labelsep}{0pt}
       \setlength{\leftmargin}{0pt}
       \setlength{\itemsep}{\the\smallskipamount}
       \renewcommand{\theenumi}{\roman{enumi}}
      }}
   {\end{list}}
% the following is a "level 2" altenumerate
\newenvironment{altenumerate2}
   {\begin{list}
      {\textup{(\theenumii)} }
      {\usecounter{enumii}
       \setlength{\labelwidth}{0pt}
       \setlength{\labelsep}{0pt}
       \setlength{\leftmargin}{2em}
       \setlength{\itemsep}{\the\smallskipamount}
       \renewcommand{\theenumii}{\alph{enumii}}
      }}
   {\end{list}}

\newenvironment{altitemize}
   {\begin{list}
      {$\bullet$}
      {\setlength{\labelwidth}{0pt}
	   \setlength{\itemindent}{5pt}
       \setlength{\labelsep}{5pt}
       \setlength{\leftmargin}{0pt}
       \setlength{\itemsep}{\the\smallskipamount}
      }}
   {\end{list}}




\numberwithin{equation}{section}
\numberwithin{theorem}{section}



%%%% macros added by Brian
%%%% many of these require the etoolbox package, which should be loaded above

\newcommand{\aform}{\ensuremath{\langle\text{~,~}\rangle}\xspace}
\newcommand{\sform}{\ensuremath{(\text{~,~})}\xspace}

\newcounter{filler}
\newcounter{ATtype}

% gets rid of indentation in itemize and enumerate enivronments, and adds
% a small space between list items:
\setitemize[0]{leftmargin=*,itemsep=\the\smallskipamount}
\setenumerate[0]{leftmargin=*,itemsep=\the\smallskipamount}

% basic right arrow, short in inlines and long in displays
\renewcommand{\to}{%
   \ifbool{@display}{\longrightarrow}{\rightarrow}%
   }
% redefine \mapsto to be short in inlines and long in displays
\let\shortmapsto\mapsto
\renewcommand{\mapsto}{%
   \ifbool{@display}{\longmapsto}{\shortmapsto}%
   }
% stretchable labeled right (2nd is xy-style) & left arrows, well-behaved inline or displayed
\newlength{\olen}
\newlength{\ulen}
\newlength{\xlen}
\newcommand{\xra}[2][]{%
   \ifbool{@display}%
      {\settowidth{\olen}{$\overset{#2}{\longrightarrow}$}%
       \settowidth{\ulen}{$\underset{#1}{\longrightarrow}$}%
       \settowidth{\xlen}{$\xrightarrow[#1]{#2}$}%
       \ifdimgreater{\olen}{\xlen}%
          {\underset{#1}{\overset{#2}{\longrightarrow}}}%
          {\ifdimgreater{\ulen}{\xlen}%
             {\underset{#1}{\overset{#2}{\longrightarrow}}}
             {\xrightarrow[#1]{#2}}}}%
      {\xrightarrow[#1]{#2}}
   }
\makeatother
\newcommand{\xyra}[2][]{%
   \settowidth{\xlen}{$\xrightarrow[#1]{#2}$}%
   \ifbool{@display}%
      {\settowidth{\olen}{$\overset{#2}{\longrightarrow}$}%
       \settowidth{\ulen}{$\underset{#1}{\longrightarrow}$}%
       \ifdimgreater{\olen}{\xlen}%
          {\mathrel{\xymatrix@M=.12ex@C=3.2ex{\ar[r]^-{#2}_-{#1} &}}}%
          {\ifdimgreater{\ulen}{\xlen}%
             {\mathrel{\xymatrix@M=.12ex@C=3.2ex{\ar[r]^-{#2}_-{#1} &}}}
             {\mathrel{\xymatrix@M=.12ex@C=\the\xlen{\ar[r]^-{#2}_-{#1} &}}}}}%
      {\mathrel{\xymatrix@M=.12ex@C=\the\xlen{\ar[r]^-{#2}_-{#1} &}}}%
   }
\makeatletter
\newcommand{\xla}[2][]{%
   \ifbool{@display}%
      {\settowidth{\olen}{$\overset{#2}{\longleftarrow}$}%
       \settowidth{\ulen}{$\underset{#1}{\longleftarrow}$}%
       \settowidth{\xlen}{$\xleftarrow[#1]{#2}$}%
       \ifdimgreater{\olen}{\xlen}%
          {\underset{#1}{\overset{#2}{\longleftarrow}}}%
          {\ifdimgreater{\ulen}{\xlen}%
             {\underset{#1}{\overset{#2}{\longleftarrow}}}
             {\xleftarrow[#1]{#2}}}}%
      {\xleftarrow[#1]{#2}}
   }
% isomorphism arrow, short in inlines and long in displays
\newcommand{\isoarrow}{%
   \ifbool{@display}{\overset{\sim}{\longrightarrow}}{\xrightarrow\sim}%
   }
% left-right arrow, short inline and long in diplays
\renewcommand{\lra}{%
   \ifbool{@display}{\longleftrightarrow}{\leftrightarrow}%
   }
% tilde for use under arrows (e.g. \xra) to designate isomorphisms
\newcommand{\undertilde}{\raisebox{0.4ex}{\smash[t]{$\scriptstyle\sim$}}}  





\begin{document}

\title[Regular formal moduli spaces and arithmetic transfer conjectures]{Regular formal moduli spaces and \\ arithmetic transfer conjectures}
\author{M. Rapoport}
\address{Mathematisches Institut der Universit\"at Bonn, Endenicher Allee 60, 53115 Bonn, Germany}
\email{rapoport@math.uni-bonn.de}
\author{B. Smithling}
\address{Johns Hopkins University, Department of Mathematics, 3400 N.\ Charles St.,\ Baltimore, MD  21218, USA}
\email{bds@math.jhu.edu}
\author{W. Zhang}
\address{Columbia University, Department of Mathematics, 2990 Broadway, New York, NY 10027, USA}
\email{wzhang@math.columbia.edu}


% \date{\today}



\begin{abstract}
We define various formal moduli spaces of $p$-divisible groups which are regular, and morphisms between them. We formulate arithmetic transfer conjectures, which are variants of the arithmetic fundamental lemma conjecture of \cite{Z12} in the presence of ramification. These conjectures include the AT conjecture of \cite{RSZ}. We prove these conjectures in low-dimensional cases. 

\end{abstract}

\maketitle

\tableofcontents



\section{Introduction}\label{Intro section}

In \cite{Z12} the third-named author proposed a relative trace formula approach to the arithmetic Gan--Gross--Prasad conjecture. In this context, he formulated the \emph{arithmetic fundamental lemma} (AFL) conjecture, cf.~\cite{Z12,RTZ}. The AFL conjecturally relates the special value of the derivative an orbital integral to an arithmetic intersection number on a \emph{Rapoport--Zink formal moduli space of $p$-divisible groups} (RZ space) attached to a unitary group. It is essential here that one is dealing with a situation that is unramified in every possible sense (the quadratic extension $F/F_0$ defining the unitary group is unramified, and the hermitian space is split; the function appearing in the derivative of the orbital integral is the characteristic function of a hyperspecial maximal compact subgroup, etc.). The AFL is proved for low ranks of the unitary group ($n=2$ and $3$) in \cite{Z12}, and for arbitrary rank $n$ and \emph{minuscule} group elements in \cite{RTZ}. 
A simplified proof for $n=3$ is given by Mihatsch in \cite{M-AFL}.
At present, the general case of the AFL seems out of reach, even though Yun has obtained interesting results concerning the function field analog \cite{Y12}. 

The present series of papers is devoted to investigating how the statement of the AFL has to be modified when the various unramifiedness hypotheses are dropped. In the context of the \emph{fundamental lemma} (FL) conjecture of Jacquet--Rallis, this question leads naturally to their \emph{smooth transfer} (ST) conjecture, cf.  \cite{JR}. In the arithmetic context, this question naturally leads  to the problem of formulating  \emph{arithmetic transfer} (AT) conjectures.  One goal of the present paper is to formulate such AT conjectures in as many cases as possible and to prove these conjectures in low dimension.

The search for such AT conjectures motivates the problem of defining RZ spaces with good properties and to construct morphisms between them beyond the unramified case.  The construction of such spaces and morphisms is the second goal of this paper.   The ground work for the construction of such RZ spaces has been laid in earlier papers on \emph{local models}. To be more specific, let us consider the case when the quadratic extension $F/F_0$ is ramified. In our previous paper \cite{RSZ}, we considered the problem of defining RZ spaces attached to a unitary group of signature $(1, n-1)$.  When $n$ is even, based on work on local models of Pappas and the first author \cite{PR}, we constructed such RZ spaces which are formally smooth. We termed this phenomenon \emph{exotic smoothness}, since smoothness is unexpected in the presence of ramification.  In the present paper, we complete the picture by again constructing such RZ spaces which are formally smooth when $n$ is odd, this time based on work on local models  of the second author \cite{S} (in our previous paper \cite{RSZ}, we only constructed an open subspace of these RZ spaces when $n$ is odd).

We stress that for applications to AT conjectures, it seems essential to have a functor description of the relevant RZ spaces. Correspondingly, it is essential to have a functor description of the relevant local models; the Pappas--Zhu definition through a closure operation in a mixed characteristic Beilinson--Gaitsgory degeneration of an affine Grassmannian \cite{PZ} (even though much more general) is not useful in this context. In fact, to define the morphisms between RZ spaces required for the AT conjecture in the case that $F/F_0$ is ramified and $n$ is even, we have to dig even deeper  into the theory of local models, and this constitutes the most difficult part of the present paper. The case when $F/F_0$ is unramified is much easier and is based on the work of Drinfeld \cite{D} and G\"ortz \cite{Goertz} on local models for $\GL_n$.  

Let us now describe the contents of the paper in more detail. 
\smallskip

Let $p$ be an odd prime number, and let $F_0$ be a finite extension of $\BQ_p$, with residue field $k$. Let $F/F_0$ be a quadratic field extension. We denote by $a\mapsto \ov a$ the non-trivial automorphism of $F/F_0$, and by $\eta=\eta_{F/F_0}$ the corresponding quadratic character on $F_0^\times$. Let $e:=(0,\dotsc,0,1)\in F_0^n$, and let $\GL_{n-1}\incl \GL_n$ be the natural embedding that identifies $\GL_{n-1}$ with the subgroup fixing $e$ under left multiplication, and fixing the transposed vector $\tensor[^t]{e}{}$ under right multiplication. Let 
\[
   S_n := \{\, s\in \Res_{F/F_0}\GL_n \mid s\ov s=1 \,\},
\]
which is acted on by $\GL_{n-1}$ by conjugation.
On the other hand, let $W_0$ and $W_1$ be the respective split and non-split $F/F_0$-hermitian spaces of dimension $n$. For $i \in \{0,1\}$, fix anisotropic vectors $u_i\in W_i$ of the same length, and denote by $W_i^\flat \subset W_i$ the orthogonal complement of the line spanned by $u_i$. The unitary group $\U(W_i^\flat)$ acts by conjugation on $\U(W_i)$.

Let us recall the matching relation between regular semi-simple elements of $S_n(F_0)$ and of $\U(W_0)(F_0)$ and $\U(W_1)(F_0)$. Here an element of  $S_n(F_0)$, resp.~of $\U(W_i)(F_0)$, is called \emph{regular semi-simple} (rs) if its orbit under $\GL_{n-1}$, resp.~$\U(W_i^\flat)$, is Zariski-closed of maximal dimension. We denote by $S_n(F_0)_\rs$ and $\U(W_i)(F_0)_\rs$ the subsets of regular semi-simple elements. 
For each $i$, choose a basis of $W_i$ by first choosing a basis of $W_i^\flat$ and then appending $u_i$ to it. This identifies $\U(W^\flat_i)(F_0)$ with a subgroup of $\GL_{n-1}(F)$ and  $\U(W_i)(F_0)$ with a subgroup of $\GL_{n}(F)$. An element $\gamma\in S_n(F_0)_\rs$ is then said to \emph{match} an element $g\in \U(W_i)(F_0)_\rs$ if these elements are conjugate under $\GL_{n-1}(F)$ when considered as elements in $\GL_n(F)$. The matching relation induces a bijection 
\[
   \big[S_n(F_0)_\rs\big] \simeq \big[ \U(W_0)(F_0)_\rs\big]\amalg \big[\U(W_1)(F_0)_\rs\big],
\]
cf.~\cite[\S2]{Z12}, where the brackets indicate the sets of orbits under $\GL_{n-1}(F_0)$, $\U(W_0^\flat)(F_0)$, and $\U(W_1^\flat)(F_0)$, respectively.

Dual to the matching of elements is the transfer of functions, which is defined through orbital integrals. For a function $f'\in C_c^\infty(S_n(F_0))$, an element $\gamma\in S_n(F_0)_\rs$, and a complex parameter $s\in\BC$, we define the weighted orbital integral
\[
   \Orb(\gamma,f', s) := \int_{\GL_{n-1}(F_0)}f'(h^{-1}\gamma h)\lvert\det h \rvert^s\eta(\det h) \, dh,
\]
as well as its special value 
\[
   \Orb(\gamma,f') := \Orb(\gamma,f', 0) .
\]
For later use in the arithmetic situation, we also introduce the special value of its derivative,
\[
   \del(\gamma,f') := \frac d{ds} \Big|_{s=0} \Orb(\gamma,f', s).
\]
Here the Haar measure on $\GL_{n-1}(F_0)$ is normalized so that $\vol(\GL_{n-1}(O_{F_0}))=1$. 
For a function $f_i\in C_c^\infty(\U(W_i)(F_0))$ and an element $g\in  \U(W_i)(F_0)_\rs$, we define the orbital integral
\[
   \Orb(g,f_i) := \int_{\U(W^\flat_i)(F_0)}f_i(h^{-1} g h)\, dh .
\]
Then the function $f'\in C_c^\infty(S_n(F_0))$ is said to \emph{transfer} to the pair of functions $(f_0,f_1)$ in $ C_c^\infty(\U(W_0)(F_0))\times  C_c^\infty(\U(W_1)(F_0))$
if, whenever $\gamma\in S_n(F_0)_\rs$ matches $g\in \U(W_i)(F_0)_\rs$,
\[
   \omega(\gamma)\Orb(\gamma,f')=\Orb(g,f_i).
\]
Here 
\[
   \omega\colon S_n(F_0)_\rs\to \BC^\times
\]
is a fixed transfer factor \cite[p.~988]{Z14}, and the Haar measures on $\U(W_i^\flat)(F_0)$ are fixed. For the particular transfer factor we will take in this paper, see \S\ref{trans factor}. 

The FL conjecture asserts a specific transfer relation in a completely unramified situation. Namely, assume that $F/F_0$ is unramified and that the special vectors $u_i$ have norm one, and normalize the Haar measure on $\U(W_0^\flat)(F_0)$ by giving a hyperspecial maximal compact subgroup volume one.  Then the FL conjecture asserts that, with respect to the ``natural'' transfer factor (see \eqref{sign} below), the characteristic function $\mathbf{1}_{S_n(O_{F_0})}$  transfers to $(\mathbf{1}_{K_0},0)$, where $K_0 \subset \U(W_0)(F_0)$ denotes a hyperspecial maximal open subgroup. 

By contrast, when $F/F_0$ is ramified, such natural choices do not exist. The ST conjecture asserts that for any $f'$, a transfer $(f_0,f_1)$ exists (non-uniquely), and that any pair $(f_0,f_1)$ arises as a transfer from some (non-unique) $f'$.  It is known to hold by \cite{Z14}. 

\smallskip

The arithmetic situation is analogous. For the AFL conjecture we assume, just as in the FL conjecture, that $F/F_0$ is unramified and that the special vectors $u_i$ have norm one. We take the same Haar measure on $\U(W^\flat_0)(F_0)$, and the same transfer factor $\omega$. Then the AFL conjecture asserts that 
\begin{equation}\label{IntroAFL}
   \omega(\gamma)\del \bigl(\gamma, \mathbf{1}_{S_n(O_{F_0})}\bigr) = -\Int(g)\cdot\log q
\end{equation}
whenever $\gamma\in S_n(F_0)_\rs$ matches $g\in \U(W_1)(F_0)_\rs$ (note that the FL conjecture asserts that $\Orb(\gamma, \mathbf{1}_{S_n(O_{F_0})}) = 0$ for such $\gamma$). Here $q$ denotes the number of elements in the residue field of $F_0$. 

The term $\Int(g)$ that appears in \eqref{IntroAFL} is an intersection number on an unramified RZ space. Let us recall its definition, cf.\ \cite{RSZ}.  Let $\breve F$ be the completion of a maximal unramified extension of $F$, and $O_{\breve F}$ its ring of integers.  For each $\Spf O_{\breve F}$-scheme $S$, we consider triples $(X,\iota,\lambda)$ over $S$, where $X$ is a formal $p$-divisible $O_{F_0}$-module of relative height $2n$ and dimension $n$, where $\iota \colon O_F\to \End(X)$ is an action of $O_F$ extending the $O_{F_0}$-action and satisfying the Kottwitz condition of signature $(1,n-1)$ on $\Lie(X)$ (cf.~\cite[\S 2]{KR-U1}), and where $\lambda$ is a principal polarization on $X$ whose Rosati involution induces the automorphism $a\mapsto \ov a$ on $O_F$ via $\iota$.  Over $S = \Spec \ov k$, there is a unique such triple $(\BX_n,\iota_{\BX_n},\lambda_{\BX_n})$ up to $O_F$-linear quasi-isogeny compatible with the polarizations.  We then denote by $\CN_n=\CN_{F/F_0,n}$ the formal scheme over $\Spf O_{\breve{F}}$ which represents the functor that associates to each $S$ the set of isomorphism classes of tuples $(X,\iota,\lambda,\rho)$, where the first three entries are as just given, and where $\rho\colon X\times_S \ov S\to \BX_n\times_{\Spec\ov k} \ov S$ is a \emph{framing} of the restriction of $X$ to the special fiber $\ov S$ of $S$, compatible with $\iota$ and $\lambda$ in a certain sense, cf.~\cite[\S2]{RTZ}. Then $\CN_n$ is formally smooth of relative formal dimension $n-1$ over $\Spf O_{\breve F}$. The automorphism group (in a certain sense) of the framing object $\BX_n$ can be identified with $\U(W_1)(F_0)$; it acts on $\CN_n$ by changing the framing. Let $\CE$ be the canonical lifting of the formal $O_F$-module of relative height one and dimension one over $\Spf O_{\breve F}$, with its canonical $O_F$-action $\iota_\CE$ and its natural polarization $\lambda_\CE$. There is a natural closed embedding of $\CN_{n-1}$ into $\CN_n$,
\[
   \delta_\CN\colon
	\xymatrix@R=0ex{
	   \CN_{n-1} \ar[r]  &  \CN_n\\
		(Y, \iota, \lambda) \ar@{|->}[r]  &  (Y \times \CE, \iota\times\ov{\iota}_\CE, \lambda\times\lambda_\CE).
	}
\]
Here $\ov{\iota}_\CE$ denotes the precomposition of $\iota_\CE$ with the nontrivial Galois automorphism on $O_F$. 
Let $\CN_{n-1,n} := \CN_{n-1}\times_{\Spf O_{\breve F}} \CN_n$, and let
$$
   \Delta\subset \CN_{n-1,n}
$$
denote the graph of $\delta_\CN$. Then $\Int(g)$ is defined as the intersection number of $\Delta$ with its translate under the automorphism $1\times g$ of $\CN_{n-1,n}$,
\[
   \Int(g) := \chi\bigl(\CN_{n-1,n}, \CO_\Delta\otimes^\BL \CO_{(1 \times g)\Delta} \bigr) .
\]
We also define \emph{homogeneous} and \emph{Lie algebra} versions of this intersection number, cf.\ \eqref{defintprod} and \eqref{lInt}.
 

It should be true in the situation of the AFL that for \emph{any} $f'\in C_c^\infty(S_n(F_0))$ with transfer  $(\mathbf{1}_{K_0},0)$, there exists a function $f'_{\corr}\in C_c^\infty(S_n(F_0))$ such that
\begin{equation*}
   \omega(\gamma)\del (\gamma, f') = -\Int(g)\cdot\log q+\omega(\gamma)\Orb (\gamma,f'_{\corr})
\end{equation*}
whenever $\gamma\in S_n(F_0)_\rs$ matches $g\in \U(W_1)(F_0)_\rs$.
This would follow from the AFL and a con\-jectural \emph{density principle} on weighted orbital integrals, cf.\ \cite[Conj.\ 5.16, Lem.\ 5.18]{RSZ}. 
This remark 
indicates
% shows
how
one should
% to
formulate AT conjectures.

\smallskip

The problem of formulating an AT conjecture arises when one drops the unramifiedness assumptions made in the AFL conjecture. We want to replace $\CN_n$ by variants where the quadratic extension $F/F_0$ is allowed to be ramified, and where separately the polarization is allowed to be non-principal.  However, the scope of the conjecture is limited by the fact that we want to keep the definition of $\Int(g)$ as an Euler--Poincar\'e characteristic of a derived tensor product. This forces on us the condition that the analog of the product $\CN_{n-1}\times_{\Spf O_{\breve F}} \CN_n$ is \emph{regular}. We do not know a systematic way of singling out such cases; in the present paper, we discuss those we have found. The principle underlying our examples is that when $F/F_0$ is unramified, we take the polarization to be \emph{principal} or \emph{almost principal} (or equivalently, \emph{$\varpi$-modular} or \emph{almost $\varpi$-modular}, where $\varpi$ denotes a uniformizer in $F_0$; cf.\ Remarks \ref{pi-modular unram} and \ref{almost pi-modular unram}). 
When $F/F_0$ is ramified, we take the polarization to be \emph{$\pi$-modular} or \emph{almost $\pi$-modular}, where $\pi$ denotes a uniformizer in $F$.

Let us now review case-by-case the variants of the AFL conjecture that we propose in this paper. 

We start with the case when $F/F_0$ is unramified.  Again let $\varpi$ denote a uniformizer in $F_0$.  To define a variant of $\CN_n$, we impose that the polarization $\lambda$ is \emph{almost principal}, i.e.\ that 
$$
\ker \lambda \subset X[\iota(\varpi)]\ \text{\emph{is of rank $q^2$.}}
$$
The corresponding formal scheme $\wt{\CN}_n$ has semi-stable reduction over $\Spf O_{\breve {F}}$ of relative formal dimension $n-1$ (cf.\ Theorem \ref{wtCN_n semistable}). For $n=2$, there is an isomorphism \cite{KR-alt}
\begin{equation*}
   \wt\CN_2 \simeq \wh\Omega^2_{F_0}\times_{\Spf O_{F_0}}\Spf O_{\breve {F}} ,
\end{equation*}
where $\wh\Omega^2_{F_0}$ denotes the formal scheme version of the Drinfeld halfspace corresponding to the local field $F_0$. Note that, in contrast to $\CN_n$, the automorphism group of the framing object for $\wt\CN_n$ identifies with $\U(W_0)(F_0)$, which therefore acts on $\wt\CN_n$. 


 We define a closed embedding of formal schemes
\begin{equation*}
   \wt\delta_\CN \colon
	\xymatrix@R=0ex{
	   \CN_{n-1} \ar[r]  &  \wt\CN_n\\
		(X, \iota, \lambda) \ar@{|->}[r]
		   &  \bigl(X \times \ov\CE, \iota \times \ov\iota_{\CE},
                 \lambda \times \varpi\lambda_{\CE} \bigr) .
   }
\end{equation*}
We therefore obtain, as in the case of the AFL, a closed embedding 
\begin{equation*}
   \wt\Delta_\CN \colon \CN_{n-1} \xra{(\id_{\CN_{n-1}},\wt\delta_\CN)} \wt\CN_{n-1,n} := \CN_{n-1}\times_{\Spf O_{\breve F}}\wt\CN_n,
\end{equation*}
whose image we denote by
\[
   \wt\Delta := \wt\Delta_\CN (\CN_{n-1}).
\]
Here we point out that $\wt{\CN}_{n-1, n}$ is regular of formal dimension $2(n-1)$. Hence for $g \in \U(W_0)(F_0)_\rs$ we may set
\[
   \Int(g) := \chi\bigl(\wt\CN_{n-1,n}, \CO_{\wt\Delta} \otimes^\BL \CO_{(1 \times g)\wt\Delta} \bigr).
\]
 
In this case, we take the special vectors $u_i \in W_i$ to have norm $\varpi$. It follows that $W_1^\flat$ is split, and therefore contains self-dual lattices. We normalize the Haar measure on $\U(W_1^\flat)(F_0)$ by giving the stabilizer of such a self-dual lattice volume one. Consider the characteristic function $\mathbf{1}_{K'}\in C_c^\infty(S_n(F_0))$, where
  \begin{align*}
   K' := S_n(O_{F_0})\cap K_0(\varpi) ,
\end{align*}
where, in turn, $K_0(\varpi)$ denotes the subgroup of matrices in $\GL_n(O_F)$ which are congruent modulo $\varpi$ to a lower triangular block matrix with respect to the decomposition $O_F^n=O_F^{n-1}\oplus O_F e$. 
We conjecture that  $(-1)^{n-1}\mathbf{1}_{K'}$ transfers to $(0, \mathbf{1}_{K_1})$, where the open compact subgroup $K_1$ of $\U(W_1)(F_0)$ is the stabilizer of an almost self-dual lattice in $W_1$, cf.\ Conjecture \ref{FL almost self-dual}. We prove that this conjecture holds, provided that $q\geq n$ and that the Lie algebra version of the FL conjecture holds (cf.\ Theorem \ref{unram variant FL}). Hence this transfer relation holds for $p \gg n$ by \cite{Go,Y}, and for any odd $p$ when $n=2$ or $n=3$ by \cite{Z12}.  The 
AT conjecture  in the present situation is now as follows. 

\begin{conjecture}\label{Intro-ConjATunr} Let $F/F_0$ be unramified. 
\begin{altenumerate}
\renewcommand{\theenumi}{\alph{enumi}}
\item
For \emph{any} $f'\in C_c^\infty(S_n(F_0))$ with transfer  $(0, \mathbf{1}_{K_1})$, there exists a function $f'_{\corr}\in C_c^\infty(S_n(F_0))$ such that
\begin{equation*}
   \omega_S(\gamma)\del (\gamma, f') = -\Int(g)\cdot\log q+\omega_S(\gamma)\Orb (\gamma,f'_{\corr})
\end{equation*}
for any $\gamma\in S_n(F_0)_\rs$ matching an element $g\in \U(W_0)(F_0)_\rs$.
\item\label{Intro-ConjATunr AFL}
Suppose that $\gamma \in S(F_0)_\rs$ matches $g \in \U(W_0)(F_0)_\rs$. Then
\begin{equation}\label{IntroATunr}
   \omega_S (\gamma)\del\bigl(\gamma, (-1)^{n-1}\mathbf{1}_{K'}\bigr) = - \Int(g)\cdot \log q .
\end{equation}
\end{altenumerate}
\end{conjecture}

We also give a \emph{homogeneous version} of this conjecture, as well as a \emph{Lie algebra version}, cf.\ Conjecture \ref{conjunramified}.
Our main result on this conjecture is the following result (cf.\ \S\ref{results atc afl}).

\begin{theorem}\label{Intro-Thmunr}
Conjecture \ref{Intro-ConjATunr}(\ref{Intro-ConjATunr AFL}) holds true in the non-degenerate case if the AFL conjecture in its Lie algebra version (cf.\ Conjecture \ref{AFLconj}(\ref{AFLconj lie})) holds, provided that $q\geq n$. 

Let $F_0 = \BQ_p$. Then   Conjecture \ref{Intro-ConjATunr} holds true  for $n=2$ and $n=3$. 
\end{theorem}

Here by the ``non-degenerate case'' we mean that the intersection $\wt\Delta \cap (1\times g)\wt\Delta$ is an artinian scheme.  Let us also remark on the restriction to $F_0 = \BQ_p$ at the end of the theorem. Indeed, strictly speaking the RZ spaces $\CN_n$ and $\wt \CN_n$ introduced above only fall under the framework of \cite{RZ} when $F_0 = \BQ_p$.  Therefore, when working in contexts where formal schemes are present, we will tacitly take $q = p$ and $F_0 = \BQ_p$ throughout this paper (including the setting of ramified $F/F_0$ to be discussed below).  On the other hand, this restriction on $F_0$ should be removable due to recent work of Ahsendorf--Cheng--Zink \cite{ACZ} and Mihatsch \cite{M-Th}. In anticipation of this, we will continue to use the general notation $q$ and $F_0$, and we often refer to $O_{F_0}$-relative polarizations, relative Dieudonn\'e modules, etc.

Now  assume  that $F/F_0$ is \emph{ramified}, again with $\pi \in F$ a uniformizer. In this case we modify the definition of the formal moduli space $\CN_{F/F_0,n}=\CN_n$ by imposing  on the polarization $\lambda$ the condition
\[
   \ker(\lambda) \subset X[\iota(\pi)]
	\text{\emph{ is of rank }} q^{2\lfloor n/2 \rfloor}.
\]
In order to obtain formal schemes with reasonable properties, we impose additional conditions on the action of $O_{F}$ induced by $\iota$  on the Lie algebra of the $p$-divisible groups involved (the \emph{Pappas wedge condition} and (variants of) the \emph{spin condition}). When $n$ is odd, there is no longer a unique framing object over $\ov k$; however, the two possible choices lead to isomorphic moduli spaces, and we will therefore ignore this issue. In both the even and the odd case,  $\CN_n$ is formally smooth of relative formal dimension $n-1$ over $\Spf O_{\breve F}$ and  essentially proper (\emph{exotic smoothness}). In the case $n=2$, the formal scheme $\CN_2$ can be identified with the base change from $\Spf O_{\breve F_0}$ to $\Spf O_{\breve F}$ of the disjoint sum of two copies of the Lubin--Tate deformation space $\CM$, cf.\ Example \ref{CN_2}. 

In the case when $n$ is odd, the morphism $\delta_\CN\colon \CN_{n-1}\to\CN_n$ can be defined exactly as in the AFL case,  since then $2\lfloor\frac{n-1}{2}\rfloor = 2\lfloor \frac{n}{2}\rfloor$. As in the AFL, the group $\U(W_1)(F_0)$ acts on $\CN_n$, and we define $\Int(g)$ as before for $g\in \U(W_1)(F_0)_\rs$.  We take the special vectors to have norm one. We recall from \cite{RSZ} our AT conjecture in this case (cf.\ \S\ref{s:ATCodd}). 

\begin{conjecture}\label{Intro-Conjramodd}
Let $F/F_0$ be ramified, and let $n\geq 3$ be odd. 
\begin{altenumerate}
\renewcommand{\theenumi}{\alph{enumi}}
\item
For any $f'\in C^\infty_c(S_n(F_0))$  with transfer $(\mathbf{1}_{K_0}, 0)$, there exists a function  $f'_\corr\in C^\infty_c(S_n(F_0))$ such that 
$$
2 \omega(\gamma)\del(\gamma,f') = -\Int(g)\cdot\log q + \omega(\gamma)\Orb(\gamma,f'_\corr)
$$ for any $\gamma\in S_n(F_0)_\rs$ matching an element $g\in \U(W_1)(F_0)_\rs$.
\item
There exists a function $f'\in C^\infty_c(S_n(F_0))$ with transfer $(\mathbf{1}_{K_0}, 0)$ such that 
\begin{equation}\label{IntroATramodd}
   2 \omega(\gamma)\del(\gamma,f')=-\Int(g)\cdot\log q 
\end{equation}
for any $\gamma\in S_n(F_0)_\rs$ matching an element $g\in \U(W_1)(F_0)_\rs$.
\end{altenumerate}
\end{conjecture}

Here $K_0$ denotes the maximal compact subgroup stabilizing an \emph{almost $\pi$-modular lattice} $\Lambda_0$ in $W_0$. The Haar measure on $\U(W^\flat_0)(F_0)$ is defined by $\vol K^\flat_0=1$ for a special maximal compact subgroup $K^\flat_0$ of $\U(W^\flat_0)(F_0)$. 

In \cite{RSZ}, we also formulate homogeneous and Lie algebra versions of this conjecture, comp.\ \S\ref{s:ATCodd}; and we prove this conjecture when $F_0 = \BQ_p$ and $n=3$.

In the case when $n$ is even, it is much less obvious how to define the morphism $\delta_\CN\colon \CN_{n-1}\to\CN_n$.  Indeed, the definition of $\delta_\CN$ in the AFL and odd ramified setting, transposed to the present case, produces $p$-divisible groups with the wrong polarization type to give points on $\CN_n$.  More precisely, consider the moduli problem of triples $(X,\iota,\lambda)$ as in the definition of $\CN_n$, except where the polarization $\lambda$ satisfies
\[
   \ker(\lambda) \subset X[\iota(\pi)]
	\text{\emph{ is of rank }} q^{n-2}.
\]
As in the case of $\CN_n$ when $n$ is odd, up to isogeny there are two such triples over $\ov k$, only one of which is isogenous ($O_F$-linearly and compatibly with the polarizations) to the framing object for $\CN_n$. Taking this as the framing object, we obtain a formal moduli space $\CP_n$ as before. The formula defining $\delta_\CN$ in the AFL and odd ramified settings then defines a morphism
\[
   \wt\delta_\CN\colon \CN_{n-1} \to \CP_n.
\]
We obtain a morphism from $\CP_n$ to $\CN_n$ --- in fact, two of them --- as follows. Let $\CP_n'$ denote the moduli space over $\Spf O_{\breve F}$ of tuples $(X,\iota,\lambda,\rho,X',\iota',\lambda',\rho',\phi)$,
where first four entries are a point on $\CN_n$, the second four entries are a point on $\CP_n$, and $\phi\colon X \to X'$ is an isogeny of degree $q$ lifting a fixed isogeny between the framing objects of $\CN_n$ and $\CP_n$.  Then $\CP_n'$ is again an RZ space, and there are evident projections
\begin{equation*}
   \CP_n' \to \CN_n 
   \quad\text{and}\quad
	\CP_n' \to \CP_n.
\end{equation*}
We show in Proposition \ref{even n decomp lem} that $\CN_n$ naturally decomposes into a disjoint union $\CN_n^+ \amalg \CN_n^-$ of open and closed formal subschemes (this generalizes the case $n = 2$ mentioned above).  Pulling back along the projection $\CP_n' \to \CN_n$, we obtain a decomposition $\CP_n' = (\CP_n')^+ \amalg (\CP_n')^-$.  The key geometric result is now that this decomposition presents $\CP_n'$ as a trivial double cover of $\CP_n$, which in turn gives rise to two embeddings of $\CN_{n-1}$ into $\CN_n$, cf.\ Theorem \ref{wtCN'pm isom} and Proposition \ref{delta^pm closed emb}.

\begin{theorem}\label{intro CP' isom}
The projection $\CP_n' \to \CP_n$ maps each of the summands $(\CP_n')^\pm$ isomorphically to $\CP_n$.  Denoting the inverse by $\psi^\pm \colon \CP_n \isoarrow (\CP_n')^\pm$, the composite
\[
   \delta_\CN^\pm \colon \CN_{n-1} \xra{\wt\delta_\CN} \CP_n \xra{\psi^\pm} (\CP_n')^\pm \to \CN_n^\pm
\]
is a closed embedding.
\end{theorem}

In other words, the first assertion in the theorem says that, loosely speaking, given any point $(X',\iota',\lambda',\rho')$ on $\CP_n$ over a connected base, there are exactly two ways to extend it to an isogeny chain $X \xra\phi X'$ such that the composite $X \xra\phi X' \xra{\lambda'} (X')^\vee \xra{\phi^\vee} X^\vee$ is a $\pi$-modular polarization $\lambda$ on $X$.  This can be viewed as an analog of the linear algebra fact that in a split, even-dimensional $F/F_0$-hermitian space, every $O_F$-lattice $\Lambda'$ such that $\Lambda' \subset (\Lambda')^\vee \subset^2 \pi\i\Lambda'$ contains exactly two $\pi$-modular lattices $\Lambda$ (and, furthermore, this remark essentially \emph{is} the proof that $\CP_n' \to \CP_n$ is a double cover on $\ov k$-points, via the interpretation of both sides in terms of Dieudonn\'e modules).  The fact that the ``simple'' way of defining $\delta_\CN$ from before does not work in the even ramified case can also be understood in terms of the group theory of lattice stabilizers; see Remark \ref{group theoretic}.

Using Theorem \ref{intro CP' isom}, we define $\Delta$ to be the union of the graph subschemes of $\delta^+_\CN$ and  $\delta^-_\CN$ inside $\CN_{n-1, n}=\CN_{n-1}\times_{\Spf O_{\breve F}}\CN_n$.
As in the case of odd $n$, the group $\U(W_1)(F_0)$ acts on $\CN_n$, and we then define $\Int(g)$ as before, for $g\in \U(W_1)(F_0)_\rs$. We take the special vectors $u_i$ of norm $-1$.  We normalize the Haar measure on $\U(W_0^\flat)(F_0)$ by giving the stabilizer $K_0^\flat$ of an almost $\pi$-modular lattice $\Lambda_0^\flat$ volume one. Consider the two $\pi$-modular lattices $\Lambda_0^\pm$ contained in $\Lambda_0^\flat\oplus O_F u_0$, and denote by $K_0^\pm$ their stabilizers in $\U(W_0)(F_0)$. We consider $K_0^\flat$ as a subgroup of $\U(W_0)(F_0)$. 
\begin{conjecture}\label{Intro-Conjrameven}
Let $F/F_0$ be ramified, and let $n\geq 2$ be even. 
\begin{altenumerate}
\renewcommand{\theenumi}{\alph{enumi}}
\item
For any $f'\in C^\infty_c(S_n(F_0))$  with transfer $(\mathbf{1}_{K_0^\flat K_0^+}+\mathbf{1}_{K_0^\flat K_0^-}, 0)$, there exists a function  $f'_\corr\in C^\infty_c(S_n(F_0))$ such that 
$$
2 \omega(\gamma)\del(\gamma,f') = -\Int(g)\cdot\log q + \omega(\gamma)\Orb(\gamma,f'_\corr)
$$ for any $\gamma\in S_n(F_0)_\rs$ matching an element $g\in \U(W_1)(F_0)_\rs$.
\item
There exists a function $f'\in C^\infty_c(S_n(F_0))$ with transfer $(\mathbf{1}_{K_0^\flat K_0^+}+\mathbf{1}_{K_0^\flat K_0^-}, 0)$ such that 
\begin{equation}\label{IntroATrameven}
   2 \omega(\gamma)\del(\gamma,f')=-\Int(g)\cdot\log q 
\end{equation}
for any $\gamma\in S_n(F_0)_\rs$ matching an element $g\in \U(W_1)(F_0)_\rs$.
\end{altenumerate}
\end{conjecture}
 We also formulate homogeneous and Lie algebra versions of this conjecture (cf.\ Conjecture \ref{conjram v3}), and we prove them all in the case of minimal rank (cf.\ \S\ref{even ram proof}).
 
\begin{theorem}
Let $F_0 = \BQ_p$.  Then Conjecture \ref{Intro-Conjrameven} holds true for   $n = 2$.
\end{theorem}

Note that there is a discrepancy of a factor of $2$ in the statements of the AFL conjecture \eqref{IntroAFL} and the AT conjecture \eqref{IntroATunr}  on the one hand, and of the AT conjectures \eqref{IntroATramodd} and \eqref{IntroATrameven} on the other.  This is a genuine difference between the unramified and ramified cases, which finds its justification in the global comparison between the height pairing and the derivative of a relative trace formula, cf.\ \cite{RSZglob}. 

There are two further cases of AT statements, which we formulate in \S\ref{s:ATC ram n=2}. In both of these, $F/F_0$ is ramified and $n=2$; and, in fact, we prove them in \S\ref{s:ramifiedn=2}. In these cases we impose that the polarization $\lambda$ in the moduli problem is \emph{principal}. Then there are two possibilities for the framing objects, and the corresponding formal schemes $\wt\CN_2^{(0)}$ and $\wt\CN_2^{(1)}$ (which are defined over $\Spf O_{\breve F_0}$) are genuinely different. In fact, there are natural identifications 
\[
   \wt\CN_2^{(0)}\simeq \wh{\Omega}^2_{F_0}\times_{\Spf O_{F_0}}\Spf O_{\breve F_0}
   \quad\text{and}\quad
	\wt\CN_2^{(1)}\simeq \CM_{\Gamma_0(\varpi)} .
\]
Here $\wh\Omega^2_{F_0}$ again denotes the formal scheme version of the Drinfeld halfspace corresponding to the local field $F_0$, and $\CM_{\Gamma_0(\varpi)}$ denotes the formal deformation space of a $\varpi$-isogeny between Lubin--Tate formal groups (after base change to $\Spf O_{\breve F}$, the latter case recovers the formal scheme $\CP_2$ from above). We refer to the body of the text for the precise AT statements in these cases (they fall formally somewhat outside the framework of the general conjectures we make in Conjectures \ref{Intro-ConjATunr}, \ref{Intro-Conjramodd}, and \ref{Intro-Conjrameven}). 

\smallskip
We now comment on the proofs of our results.

In the situation of Theorem \ref{Intro-Thmunr}, the field extension $F/F_0$ is unramified, while the polarization in the moduli problem for $\wt\CN_n$ is taken to be almost principal, reflecting the fact the compact open subgroup $K_1$ is  the stabilizer of an almost self-dual lattice in $W_1$. The key observation of our proof is that, although the automorphism groups of the framing objects for $\CN_n$ and $\wt\CN_n$ are not directly related, their Lie algebras are. Therefore we first use the Cayley transform to reduce the group version of the AT conjecture to the corresponding Lie algebra version, and then to the Lie algebra version of the AFL conjecture. 

In the situation of Conjecture \ref{Intro-Conjrameven} when $n=2$, the field extension $F/F_0$ is ramified, and the moduli space $\CN_2$ can be identified with the base change from $\Spf O_{\breve F_0}$ to $\Spf O_{\breve F}$ of the disjoint union of two copies of the Lubin--Tate deformation space $\CM$. On the geometric side, Gross's theory of the canonical lifting allows us to compute explicitly the intersection number $\Int(g)$. On the analytic side, we develop a germ expansion of the derivative of the orbital integrals around every semi-simple (but irregular) point. The irregular orbital integrals of the test function on the unitary side completely determine the derivative of the orbital integrals, up to an orbital integral function. 

The proofs of the two sporadic cases of AT theorems stated in  \S\ref{s:ATC ram n=2} are parallel to those of Conjecture \ref{Intro-Conjrameven} for $n=2$. 

Let us also comment on the proof of Theorem \ref{intro CP' isom}, which holds for any even $n$.  The proof of the first assertion consists of two steps, the first of which is to show, via a straightforward Dieudonn\'e module argument, that the morphism in question induces a bijection on the underlying point sets of the formal schemes.  The remaining step, which is more difficult, is to show the the corresponding morphism on local models is an isomorphism, and hence the two sides have the same deformation theories.  Here the ``refined'' spin condition introduced in \cite{S} plays an important role, insofar as it is necessary for flatness of the local models, cf.\ Remarks \ref{Yu flatness} and \ref{not flat}.  We also remark that this isomorphism between local models can be viewed as a reflection of the group-theoretic fact that, for an $O_F$-lattice $\Lambda'$ in a split, even-dimensional $F/F_0$-hermitian space such that $\Lambda' \subset (\Lambda')^\vee \subset^2 \pi\i\Lambda'$, and for $\Lambda$ one of the two $\pi$-modular lattices contained in $\Lambda'$, the connected stabilizer of $\Lambda'$ in the unitary group is the same as the common stabilizer group of $\Lambda$ and $\Lambda'$.
We prove the second assertion in Theorem \ref{intro CP' isom} in a similar way, via a Dieudonn\'e module step followed by a local model step.

\smallskip
We finally give an overview of the contents of this paper, which consists of four parts. 

In Part 1, we give the group-theoretic setup (in its homogeneous, its inhomogeneous, and its Lie algebra versions), and we review the statements of the FL conjecture and the AFL conjecture. 

In Part 2, we introduce the RZ spaces that will appear in the various AT conjectures. Here the auxiliary spaces in \S\ref{aux spaces} are introduced because they are needed to construct the morphisms $\delta^\pm_\CN$ mentioned above. 

In Part 3, we formulate case by case the AT conjectures mentioned above. 

In Part 4, we prove the AT conjectures in some instances. Besides the general result of Theorem \ref{Intro-Thmunr}, and after the result of \cite{RSZ} concerning the case when $F/F_0$ is ramified and $n=3$, these instances all occur for $n=2$. 




\subsection*{Acknowledgements} We are grateful to U.~G\"ortz, X.~He, and S.~Yu for helpful discussions.   We also acknowledge the hospitality of the ESI (Vienna) and the MFO (Oberwolfach), where part of this work was carried out.  We finally thank the referee for his/her remarks on the text.

M.R. is supported by a grant from  the Deutsche Forschungsgemeinschaft through the grant SFB/TR 45. B.S. is supported by a Simons Foundation grant \#359425 and an NSA grant H98230-16-1-0024. W.Z. is supported by NSF
grants DMS \#1301848 and \#1601144, and by a Sloan research fellowship. 





\subsection*{Notation}
Throughout the paper we fix an odd prime number $p$.  We let $F_0$ be a finite extension of $\BQ_p$, and we denote by $O_{F_0}$ its ring of integers, by $\varpi$ a uniformizer, and by $k$ its residue field. We set $q := \# k$ (a power of $p$), and we fix an algebraic closure $\ov k$ of $k$.  We write $v$ for the normalized (i.e.~$\varpi$-adic) valuation on $F_0$.  
We let $F$ be a quadratic extension of $F_0$, with ring of integers $O_F$ and residue field $k_F$.
When $F/F_0$ is unramified, we take $\pi := \varpi$ as a uniformizer for $F$; and when $F/F_0$ is ramified, since $p \neq 2$, we may and will choose a uniformizer $\pi$ for $F$ such that (after possibly changing $\varpi$) $\pi^2=\varpi$.  We denote by $a\mapsto \ov a$ the nontrivial automorphism of $F/F_0$, and by  $\eta = \eta_{F/F_0}$ the corresponding  quadratic character on $F_0^\times$.  
We denote the group of norm one elements in $F^\times$ by
\[
   F^1 := \{\, a \in F \mid a \ov a = 1 \,\}.
\]
We denote by $\breve F_0$ the completion of a maximal unramified extension of $F_0$, and by $\breve F$ the analogous object for $F$; thus $\breve F/\breve F_0$ is an extension of degree $1$ or $2$ according as $F/F_0$ is unramified or ramified.  Given a scheme $S$ over $\Spec O_{\breve F}$ (or more commonly for us, over $\Spf O_{\breve F}$), we denote its special fiber by
\[
   \ov S := S \times_{\Spec O_{\breve F}} \Spec \ov k.
\]

As stated above, when working in an algebro-geometric context where formal schemes are present, we always understand that $q = p$ and $F_0 = \BQ_p$.

A polarization on a $p$-divisible group $X$ is an anti-symmetric isogeny $X \to X^\vee$, where $X^\vee$ denotes the dual.  For any polarization $\lambda$ on $X$, we denote the Rosati involution on $\End^\circ(X)$ by
\[
   \Ros_\lambda\colon f \mapsto \lambda^{-1} \circ f^\vee \circ \lambda;
\]
here and elsewhere the superscript $\circ$ denotes the operation $-\otimes_\BZ \BQ$.  For any quasi-isogeny $\rho \colon X \to Y$ and polarization $\lambda$ on $Y$, we define the pullback quasi-polarization
\[
   \rho^* (\lambda) := \rho^\vee \circ \lambda \circ \rho
\]
on $X$.

We denote by $\BE$ ``the'' formal $O_{F_0}$-module of relative height $2$ and dimension $1$ over $\Spec \ov k$.  We set
\[
   O_D := \End_{O_{F_0}}(\BE)
	\quad\text{and}\quad
	D := O_D \otimes_{O_{F_0}} F_0.
\]
Thus $D$ is ``the'' quaternion division algebra over $F_0$, and $O_D$ is its maximal order.  We make $\BE$ into a formal $O_F$-module of relative height $1$ by fixing any $F_0$-embedding
\begin{equation*}
   \iota_\BE\colon F \to D.
\end{equation*}
When $F/F_0$ is unramified, the requirement that $O_F$ acts on $\Lie\BE$ via the structure map dictates an embedding of $k_F$ into $\ov k$, and hence an embedding $F \to \breve F_0$, via which we take $\breve F = \breve F_0$. We denote the main involution on $D$ by $c \mapsto \ov c$, and the reduced norm by $\RN$.  We also write $\RN$ for the norm map $F^\times \to F_0^\times$; of course, all of this notation is compatible with the embedding $\iota_\BE\colon F \to D$.  
When $F/F_0$ is ramified, we write $D^-$ for the $-1$-eigenspace in $D$ of the conjugation action of $\iota_\BE(\pi)$, so that $D = F \oplus D^-$.
  We fix an $O_{F_0}$-linear principal polarization
(any two of which differ by an $O_{F_0}^\times$-multiple)
\[
   \lambda_\BE\colon \BE \isoarrow \BE^\vee.
\] 
The Rosati involution $\Ros_{\lambda_\BE}$ induces the main involution on $D$, and hence the nontrivial Galois involution on $F$ via $\iota_\BE$.

We denote by $\CE$ the canonical lift of $\BE$ over $\Spf O_{\breve F}$ with respect to $\iota_\BE$, equipped with its $O_F$-action $\iota_\CE$, $O_F$-linear framing isomorphism $\rho_\CE\colon \CE_{\ov k} \isoarrow \BE$, and principal polarization $\lambda_\CE$ lifting $\rho_\CE^*(\lambda_\BE)$.  We denote by $\ov\BE$ the same object as $\BE$, except where the $O_F$-action $\iota_{\ov\BE}$ is equal to the precomposition of $\iota_\BE$ by the nontrivial automorphism of $F/F_0$; and ditto for $\ov\CE$ and $\iota_{\ov\CE}$ in relation to $\CE$ and $\iota_\CE$.  On the level of $O_{F_0}$-modules, we set
\[
   \lambda_{\ov\BE} := \lambda_\BE,
	\quad
	\lambda_{\ov\CE} := \lambda_\CE,
	\quad\text{and}\quad
	\rho_{\ov\CE} := \rho_\CE.
\]
Note that $\ov\BE$ is \emph{not} a formal $O_{F_0}$-module when $F/F_0$ is unramified, provided we keep the same map $O_F \to \ov k$ dictated above; and $\ov\CE$ is never a formal $O_{F_0}$-module.

Given a $p$-divisible group $X$ over $\Spec \ov k$ equipped with an $O_F$-action $\iota$, we define
\begin{equation}\label{defV}
	\BV(X) := \Hom_{O_F}^\circ\bigl(\ov \BE, X\bigr).
\end{equation}
When $X$ is equipped with a polarization $\lambda$ such that $\Ros_\lambda$ induces the nontrivial Galois involution on $O_F$ (via $\iota$), $\BV(X)$ carries a natural $F/F_0$-hermitian form, cf.~e.g.~\cite[Def.~3.1]{KR-U1}: for $x,y \in \BV(X)$, the composition
\[
   \ov\BE \xra x X \xra\lambda X^\vee \xra{y^\vee} \ov\BE^\vee \xra{\lambda_{\ov\BE}^{-1}} \ov\BE
\]
lies in $\End_{O_F}^\circ(\ov\BE)$, and hence identifies via $\iota_{\ov\BE}$ with an element in $F$, which we define to be the pairing of $x$ and $y$.

Given modules $M$ and $N$ over a ring $R$, we write $M \subset^r N$ to indicate that $M$ is an $R$-submodule of $N$ of finite colength $r$.  Typically $R$ will be $O_F$ or $O_{\breve F}$, and the quotient $N/M$ will be a vector space over the residue field of dimension $r$.  When $\Lambda$ is an $O_F$-lattice in an $F/F_0$-hermitian space, we denote the dual lattice with respect to the hermitian form by $\Lambda^\vee$, and we call $\Lambda$ a \emph{vertex lattice of type $r$} if $\Lambda \subset^r \Lambda^\vee \subset \pi^{-1} \Lambda$.  Note that this terminology differs slightly from e.g.~\cite{KR-U1,RTW}.  Of course, a \emph{vertex lattice} is a vertex lattice of type $r$ for some $r$.  Let us single out the following special cases.  A \emph{self-dual} lattice is, of course, a vertex lattice of type $0$.  An \emph{almost self-dual} lattice is a vertex lattice of type $1$.  At the other extreme, a vertex lattice $\Lambda$ is \emph{$\pi$-modular} if $\Lambda^\vee = \pi^{-1} \Lambda$, and \emph{almost $\pi$-modular} if $\Lambda \subset \Lambda^\vee \subset^1 \pi^{-1}\Lambda$.

Given a variety $V$ over $\Spec F_0$, we denote by $C_c^\infty(V)$ the set of locally constant, compactly supported functions on the space $V(F_0)$ relative to the $\varpi$-adic topology. 

We write $1_n$ for the $n \times n$ identity matrix.  We use a subscript $S$ to denote base change to a scheme (or other object) $S$, and when $S = \Spec A$, we often use a subscript $A$ instead.







\part{Setup and background}

In this first part of the paper we describe the group-theoretic setup involved in our various AT conjectures, and we review the AFL conjecture of the third author \cite{Z12}.



\section{Group-theoretic setup and definitions}\label{setup}

We begin by recalling the setup of \cite{RSZ}, except we make no assumption on the ramification of $F/F_0$.  Let $n \geq 2$ be an integer.


\subsection{Homogeneous group setting}\label{setup homog}
Let
\[
   e := (0,\dotsc,0,1) \in F^n,
\]
and consider the embedding of algebraic groups over $F$,
\begin{equation}\label{GL_n-1 emb}
	\begin{gathered}
   \xymatrix@R=0ex{
	   \GL_{n-1} \ar[r]  &  \GL_n\\
		\gamma_0 \ar@{|->}[r]  &  \diag(\gamma_0,1)
	}
	\end{gathered};
\end{equation}
this identifies $\GL_{n-1}$ with the subgroup of points $\gamma$ in $\GL_n$ such that $\gamma e = \tensor[^t]{\gamma}{} e = e$.  Next define
the
algebraic groups over $F_0$,
\begin{align*}
   G' &:= \Res_{F/F_0}(\GL_{n-1} \times \GL_n),\\
	H_1' &:= \Res_{F/F_0} \GL_{n-1},\\
	H_2' &:= \GL_{n-1}\times\GL_n.
\end{align*}
We embed $H_1'$ in $G'$ by taking the graph of the map \eqref{GL_n-1 emb}, and we embed $H_2'$ in $G'$ via the evident natural map. Let
\[
   H_{1,2}' := H_1' \times H_2'.
\]
We consider the natural right action of $H_{1,2}'$ on $G'$,
\[
   \gamma \cdot (h_1,h_2) = h_1^{-1}\gamma h_2.
\]
We say that an element $\gamma \in G'(F_0)$ is \emph{regular semi-simple} if it is regular semi-simple for this action, i.e.~its orbit under $H_{1,2}'$ is Zariski-closed in $G'$, and its stabilizer in $H_{1,2}'$ is of minimal dimension.  In the situation at hand, it is equivalent that $\gamma$ have closed orbit and trivial stabilizer, which follows from \cite[Th.~6.1]{RS}. We denote by $G'(F_0)_\rs$ the set of regular semi-simple elements in $G'(F_0)$.

Next let $W$ be an $F/F_0$-hermitian space of dimension $n$.  Up to isometry there are two possibilities for $W$, the split and non-split cases, and we write $\chi(W) = 1$ or $\chi(W) = -1$ accordingly.  These satisfy the formula
\begin{equation}\label{chi formula}
   \chi(W) = \eta\bigl((-1)^{n(n-1)/2}\det W\bigr),
\end{equation}
where we recall that $\eta = \eta_{F/F_0}$ is the quadratic character on $F_0^\times$ attached to $F/F_0$, and we set $\det W := \det J \bmod \RN F^\times$ for any hermitian matrix $J$ representing the form on $W$.  We fix an anisotropic vector
\[
   u \in W,
\]
which we call the \emph{special vector}.  Let
\[
   W^\flat := u^\perp \subset W.
\]
Then there is an orthogonal decomposition $W = W^\flat \oplus Fu$. Setting $\epsilon := (u,u)$, it follows from \eqref{chi formula} that
\begin{equation}\label{chi decomp formula}
   \chi(W) = \chi(W^\flat)\eta\bigl((-1)^{n-1}\epsilon\bigr).
\end{equation}
We define the algebraic groups over $F_0$,
\begin{equation}\label{unitary group defs}
\begin{aligned}
	G &:= \U(W),\\
	H &:= \U(W^\flat),\\
	G_W &:= H \times G,\\
	H_W &:= H \times H.
\end{aligned}
\end{equation}
We embed $H$ in $G$ in the natural way as the stabilizer of the special vector $u$, and we embed $H$ in $G_W$ as the graph of this embedding.  We then consider the natural right action of $H_W$ on $G_W$,
\[
   g \cdot (h_1,h_2) = h_1^{-1}gh_2.
\]
We say that an element $g \in G_W(F_0)$ is \emph{regular semi-simple} if it is regular semi-simple for this action, and we denote the set of such elements by $G_W(F_0)_\rs$.

Now choose an $F$-basis for $W^\flat$, and complete it to a basis for $W$ by appending $u$ (and thus identifying $u$ with $e \in F^n$). This determines closed embeddings
\[
   H \inj H_1',
	\quad
	G \inj \Res_{F/F_0} \GL_n,
	\quad\text{and}\quad
	G_W \inj G',
\]
where the third embedding is the product of the first two.  We call the maps obtained in this way \emph{special embeddings}.

\begin{definition}
An element $\gamma \in G'(F_0)_\rs$ and an element $g \in G_W(F_0)_\rs$ \emph{match} if they are in the same $H_{1,2}'(F_0)$-orbit when $g$ is regarded as an element in $G'(F_0)$ via any special embedding.
\end{definition}

The notion of matching is independent of the choice of special embedding. Now let $W_0$ and $W_1$ respectively denote the split and non-split hermitian spaces of dimension $n$, and take the special vectors in each to have the same norm (which is always possible since $n \geq 2$).  Then the basic group-theoretic fact of concern to us is that the matching relation induces a bijection on regular semi-simple orbits (which follows from the analogous bijection \eqref{matching bij inhomog} below in the inhomogeneous setting),
\begin{equation}\label{matching bij homog}
   G'(F_0)_\rs/H_{1,2}'(F_0) \simeq \bigl(G_{W_0}(F_0)_\rs/H_{W_0}(F_0)\bigr) \amalg \bigl(G_{W_1}(F_0)_\rs/H_{W_1}(F_0)\bigr).
\end{equation}

The matching bijection \eqref{matching bij homog} gives rise to the notion of \emph{transfer of smooth functions} with respect to the following orbital integrals. For $\gamma\in G'(F_0)_\rs$, a function $f'\in C_c^\infty(G')$, and a complex parameter $s\in \BC$, we define the weighted orbital integral
\begin{equation*}
   \Orb(\gamma, f', s) := 
	   \int_{H_{1,2}'(F_0)} f'(h_1^{-1}\gamma h_2) \lv\det h_1\rv^s \eta(h_2)\, dh_1\, dh_2,
\end{equation*}
where $\lv\phantom{a}\rv$ denotes the normalized absolute value on $F$, where we set
\[
   \eta(h_2) := \eta(\det h_2')^n \eta(\det h_2'')^{n-1}
	\quad\text{for}\quad
	h_2 = (h_2', h_2'')\in H_2'({F_0}) = \GL_{n-1}(F_0) \times \GL_n(F_0),
\] 
and where we use fixed Haar measures on $H_1'(F_0)$ and $H_2'(F_0)$ and the product Haar measure on $H_{1,2}'(F_0) = H_1'(F_0) \times H_2'(F_0)$.
We further define the special values
\begin{equation*}
   \Orb(\gamma, f') := \Orb(\gamma, f', 0)
	\quad\text{and}\quad
	\del(\gamma, f') := \frac{d}{ds} \Big|_{s=0} \Orb({\gamma},  f',s) . 
\end{equation*}
The integral defining $\Orb(\gamma,f',s)$ is absolutely convergent, and $\Orb(\gamma,f')$ has the transformation property
\[
   \Orb(h_1^{-1}\gamma h_2,f') = \eta(h_2)\Orb(\gamma,f') 
	\quad\text{for}\quad 
	(h_1, h_2)\in H_{1, 2}'(F_0)=H_1'(F_0)\times H_2'(F_0) .
\]
For $W$ an $n$-dimensional hermitian space as above, an element $g \in G_W(F_0)_\rs$, and a function $f \in C_c^\infty(G_W)$, we similarly define the orbital integral
\begin{equation*}
   \Orb(g, f) := \int_{H_W(F_0)} f(h_1^{-1} g h_2)\, dh_1\, dh_2 .
\end{equation*}
Here the Haar measure on $H_W(F_0) = H(F_0) \times H(F_0)$ is a product of identical Haar measures on $H(F_0)$.

Finally, recall that a \emph{transfer factor} for $G'$ is a function $\omega\colon G'({F_0})_\rs\to \BC^\times$ such that
\[
   \omega(h_1^{-1}\gamma h_2)=\eta(h_2)\omega(\gamma)
	\quad\text{for all}\quad
	(h_1,h_2)\in H_1'(F_0) \times H_2'(F_0).
\] 
We will specify different transfer factors depending on the context later in the paper.  We can now state the definition of smooth transfer in the present context; we again denote by $W_0$ and $W_1$ the respective split and non-split hermitian spaces of dimension $n$.

\begin{definition}\label{transfer homog}
A function $f'\in C_c^\infty(G')$ and a pair of functions $(f_0,f_1) \in C_c^\infty(G_{W_0}) \times C_c^\infty(G_{W_1})$ are \emph{transfers} of each other (for the fixed choices of Haar measures, a fixed choice of transfer factor, and fixed choices of special vectors $u_i \in W_i$) if for each $i \in \{0,1\}$ and each $g\in G_{W_i}(F_0)_\rs$,
\[
 \Orb(g,f_i)=\omega(\gamma) \Orb(\gamma,f')
\]
whenever $\gamma\in G'(F_0)_\rs $ matches $g$.
\end{definition}



\subsection{Inhomogeneous group setting}\label{setup inhomog}
In this subsection we give an ``inhomogeneous'' analog of the previous subsection, whose notation we retain.  The role of $G'$ in the inhomogeneous setting is played by the symmetric space
\begin{equation}\label{S_n}
   S := S_n := \bigl\{\, \gamma \in \Res_{F/F_0}\GL_n \bigm| \gamma \ov\gamma = 1_n \,\bigr\}.
\end{equation}
Note that in some later parts of the paper (especially in Part \ref{spaces} in the context of RZ spaces) we will also use the symbol $S$ to denote an arbitrary test scheme; context should always make the meaning clear.
The role of $H_{1,2}'$ in the inhomogeneous setting is played by the group over $F_0$
\[
   H' := \GL_{n-1},
\]
which acts naturally on the right on $S$ by conjugation (via the map \eqref{GL_n-1 emb}).  The homogeneous and inhomogeneous settings are related via the maps
\begin{equation}\label{G' -> Res GL_n}
	\begin{gathered}
 \xymatrix@R=0ex{
	   G' \ar[r]  &  \Res_{F/F_0} \GL_n\\
		(\gamma_1,\gamma_2) \ar@{|->}[r]  &  \gamma_1^{-1}\gamma_2
	}
	\end{gathered}
\end{equation}
(defined again using \eqref{GL_n-1 emb}) and
\begin{equation}\label{Res GL_n -> S}
   \begin{gathered}
     r\colon \xymatrix@R=0ex{
	   \Res_{F/F_0} \GL_n \ar[r]  &  S\\
		\gamma \ar@{|->}[r]  &  \gamma \ov\gamma^{-1}
	}
	\end{gathered}.
\end{equation}
These maps induce respective isomorphisms of varieties
\[
   H_1' \bs G' \isoarrow \Res_{F/F_0} \GL_n
	\quad\text{and}\quad
	(\Res_{F/F_0} \GL_n) / \GL_n \isoarrow S,
\]
and a bijection on $F_0$-rational points
\[
   G'(F_0)/H_{1,2}'(F_0) \isoarrow S(F_0)/H'(F_0).
\]

On the unitary side, let $W$ be an $n$-dimensional $F/F_0$-hermitian space, and choose a special vector $u \in W$, as in the previous subsection.  Then the role of $G_W$ is played by $G$, and the role of $H_W$ is played by $H$, cf.~\eqref{unitary group defs}.  The natural map
\begin{equation}\label{G_W -> G}
	\begin{gathered}
   \xymatrix@R=0ex{
	   G_W \ar[r]  &  G\\
		(g_1,g_2) \ar@{|->}[r]  &  g_1^{-1}g_2
	}
	\end{gathered}
\end{equation}
induces an isomorphism of varieties
\[
   H \bs G_W \isoarrow G,
\]
where $H$ acts on $G_W$ via its diagonal embedding; and a bijection on $F_0$-rational points
\[
   G_W(F_0)/H_W(F_0) \isoarrow G(F_0)/H(F_0),
\]
where $H$ acts on $G$ by conjugation.

Now let us say that an element $\gamma \in \RM_n(F)$ is \emph{regular semi-simple} if it is regular semi-simple for the conjugation action of $\GL_{n-1,F}$ on $\RM_{n,F}$ with respect to the embedding \eqref{GL_n-1 emb}.  It is equivalent that $\gamma$ have Zariski-closed orbit and trivial stabilizer; or that the sets of vectors $\{\gamma^i e\}_{i=0}^{n-1}$ and $\{\tensor[^t]{\gamma}{^i} e \}_{i=0}^{n-1}$ are linearly independent over $F$ \cite[Th.~6.1]{RS}.  We say that an element $\gamma \in S(F_0)$ is \emph{regular semi-simple} if it is regular semi-simple for the conjugation action of $H'$ on $S$.  It is equivalent that $\gamma$ be regular semi-simple as an element in $\RM_n(F)$ in the sense just given.  The notions of regular semi-simplicity in the homogeneous and inhomogeneous settings are compatible in the sense that an element $\gamma \in G'(F_0)$ is regular semi-simple if and only if its image in $S(F_0)$ under the composite of the maps \eqref{G' -> Res GL_n} and \eqref{Res GL_n -> S} is.  Similarly, an element $g \in G(F_0)$ is \emph{regular semi-simple} if it is regular semi-simple for the conjugation action of $H$ on $G$; or equivalently if it is regular semi-simple as an element in $\RM_n(F)$ under one, hence any, special embedding $G \inj \Res_{F/F_0} \GL_n$.  An element $g \in G_W(F_0)$ is regular semi-simple if and only if its image in $G(F_0)$ under the map \eqref{G_W -> G} is.  We denote by $S(F_0)_\rs$ and $G(F_0)_\rs$ the sets of regular semi-simple elements in $S(F_0)$ and $G(F_0)$, respectively.  In the inhomogeneous setting the notion of matching takes the following form.

\begin{definition}
An element $\gamma \in S(F_0)_\rs$ and an element $g \in G(F_0)_\rs$ \emph{match} if they are in the same $\GL_{n-1}(F)$-orbit when $g$ is regarded as an element in $\GL_n(F)$ via any special embedding.
\end{definition}

The matching relation is again independent of the choice of special embedding, and it induces a bijection on regular semi-simple orbits \cite[\S2]{Z12},
\begin{equation}\label{matching bij inhomog}
	S(F_0)_\rs/H'(F_0) \simeq \bigl( G_0(F_0)_\rs/H_0(F_0)\bigr) \amalg \bigl( G_1(F_0)_\rs/H_1(F_0)\bigr),
\end{equation}
where we write
\[
   G_0 := G
	\quad\text{and}\quad
	H_0 := H
\]
when $W = W_0$ is split, and
\[
   G_1 := G
	\quad\text{and}\quad
	H_1 := H
\]
when $W = W_1$ is non-split.  (Note that the quasi-splitness of $H_0$ and $H_1$ is then governed by the formula \eqref{chi decomp formula}.) Here as before we take the special vectors in $W_0$ and $W_1$ to have the same norm.

The formalism of orbital integrals and smooth transfer carries over readily from the homogeneous setting to the inhomogeneous setting.  For $\gamma \in S(F_0)_\rs$, $f' \in C_c^\infty(S)$, and $s \in \BC$, we define
\begin{equation}\label{Orb(gamma,f',s)}
   \Orb(\gamma,f',s) := \int_{H'(F_0)} f'(h^{-1}\gamma h) \lv \det h \rv^s \eta(h)\, dh,
\end{equation}
where $\lv\phantom{a}\rv$ denotes the normalized absolute value on $F_0$, where we set
\[
   \eta(h) := \eta(\det h),
\]
and where we use a fixed Haar measure on $H'(F_0) = \GL_{n-1}(F_0)$.  We define the special values
\[
   \Orb(\gamma, f') := \Orb(\gamma, f', 0)
	\quad\text{and}\quad
	\del(\gamma, f') := \frac{d}{ds} \Big|_{s=0} \Orb({\gamma},  f',s) . 
\]
As in the homogeneous setting, the integral defining $\Orb(\gamma,f',s)$ is absolutely convergent, and when $s = 0$ it transforms as
\[
   \Orb(h^{-1}\gamma h, f') = \eta(h) \Orb(\gamma,f')
	\quad\text{for all}\quad
	h \in H'(F_0).
\]
On the unitary side, for $g \in G(F_0)_\rs$ and $f \in C_c^\infty(G)$, we define
\[
   \Orb(g,f) := \int_{H(F_0)} f(h^{-1}gh) \, dh,
\]
where we use the same fixed Haar measure on $H(F_0)$ as in the previous subsection.  Finally, a \emph{transfer factor} for $S$ is a function $\omega\colon S(F_0)_\rs \to \BC^\times$ such that
\[
   \omega(h^{-1}\gamma h) = \eta(h) \omega(\gamma)
	\quad\text{for all}\quad
	h \in H'(F_0).
\]
With this we arrive at the inhomogeneous version of smooth transfer.

\begin{definition}
A function $f' \in C_c^\infty(S)$ and a pair of functions $(f_0,f_1) \in C_c^\infty(G_0) \times C_c^\infty(G_1)$ are \emph{transfers} of each other (for the fixed choices of Haar measures, a fixed choice of transfer factor, and fixed choices of special vectors) if for each $i \in \{0,1\}$ and each $g \in G_i(F_0)_\rs$,
\[
   \Orb(g,f_i) = \omega(\gamma) \Orb(\gamma,f')
\]
whenever $\gamma \in S(F_0)_\rs$ matches $g$.
\end{definition}



\subsection{Lie algebra setting}\label{setup lie}
In this subsection we give a ``Lie algebra'' analog of the inhomogeneous group setup.  The role of $S$ is played by its tangent space at the identity matrix,
\[
   \fks := \fks_n := \bigl\{\, y \in \Res_{F/F_0} \RM_n \bigm| y + \ov y = 0 \,\bigr\}.
\]
The group action we consider is the natural right action of $H'$ on \fks by conjugation.  For $W$ an $n$-dimensional hermitian space, the role of $G$ is played by its Lie algebra
\[
   \fkg := \Lie G.
\]
Upon choosing a special vector in $W$, we then consider the right adjoint action of $H$ on \fkg.

We say that an element in $y \in \fks(F_0)$ is \emph{regular semi-simple} if it is regular semi-simple for the action of $H'$, and we denote the set of such elements by $\fks(F_0)_\rs$.  It is equivalent that $y$ have closed $H'$-orbit and trivial stabilizer; or that $y$ be regular semi-simple as an element in $\RM_n(F)$ in the sense of the previous subsection.  We say that an element $x \in \fkg(F_0)$ is \emph{regular semi-simple} if it is regular semi-simple for the action of $H$, and we denote the set of such elements by $\fkg(F_0)_\rs$.  As in \S\ref{setup homog}, the choice of a basis for $W^\flat$, extended by the special vector to a basis for $W$, determines a closed embedding
\[
   \fkg \inj \Res_{F/F_0}\RM_n,
\]
which we again call a \emph{special embedding}.  For $x \in \fkg(F_0)$ to be regular semi-simple, it is again equivalent that $x$ have closed $H$-orbit and trivial stabilizer; or that $x$ be regular semi-simple as an element in $\RM_n(F)$ under one, hence any, special embedding.

\begin{definition}
An element $y \in \fks(F_0)_\rs$ and an element $x \in \fkg(F_0)_\rs$ \emph{match} if they are in the same $\GL_{n-1}(F)$-orbit when $x$ is regarded as an element in $\RM_n(F)$ via any special embedding.
\end{definition}

As before, the matching relation is independent of the choice of special embedding, and it induces a bijection on regular semi-simple orbits \cite[\S5]{JR},
\[
   \fks(F_0)_\rs/H'(F_0) \simeq \bigl(\fkg_0(F_0)_\rs / H_0(F_0)\bigr) \amalg \bigl(\fkg_1(F_0)_\rs / H_1(F_0)\bigr),
\]
where as in the inhomogeneous group setting we use the subscripts $0$ and $1$ on $\fkg$ and $H$ according as $W$ is split or non-split, and we take the special vectors to have the same norm.

The formalism of orbital integrals and smooth transfer again carries over in a straightforward way to the present setting.  For $y \in \fks(F_0)_\rs$, $\phi' \in C_C^\infty(\fks)$, and $s \in \BC$, we define
\[
   \Orb(y,\phi',s) := \int_{H'(F_0)} \phi'(h^{-1}yh) \lv\det h \rv^s \eta(h) \, dh,
\]
as well as the special values
\[
   \Orb(y,\phi') := \Orb(y,\phi,0)
	\quad\text{and}\quad
	\del(y,\phi') := \frac{d}{ds} \Big|_{s=0} \Orb(y, \phi',s) . 
\]
The notation in the integral defining $\Orb(y,\phi',s)$ is as in \eqref{Orb(gamma,f',s)}. This integral is again absolutely convergent and transforms when $s = 0$ as
\[
   \Orb(h^{-1}yh,\phi') = \eta(h)\Orb(y,\phi')
	\quad\text{for all}\quad
	h \in H'(F_0).
\]
On the unitary side, for $x \in \fkg(F_0)_\rs$ and $\phi \in C_c^\infty(\fkg)$, we define
\[
   \Orb(x,\phi) := \int_{H(F_0)} \phi(h^{-1}xh) \, dh,
\]
where we use the same Haar measure on $H(F_0)$ as before.  A \emph{transfer factor} for \fks is a function $\omega\colon \fks(F_0)_\rs \to \BC^\times$ such that
\[
   \omega(h^{-1}\gamma h) = \eta(h)\omega(\gamma)
	\quad\text{for all}\quad
	h \in H'(F_0).
\]

\begin{definition}
A function $\phi' \in C_c^\infty(\fks)$ and a pair of functions $(\phi_0,\phi_1) \in C_c^\infty(\fkg_0) \times C_c^\infty(\fkg_1)$ are \emph{transfers} of each other (for the fixed choices of Haar measures, a fixed choice of transfer factor, and fixed choices of special vectors) if for each $i \in \{0,1\}$ and each $x\in \fkg_i(F_0)_\rs$,
\[
   \Orb(x,\phi_i) = \omega(y) \Orb(y,\phi')
\]
whenever $y\in \fks(F_0)_\rs $ matches $x$.
\end{definition}



\subsection{Transfer factors}\label{trans factor}
We now fix transfer factors for use throughout the rest of the paper, which are slight variants of the ones in \cite[\S2.4]{Z14}. First fix an extension $\wt\eta$ of the quadratic character $\eta$ from $F_0^\times$ to $F^\times$ (not necessarily of order $2$). If $F$ is unramified, then we take the natural extension $\wt\eta(x)=(-1)^{v(x)}$. For $S$ we take the transfer factor
\[
   \omega_S(\gamma) := \wt\eta\bigl(\det(\gamma)^{-\lfloor n/2\rfloor } \det(\gamma^ie)_{0 \leq i \leq n-1}\bigr), \quad \gamma \in S(F_0)_\rs.
\]
For $G'$ we take the transfer factor
\begin{equation*}
   \omega_{G'}(\gamma) := 
	\begin{cases}
		\omega_S\bigl(r(\gamma_1^{-1}\gamma_2)\bigr), & n \text{ odd}; \\
      \wt\eta(\gamma_1^{-1}\gamma_2) \omega_S\bigl(r(\gamma_1^{-1}\gamma_2)\bigr), & n \text{ even}, 
   \end{cases}
	\quad
	\gamma= (\gamma_1,\gamma_2)\in  G'(F_0)_\rs,
\end{equation*}
where $r$ is defined in \eqref{Res GL_n -> S}, and where for any $\gamma_0 \in \GL_n(F)$ we set
\[
   \wt\eta(\gamma_0) := \wt\eta(\det \gamma_0).
\]
For \fks we take the transfer factor
\begin{equation}\label{fks transfer factor ram}
   \omega_\fks(y) := \wt\eta\bigl(\det(y^ie)_{0 \leq i \leq n-1}\bigr), \quad y \in \fks(F_0)_\rs.
\end{equation}








\section{Review of the FL conjecture}\label{s:FL}
To set the stage, in this section we review the FL conjecture in its homogeneous, inhomogeneous, and Lie algebra versions, cf.~\cite{JR, Z12, RTZ}.  Let $F/F_0$ be unramified and $n \geq 2$.  As in the previous section, let $W_0$ and $W_1$ respectively be the split and non-split $F/F_0$-hermitian spaces of dimension $n$. Assume furthermore that the special vectors $u_i \in W_i$ have common norm which is a unit in $O_{F_0}$.  Then by \eqref{chi decomp formula} the orthogonal complement $W_i^\flat$ of $u_i$ in $W_i$ is again split for $i=0$ and non-split for $i=1$.  As in the previous section, we write $G_i = \U(W_i)$, $\fkg_i = \Lie G_i$, and $H_i = \U(W_i^\flat)$. Fix a self-dual $O_F$-lattice
\[
   \Lambda_0^\flat \subset W_0^\flat,
\]
which exists and is unique up to $H_0(F_0)$-conjugacy since $W_0^\flat$ is split.  Let
\[
   \Lambda_0 := \Lambda_0^\flat \oplus O_Fu_0 \subset W_0,
\]
which is again self-dual.  We denote by
\[
   K_0^\flat \subset H_0(F_0)
\]
the stabilizer of $\Lambda_0^\flat$, and by
\[
   K_0 \subset G_0(F_0)
	\quad\text{and}\quad
	\fkk_0 \subset \fkg_0(F_0)
\]
the respective stabilizers of $\Lambda_0$.  Then $K_0^\flat$ and $K_0$ are both hyperspecial maximal parahoric subgroups.

We normalize the Haar measures on the groups
\[
   H'(F_0) = \GL_{n-1}(F_0), \quad \GL_n(F_0),\quad H_1'(F_0) = \GL_{n-1}(F),\quad\text{and}\quad H_0(F_0)
\]
by assigning each of the respective subgroups
\[
   \GL_{n-1}(O_{F_0}),\quad \GL_n(O_{F_0}),\quad \GL_{n-1}(O_F), \quad\text{and}\quad K_0^\flat
\]
measure one.  We then take the product measure on the groups $H_2'(F_0) = \GL_{n-1}(F_0) \times \GL_n(F_0)$, $H_{1,2}'(F_0) = H_1'(F_0) \times H_2'(F_0)$, and $H_{W_0}(F_0) = H_0(F_0) \times H_0(F_0)$.  The Haar measures on $H_1(F_0)$ and $H_{W_1}(F_0)$ will not be important for us.  The transfer factors are defined in \S\ref{trans factor}. They take the following simple form on $S(F_0)_\rs$ and $\fkg(F_0)_\rs$, 
\begin{equation}\label{sign}
\begin{aligned}
   \omega_S(\gamma) &= (-1)^{v(\det(\gamma^i e)_{0 \leq i \leq n-1})}, \\
   \omega_\fks(y) &= (-1)^{v(\det(y^i e)_{0 \leq i \leq n-1})}.
\end{aligned}
\end{equation}
With respect to these normalizations, the FL conjecture is the following statement.

\begin{conjecture}[Fundamental lemma]\label{FLconj}\hfill
\begin{altenumerate}
\renewcommand{\theenumi}{\alph{enumi}}
\item
\textup{(Homogeneous version)} The characteristic function $\mathbf{1}_{G'(O_{F_0})} \in C_c^\infty(G')$ transfers to the pair of functions $(\mathbf{1}_{K_0^\flat\times {K}_0}, 0) \in C_c^\infty(G_{W_0}) \times C_c^\infty(G_{W_1})$. 
\item
\textup{(Inhomogeneous version)} The characteristic function $\mathbf{1}_{S(O_{F_0})} \in C_c^\infty(S)$ transfers to the pair of functions $(\mathbf{1}_{K_0},0) \in C_c^\infty(G_0)\times C_c^\infty(G_1)$.
\item\label{FLconj lie}
\textup{(Lie algebra version)} The characteristic function $\mathbf{1}_{\fks(O_{F_0})} \in  C_c^\infty(\fks)$ transfers to the pair of functions $(\mathbf{1}_{\fkk_0},0) \in C_c^\infty(\fkg_0)\times C_c^\infty(\fkg_1)$.
\end{altenumerate}
\end{conjecture}

We note that the equal characteristic analog of the FL conjecture was proved by Z.~Yun for $p> n$; J.~Gordon deduced the $p$-adic case for $p$ large, but unspecified, cf.\ \cite{Go,Y}.   








\section{Review of the AFL conjecture}\label{s:AFL}
We continue with the notation and normalizations introduced in the last section. In particular, $F/F_0$ is unramified, and the special vectors $u_i$ have norm a unit in $O_{F_0}$.  Note that the FL conjecture predicts that the orbital integrals $\Orb(\gamma, \mathbf{1}_{G'(O_{F_0})})$, $\Orb(\gamma, \mathbf{1}_{S(O_{F_0})})$, and $\Orb(y, \mathbf{1}_{\fks(O_{F_0})})$ vanish whenever $\gamma$, resp.~$\gamma$, resp.~$y$ matches with elements in $G_{W_1}(F_0)_\rs$, resp.~$G_1(F_0)_\rs$, resp.\ $\fkg_1(F_0)_\rs$.  The AFL conjecture then proposes an identity for the derivatives of these orbital integrals at such elements, in terms of geometry.

\begin{conjecture}[Arithmetic fundamental lemma]\label{AFLconj}\hfill
\begin{altenumerate}
\renewcommand{\theenumi}{\alph{enumi}}
\item
\textup{(Homogeneous version)}\label{AFLconj homog} 
Suppose that $\gamma\in G'({F_0})_\rs$ matches an element $g\in G_{W_1}({F_0})_\rs$. Then 
\[
   \omega_{G'}(\gamma)\del\bigl(\gamma, \mathbf{1}_{G'(O_{F_0})}\bigr) 
	   = - 2\Int(g)\cdot\log q. 
\]
\item
\textup{(Inhomogeneous version)}\label{AFLconj inhomog} 
Suppose that $\gamma\in S({F_0})_\rs$ matches an element $g\in G_1({F_0})_\rs$. Then 
\[
   \omega_S(\gamma)\del\bigl(\gamma, \mathbf{1}_{S(O_{F_0})}\bigr) 
	   = -\Int(g)\cdot\log q. 
\]
\item
\textup{(Lie algebra version)}\label{AFLconj lie}
Suppose that $y\in \fks({F_0})_\rs$ matches an element $x\in \fkg_1({F_0})_\rs$, and assume that the intersection $\Delta \cap \Delta_x$ is an artinian scheme. Then 
\[
   \omega_\fks(y)\del\bigl(y, \mathbf{1}_{\fks(O_{F_0})}\bigr) 
	   = -\lInt(x)\cdot\log q. 
\]
\end{altenumerate}
\end{conjecture}

Let us explain the right-hand side in each part (as well as the expression $\Delta \cap \Delta_x$ in \eqref{AFLconj lie}).  For any $n \geq 1$, let $\CN_n = \CN_{n, F/F_0}$ denote the formal moduli scheme over $\Spf O_{\breve {F}}$ of \cite{KR-U1, VW}.\footnote{Recall that, since $F/F_0$ is unramified, we have $\breve F=\breve F_0$ as in the Introduction.}   In other words, we consider triples $(X, \iota, \lambda)$ over $\Spf O_{\breve F}$-schemes $S$, where $X$ is a $p$-divisible group of absolute height $2nd$ and dimension $n$ over $S$, equipped with an action $\iota$ of $O_{F}$ such that the induced action of $O_{F_0}$ on $\Lie X$ is via the structure morphism $O_{F_0}\to \CO_S$, and with a principal ($O_{F_0}$-relative) polarization $\lambda$. Here $d:=[{F_0}: \BQ_p]$.  Hence $(X, \iota|_{O_{F_0}})$ is a formal $O_{F_0}$-module of relative height $2n$ and dimension $n$. We require that the Rosati involution $\Ros_\lambda$ induces the non-trivial Galois automorphism in $\Gal({F}/{F_0})$ on $O_{F}$, and that the \emph{Kottwitz condition} of signature $(1, n-1)$ is satisfied, i.e.
\begin{equation}\label{kottwitzcond}
   \charac \bigl(\iota(a)\mid \Lie X\bigr)=(T-a)(T-\ov a)^{n-1} \in \CO_S[T]
	\quad\text{for all}\quad
	a\in O_{F} . 
\end{equation} 
An isomorphism $(X, \iota, \lambda) \isoarrow (X', \iota', \lambda')$ between two such triples is an $O_{F}$-linear isomorphism $\varphi\colon X\isoarrow X'$ such that $\varphi^*(\lambda')=\lambda$.

It is not hard to see that over the residue field $\ov k$ of $O_{\breve {F}}$ there is a unique such triple $(\BX_n, \iota_{\BX_n}, \lambda_{\BX_n})$ such that $\BX_n$ is  supersingular, up to $O_F$-linear quasi-isogeny compatible with the polarization, cf.~\cite[Prop.~1.15]{V2}. Then $\CN_n$ represents the functor over $\Spf O_{\breve F}$ that associates to each $S$ the set of isomorphism classes of quadruples $(X, \iota, \lambda, \rho)$ over $S$, where the final entry is an $O_F$-linear quasi-isogeny of height zero defined over the special fiber,
\[
   \rho \colon X\times_S\ov S \to \BX_n \times_{\Spec \ov k} \ov S,
\]
such that $\rho^*((\lambda_{\BX_n})_{\ov S}) = \lambda_{\ov S}$ (a \emph{framing}).

\begin{remark}
The definition of $\CN_n$ given here differs slightly from that in \cite{KR-U1, VW}.  First of all, $\CN_n$ is in fact an open and closed formal subscheme of the space defined in these papers (it is the locus, denoted by $\CN_0$ in \cite{VW}, where the framing $\rho$ has height zero).  Furthermore, within this locus, the moduli problem in these papers imposes the weaker condition that $\lambda_{\ov S}$ differs from $\rho^*((\lambda_{\BX_n})_{\ov S})$ locally on $\ov S$ by a unit in $O_{F_0}$, but it also weakens the notion of an isomorphism. This changes nothing in the outcome: the  formal scheme in loc.~cit.~is identical to the formal scheme defined here, cf.~also \cite[Rem.~3.6]{RSZ}. 
\end{remark}

The following theorem summarizes basic facts on the structure of the formal scheme $\CN_n$. 

\begin{theorem}[Vollaard--Wedhorn \cite{VW}]\hfill\label{structN}
\begin{altenumerate} 
\item\label{structN i} 
For any $n$, the formal scheme $\CN_n$ is formally locally of finite type, separated, essentially proper,\footnote{Recall that \emph{essentially proper} means that each irreducible component of the reduced underlying scheme is proper over $\Spec \ov k$.} and formally smooth of relative formal dimension $n-1$ over $\Spf O_{\breve {F}}$.  In particular, $\CN_n$ is regular of formal dimension $n$.
\item\label{structN ii}  
The underlying scheme $(\CN_n)_\red$ has a Bruhat--Tits stratification by Deligne--Lusztig varieties of dimensions $0, 1,\dotsc,\lfloor \frac{n-1}{2}\rfloor$ attached to unitary groups in an  odd number of variables and to Coxeter elements, with strata parametrized by the vertices of the Bruhat--Tits complex of the special unitary group for the non-split $n$-dimensional $F/F_0$-hermitian space.\qed 
\end{altenumerate}
\end{theorem}

\begin{corollary}  For $n \geq 2$, the product $\CN_{n-1, n}:=\CN_{n-1}\times_{\Spf O_{\breve {F}}}\CN_n $ is a regular formal scheme of formal dimension $2(n-1)$.\qed
\end{corollary}

Returning to our explanation of the statement of Conjecture \ref{AFLconj}, now recall from the Introduction the formal $O_F$-module $\BE$ over $\ov k$ and its canonical lift $\CE$ over $O_{\breve F}$, as well as the ``conjugate'' objects $\ov\BE$ and $\ov\CE$.  For $n \geq 2$, there is a natural closed embedding of formal schemes
\begin{equation*}
   \delta_\CN\colon 
	\xymatrix@R=0ex{
	   \CN_{n-1} \ar[r]  &  \CN_n\\
		(X, \iota, \lambda, \rho) \ar@{|->}[r]  &  \bigl(X\times\ov {\CE}, \iota\times \iota_{\ov\CE}, \lambda\times \lambda_{\ov\CE}, \rho\times\rho_{\ov\CE}\bigr),
		}
\end{equation*}
where we set $\BX_1 = \BE$ and inductively take
\begin{equation}\label{BX_n unram}
   \BX_n = \BX_{n-1} \times \ov\BE
\end{equation}
as the framing object for $\CN_n$.  Let 
\begin{equation*}
   \Delta_\CN \colon \CN_{n-1} \xra{(\id_{\CN_{n-1}},\delta_\CN)} \CN_{n-1}\times_{\Spf O_{\breve F}}\CN_n = \CN_{n-1,n}
\end{equation*}
be the graph morphism of $\delta_\CN$.  Then
\[
   \Delta := \Delta_\CN(\CN_{n-1})
\]
is a closed formal subscheme of half the formal dimension of $\CN_{n-1, n}$. Note that
\begin{equation}\label{Aut cong U}
   \Aut^\circ (\BX_n,\iota_{\BX_n},\lambda_{\BX_n}) \cong \U\bigl(\BV(\BX_n)\bigr)(F_0), 
\end{equation}
where the left-hand side is the group of self-framings of $\BX_n$, and where $\BV(\BX_n)$ is the hermitian space \eqref{defV} attached to $\BX_n$.  The left-hand side acts naturally on $\CN_n$ by acting on the framing: $g\cdot (X,\iota,\lambda,\rho) = (X,\iota,\lambda, g \circ \rho)$.  Furthermore $\BV(\BX_n)$ contains a natural special vector $u$ given by the inclusion of $\ov\BE$ in $\BX_n = \BX_{n-1} \times \ov\BE$ via the second factor. The norm of $u$ is $1$. It is easy to compute directly that $\BV(\BX_1) = \BV(\BE)$ is non-split, and then by induction and \eqref{chi decomp formula}, $\BV(\BX_n)$ is a non-split hermitian space of dimension $n$ for any $n$. Applying this to $n$ and $n-1$,  we can choose identifications  $W_1=\BV(\BX_n)$ and $W_1^\flat=\BV(\BX_{n-1})$ compatible with the natural inclusions on both sides. Hence we obtain an action of $H_1(F_0)$ on $\CN_{n-1}$, of $G_1(F_0)$ on $\CN_n$, and of $G_{W_1}(F_0)$ on $\CN_{n-1, n}$; and furthermore the maps $\delta_\CN$ and $\Delta_\CN$ are equivariant with respect to the respective embeddings $H_1(F_0) \inj G_1(F_0)$ and $H_1({F_0})\hookrightarrow G_{W_1}({F_0})$ defined in \S\ref{setup homog}. 

Now we are ready to define the right-hand side of the identities appearing in Conjecture \ref{AFLconj}. For $g \in G_{W_1}(F_0)$, we denote by $\Int(g)$ the intersection product on $\CN_{n-1, n}$ of $\Delta$ with its translate $g\Delta$, defined through the derived tensor product of the structure sheaves,
\begin{equation}\label{defintprod}
   \Int(g) := \la \Delta, g\Delta\ra_{\CN_{n-1, n}} := \chi({\CN_{n-1, n}},  \CO_\Delta\otimes^\BL\CO_{g\Delta}) . 
\end{equation}
We similarly define $\Int(g)$ for $g \in G_1(F_0)$,
\[
   \Int(g) := \bigl\la \Delta, (1 \times g)\Delta \bigr\ra_{\CN_{n-1,n}}.
\]
In both cases, when $g$ is regular semi-simple, the right-hand side of this definition is finite, at least when $F_0=\BQ_p$, cf.\ \cite[Lem.~2.8]{Z12}. The proof in loc.~cit.~uses global methods.

\begin{remark}\label{reltospecialunr}
In \cite{KR-U1}, there is associated to $u\in \BV(\BX_n)$ a special cycle $\CZ(u)$ in $\CN_n$, namely, the locus where the quasi-homomorphism $u\colon \ov\BE\to \BX_n$ lifts to a homomorphism from $\ov\CE$ to the universal object over $\CN_n$. By \cite[Prop.\ 3.5]{KR-U1}, $\CZ(u)$ is a relative divisor. Then $\delta_\CN$ induces  an obvious closed embedding $\CN_{n-1}\to \CZ(u)$. By \cite[Lem.\ 5.2]{KR-U1}, this is an isomorphism. Similarly, for $g\in \U(\BV(\BX_n))$, there is an identification $g \delta_\CN(\CN_{n-1})=\CZ(gu)$.
\end{remark}

We make an analogous definition in the Lie algebra case, as in \cite[\S4.4]{PRS}.  Note that, analogously to \eqref{Aut cong U}, we can identify the $F_0$-points of $\fkg_1 = \Lie\U(\BV(\BX_n))$ with a subgroup of the $O_F$-linear quasi-endomorphisms of $\BX_n$ (those $x$ for which $x + \Ros_{\lambda_{\BX_n}}(x) = 0$).  Now, for any quasi-endomorphism $x$ of $\BX_n$, define $\Delta_x \subset \CN_{n-1,n}$ to be the closed formal subscheme (abusing notation in the obvious way)
\begin{equation}\label{Delta_x}
   \Delta_x := \bigl\{\, (Y,X) \in \CN_{n-1,n} \bigm| x\colon \BX_n \rightarrow \BX_n \text{ lifts to a homomorphism } Y \times \ov\CE \rightarrow X \,\bigr\}.
\end{equation}
For $g \in G_1(F_0)$, $\Delta_g$ is simply the translate $(1 \times g) \Delta$.  For any $x$, in the case that the intersection $\Delta \cap \Delta_x$ is an artinian scheme, we define
\begin{equation}\label{lInt}
   \lInt(x) := \length(\Delta\cap\Delta_x).
\end{equation}
This completes the explanation of the statement of the AFL in all cases.  
\begin{remark}
As already pointed out in \cite[\S4.4]{RSZ}, we do not have a Lie algebra version of the AFL outside the \emph{non-degenerate case}, i.e.\ when $\Delta\cap\Delta_x$ is not an artinian scheme. 
\end{remark}

We note that the left-hand sides of the identities in Conjecture \ref{AFLconj} are constant on the orbit of $\gamma$ under $H_{1,2}'(F_0)$, resp.~$\gamma$ under $H'(F_0)$, resp.~$y$ under $H'(F_0)$.  Similarly, the right-hand sides of these identities are constant on the orbit of $g$ under $H_{W_1}(F_0)$, resp.~$g$ under $H_1(F_0)$, resp.~$x$ under $H_1(F_0)$, cf.~\cite[Rems.~4.3, 4.4, 4.6]{PRS}. Hence Conjecture \ref{AFLconj} ``makes sense'' in the sense that it does not depend on the choice of matching elements.
 
Our aim in Parts \ref{spaces} and \ref{conjectures} of the paper is to formulate variants of Conjecture \ref{AFLconj} which apply to cases where the various unramifiedness hypotheses in Conjecture \ref{AFLconj} are dropped. As explained in the Introduction, we still want to have identities like in the AFL, but the function on $G'(F_0)$ transferring to $(\mathbf{1}_{K_0^\flat\times {K}_0}, 0)$ on $G_{W_0}(F_0)\times G_{W_1}(F_0)$ (and analogously in the inhomogeneous and Lie algebra settings) will not be explicit anymore. Rather, the statement of the ATC will be that some choice of function may be found which transfers to $(\mathbf{1}_{K_0^\flat\times {K}_0}, 0)$ on $G_{W_0}(F_0)\times G_{W_1}(F_0)$, and which also satisfies a suitable analog of the AFL identity (and again analogously in the inhomogeneous and Lie algebra settings).   
\begin{remark}\label{pi-modular unram}
A first natural variant of the moduli problem defining $\CN_n$ (still with $n \geq 1$ and $F/F_0$ unramified) is to consider quadruples $(X,\iota,\lambda,\rho)$ exactly as above, except where the polarization $\lambda$ satisfies $\ker \lambda = X[\iota(\varpi)]$.  The resulting moduli space yields nothing new, however: there is an isomorphism from $\CN_n$ to it defined by $(X,\iota,\lambda,\rho) \mapsto (X,\iota,\varpi\lambda, \rho)$.
\end{remark}


 
 
 
 
 
 
 
 
\part{Some regular formal moduli spaces}\label{spaces}

In this part of the paper we define variants of the formal moduli space $\CN_n$ that appeared in the AFL conjecture.  In the various AT conjectures which we formulate in Part \ref{conjectures}, the right-hand side will involve an intersection number of cycles in a product of such moduli spaces.  Therefore we are looking for analogs of $\Delta_\CN$ where the target is a \emph{regular} formal scheme.  We do not know of a systematic method of finding such variants.  In the following sections we present the examples we have found.




 
\section{Unramified almost self-dual type}\label{unram non-max}

In this section we continue with the notation of \S\ref{s:AFL}. In particular, $F/F_0$ is an unramified extension. For any $n \geq 2$, we now define a variant $\wt\CN_n$ of the formal scheme $\CN_n$ over $\Spf O_{\breve F} = \Spf O_{\breve F_0}$.  This variant parametrizes isomorphism classes of quadruples $(X, \iota, \lambda, \rho)$ as in the case of $\CN_n$, except that instead of requiring the polarization $\lambda$ to be principal, we impose that
\begin{equation}\label{polarization cond almost varpi-modular}
   \ker \lambda \subset X[\iota(\varpi)]\ \text{\emph{is of rank $q^2$.}}
\end{equation}
Mimicking \cite[\S1]{V2}, one sees that as in the case of $\CN_n$, up to quasi-isogeny there is a unique supersingular triple $(\smash{\wt\BX_n}, \iota_{\wt\BX_n}, \lambda_{\wt\BX_n})$ for this moduli problem over $\ov k$.
To fix a particular choice, first let
\begin{equation}\label{ovBE'}
   \ov\BE' := \ov\BE,
	\quad
	\iota_{\ov\BE'} := \iota_{\ov\BE},
	\quad\text{and}\quad
	\lambda_{\ov\BE'} := \varpi\lambda_{\ov\BE}.
\end{equation}
Then we set
\begin{equation}\label{wtBX_n unram}
   \wt\BX_n := \BX_{n-1} \times \ov\BE',
	\quad
	\iota_{\wt\BX_n} := \iota_{\BX_{n-1}} \times \iota_{\ov\BE'},
	\quad\text{and}\quad
	\lambda_{\wt\BX_n} := \lambda_{\BX_{n-1}} \times \lambda_{\ov\BE'},
\end{equation}
where $\BX_{n-1}$ is the framing object for $\CN_{n-1}$ in \eqref{BX_n unram}.  We then take the target of the framing $\rho$ to be the constant object over the special fiber obtained from $(\smash{\wt\BX_n}, \iota_{\wt\BX_n}, \lambda_{\wt\BX_n})$.

To describe the basic structure of $\wt\CN_n$, we will give an analog of Theorem \ref{structN}\eqref{structN i}.  For both the statement and proof we will need the \emph{local model} for $\wt\CN_n$, cf.\ \cite{PRS,RZ}, whose definition we first recall; this is similar to (an instance of) Definition \ref{LM def} below. Endow $F^n$ with the (non-split) $F/F_0$-hermitian form $h$ given by the matrix $\diag(\varpi,1,\dotsc,1)$.  Fix an element $\delta \in O_F^\times$ satisfying $\ov \delta = -\delta$, and define the alternating $F_0$-bilinear form on $F^n$,
\[
   \la x,y \ra = \frac 1 2 \tr_{F/F_0}\bigl(\delta h(x,y)\bigr), \quad x,y \in F^n.
\]
Define the $O_F$-lattices in $F^n$,
\[
   \Lambda_0 := O_F^n
	\quad\text{and}\quad
	\Lambda_1 := \varpi\i O_F \oplus O_F^{n-1}.
\]
Then $\Lambda_1$ is the dual lattice of $\Lambda_0$ with respect to both $h$ and \aform.  The \emph{local model} $\wt N_n$ is the scheme over $\Spec O_F$ representing the functor that associates to each $O_F$-scheme $S$ the set of all pairs $(\CF_0,\CF_1)$ such that
\begin{altitemize}
\item for each $i = 0,1$, $\CF_i$ is an $O_F \otimes_{O_{F_0}} \CO_S$-subsheaf of $\Lambda_i \otimes_{O_{F_0}} \CO_S$ which Zariski-locally on $S$ is an $\CO_S$-direct summand of rank $n$; 
\item the natural maps $\Lambda_0 \otimes_{O_{F_0}} \CO_S \to \Lambda_1 \otimes_{O_{F_0}} \CO_S$ and $\smash[t]{\Lambda_1 \otimes_{O_{F_0}} \CO_S \xra{\varpi \otimes \id} \Lambda_0 \otimes_{O_{F_0}} \CO_S}$ carry $\CF_0$ into $\CF_1$ and $\CF_1$ into $\CF_0$, respectively; 
\item $\CF_0^\perp = \CF_1$ with respect to the natural perfect pairing $(\Lambda_0 \otimes_{O_{F_0}} \CO_S) \times (\Lambda_1 \otimes_{O_{F_0}} \CO_S) \to \CO_S$ induced by \aform; and 
\item the Kottwitz condition of signature $(n-1,1)$
\[
   \charac(a \otimes 1 \mid \CF_i) = (T - a)^{n-1} (T - \ov a) \in \CO_S[T]
	\quad\text{for all}\quad
	a \in O_F,\quad i = 0,1
\]
is satisfied.
\end{altitemize}
Note that for any point $(X,\iota,\lambda,\rho)$ on $\wt\CN_n$, there is a unique isogeny $\lambda'$ such that the composite $X \xra\lambda X^\vee \xra{\lambda'} X$ is $\iota(\varpi)$. It follows easily from this that the base change $(\wt N_n)_{\Spf O_{\breve F}}$ identifies with the local model for $\wt\CN_n$ as in \cite[Ch.~3]{RZ}. The analog of Theorem \ref{structN}\eqref{structN i} for $\wt\CN_n$ is now as follows.

\begin{theorem}\label{wtCN_n semistable}
The formal scheme $\wt{\CN}_n$ is formally locally of finite type, separated, essentially proper, and of semi-stable reduction over $\Spf O_{\breve {F}}$, of relative formal dimension $n-1$. More precisely, the local model $\wt N_n$ has semi-stable reduction such that the special fiber is the union of two smooth schemes of dimension $n-1$ intersecting along a smooth scheme of dimension $n-2$. In particular, $\wt\CN_n$ is regular of formal dimension $n$, and the completed local ring at any closed point of $\wt\CN_n$ is isomorphic to either $O_{\breve F}[[X_1,\ldots, X_{n-1}]]$ or to $O_{\breve F}[[X_0, X_1,\ldots, X_{n-1}]]/(X_0 X_1-\varpi)$. 
\end{theorem}

\begin{proof}
The first three properties are general properties of RZ spaces (see \cite[Lem.\ 2.3.23]{F} for separatedness).  For the rest of the theorem, by the general formalism of RZ spaces (see \cite[Prop.~3.33]{RZ}), it suffices to prove the claim for the local model.  Since $F/F_0$ is unramified and $S$ is an $O_F$-scheme, we have the standard isomorphism
\begin{equation*}
	\xymatrix@R=0ex{
      O_F \otimes_{O_{F_0}} \CO_S \ar[r]^-\sim  &  \CO_S \times \CO_S\\
		a \otimes b \ar@{|->}[r]  &  (ab, \ov a b).
	}
\end{equation*}
Correspondingly, for any $S$-point $(\CF_0,\CF_1)$ on $\wt N_n$, there are decompositions
\[
   \CF_i = \CF_i' \oplus \CF_i'' \subset \Lambda_i \otimes_{O_{F_0}} \CO_S = (\Lambda_i \otimes_{O_{F_0}} \CO_S)' \oplus (\Lambda_i \otimes_{O_{F_0}} \CO_S)'',
	\quad
	i = 0,1,
\]
where $\CO_S \times \CO_S$ acts via its first factor on the primed sheaves, and via its second factor on the double-primed sheaves.
By the Kottwitz condition, $\CF_i' \subset (\Lambda_i \otimes_{O_{F_0}} \CO_S)'$ is an $\CO_S$-locally direct summand of rank $n-1$. By the perpendicularity condition, $\CF_0'$ and $\CF_1'$ determine $\CF_1''$ and $\CF_0''$, respectively.  It follows that the map $(\CF_i)_{i=0,1} \mapsto (\CF_i' \subset (\Lambda_i \otimes_{O_{F_0}} \CO_S)')_{i=0,1}$ is an isomorphism from $\wt N_n$ to the standard local model over $\Spec O_F$ in \cite{Goertz} for the group $\GL_n$, the cocharacter $\mu = (1^{(n-1)},0)$, and the periodic lattice chain determined by the (adjacent) lattices $(\Lambda_0 \otimes_{O_{F_0}} O_F)' \subset (\Lambda_1 \otimes_{O_{F_0}} O_F)'$.  By \S4.4.5 in loc.~cit.~(in the case $\kappa = 1$ and $r = n-1$) this latter scheme has semi-stable reduction of the asserted form.
\end{proof}

Now define 
\begin{equation*}
   \wt{\CN}_{n-1, n} := \CN_{n-1}\times_{\Spf O_{\breve {F}}}\wt{\CN}_n.
\end{equation*}
Since $\wt{\CN}_n$ only occurs here as the ``bigger'' formal scheme, we won't need to know an analog of Theorem \ref{structN}\eqref{structN ii} for the structure of $(\wt{\CN}_n)_\red$. 

\begin{corollary}
The formal scheme $\wt{\CN}_{n-1, n}$ is regular of formal dimension $2(n-1)$.  \qed
\end{corollary}

\begin{remark}[$n=2$]
For $n=2$, the formal scheme $\wt{\CN}_n$ is isomorphic to 
\begin{equation}\label{excDrin}
   \wt\CN_2 \simeq \wh\Omega^2_{F_0}\times_{\Spf O_{F_0}}\Spf O_{\breve {F}} ,
\end{equation} cf.~\cite{KR-alt}.  Here $\wh\Omega^2_{F_0}$ denotes the formal scheme version of the Drinfeld halfspace corresponding to the local field $F_0$.
\end{remark}

\begin{remark}[$n=1$]
For $n = 1$, the definition of $\wt\CN_1$ still makes sense, but the result is trivial: this space is just $\Spf O_{\breve F}$ itself, with universal object $(\CE,\iota_\CE,\varpi \lambda_\CE,\rho_\CE)$.
\end{remark}

\begin{remark}\label{almost pi-modular unram}
Let us consider the variant of the moduli problem for $\wt\CN_n$ where the condition on the polarization $\lambda$ is replaced by
\[
   \ker\lambda \subset X[\iota(\varpi)] \text{ \emph{is of rank} } q^{2(n-1)}.
\]
Then, in analogy with Remark \ref{pi-modular unram}, the resulting moduli space is isomorphic to $\wt\CN_n$.  Indeed, given a point $(X,\iota,\lambda,\rho)$ on $\CN_n$, let $O_F$ act on $X^\vee$ via the rule $\ov\iota^\vee\colon a \mapsto \iota(\ov a)^\vee$.  Then $\lambda$ is $O_F$-linear.  Since $\ker\lambda \subset X[\iota(\varpi)]$, there exists a unique (automatically $O_F$-linear) isogeny $\lambda'\colon X^\vee \to X$ such that $\lambda'\circ\lambda = \iota(\varpi)$.  Since $F/F_0$ is unramified and $\lambda$ is a polarization, so is $\lambda'$.  Furthermore, since $\ker\lambda \subset X[\iota(\varpi)]$ of rank $q^2$, we have $\ker\lambda' \subset X^\vee[\ov\iota^\vee(\varpi)]$ of rank $q^{2(n-1)}$.  In this way we obtain a morphism $(X,\iota,\lambda,\rho) \mapsto (X^\vee,\ov\iota^\vee,\lambda',(\rho^\vee)\i)$ from $\wt\CN_n$ to the variant moduli space we have just defined, and it is easy to see that this is an isomorphism.
\end{remark}





\section{Ramified, even, $\pi$-modular type}\label{even ram max}

In this and the next three sections we define analogs of $\CN_n$ (and of $\wt\CN_n$) when the quadratic extension $F/F_0$ is ramified, beginning in this section with the case that $n \geq 2$ is even.  Recall that $F/F_0$ is implicit in the definition of $\CN_n$ in \S\ref{s:AFL}. Therefore we may recycle the notation $\CN_n=\CN_{n, {F}/{F_0}}$ in the present situation. We define $\CN_n$ to be the formal scheme over $\Spf O_{\breve {F}}$ that parametrizes isomorphism classes of quadruples $(X, \iota, \lambda, \rho)$ as in \S\ref{s:AFL}, except that instead of requiring the polarization $\lambda$ to be principal, we impose that it is \emph{$\pi$-modular}, i.e.
\begin{equation*}
   \ker \lambda =X[\iota(\pi)] . 
\end{equation*}
We furthermore require that $\iota$ satisfies the \emph{wedge condition}
\begin{equation}\label{wedge condition}
	\sidewedge{^2} \bigl(\iota(\pi)+\pi \mid \Lie X\bigr) = 0
\end{equation}
and the \emph{spin condition}
\begin{equation}\label{spin condition}
   \text{\emph{the endomorphism $\iota(\pi)\mid \Lie X$ is nowhere zero,}}
\end{equation}
i.e.~$\iota(\pi)$ is a nonzero operator on $\Lie X\otimes\kappa(s)$ for all points $s$ of the base scheme $S$.
Since $S$ is a $\Spf O_{\breve {F}}$-scheme, $\pi\cdot \kappa(s) = 0$ for all $s$. Therefore, in the presence of the wedge condition, the spin condition says that  $\iota(\pi) \mid \Lie X\otimes\kappa(s)$ has rank $1$ for all $s$. Note that this is a purely pointwise condition on $S$, i.e.~it holds if and only if it holds after base change to $S_\red$.  As before, up to quasi-isogeny there is a unique supersingular framing object $(\BX_n, \iota_{\BX_n}, \lambda_{\BX_n})$ over $\ov k$, which follows in the case of this moduli problem from Prop.~3.1 and its proof in \cite{RSZ}.   The last entry $\rho$ in the quadruple above is a framing to the constant object over $\ov S$ defined by $(\BX_n, \iota_{\BX_n}, \lambda_{\BX_n})$, as before.

\begin{remark}
It is not necessary to explicitly make the Kottwitz condition \eqref{kottwitzcond} part of the definition of $\CN_n$.  Indeed, let $\varphi$ denote the operator $\iota(\pi) + \pi$ acting on $\Lie X$.  Then conditions \eqref{wedge condition} and \eqref{spin condition} imply that $\im \varphi$ is a locally direct summand of $\Lie X$ of $\CO_S$-rank $1$.  Hence $\ker \varphi$ is a locally direct summand of rank $n-1$.  Since $\iota(\pi)$ visibly acts as multiplication by $\pi$ on $\im \varphi$ and by $-\pi$ on $\ker\varphi$, it follows that $X$ satisfies the Kottwitz condition.
\end{remark}

For use later in the paper we fix essentially the same explicit choice of framing object as in \cite[\S3.3]{RSZ}.  When $n = 2$, we take
\[
   \BX_2 := \BE \times \BE
\]
as a formal $O_{F_0}$-module, and we define $\iota_{\BX_2}$ by
\[
   \iota_{\BX_2}(a + b\pi) :=
	\begin{bmatrix}
		a  &  b\varpi\\
		b  &  a
	\end{bmatrix},
	\quad
	a,b \in O_{F_0}.
\]
(This identifies $\BX_2$ with the Serre tensor construction $O_F \otimes_{O_{F_0}} \BE$.)  For the polarization, for technical convenience later in the paper we take a rescaled version of the one in loc.\ cit.,
\begin{equation}\label{lambda_BX_2}
   \lambda_{\BX_2} :=
	\begin{bmatrix}
		-2\lambda_\BE\\
		  &  2\varpi \lambda_\BE
	\end{bmatrix}.
\end{equation}
We then take
\begin{align*}
   \BX_n &:= \BX_2 \times \ov\BE^{n-2},\\
   \iota_{\BX_n} &:= \iota_{\BX_2} \times \iota_{\ov\BE}^{n-2},\\
   \lambda_{\BX_n} &:= \lambda_{\BX_2} \times 
      \diag \biggl(
	     \underbrace{\begin{bmatrix} 
	           0  &  \lambda_{\ov\BE}\, \iota_{\ov\BE}(\pi)\\
	           -\lambda_{\ov\BE}\, \iota_{\ov\BE}(\pi)  &  0
			\end{bmatrix}
			,\dotsc,
			\begin{bmatrix} 
	           0  &  \lambda_{\ov\BE}\, \iota_{\ov\BE}(\pi)\\
	           -\lambda_{\ov\BE}\, \iota_{\ov\BE}(\pi)  &  0
			\end{bmatrix}}_{(n-2)/2 \text{ times}}\biggr).
\end{align*}

\begin{remark}
By \cite[Lem.~3.5]{RSZ}, the associated $F/F_0$-hermitian space $\BV(\BX_n)$ defined in \eqref{defV} is the non-split space of dimension $n$.  (Note that, since the polarization \eqref{lambda_BX_2} is a scalar multiple of the one considered in loc.\ cit.\ when $n = 2$, the splitness of the hermitian spaces is the same.)
\end{remark}

Unfortunately, we know less about the structure of $\CN_n$ than in the unramified case, but at least the analog of Theorem \ref{structN}\eqref{structN i} is known.

\begin{theorem}[Exotic smoothness {\cite[Prop.~3.8]{RSZ}}]\label{exotsmeven}
Recall that $n$ is even. The formal scheme $\CN_n$ is formally locally of finite type, separated, essentially proper, and formally smooth of relative formal dimension $n-1$ over $\Spf O_{\breve {F}}$. In particular, $\CN_n$ is regular of formal dimension $n$.  \qed
\end{theorem}

The analog of Theorem \ref{structN}\eqref{structN ii} is only known for low values of $n$.  To give the precise formulation, we first need to explain a natural decomposition of $\CN_n$ that occurs in the even ramified setting.  Let
\[
   \BM
	\quad\text{and}\quad
	\BN := \BM \otimes_{O_{\breve F_0}} \breve F_0
\]
denote the covariant relative Dieudonn\'e module and rational Dieudonn\'e module, respectively, of $\BX_n$.  The action $\iota_{\BX_n}$ makes $\BM$ into an $O_F \otimes_{O_{F_0}} O_{\breve F_0} = O_{\breve F}$-module. The polarization $\lambda_{\BX_n}$ induces a nondegenerate alternating $\breve F_0$-bilinear form \aform on $\BN$ satisfying
\[
   \la ax,y \ra = \la x, \ov a y \ra
	\quad\text{for all}\quad
	x,y \in \BN,\ a \in \breve F.
\]
The form
\begin{equation*}
   h(x,y) := \la \pi x, y \ra + \la x,y \ra\pi,
	\quad
	x,y \in \BN,
\end{equation*}
then makes $\BN$ into an $\breve F/\breve F_0$-hermitian space of dimension $n$.  By Dieudonn\'e theory, for a perfect field extension $K$ of $\ov k$, the set of $K$-points on $\CN_n$ identifies with a certain subset $\CS$ of $O_{\breve F} \otimes_{O_{\breve F_0}} W(K)$-lattices $M \subset \BN \otimes_{O_{\breve F_0}} W(K)$, all of which are $\pi$-modular, i.e.\ $M^\vee = \pi^{-1}M$, where $M^\vee$ denotes the common dual lattice with respect to $h$ and \aform.
For a lattice $M \in \CS$, let us say that the corresponding $K$-point on $\CN_n$ lies in $\CN_n^+$ or $\CN_n^-$ according as the $O_{\breve F} \otimes_{O_{\breve F_0}} W(K)$-length of the module
\begin{equation}\label{parity test lattice}
   \bigl(M + \BM \otimes_{O_{\breve F_0}} W(K)\bigr) \big/ \BM \otimes_{O_{\breve F_0}} W(K)
\end{equation}
is even or odd.  The parity of this length may also be described as follows.  Since the $\pi$-modular lattices in a hermitian space are all conjugate under the unitary group, and since $\BM \otimes_{O_{\breve F_0}} W(K)$ is itself $\pi$-modular in $\BN \otimes_{O_{\breve F_0}} W(K)$, there exists an element $g \in \U(\BN)(\breve F_0 \otimes_{O_{\breve F_0}} W(K))$ such that $g\cdot (\BM \otimes_{O_{\breve F_0}} W(K)) = M$.  The determinant $\det g$ is a norm one element in $\breve F \otimes_{O_{\breve F_0}} W(K)$, and hence lies in $O_{\breve F} \otimes_{O_{\breve F_0}} W(K)$ with reduction mod $\pi$ equal to $\pm 1 \in K$.  Then the length of \eqref{parity test lattice} is even or odd according as this reduction is $1$ or $-1$ (independent of the choice of $g$) by \cite[Lem.~3.2]{RSZ}.

\begin{proposition}\label{even n decomp lem}
$\CN_n^+$ and $\CN_n^-$ define a decomposition
\[
   \CN_n = \CN_n^+ \amalg \CN_n^-
\]
into open and closed formal subschemes.
\end{proposition}

\begin{proof}
We must show that the parity of the length of \eqref{parity test lattice} is a locally constant function on (perfect points of) the scheme $(\CN_n)_\red$.  Let $x \in (\CN_n)_\red$, and let
\[
   R := \varinjlim \bigl[\CO_{(\CN_n)_\red,x} \xra{\Frob} \CO_{(\CN_n)_\red,x} \xra{\Frob} \dotsb\bigr]
\]
be the direct perfection of the local ring $\CO_{(\CN_n)_\red,x}$ at $x$.  Since $(\CN_n)_\red$ is locally of finite type over $\Spec \ov k$, it suffices to show that the parity in question is constant on points of $\Spec R$ (which is homeomorphic to $\Spec \CO_{(\CN_n)_\red,x}$).  For this we apply Gabber's result, reproved by Lau in \cite[Th.~6.4]{Lau}, that the category of $p$-divisible groups over a perfect ring is equivalent to the category of Dieudonn\'e modules over the corresponding Witt vector ring.  Since $R$ is a perfect local ring, the rings
\[
   W := W(R) \quad\text{and}\quad W' := O_{\breve F} \otimes_{\breve F_0} W(R)
\]
are local and $\varpi$-torsion-free.  Thus to the tautological $R$-point $\Spec R \to \CN_n$ corresponds a $W'$-submodule
\[
   M \subset \BN \otimes_{O_{\breve F_0}} W
\]
which is free of rank $n$ and $\pi$-modular in the obvious sense, i.e.~the dual module
\[
   M^\vee := \bigl\{\, x \in \BN \otimes_{O_{\breve F_0}} W \bigm| h(x,M) \subset W' \,\bigr\}
\]
is equal to $\pi^{-1}M$ inside $\BN \otimes_{O_{\breve F_0}} W$.  

To proceed, we claim that the unitary group acts transitively on the $\pi$-modular submodules in $\BN \otimes_{O_{\breve F_0}} W$.  Indeed, this follows by the usual argument for hermitian spaces over complete, discretely valued fields; let us give a sketch.  It suffices to show that any $\pi$-modular $L$ admits a $W'$-basis with respect to which the hermitian form is $\bigl[\begin{smallmatrix} & -\pi\\ \pi \end{smallmatrix}\bigr] \oplus \dotsb \oplus \bigl[\begin{smallmatrix} & -\pi\\ \pi \end{smallmatrix}\bigr]$.  Let $e \in L$ be an element in a basis for $L$.  Since $L^\vee = \pi\i L$, there exists $f \in L$ such that $h(e,f) = \pi$; and furthermore $h(e,e), h(f,f) \in \pi W' \cap W = \varpi W$.  Say $h(e,e) = \varpi a$ for $a \in W$.  Then
\[
   h\biggl(e + \frac{\pi a}2 f, e + \frac{\pi a}2 f\biggr) = - \frac{\varpi a^2}4 h(f,f) \subset \varpi^2 W.
\]
Continuing by successive approximation, we reduce to the case that $e$ is isotropic. After adding an appropriate multiple of $\pi e$ to $f$, we may then assume that $f$ is isotropic too. Again since $L$ is $\pi$-modular, $h(e,L)$ and $h(f,L)$ are contained in $\pi W'$, and it follows that we can split $W'e + W'f$ off from $L$ as an orthogonal direct summand.  The claim now follows by induction.

By the claim, there exists $g \in \U(\BN)(W[\frac 1 \varpi])$ such that $g\cdot (\BM \otimes_{O_{\breve F_0}} W) = M$.  Since $\det g$ is a norm one element in $W'[\frac 1 \pi]$, we have $\det g \in W'$, and $a := \det g \bmod \pi$ is a square one element in $R$.  Since $R$ is a local ring of residue characteristic not $2$, it follows that $a = \pm 1$ in $R$. Since the parity of the length in question at each residue field of $R$ is determined by the image of $a$ in the residue field, the lemma follows.
\end{proof}

\begin{example}[$n = 2$]\label{CN_2}
Proposition \ref{even n decomp lem} generalizes \cite[Lem.~6.1]{RSZ}, which shows that $(\CN_2)_\red$ is a disjoint union of two points.  In fact, when $n = 2$, the space $\CN_2$ is already defined over $\Spf O_{\breve F_0}$ (the Kottwitz condition $\charac( \iota(\pi) \mid \Lie X ) = T^2- \varpi$ makes sense over $O_{\breve F_0}$, and after base change to $\Spf O_{\breve F}$ this implies the wedge condition \eqref{wedge condition}).  Let $(\CN_2)_{\Spf O_{\breve F_0}}$ denote this descended formal scheme. Then the decomposition in the lemma is induced by a decomposition
\[
   (\CN_2)_{\Spf O_{\breve F_0}} = (\CN_2)_{\Spf O_{\breve F_0}}^+ \amalg (\CN_2)_{\Spf O_{\breve F_0}}^-,
\]
and the summands on the right-hand side are both isomorphic to the universal deformation space $\CM$ of ``the'' formal $O_{F_0}$-module of relative height $2$ and dimension $1$ over $\ov k$; see \cite[Prop.~6.3]{RSZ}  (which remains valid over $\Spf O_{\breve F_0}$; here, in keeping with our definition of $\lambda_{\BX_2}$ as $-2$ times the polarization of the framing object defined in \cite{RSZ}, we also multiply the polarization in the definition of the isomorphism $\CM \isoarrow (\CN_2)_{\Spf O_{\breve F_0}}^+$ by $-2$). 
Note that when $F_0=\BQ_p$, the formal scheme $\CM$ can be identified with the completion of the moduli space of elliptic curves at a supersingular point.
\end{example}

Now let $\CN_n^\pm$ denote either of the formal subschemes $\CN_n^+$ and $\CN_n^-$.  The following analog of Theorem \ref{structN}\eqref{structN ii} has recently been proved by H. Wu.


\begin{theorem}[Wu \cite{Wu}]\label{stratification conj even n ram}
The reduced underlying scheme $(\CN_n^\pm)_\red$ has a Bruhat--Tits stratification by Deligne--Lusztig varieties of dimensions $0, 1,\dotsc, \frac{n}{2} -1$ attached to \emph{non-split} orthogonal groups in an  even number of variables and to Coxeter elements, with strata parametrized by the vertices of the Bruhat--Tits complex of $\SU(\BV(\BX_n))$.\qed
\end{theorem}

This result was previously shown to hold in the equal characteristic analog studied by G\"ortz--He \cite{Goertz-He}.

\begin{example}[$n = 4$]\label{CN_4 eg}
In the case of $\CN_4^\pm$, the description in \cite{Goertz-He} is that every irreducible component in $(\CN_4^\pm)_\red$ is a projective line containing $p^2 + 1$ special points, and every special point lies in the intersection of $p + 1$  projective lines.  The following figure illustrates the case $p = 3$.

\medskip
\begin{center}
\begin{tikzpicture}
   \draw (-7,0) .. controls (-3,-1) and (3,-1) .. (7,0)
	foreach \t in {0, ..., 9} {
	   pic [pos=0.05+0.1*\t, rotate=1.5*(-4.5+\t)] {code={
		   \draw (0,0) arc [radius = 4, start angle=10, end angle=25];
	      \draw (0,0) arc [radius = 4, start angle=10, end angle=-5];
      	\draw (0,0) arc [radius = 3, start angle=125, end angle=110];
	      \draw (0,0) arc [radius = 3, start angle=125, end angle=140];
			\draw (0,0) arc [radius = 5, start angle=160, end angle=150];
			\draw (0,0) arc [radius = 5, start angle=160, end angle=170];
		}}
	};
\end{tikzpicture}
\end{center}
\end{example}





\section{Ramified, odd, almost $\pi$-modular type}\label{odd ram max}

In this section we define the formal scheme $\CN_n$ over $\Spf O_{\breve F}$ when $F/F_0$ is ramified and $n \geq 1$ is odd.  We define $\CN_n$ to be the moduli space for quadruples $(X, \iota, \lambda, \rho)$ as before, with $\rho$ a framing into a fixed framing object, except this time we impose that the polarization $\lambda$ is \emph{almost $\pi$-modular}, i.e.
\begin{equation*}
   \ker \lambda \subset X[\iota(\pi)]\  \text{\emph{is of rank $q^{n-1}$}.} 
\end{equation*} 
We furthermore require that the triple $(X,\iota,\lambda)$ satisfies condition \eqref{odd spin cond} below; this condition is a little complicated to formulate and will require some preparation. (For the relationship of \eqref{odd spin cond} to the Kottwitz, wedge, and spin conditions introduced previously, see Remark \ref{odd N_n crit}.)  Since we will also need an analog of this condition in \S\ref{aux spaces} for even $n$, for the moment let $n$ be any positive integer. Let
\[
   m := \lfloor n/2 \rfloor.
\]
Let $e_1,\dotsc,e_n$ denote the standard basis in $F^n$, and let $h$ be the standard split $F/F_0$-hermitian form on $F^n$ with respect to this basis,
\begin{equation}\label{herm form}
   h(ae_i,be_j) := a \ov b \delta_{i,n+1-j} \quad\text{(Kronecker delta)}.
\end{equation}
Let \aform and \sform be the respective alternating and symmetric $O_{F_0}$-bilinear forms $F^n \times F^n \to F_0$ defined by
\begin{equation}\label{aform and sform}
   \langle x,y \rangle := \frac 1 2 \tr_{F/F_0} \bigl(\pi^{-1}h(x,y)\bigr)
   \quad\text{and}\quad
   (x,y) := \frac 1 2 \tr_{F/F_0}h(x,y).
\end{equation}
For $i = bn + c$ with $0 \leq c < n$, define the $O_F$-lattice
\[
   \Lambda_i := \sum_{j = 1}^c \pi^{-b-1}O_F e_j + \sum_{j = c+1}^n \pi^{-b} O_F e_j \subset F^n.
\]
For each $i$, the form \aform induces a perfect pairing
\[
   \Lambda_i \times \Lambda_{-i} \to O_{F_0}.
\]
In this way, for fixed nonempty $I \subset \{0,\dotsc,m\}$, the set
\[
   \Lambda_I := \{\, \Lambda_i \mid i \in \pm I + n\BZ \, \}
\]
forms a polarized chain of $O_F$-lattices over $O_{F_0}$ in the sense of \cite[Def.\  3.14]{RZ}.

Now define the $2n$-dimensional $F$-vector space
\begin{equation*}
   V := F^n \otimes_{F_0} F,
\end{equation*}
where $F$ acts on the right tensor factor.
The $n$th wedge power $\tensor*[^n] V {} := \bigwedge_F^n V$ admits a canonical decomposition
\begin{equation}\label{nV decomp}
   \tensor*[^n] V {} = 
      \bigoplus_{\substack{r+s = n\\\epsilon \in \{\pm1\}}} \tensor*[^n]{V}{_\epsilon^{r,s}}
\end{equation}
which is described in \cite[\S\S2.3, 2.5]{S}.%
%
\footnote{Here and below we replace the symbol $W$ used in loc.\ cit.\ with $\tensor*[^n] V{}$.}
%
Let us briefly review it.  The operator $\pi \otimes 1$ acts $F$-linearly on $V$ with eigenvalues $\pm \pi$; let
\[
   V = V_\pi \oplus V_{-\pi}.
\]
denote the corresponding eigenspace decomposition. For a partition $r + s = n$, define%
\footnote{Here and below we interchange $r$ and $s$ in the notation relative to \cite{S}.}
%
\[
   \tensor*[^n]V{^{r,s}} := \sideset{}{_F^r}\bigwedge V_\pi \otimes_F \sideset{}{_F^s}\bigwedge V_{-\pi},
\]
which is naturally a subspace of $\tensor*[^n] V{}$.  Furthermore, the symmetric form \sform splits after base change to $V$, and therefore there is a decomposition
\begin{equation}\label{^nV decomp}
   \tensor*[^n] V{} = \tensor*[^n] V{_1} \oplus \tensor*[^n] V{_{-1}}
\end{equation}
as an $\SO(\sform)(F)$-representation.  The subspaces $\tensor*[^n]V{_{\pm 1}}$ have the property that for any Lagrangian (i.e.~totally isotropic $n$-dimensional) subspace $\CF \subset V$, the line $\bigwedge_F^n \CF \subset \tensor*[^n] V{}$ is contained in one of them, and in this way they distinguish the two connected components of the orthogonal Grassmannian $\OGr(n,V)$ over $\Spec F$.  The subspaces $\tensor*[^n]V{_{\pm 1}}$ are canonical up to labeling, and we will follow the labeling conventions in loc.\ cit., to which we refer the reader for details.  The summands in the decomposition \eqref{nV decomp} are then given by
\[
   \tensor*[^n] V{_\epsilon^{r,s}} := \tensor*[^n] V{^{r,s}} \cap \tensor*[^n] V {_\epsilon}
\]
(intersection in $\tensor*[^n] V{}$) for $\epsilon \in \{\pm 1\}$.

Given an $O_F$-lattice $\Lambda \subset F^n$, now define
\[
   \tensor*[^n]\Lambda{} := \sideset{}{_{O_F}^n} \bigwedge (\Lambda \otimes_{O_{F_0}} O_F),
\]
which is naturally a lattice in $\tensor*[^n]V{}$.  For fixed $r$, $s$, and $\epsilon$, define
\begin{equation}\label{^nLambda_epsilon^r,s}
   \tensor*[^n]\Lambda{_{\epsilon}^{r,s}} := \tensor*[^n]\Lambda{}\cap \tensor*[^n] V{_\epsilon^{r,s}}
\end{equation}
(intersection in $\tensor*[^n] V{}$).  Then $\tensor*[^n]\Lambda{_{\epsilon}^{r,s}}$ is a direct summand of $\tensor*[^n]\Lambda{}$, since the quotient $\tensor*[^n]\Lambda{} / \tensor*[^n]\Lambda{_{\epsilon}^{r,s}}$ is torsion-free.  For an $O_F$-scheme $S$, define
\begin{equation}\label{L def}
   L_{i,\epsilon}^{r,s}(S) := 
	   \im \bigl[ \tensor*[^n]{(\Lambda_i)}{_{\epsilon}^{r,s}} \otimes_{O_F} \CO_S \rightarrow \tensor*[^n]\Lambda{_i} \otimes_{O_F} \CO_S \bigr].
\end{equation}
For nonempty $I \subset \{0,\dotsc,m\}$, let $\uAut(\Lambda_I)$ denote the scheme of automorphisms of the polarized $O_F$-lattice chain $\Lambda_I$ over $\Spec O_{F_0}$, in the sense of \cite[Th.~3.16]{RZ} or \cite[p.~581]{P} (this is denoted by $\CP$ in \cite{P}).

\begin{lemma}\label{L stability}
For any $O_F$-scheme $S$ and $\Lambda_i \in \Lambda_I$, the submodule $L_{i,\epsilon}^{r,s}(S) \subset \tensor*[^n]\Lambda{_i} \otimes_{O_F} \CO_S$ is stable under the natural action of $\uAut(\Lambda_I)(S)$ on $\tensor*[^n]\Lambda{_i} \otimes_{O_F} \CO_S$.
\end{lemma}

\begin{proof}
Let $C \subset \uAut(\Lambda_I)_{O_F}$ be the stabilizer of $L_{i,\epsilon}^{r,s}$,
\[
   C(S) := \bigl\{\, g \in \uAut(\Lambda_I)(S) \bigm| g \cdot L_{i,\epsilon}^{r,s}(S) = L_{i,\epsilon}^{r,s}(S) \,\bigr\}.
\]
Then $C$ is a closed subscheme of $\uAut(\Lambda_I)_{O_F}$.  Since $\uAut(\Lambda_I)_{F_0} \cong \U(h)$, it is obvious that $C$ contains the $F$-generic fiber $\uAut(\Lambda_I)_F$.  Therefore $C = \uAut(\Lambda_I)_{O_F}$, since $\uAut(\Lambda_I)_{O_F}$ is smooth, and hence flat, over $\Spec O_F$ by \cite[Th.\ 3.16]{RZ} and \cite[Th.\ 2.2(a)]{P}.
\end{proof}

This concludes our discussion for general $n$.  We now formulate our condition on the triple $(X,\iota,\lambda)$ over a $\Spf O_{\breve F}$-scheme $S$ in the case of odd $n$, which will make use of the above discussion in the case $I = \{m\}$. Let $M(X)$ and $M(X^\vee)$ denote the respective Lie algebras of the universal vector extensions of $X$ and $X^\vee$.  Since $\ker\lambda \subset X[\iota(\pi)]$, there is a unique (necessarily $O_F$-linear) isogeny $\lambda'$ such that the composite
\[
   X \xra{\lambda} X^\vee \xra{\lambda'} X
\]
is $\iota(\pi)$.  Since $\ker\lambda$ furthermore has rank $q^{n-1}$, the induced diagram
\[
   M(X) \xra{\lambda_*} M(X^\vee) \xra{\lambda'_*} M(X)
\]
extends periodically to a polarized chain of $O_F \otimes_{O_{F_0}} \CO_S$-modules of type $\Lambda_{\{m\}}$, in the terminology of \cite{RZ}.  By Theorem 3.16 in loc.\ cit., \'etale-locally on $S$ there exists an isomorphism of polarized chains
\begin{equation}\label{chain triv}
   [{}\dotsb \xra{\lambda'_*} M(X) \xra{\lambda_*} M(X^\vee) \xra{\lambda'_*} \dotsb{}] \isoarrow \Lambda_{\{m\}} \otimes_{O_{F_0}} \CO_S,
\end{equation}
which in particular gives an isomorphism of $O_F \otimes_{O_{F_0}} \CO_S$-modules
\begin{equation}\label{M(X) triv}
   M(X) \isoarrow \Lambda_{-m} \otimes_{O_{F_0}} \CO_S.
\end{equation}
The module $M(X)$ fits into the covariant Hodge filtration
\[
   0 \to \Fil^1 \to M(X) \to \Lie X \to 0
\]
for $X$, and the condition we finally impose is that
\begin{align*}
	&\text{\em upon identifying $\Fil^1$ with a submodule of $\Lambda_{-m} \otimes_{O_{F_0}} \CO_S$ via \eqref{M(X) triv}, the line bundle}\\
	\shortintertext{
	\begin{equation}\label{odd spin cond}
	   \sideset{}{_{\CO_S}^n}\bigwedge \Fil^1 \subset  \tensor[^n]\Lambda{_{-m}} \otimes_{O_F} \CO_S
	\end{equation}
	}
	&\text{\em is contained in $L_{-m,-1}^{n-1,1}(S)$.}
\end{align*}
Note that Lemma \ref{L stability} gives exactly what is needed to conclude that condition \eqref{odd spin cond} is independent of the choice of chain isomorphism in \eqref{chain triv}.

To complete the definition of $\CN_n$, it remains to specify a framing object $(\BX_n, \iota_{\BX_n}, \lambda_{\BX_n})$ for this moduli problem over $\ov k$. In contrast to the cases we have encountered previously, such a triple is \emph{not unique up to quasi-isogeny}. In fact, there are two isogeny classes (as always, up to $O_F$-linear quasi-isogeny compatible with the polarizations) such that $\BX_n$ is supersingular, corresponding to the two possible isometry classes of the hermitian space $C$ in the proof of \cite[Prop.~3.1]{RSZ}.\footnote{Note that the statement in loc.\ cit.\ considers quasi-isogenies which are compatible with the polarizations only up to scalar, whereas here we are requiring compatibility on the nose.}  As an explicit representative for which $\BV$ is non-split, we take the same framing object as in \cite{RSZ}.  Thus when $n = 1$ we define
\begin{equation}\label{BX_1}
   \BX_1^{(1)} := \BE,
	\quad
	\iota_{\BX_1^{(1)}} := \iota_\BE,
	\quad\text{and}\quad
	\lambda_{\BX_1^{(1)}} := -\lambda_\BE.
\end{equation}
Then $\BV(\BX_1^{(1)}) = \Hom_{O_F}^\circ(\ov\BE,\BE)$ is the $-1$-eigenspace $D^-$ for the conjugation action by $\iota_\BE(\pi)$ in $D$, endowed with the hermitian norm $(x,x) = -\RN x$, which is indeed non-split.  When $n \geq 3$, we take 
\begin{equation}\label{BX_n odd}
   \BX_n^{(1)} := \BX_{n-1} \times \ov \BE,
	\quad
	\iota_{\BX_n^{(1)}} := \iota_{\BX_{n-1}} \times \iota_{\ov\BE},
	\quad\text{and}\quad
	\lambda_{\BX_n^{(1)}} := \lambda_{\BX_{n-1}} \times \lambda_{\ov\BE};
\end{equation}
here $n-1$ is even and $\BX_{n-1}$ is as defined in \S\ref{even ram max}.  Then by \eqref{chi decomp formula} and the fact that $\BV(\BX_{n-1})$ is the non-split hermitian space of dimension $n-1$, $\BV(\BX_n^{(1)})$ is indeed the non-split space of dimension $n$.  To fix a framing object in the other isogeny class, for all $n$ we simply multiply the polarization of $\BX_n^{(1)}$ by a non-norm unit, i.e.~we fix $\ep\in O_{F_0}^\times\smallsetminus \RN F^\times$ and define
\begin{equation}\label{BX_n^{(0)}}
   \BX_n^{(0)} := \BX_n^{(1)},
	\quad
	\iota_{\BX_n^{(0)}} := \iota_{\BX_n^{(1)}},
	\quad\text{and}\quad
	\lambda_{\BX_n^{(0)}} := \ep\lambda_{\BX_n^{(1)}}.
\end{equation}
Then, since $n$ is odd and $\ep \notin \RN F^\times$, $\BV(\BX_n^{(0)})$ is the split hermitian space of dimension $n$.  Note that such an $\ep$ exists since $F/F_0$ is ramified.

Taking $\BX_n^{(0)}$ and $\BX_n^{(1)}$ as the framing objects, we obtain respective moduli spaces  $\CN_n^{(0)}$ and $\CN_n^{(1)}$. However, these spaces are isomorphic via the map
\[
   \xymatrix@R=0ex{
	   \CN_n^{(1)} \ar[r]^-\sim  &  \CN_n^{(0)}\\
		(X, \iota, \lambda, \rho) \ar@{|->}[r]  &  \bigl(X, \iota, \lambda\circ\iota(\ep), \rho\bigr).
	}
\]
To simplify notation in the rest of the paper, from now on we set
\[
   \CN_n := \CN_n^{(1)}
	\quad\text{and}\quad
	\BX_n := \BX_n^{(1)}.
\]

\begin{example}[$n=1$]\label{CN_1}
When $n = 1$, the moduli problem for $\CN_1$ is just the moduli problem of lifting $\BE$ as a formal $O_F$-module.  Thus the solution is $\CN_1 = \Spf O_{\breve F}$, with universal object the canonical lift $(\CE, \iota_\CE, -\lambda_\CE, \rho_\CE)$.  (In this case condition \eqref{odd spin cond} is redundant in the moduli problem.)
\end{example}

\begin{remark}\label{odd N_n crit}
Note that the Kottwitz condition \eqref{kottwitzcond}, the wedge condition \eqref{wedge condition}, and the spin condition \eqref{spin condition} all continue to make sense as written in the odd ramified setting.  The first two of these conditions are implied by condition \eqref{odd spin cond}, cf.~\cite[Lem.~5.1.2, Rem.~5.2.2]{S} (which shows that these implications hold on the local model\footnote{Strictly speaking, loc.~cit.~shows these these implications hold in the case of signature opposite to ours, but up to isomorphism the local model is the same, cf.~\cite[p.~19\ fn.~5]{RSZ}. The same remark applies to essentially all of the subsequent references we make to the local models in \cite{A}, \cite{PR}, \cite[\S2.6]{PRS}, and \cite{S}.}).  On the other hand, let $\CN_n^\circ$ be the moduli space of quadruples $(X,\iota,\lambda,\rho)$ as in the definition of $\CN_n$, except that instead of imposing condition \eqref{odd spin cond}, we impose conditions \eqref{wedge condition} and \eqref{spin condition}.  Then \eqref{wedge condition} and \eqref{spin condition} imply condition \eqref{odd spin cond}, and in this way $\CN_n^\circ$ is an open formal subscheme of $\CN_n$.  Indeed, this statement follows from the analogous statement for the corresponding local models, which is explained in \cite[\S3.3]{S}.   (More precisely, loc.~cit.~shows that the local model for $\CN_n^\circ$ is the complement of the ``worst point'' in the local model for $\CN_n$.)  We note that when $n \geq 3$, the framing objects $\BX_n^{(1)}$ and $\BX_n^{(0)}$ obviously satisfy \eqref{wedge condition} and \eqref{spin condition} (because $\BX_{n-1}$ does), and therefore they indeed satisfy \eqref{odd spin cond}; and it is trivial to check directly that $\BX_1^{(1)}$ and $\BX_1^{(0)}$ satisfy \eqref{odd spin cond} when $n=1$. We further note that \cite{RSZ} uses the notation $\CN_n$ for our $\CN_n^\circ$, and our $\CN_n$ is the ``better'' formal scheme alluded to in Rem.~3.13 of loc.~cit.
\end{remark}

\begin{remark}
There is a natural analog of condition \eqref{odd spin cond} on $\CN_n$ when $n$ is even (still with $F/F_0$ ramified).  However this analog is automatically satisfied on the whole space, which follows from the fact that this condition is automatically satisfied in the generic fiber of the local model for $\CN_n$, and this local model is already flat (in fact smooth).
\end{remark}

As when $n$ is even, we know less about the structure of $\CN_n$ than in the unramified case, but at least we have the analog of Theorem \ref{structN}\eqref{structN i}. 

\begin{theorem}[Exotic smoothness]\label{exotsmodd} Recall that $n$ is odd. 
The formal scheme $\CN_n$ is formally locally of finite type, separated, essentially proper, and formally smooth of relative formal dimension $n-1$ over $\Spf O_{\breve {F}}$. In particular, $\CN_n$ is regular of dimension $n$.  
\end{theorem}

\begin{proof}
This is proved in the same way as \cite[Prop.~3.8]{RSZ}, using that the local model for $\CN_n$ is a closed subscheme of the ``naive'' local model, and is furthermore smooth by Richarz's result \cite[Prop.~4.6]{A} and \cite[Th.\ 1.4]{S}.  (Note that \cite[Prop.~3.8]{RSZ} proves that $\CN_n^\circ$ satisfies all the conclusions of this theorem except essential properness.)
\end{proof}

The analog of Theorem \ref{structN}\eqref{structN ii} has again been recently proved by Wu, and was previously known to hold in the equal characteristic analog \cite{Goertz-He}.

\begin{theorem}[Wu \cite{Wu}]\label{BT conj odd n ram}
The reduced underlying scheme $(\CN_n)_\red$ has a Bruhat--Tits stratification by Deligne--Lusztig varieties of dimensions $0, 1,\ldots, \frac{n-1}{2}$ attached to orthogonal groups in an  odd number of variables and to Coxeter elements, with strata  parametrized by the vertices of the Bruhat--Tits complex of $\SU(\BV(\BX_n^{(1)}))$.\qed
\end{theorem}

\begin{example}[$n=3$]
In the case $n=3$, as in Example \ref{CN_4 eg}, there are strata of dimensions $0$ and $1$ in $(\CN_3)_\red$. Every irreducible component is a projective line containing $p + 1$ special points, and every special point lies in the intersection of $p + 1$ projective lines.  The following figure illustrates the case $p = 3$.

\medskip
\begin{center}
\begin{tikzpicture}
   \draw (-4,0) .. controls (-2,-0.75) and (2,-0.75) .. (4,0)
	foreach \t in {0, ..., 3} {
	   pic [pos=0.125+0.25*\t, rotate=3*(-1.5+\t)] {code={ 
		   \draw (0,0) arc [radius = 4, start angle=10, end angle=25];
	      \draw (0,0) arc [radius = 4, start angle=10, end angle=-5];
      	\draw (0,0) arc [radius = 3, start angle=125, end angle=110];
	      \draw (0,0) arc [radius = 3, start angle=125, end angle=140];
			\draw (0,0) arc [radius = 5, start angle=160, end angle=150];
			\draw (0,0) arc [radius = 5, start angle=160, end angle=170];
		}}
	};
\end{tikzpicture}
\end{center}
\end{example}
 
Taking Theorems \ref{exotsmeven} and \ref{exotsmodd} together, we obtain the following corollary. For arbitrary $n \geq 2$, define
\begin{equation*}
   \CN_{n-1, n} := \CN_{n-1}\times_{\Spf O_{\breve {F}}}\CN_n .
\end{equation*}

\begin{corollary} For arbitrary $n$, the formal scheme $\CN_{n-1, n}$ is regular of formal dimension $2(n-1)$.  \qed
\end{corollary}

\begin{remark}\label{self-dual special parahoric}
For $n$ even or odd, the space $\CN_n$ is an (open and closed formal subscheme of an) RZ space with ``special maximal parahoric level structure'' in the sense that, in the notation of \cite[\S1.38, Def.~3.18]{RZ}, it arises from a PEL datum with $B = F$, $V = F^n$, $\sform = \aform$, $b^* = \ov b$, $G = \GU(h)$, and $\CL = \Lambda_{\{m\}}$; and the stabilizer of the lattice chain $\Lambda_{\{m\}}$ in $\GU(h)(F_0)$ is a special maximal parahoric subgroup.  For $F/F_0$ ramified, up to conjugacy there is one further case of a special maximal parahoric subgroup in $\GU(h)(F_0)$, namely the stabilizer of a self-dual lattice in $F^n$ when $n$ is odd \cite[\S1.2.3]{PR}.  The corresponding RZ space, in which the polarization $\lambda$ in the moduli problem is \emph{principal} (still with Kottwitz condition \eqref{kottwitzcond} of signature $(1,n-1)$), is studied for $n$ both even and odd in \cite{RTW}.  This space is not regular for $n \geq 3$, and therefore it does not appear to fit into the framework of this paper.  The case $n = 2$ is exceptional,\footnote{Exceptional in three ways: in this case the space is defined over $\Spf O_{\breve F_0}$ instead of $\Spf O_{\breve F}$; it is regular; and the corresponding parahoric subgroup of $\GU(h)(F_0)$ is not a maximal parahoric subgroup, but an Iwahori subgroup, cf.\ \cite[Rem.~2.35]{PRS}.} however, and we now turn to it
in the next section.
\end{remark}







\section{Ramified self-dual type, $n = 2$}\label{ram self-dual n=2}

In this section, continuing from Remark \ref{self-dual special parahoric}, we consider the formal moduli space of \cite{RTW} in the special case $n = 2$, still with $F/F_0$ ramified; see also \cite{KR-alt}.  This is a moduli space for quadruples $(X, \iota, \lambda, \rho)$ as before, with $(X,\iota)$ satisfying the Kottwitz condition
\begin{equation}\label{Kottwitz cond n=2}
   \charac\bigl( \iota(\pi) \mid \Lie X\bigr) = T^2- \varpi,
\end{equation}
and where this time the polarization $\lambda$ is principal.  As in the previous section in the case of odd $n$ (and via the same argument), there are \emph{two} isogeny classes of supersingular framing objects over $\ov k$.  
Accordingly we obtain two moduli spaces, both defined over $\Spf O_{\breve F_0}$, which we denote by $\wt\CN_2^{(0)}$ and $\wt\CN_2^{(1)}$ according as the hermitian space \eqref{defV} of the framing object is split or non-split. These two spaces really are different, in contrast to the case of $\CN_n^{(0)}$ and $\CN_n^{(1)}$ in the previous section. In fact, we can describe both of these spaces explicitly.

\begin{altenumerate}
\item
For the formal scheme $\wt\CN_2^{(0)}$, there is a natural isomorphism
\begin{equation}\label{ramified Drinfeld isom}
   \wt\CN_2^{(0)}\cong \wh\Omega^2_{F_0}\times_{\Spf O_{F_0}}\Spf O_{\breve F_0}
\end{equation} 
which is equivariant for the respective actions of $\SU(\wt\BX_2^{(0)}) \cong \SL_2(F_0)$ on both sides.
This is the alternative description of the Drinfeld half-plane in  \cite{KR-alt}. 
\item\label{Gamma_0(varpi) isom}
For the formal scheme $\wt\CN_2^{(1)}$, there is an isomorphism
\begin{equation*}
   \wt\CN_2^{(1)}\simeq \Spf O_{\breve F_0}[[x, y]]/(xy-\varpi) .
\end{equation*}
\end{altenumerate}

More precisely, we are now going to show in \eqref{Gamma_0(varpi) isom} that $\wt\CN_2^{(1)}$ is isomorphic to the deformation space with Iwahori level structure $\CM_{\Gamma_0(\varpi)}$. Let us recall the definition of this latter space.
 
\begin{definition}
The formal scheme $\CM_{\Gamma_0(\varpi)}$ represents the functor over $\Spf O_{\breve F_0}$ that associates to each scheme $S$ the set of isomorphism classes of quadruples 
\[
   (Y,Y',\phi\colon Y\rightarrow Y', \rho_Y),
\]
where $Y$ and $Y'$ are formal $O_{F_0}$-modules of relative height $2$ and dimension $1$ over $S$, $\phi$ is an isogeny of degree $q$, and $\rho_Y \colon Y\times_S\ov S\to \BE\times_{\Spec \ov k}\ov S$ is an $O_{F_0}$-linear quasi-isogeny of height $0$.
\end{definition}

When $F_0=\BQ_p$, it follows that $\CM_{\Gamma_0(p)}$ can be identified with the formal completion at a supersingular point of the moduli space of elliptic curves with $\Gamma_0(p)$-structure. 

To define the desired isomorphism $\CM_{\Gamma_0(\varpi)} \to \wt\CN_2^{(1)}$, let $(Y,Y',\phi,\rho_Y)$ be an $S$-point on $\CM_{\Gamma_0(\varpi)}$.  Set
\[
   X := Y \times Y'.
\]
Since $\ker \phi$ is $\varpi$-power torsion and of rank $q$, i.e.~of relative $O_{F_0}$-height $1$, it is killed by $\varpi$.  Hence there exists a unique (necessarily $O_{F_0}$-linear) isogeny $\phi'$ such that the composite
\begin{equation}\label{phi'}
   Y \xra\phi Y' \xra{\phi'} Y
\end{equation}
is multiplication by $\varpi$.  Let
\[
   \iota(\pi) :=
	\begin{bmatrix}
		  &  \phi'\\
	   \phi
	\end{bmatrix} \in \End_{O_{F_0}}(X).
\]
Then $\iota(\pi)^2$ is multiplication by $\varpi$.  Hence $\iota(\pi)$ defines an $O_F$-action $\iota$ on $X$ extending the $O_{F_0}$-action.  It is easy to verify that $\iota$ satisfies the Kottwitz condition \eqref{Kottwitz cond n=2}.  Now define the composite quasi-isogeny over the special fiber $\ov S$,
\begin{equation}\label{rho_Y'}
   \rho_{Y'}\colon Y_{\ov S}' \xra{\phi^{-1}} Y_{\ov S} \xra{\rho_Y} \BE_{\ov S} \xra{\iota_\BE(\pi)} \BE_{\ov S}.
\end{equation}
Then the pullbacks $\rho_Y^*(\lambda_\BE)$ and $\rho_{Y'}^*(\lambda_\BE)$ lift to principal polarizations $\lambda_Y$ of $Y$ and $\lambda_{Y'}$ of $Y'$, respectively (since the same holds for the universal object over the Lubin--Tate space $\CM$ of formal $O_{F_0}$-modules of dimension $1$ and relative height $2$ equipped with a quasi-isogeny of height $0$ to $\BE$ in the special fiber).  Let
\[
   \lambda :=
	\begin{bmatrix}
		\lambda_Y\\
		  &  \lambda_{Y'}
	\end{bmatrix}
	\in \Hom_{O_{F_0}}(X,X^\vee).
\]

In the particular case that $S = \Spec \ov k$ and $(Y,Y',\phi,\rho_Y) = (\BE,\BE,\iota_\BE(\pi),\id_\BE)$, our construction produces the triple
\begin{equation}\label{BX def}
   \BX := \BE \times \BE,
	\quad
	\iota_\BX(\pi) :=
	\begin{bmatrix}
		  &  \iota_\BE(\pi)\\
		\iota_\BE(\pi)
	\end{bmatrix},
	\quad
	\lambda_\BX :=
	\begin{bmatrix}
		\lambda_\BE\\
		  &  \lambda_\BE
	\end{bmatrix}.
\end{equation}
It is straightforward to calculate that the space $\BV(\BX)$ defined in \eqref{defV} has no nonzero isotropic vectors, so that $\BV(\BX)$ is the non-split $F/F_0$-hermitian space of dimension $2$.  Hence we may and will take $(\BX,\iota_\BX,\lambda_\BX)$ as the framing object for $\wt\CN_2^{(1)}$.\footnote{Note that later on, for technical convenience, we will rescale the polarization $\lambda_\BX$, cf.\ Example \ref{CP_n diagram n=2}.}  For a general $S$ and quadruple $(Y,Y',\phi,\rho_Y)$, we define the framing map
\[
   \rho := \rho_Y \times \rho_{Y'}\colon X_{\ov S} \to \BX_{\ov S}.
\]
Then tautologically $\rho^*(\lambda_\BX) = \lambda_{\ov S}$, and $\rho$ is readily seen to be $O_F$-linear.  Since it is obvious that $\Ros_{\lambda_\BX}(\iota_\BX(\pi)) = - \iota_\BX(\pi)$, it follows that $\Ros_\lambda(\iota(\pi)) = - \iota(\pi)$.  In this way we have defined a morphism
\begin{equation}\label{M_Gamma_0 map}
\begin{gathered}
   \xymatrix@R=0ex{
	   \CM_{\Gamma_0(\varpi)} \ar[r]  &  \wt\CN_2^{(1)}\\
		(Y,Y',\phi,\rho_Y) \ar@{|->}[r]  &  (X,\iota,\lambda,\rho).
	}
\end{gathered}
\end{equation}

\begin{proposition}\label{M_Gamma_0 isom}
The morphism $\CM_{\Gamma_0(\varpi)} \to \wt\CN_2^{(1)}$ is an isomorphism.
\end{proposition} 

\begin{proof}
We first show that the source and target each have only one $\ov k$-valued point. For $\CM_{\Gamma_0(\varpi)}$, this is well-known and easily checked. For $\wt\CN_2^{(1)}$, consider the covariant isocrystal $\BN$ of the framing object $\BX$, which has the structure of an $\breve F/\breve F_0$-hermitian space of dimension $2$ as in \S\ref{even ram max}. By Dieudonn\'e theory, $\wt\CN_2^{(1)}(\ov k)$ identifies with the set of $O_{\breve F}$-lattices $M$ in \BN which are self-dual and satisfy $\varpi M\subset^2 VM\subset^2 M$, where $V$ denotes the Verschiebung on $\BN$. Let $\sigma$ denote the Frobenius operator on $\breve F_0$, let $\zeta \in O_{\breve F_0}^\times$ be a square root of $-1$, and let $\tau := \zeta \pi V^{-1}$. Then $\tau$ is a $\sigma$-linear operator on $\BN$ with all slopes equal to zero. Let $C := \BN^\tau$.  Then the restriction of the hermitian form to $C$ makes $C$ into a $2$-dimensional $F/F_0$-hermitian space, cf.~\cite[pp.~1170--1]{RTW}.\footnote{Note that the quantity $\eta$ in loc.~cit.~should be a square root of $-\epsilon^{-1}$, rather than  a square root of $\epsilon^{-1}$.}  We claim that $C$ is non-split.  Indeed we can see this in at least two ways.  First consider the framing object $\BX_2$ of $\CN_2$ defined in \S\ref{even ram max}.  The $O_{F_0}$-linear isogeny
\[
   \varsigma_0 \colon \BX_2 = \BE \times \BE \xra{\id \times \iota_\BE(\pi)} \BX = \BE \times \BE
\]
is in fact $O_F$-linear (in terms of the Serre construction $\BX_2 = O_F \otimes_{O_{F_0}} \BE$, $\varsigma_0$ is induced by the inclusion of $\BE$ into the first factor in the target) and satisfies $\varsigma_0^*(\lambda_\BX) = -\frac 1 2\lambda_{\BX_2}$.  Hence $\varsigma_0$ gives an identification of $\breve F/\breve F_0$-hermitian isocrystals between the (rescaled) isocrystal for $\BX_2$ and $\BN$.  The ``$\tau$-fixed'' space in the former isocrystal is non-split by \cite[Lem.~3.3]{RSZ} (as is used in the proofs of Prop.~3.1 and Lem.~6.1 in loc.~cit.), which proves the claim.  A second way to see that $C$ is non-split is by explicit computation: up to isomorphism, the isocrystal with $F$-action for $\BE$ is given by $\breve F_0^2$ with Verschiebung
\[
   \begin{bmatrix} & \varpi \\ 1 \end{bmatrix} \sigma\i
\]
and with $\pi$ acting by
\[
   \begin{bmatrix} & \varpi \\ 1 \end{bmatrix}.
\]
(Of course the alternating form on this $2$-dimensional space is uniquely determined up to scalar.) From this and \eqref{BX def} one obtains an explicit form for $\BN$, and it is easy to then calculate that $C$ has no nonzero isotropic vectors, which characterizes it as the non-split space of dimension $2$.

Now let $M \subset \BN$ correspond to a point in $\wt\CN_2^{(1)}(\ov k)$. By an obvious variant of \cite[Prop.~2.17]{RZ} (with $\breve F$ in place of $W_\BQ$, $\pi$ in place of $p$, etc.), since $\BN$ is $2$-dimensional over $\breve F$, either $M=\tau M$, or $M\neq \tau M$ and $M+\tau M=\tau(M+\tau M)$. In the first case $M^\tau$ is a self-dual $O_F$-lattice in $C$, and hence is the unique such lattice since $C$ is non-split of dimension $2$. The other case does not occur, since otherwise $\pi(M+\tau M)^\tau$ would be a $\pi$-modular lattice in $C$ (via the same proof as for \cite[Lem.~3.2(iii)]{KR-alt}), contrary to the fact that $C$ is non-split.  This completes the proof that $\wt\CN_2^{(1)}(\ov k)$ consists of a single point.

To complete the proof of the proposition, it now suffices to show that the morphism \eqref{M_Gamma_0 map} is formally \'etale. We will do this via the local models for the source and target spaces, which we now pause to discuss.
\let\qed\relax
\end{proof}

The local model for $\CM_{\Gamma_0(\varpi)}$ is the standard Iwahori local model for $\GL_2$ and the cocharacter $\mu = (1,0)$ over $\Spec O_{F_0}$, cf.~\cite{Goertz} or \cite[Eg.~2.4]{PRS}.  Let us review the definition.  Let $f_1,f_2$ denote the standard basis for $F_0^2$, and define the $O_{F_0}$-lattices
\[
   \lambda_0 := O_{F_0}f_1 + O_{F_0}f_2,
	\quad\text{and}\quad
	\lambda_1 := O_{F_0}\varpi\i f_1 + O_{F_0} f_2.
\] 
The local model $M_{\Gamma_0(\varpi)}$ associated to these data is the scheme representing the functor that associates to each $O_{F_0}$-scheme $S$ the set of pairs $(\CF_0,\CF_1)$, where $\CF_i \subset \lambda_i \otimes_{O_{F_0}} \CO_S$ is an $\CO_S$-locally direct summand of rank $1$ for each $i$, and where the natural maps
\begin{equation}\label{Phi Phi'}
   \Phi\colon \lambda_0 \otimes_{O_{F_0}} \CO_S \to \lambda_1 \otimes_{O_{F_0}} \CO_S
	\quad\text{and}\quad
	\Phi'\colon \lambda_1 \otimes_{O_{F_0}} \CO_S \xra{\varpi \otimes \id} \lambda_0 \otimes_{O_{F_0}} \CO_S
\end{equation}
carry $\CF_0$ into $\CF_1$ and $\CF_1$ into $\CF_0$, respectively.

To define the local model for $\wt\CN_2^{(1)}$, we use the notation of \S\ref{odd ram max} in the case $n = 2$.  In particular, recall the $O_F$-lattice $\Lambda_0 = O_F^2 \subset F^2$, which is self-dual with respect to the alternating form \aform defined in \eqref{aform and sform}.  The local model $\wt N_2^{(1)}$ is the scheme representing the functor that associates to each $O_{F_0}$-scheme $S$ the set of all $O_F \otimes_{O_{F_0}} \CO_S$-submodules $\CF \subset \Lambda_0 \otimes_{O_{F_0}} \CO_S$ which are $\CO_S$-locally direct summands of rank $2$, which are La\-grangian for the form $\aform \otimes_{O_{F_0}} \CO_S$, and which satisfy the Kottwitz condition $\charac(\pi \otimes 1 \mid \CF) = T^2 - \varpi$.  (This is Definition \ref{LM def} below in the special case $(r,s) = (1,1)$ and $I = \{0\}$, cf.~also Remark \ref{forgetful LM isom n=2}.)

We now define an analog of the map \eqref{M_Gamma_0 map} for $M_{\Gamma_0(\varpi)}$ and $\wt N_2^{(1)}$. First make the direct sum $\lambda_0 \oplus \lambda_1$ into an $O_F$-module by taking $S = \Spec O_{F_0}$ in \eqref{Phi Phi'} and letting $\pi$ act as
\[
   \begin{bmatrix}
		  &  \Phi'\\
		\Phi
	\end{bmatrix}.
\]
Of course this is well-defined since the square of this matrix is multiplication by $\varpi$. We then identify
\begin{equation}\label{lambda_0 oplus lambda_1}
   \lambda_0 \oplus \lambda_1 \cong \Lambda_0
\end{equation}
as $O_F$-modules by identifying the elements $f_2 \in \lambda_0$ and $\varpi^{-1}f_1 \in \lambda_1$ with the standard basis elements $e_1,e_2 \in \Lambda_0$, respectively.  Relative to these identifications, we define
\begin{equation}\label{LM isom n=2}
\begin{gathered}
   \xymatrix@R=0ex{
	   M_{\Gamma_0(\varpi)} \ar[r]  &  \wt N_2^{(1)}\\
		(\CF_0,\CF_1) \ar@{|->}[r]  &  \CF_0 \oplus \CF_1.
	}
\end{gathered}
\end{equation}
It is easy to see that $\CF_0 \oplus \CF_1$ satisfies all the conditions in the definition of $\wt N_2^{(1)}$, so that this morphism is well-defined.

\begin{lemma}\label{M_Gamma_0 LM isom}
The morphism $M_{\Gamma_0(\varpi)} \to \wt N_2^{(1)}$ is an isomorphism.
\end{lemma}

\begin{proof}
This is easily checked locally on standard affine charts. For example, the most interesting chart on the source consists of all points of the form
\[
   \CF_0 = \spann\{ f_1 + x f_2\},\quad \CF_1 = \spann\{y \varpi\i f_1 + f_2\}
\]
such that $xy = \varpi$, cf.~\cite[Eg.~2.4]{PRS}.  The most interesting chart on the target consists of all points expressible as the column span of
\[
   \begin{bmatrix}
		x_{11}  &  x_{12}\\
		x_{21}  &  x_{22}\\
		1\\
		  &  1
	\end{bmatrix}
\]
relative to the $O_{F_0}$-basis $e_1,e_2,\pi e_1, \pi e_2$ for $\Lambda_0$; this is easily seen to be the scheme of such matrix entries such that $x_{11} = x_{22} = 0$ and $x_{12}x_{21} = \varpi$, cf.~\cite[Rem.~2.35]{PRS}.  Thus the map \eqref{LM isom n=2} visibly identifies these two charts.  One sees similarly (and in fact more easily) that \eqref{LM isom n=2} is an isomorphism on all other standard charts, as desired.
\end{proof}

\begin{remark}
The map \eqref{LM isom n=2} makes explicit the isomorphism between these local models alluded to at the end of \cite[Rem.~2.35]{PRS}.
\end{remark}

\begin{proof}[Completion of the proof of Proposition \ref{M_Gamma_0 isom}]
It remains to show that the map \eqref{M_Gamma_0 map} is formally \'etale, which follows by combining Lemma \ref{M_Gamma_0 LM isom} with the \emph{local model diagrams}
\[
   \begin{gathered}
   \xy
	   (0,17)*+{\CM_{\Gamma_0(\varpi)}^\triv}="triv";
		(-16,0)*+{\CM_{\Gamma_0(\varpi)}}="RZ";
		(16,0)*+{(M_{\Gamma_0(\varpi)})_{\Spf O_{\breve F_0}}}="loc";
		{\ar "triv";"RZ" _-\mu};
		{\ar "triv";"loc" ^-{\mu'}}; 
	\endxy
	\end{gathered}
	\quad\text{and}\quad
	\begin{gathered}
	\xy
	   (0,17)*+{\bigl(\wt\CN_2^{(1)}\bigr)^\triv}="triv";
		(-16,0)*+{\wt\CN_2^{(1)}}="RZ";
		(16,0)*+{\bigl(\wt N_2^{(1)}\bigr)_{\Spf O_{\breve F_0}}}="loc";
		{\ar "triv";"RZ" _-\nu};
		{\ar "triv";"loc" ^-{\nu'}}; 
	\endxy
	\end{gathered}.
\]
Here $\CM_{\Gamma_0(\varpi)}^\triv$ is a moduli space for tuples $(Y,Y',\phi,\rho_Y,\gamma_0,\gamma_1)$, where the first four entries form a point on $\CM_{\Gamma_0(\varpi)}$, and where, letting $S$ denote the base scheme and $M$ denote the functor that assigns to a $p$-divisible group the Lie algebra of its universal vector extension,
\[
   \gamma_0 \colon M(Y) \isoarrow \lambda_0 \otimes_{O_{F_0}} \CO_S
	\quad\text{and}\quad
	\gamma_1 \colon M(Y') \isoarrow \lambda_1 \otimes_{O_{F_0}} \CO_S
\]
are isomorphisms of $\CO_S$-modules.  We require that $\gamma_0$ and $\gamma_1$ respect the alternating forms on both sides, where the forms on the targets are defined by restricting \aform via \eqref{lambda_0 oplus lambda_1}; and that the diagram
\[
   \begin{gathered}
   \xymatrix{
	   M(Y) \ar[r]^-{\phi_*} \ar[d]_-{\gamma_0}^-\sim
		   &  M(Y') \ar[r]^-{\phi'_*} \ar[d]_-{\gamma_1}^-\sim
			&  M(Y) \ar[d]_-{\gamma_0}^-\sim\\
	   \lambda_0 \otimes_{O_{F_0}} \CO_S \ar[r]^-\Phi  
		   &  \lambda_1 \otimes_{O_{F_0}} \CO_S \ar[r]^-{\Phi'} 
			&  \lambda_0 \otimes_{O_{F_0}} \CO_S
	}
	\end{gathered}
\]
commutes, where $\phi'$ is as in \eqref{phi'}.  Similarly, $(\wt\CN_2^{(1)})^\triv$ is a moduli space for points $(X,\iota,\lambda,\rho)$ on $\wt\CN_2^{(1)}$ endowed with an $O_F \otimes_{O_{F_0}} \CO_S$-linear trivialization $\gamma\colon M(X) \isoarrow \Lambda_0 \otimes_{O_{F_0}} \CO_S$ that respects the alternating forms on both sides.  Furthermore $\mu$ and $\nu$ are the natural forgetful maps, and
\begin{align*}
   \mu'(Y,Y',\phi,\rho_Y,\gamma_0,\gamma_1) &:= \bigl(\gamma_0(\ker[M(Y) \rightarrow \Lie Y]), \gamma_1(\ker[M(Y') \rightarrow \Lie Y'])\bigr),\\
	\nu'(X,\iota,\lambda,\rho) &:= \gamma(\ker[M(X) \rightarrow \Lie X]).
\end{align*}
It is obvious that the maps \eqref{M_Gamma_0 map} and \eqref{LM isom n=2}, together with the map
\[
   \xymatrix@R=0ex{
	   \CM_{\Gamma_0(\varpi)}^\triv \ar[r]  &  \bigl(\wt\CN_2^{(1)}\bigr)^\triv \\
		(Y,Y',\phi,\rho_Y,\gamma_0,\gamma_1) \ar@{|->}[r]  &  (X,\iota,\lambda,\rho, \gamma_0 \oplus \gamma_1)
	}
\]
defined in terms of \eqref{M_Gamma_0 map} and the identification \eqref{lambda_0 oplus lambda_1}, give a morphism of local model diagrams.  Since the map \eqref{LM isom n=2} on local models is an isomorphism, it follows from \cite[Prop.~3.33]{RZ} that \eqref{M_Gamma_0 map} is formally \'etale.
\end{proof}

\begin{remark}[Equivariance] The group $O_D^\times = \Aut_{O_{F_0}}(\BE)$ acts naturally on $\CM_{\Gamma_0(\varpi)}$ by composing with the framing $\rho_Y$; hence so does its subgroup $D^1$ of norm one elements. Similarly, $\U(\BV(\wt\BX_2^{(1)}))$ acts on $\wt\CN_2^{(1)}$; hence so does its subgroup $\SU(\BV(\wt\BX_2^{(1)}))$. The isomorphism \eqref{M_Gamma_0 map} is then equivariant for these actions under the natural identification $D^1 \cong \SU(\wt\BX_2^{(1)})$.  Note that this equivariance does not express the actions of the larger groups $O_D^\times$ and $\U(\wt\BX_2^{(1)})$ in terms of the other side of the isomorphism \eqref{M_Gamma_0 map}. 
\end{remark}





\section{Some auxiliary spaces in the ramified case}\label{aux spaces}

In this section we give two closely related generalizations (different than in \cite{RTW}) of the space $\wt\CN_2^{(1)}$ of the previous section to any even $n$.  However the spaces we define are not regular, and they will play only an auxiliary role in the ATC we formulate in \S\ref{s:ATCeven}.  Let $n \geq 2$ be even, still with $F/F_0$ ramified.

The first space we define, which we denote by $\CP_n$, is a moduli space over $\Spf O_{\breve F}$ for quadruples $(X,\iota,\lambda,\rho)$ as before, with the framing object to be specified below, except in this case we impose on the polarization $\lambda$ that
\begin{equation*}
   \ker \lambda \subset X[\iota(\pi)]\  \text{\emph{is of rank $q^{n-2}$}}. 
\end{equation*}
We further require that the triple $(X,\iota,\lambda)$ satisfies the wedge condition \eqref{wedge condition} and condition \eqref{even wtCN spin cond} below, which is the natural analog of condition \eqref{odd spin cond}.  As in \S\ref{odd ram max}, let $M(X)$ and $M(X^\vee)$ denote the respective Lie algebras of the universal vector extensions of $X$ and $X^\vee$.  Since $\ker \lambda$ is contained in $X[\iota(\pi)]$ and of rank $q^{n-2}$, there is a unique (necessarily $O_F$-linear) isogeny $\lambda'$ such that the composite
\[
   X \xra{\lambda} X^\vee \xra{\lambda'} X
\]
is $\iota(\pi)$, and the induced diagram
\[
   M(X) \xra{\lambda_*} M(X^\vee) \xra{\lambda'_*} M(X)
\]
then extends periodically to a polarized chain of $O_F \otimes_{O_{F_0}} \CO_S$-modules of type $\Lambda_{\{m-1\}}$.  By \cite[Th.~3.16]{RZ}, \'etale-locally on $S$ there exists an isomorphism of polarized chains
\begin{equation*}
   [{}\dotsb \xra{\lambda'_*} M(X) \xra{\lambda_*} M(X^\vee) \xra{\lambda'_*} \dotsb{}] \isoarrow \Lambda_{\{m-1\}} \otimes_{O_{F_0}} \CO_S,
\end{equation*}
which in particular gives an isomorphism of $O_F \otimes_{O_{F_0}} \CO_S$-modules
\begin{equation}\label{M(X) triv 2}
   M(X) \isoarrow \Lambda_{-(m-1)} \otimes_{O_{F_0}} \CO_S.
\end{equation}
Denoting by $\Fil^1 \subset M(X)$ the covariant Hodge filtration for $X$, the analog of \eqref{odd spin cond} we impose is that
\begin{align*}
	&\text{\em upon identifying $\Fil^1$ with a submodule of $\Lambda_{-(m-1)} \otimes_{O_{F_0}} \CO_S$ via \eqref{M(X) triv 2}, the line bundle}\\
	\intertext{
	\begin{equation}\label{even wtCN spin cond}
      \sideset{}{_{\CO_S}^n}\bigwedge \Fil^1 \subset  \tensor[^n]\Lambda{_{-(m-1)}} \otimes_{O_F} \CO_S
	\end{equation}
	}
	&\text{\em is contained in $L_{-(m-1),-1}^{n-1,1}(S)$, cf.~(\ref{L def}).}
\end{align*}
Just as before, condition \eqref{even wtCN spin cond} is independent of the above choice of chain isomorphism by Lemma \ref{L stability}.

As in the previous two sections, over $\ov k$ there are \emph{two} supersingular isogeny classes of framing objects for this moduli problem, distinguished by the splitness of the hermitian space $\BV$ in \eqref{defV}.  To complete the definition of $\CP_n$, we will choose a framing object $\wt\BX_n$ for which $\BV(\wt\BX_n)$ is non-split.  First let $\ov\BX_1$ be the framing object $\BX_1 = \BX_1^{(1)}$ (cf.\ \eqref{BX_1}) endowed with the conjugate $O_F$-action,
\[
   \bigl(\ov\BX_1, \iota_{\ov\BX_1}, \lambda_{\ov\BX_1}\bigr) :=
	   \bigl(\ov\BE,\iota_{\ov\BE},-\lambda_{\ov\BE}\bigr).
\]
Then we take $\wt\BX_n$ to be the product of the framing object $\BX_{n-1} = \BX_{n-1}^{(1)}$ (cf.\ \eqref{BX_n odd}) and $\ov\BX_1$,
\begin{equation}\label{wtBX_n^(1) def}
   \bigl(\wt\BX_n, \iota_{\wt\BX_n}, \lambda_{\wt\BX_n} \bigr) := 
	   \bigl(\BX_{n-1} \times \ov\BX_1, \iota_{\BX_{n-1}} \times \iota_{\ov\BX_1}, \lambda_{\BX_{n-1}} \times \lambda_{\ov\BX_1} \bigr).
\end{equation}
Since $\BV(\BX_{n-1})$ is non-split and $n$ is even, it follows from \eqref{chi decomp formula} that $\BV(\wt\BX_n)$ is indeed the non-split space of dimension $n$.  Furthermore, $\wt\BX_n$ obviously satisfies \eqref{wedge condition} because $\BX_{n-1}$ does, and it is easy to see that $\wt\BX_n$ satisfies \eqref{even wtCN spin cond} because $\BX_{n-1}$ satisfies \eqref{odd spin cond}.

\begin{remark}\label{kottwitzonP2}
As in Remark \ref{odd N_n crit}, the Kottwitz condition \eqref{kottwitzcond} is implied on $\CP_n$ by condition \eqref{even wtCN spin cond}, cf.~\cite[Lem.~5.1.2]{S}.  Furthermore, it will be shown in forthcoming work of Yu \cite{Yu} that \eqref{even wtCN spin cond} also implies the wedge condition \eqref{wedge condition} (and hence \eqref{wedge condition} is redundant in the definition of $\CP_n$).  On the other hand, when $n = 2$ the Kottwitz condition implies \eqref{wedge condition} and \eqref{even wtCN spin cond}, since this is obviously true in the generic fiber of the local model, and the local model defined by the Kottwitz condition alone is already flat. Hence $\CP_2 \simeq (\wt\CN_2^{(1)})_{\Spf O_{\breve F}}$.  (Strictly speaking, to make such an identification precise we must specify a quasi-isogeny between the framing objects $\wt\BX_2$ and $\BX$ on the two sides; we will do so in Example \ref{CP_n diagram n=2} below.)  Note that although $\wt\CN_2^{(1)}$ is regular, the space $\CP_2$ is not, since the ramified base change $O_{\breve F_0} \to O_{\breve F}$ does not preserve semi-stable reduction.
\end{remark}

\begin{remark}
Of course one obtains another formal moduli space by taking a framing object in the supersingular isogeny class for which $\BV$ is split; this recovers the space $(\wt\CN_2^{(0)})_{\Spf O_{\breve F}}$ when $n = 2$. As the case $n = 2$ shows, and in contrast to the situation in \S\ref{odd ram max}, the resulting space really is different from $\CP_n$.  However, when $n \geq 4$ we will have no occasion to consider this space further.
\end{remark}

It follows from the general theory of RZ spaces \cite{RZ} that $\CP_n$ is formally locally of finite type and essentially proper over $\Spf O_{\breve F}$.  However, as we have already noted, it is not regular.  Having fixed the polarization type in the moduli problem for $\CP_n$, the remaining conditions in its definition are the ``right'' ones in the sense that the corresponding local model is flat, which will be shown by Yu in \cite{Yu}, cf.~Remark \ref{Yu flatness} below.

The second moduli space we define, which we denote by $\CP_n'$, will turn out to be isomorphic to two copies of $\CP_n$, and in this sense is another generalization of $\wt\CN_2^{(1)}$. The advantage of $\CP_n'$ is that, by definition, it will also admit a natural map to $\CN_n$.  To state the definition, we first need to fix an $O_F$-linear isogeny of degree $q$,
\begin{equation}\label{phi_0}
   \phi_0 \colon \BX_n \to \wt\BX_n,
\end{equation}
such that $\phi_0^*(\lambda_{\wt\BX_n}) = \lambda_{\BX_n}$; here we recall the framing object $\BX_n$ from \S\ref{even ram max}. When $n = 2$, we have
\[
   \BX_2 = O_F \otimes_{O_{F_0}} \BE
	\quad\text{and}\quad
	\wt\BX_2 = \BE \times \ov\BE
\]
as $O_F$-modules, and we define $\phi_0$ to be the $O_F$-linear isogeny induced by adjunction from the diagonal map $\BE \xra{(\id,\id)} \BE \times \BE$. It is easy to verify from the explicit expressions \eqref{lambda_BX_2} and \eqref{wtBX_n^(1) def} of the polarizations that $\phi_0^*(\lambda_{\wt\BX_2}) = \lambda_{\BX_2}$.  When $n \geq 4$, we have
\[
   \BX_n = \wt\BX_n = \BX_{n-2} \times \ov\BE \times \ov\BE
\]
as $O_F$-modules, and we define
\[
   \phi_0 := \id_{\BX_{n-2}} \times
	   \begin{bmatrix}
			1  &  \iota_{\ov\BE}(\pi)/2\\
			1  &  -\iota_{\ov\BE}(\pi)/2
		\end{bmatrix}.
\]
It is again easy to check that $\phi_0^*(\lambda_{\wt\BX_n}) = \lambda_{\BX_n}$.

We now define $\CP_n'$ to be the moduli space for tuples
\[
   (X, \iota, \lambda, \rho, X', \iota', \lambda', \phi\colon X \rightarrow X'),
\]
where $(X, \iota, \lambda, \rho)$ is a point on $\CN_n$, $(X',\iota',\lambda',\rho')$ is a point on $\CP_n$, and $\phi$ is an $O_F$-linear isogeny of degree $q$.  Here we define $\rho'$ to be the composite quasi-isogeny
\[
   \rho'\colon X'_{\ov S} \xra{\phi_{\ov S}\i} X_{\ov S} \xra\rho \BX_{n,\ov S} \xra{\phi_{0,\ov S}} \wt\BX_{n,\ov S},
\]
where $S$ denotes the base scheme. Note that since $\phi_0^*(\lambda_{\wt\BX_n}) = \lambda_{\BX_n}$, $\rho^*(\lambda_{\BX_n,\ov S}) = \lambda_{\ov S}$, and $\rho^{\prime *}(\lambda_{\wt\BX_n,\ov S}) = \lambda'_{\ov S}$, it follows from rigidity for quasi-isogenies that $\phi^*(\lambda') = \lambda$.  The notion of isomorphism between tuples as above is the obvious one.

By definition, there are tautological projection maps
\begin{equation}\label{CP_n diagram}
	\begin{gathered}
   \xymatrix@C-2ex{
      & \CP_n' \ar[dl] \ar[dr]^-{\varphi}\\
	  \CP_n & & \CN_n .
   }
	\end{gathered}
\end{equation}
By Proposition \ref{even n decomp lem}, $\CN_n$ decomposes into a disjoint union $\CN_n = \CN_n^+ \amalg \CN_n^-$.  Pulling back along $\varphi$, we obtain a decomposition
\begin{equation}\label{wtCN'pm}
   \CP_n' = (\CP_n')^+ \amalg (\CP_n')^-.
\end{equation}

\begin{theorem}\label{wtCN'pm isom}
Writing $(\CP_n')^\pm$ for either of the summands in \eqref{wtCN'pm}, the projection $\CP_n' \to \CP_n$ induces an isomorphism
\[
   (\CP_n')^\pm \isoarrow \CP_n.
\]
\end{theorem}

\begin{proof}
We follow the same strategy as in the proof of Proposition \ref{M_Gamma_0 isom}.  We first show that the map is a bijection on $\ov k$-points. Let $\BN$ denote the covariant isocrystal of the framing object $\BX_n$, made into an $\breve F/\breve F_0$-hermitian space as in \S\ref{even ram max}. Let $V$ denote the Verschiebung on $\BN$.  By Dieudonn\'e theory, $\CP_n'(\ov k)$ identifies with the set of pairs of $O_{\breve F}$-lattices $L \subset L'$ in $\BN$ such that $\varpi L \subset VL \subset L$ and $\varpi L' \subset VL' \subset L'$, such that\footnote{Here the condition $VL' \subset^{\leq 1} VL' + \pi L'$ is manifestly equivalent to the wedge condition in the moduli problem for $\CP_n$, via the canonical isomorphism $\Lie X' \cong L'/VL'$.  For the purposes of the proof, we only need to know that the moduli problem \emph{implies} this condition on $L'$; we leave it as an exercise to show that, for $\ov k$-points, condition \eqref{even wtCN spin cond} imposes nothing further.}
\begin{equation*}
   VL \subset^1 VL + \pi L
	\quad\text{and}\quad
	VL' \subset^{\leq 1} VL' + \pi L',
\end{equation*}
and such that
\begin{equation}\label{L,L'}
   L \subset^1 L' \subset^{n-2} (L')^\vee \subset^1 L^\vee = \pi\i L.
\end{equation}
Our problem is to show that, starting from $L'$, we can uniquely recover $L$. 
Note that a $\pi$-modular lattice $L$ fits into the diagram \eqref{L,L'} if and only if
\begin{equation}\label{L,L' diagram}
   \pi(L')^\vee \subset^1 L \subset^1 L'.
\end{equation}
The hermitian form on $\BN$ induces a nondegenerate \emph{symmetric} $\ov k$-bilinear form on the $2$-dimensional space $L'/\pi(L')^\vee$, and the $\pi$-modular lattices $L$ satisfying \eqref{L,L' diagram} then correspond to the isotropic lines in the $2$-dimensional space $L'/\pi(L')^\vee$.  This gives at most two possibilities for $L$; since these possibilities have odd colength in their sum $L'$, by definition, one of them will correspond to a point on $(\CP_n')^+$, and the other a point on $(\CP_n')^-$.  Thus to complete this part of the proof, we have to show that any $\pi$-modular $L$ satisfying \eqref{L,L' diagram} automatically satisfies $\varpi L \subset VL \subset L$ and $VL \subset^1 VL + \pi L$.  Since the Dieudonn\'e module $\BM$ of $\BX_n$ satisfies $V\BM \subset^1 V\BM + \pi\BM$, it follows from \cite[Lem.~3.3]{RSZ} that the colength of $VL$ in $VL + \pi L$ is odd. The diagram
\begin{equation*}
\begin{gathered}
   \xymatrix@R-2ex@C-2ex{
	   VL + \pi L \ar@{}[d]|-*{\cup} \ar@{}[r]|-*{\subset}  &  V L' + \pi L' \ar@{}[d]|-*{\tensor[^{\makebox[0ex][r]{$\scriptstyle \leq 1$}}]{\cup}{}}\\
		VL \ar@{}[r]|-*{\subset^{\smash{1}}}  &  VL'
	}
\end{gathered}
\end{equation*}
then shows that this colength is $\leq 2$. Hence the colength is $1$.  This implies, in turn, that $\pi$ kills the quotient $(VL + \pi L)/VL$, so that $\varpi L \subset VL$.  The containment $VL \subset L$ follows similarly from the relation $L \subset^1 L + \pi\i VL$, which in turn follows similarly from $L \subset^1 L' \subset^{\leq 1} L' + \pi\i VL'$, where in the second containment we use that, since the isocrystal $\BN$ is supersingular, the lattices $L'$ and $\pi\i V L'$ have the same colength in any lattice that contains them both.
	
To complete the proof of the proposition, since $(\CP_n')^\pm$ is formally locally of finite type over $\Spf O_{\breve F}$, it now suffices to show that $(\CP_n')^\pm \to \CP_n$ is formally \'etale.  This follows from Proposition \ref{lm isom}\eqref{lm isom ii} below in the case $I = \{m-1\}$, via an entirely similar argument involving the local model diagrams as in the proof of Proposition \ref{M_Gamma_0 isom}. The easy details are left to the reader.
\end{proof}

\begin{example}[$n=2$]\label{CP_n diagram n=2}
When $n = 2$, Proposition \ref{M_Gamma_0 isom} identifies $\wt\CN_2^{(1)} \cong \CM_{\Gamma_0(\varpi)}$. Thus by Remark \ref{kottwitzonP2}, $\CP_2$ is isomorphic to the base change $(\CM_{\Gamma_0(\varpi)})_{\Spf O_{\breve F}}$.  To specify a particular isomorphism, it is convenient to first replace the polarization $\lambda_\BX$ of the framing object \BX for $\wt\CN_2^{(1)}$ by $-2 \lambda_\BX$, and to then modify the isomorphism $\CM_{\Gamma_0(\varpi)} \isoarrow \wt\CN_2^{(1)}$ to send
\[
   (Y,Y',\phi,\rho_Y) \mapsto \bigl(Y \times Y', \iota, -2(\lambda_Y \times \lambda_{Y'}), \rho\bigr),
\]
where $\iota$ and $\rho$ are as defined in \S\ref{ram self-dual n=2}.  Up to canonical isomorphism, this leaves the moduli problem for $\wt\CN_2^{(1)}$ unchanged, and the modified morphism remains an isomorphism.  Furthermore, using this rescaled $\lambda_\BX$, and with respect to the $O_{F_0}$-linear decompositions $\wt\BX_2 = \BX = \BE^2$, the morphism
\begin{equation}\label{psi_0}
   \psi_0\colon \BX \xra[\undertilde]{\left[\begin{smallmatrix} 1 & 1\\ 1 & -1 \end{smallmatrix}\right]} \wt\BX_2
\end{equation}
is an $O_F$-linear isomorphism such that $\psi_0^*(\lambda_{\wt\BX_2}) = \lambda_\BX$.  Hence $\psi_0$ determines an isomorphism $(\wt\CN_2^{(1)})_{\Spf O_{\breve F}} \isoarrow \CP_2$ sending $(X,\iota,\lambda,\rho) \mapsto (X,\iota,\lambda,\psi_0 \circ \rho)$, and in this way we identify $\CP_2$ with $(\CM_{\Gamma_0(\varpi)})_{\Spf O_{\breve F}}$.

In fact, the entire diagram \eqref{CP_n diagram} comes by extension of scalars from the diagram over $\Spf O_{\breve F_0}$,
\[
   \xymatrix@C-10ex{
      & \CM_{\Gamma_0(\varpi)} \amalg \CM_{\Gamma_0(\varpi)} \ar[dl] \ar[dr]^-{\varphi}\\
	  \CM_{\Gamma_0(\varpi)} & & \CM \amalg \CM .
   }
\]
Here on the lower right we use the identification $(\CN_2)_{\Spf O_{\breve F_0}} \cong \CM \amalg \CM$, where $\CM$ denotes the Lubin--Tate moduli space of formal $O_{F_0}$-modules of dimension $1$ and relative height $2$ equipped with a quasi-isogeny of height $0$ to $\BE$ in the special fiber, cf.~Example \ref{CN_2}.  By definition the morphism $\varphi$ respects the disjoint union decompositions in its source and target.  Thus $\varphi$ is given by two maps $\CM_{\Gamma_0(\varpi)} \to \CM$, and one easily unwinds the definitions to find that these are the tautological projections $(Y,Y',\phi,\rho_Y) \mapsto (Y,\rho_Y)$ and $(Y,Y',\phi,\rho_Y) \mapsto (Y',\rho_{Y'})$, where $\rho_{Y'}$ is defined in \eqref{rho_Y'}.
\end{example}

\begin{remark}
As Example \ref{CP_n diagram n=2} shows, the morphism $\varphi$ is finite when $n = 2$.  When $n \geq 4$, this is no longer the case.  Indeed, the fiber over a $\ov k$-point $(X,\iota,\lambda,\rho)$ is given by the scheme of isotropic subgroup schemes of order $q$ in $X[\iota(\pi)]$.
\end{remark}

The remaining step in the proof of Theorem \ref{wtCN'pm isom} is to show that the corresponding map on local models is an isomorphism.  In fact we will formulate the result we need for any signature.
For the moment let $n$ be even or odd, fix a partition $r + s = n$, and set
\[
   E := F_0
	\quad\text{if}\quad
	r = s,
	\quad\text{and}\quad
	E = F
	\quad\text{if}\quad
	r \neq s.
\]
We set $m := \lfloor n/2 \rfloor$ and again take up the notation of \S\ref{odd ram max}.

\begin{definition}\label{LM def}
For nonempty $I \subset \{0,\dotsc,m\}$, the \emph{naive local model $M_I^\naive$} is the scheme over $\Spec O_E$ representing the functor that assigns to each $O_E$-scheme $S$ the set of all families
\[
   (\CF_i \subset \Lambda_i \otimes_{O_{F_0}} \CO_S)_{i \in \pm I + n\BZ}
\]
such that
\begin{altenumerate}
\renewcommand{\theenumi}{\arabic{enumi}}
\item\label{LM rank cond} for all $i$, $\CF_i$ is an $O_F \otimes_{O_{F_0}} \CO_S$-submodule of $\Lambda_i \otimes_{O_{F_0}} \CO_S$ which is Zariski-locally on $S$ an $\CO_S$-direct summand of rank $n$;
\item\label{LM functoriality cond} for all $i < j$, the natural arrow $\Lambda_i \otimes_{O_{F_0}} \CO_S \to \Lambda_j \otimes_{O_{F_0}} \CO_S$ carries $\CF_i$ into $\CF_j$;
\item\label{LM periodic cond} for all $i$, the isomorphism $\Lambda_i \otimes_{O_{F_0}} \CO_S \xra[\undertilde]{\pi \otimes 1} \Lambda_{i-n} \otimes_{O_{F_0}} \CO_S$ identifies $\CF_i \isoarrow \CF_{i-n}$;
\item\label{LM perp cond} for all $i$, the perfect $\CO_S$-bilinear pairing
\[
   \aform_i\colon (\Lambda_i \otimes_{O_{F_0}} \CO_S) \times (\Lambda_{-i} \otimes_{O_{F_0}} \CO_S)
   \xra{\aform \otimes \CO_S} \CO_S
\]
identifies $\CF_i^\perp$ with $\CF_{-i}$ inside $\Lambda_{-i} \otimes_{O_{F_0}} \CO_S$; and
\item (\emph{Kottwitz condition}) for all $i$, the section $\pi \otimes 1 \in O_F \otimes_{O_{F_0}} \CO_S$ acts on $\CF_i$ as an $\CO_S$-linear endomorphism with characteristic polynomial
\[
   \charac(\pi \otimes 1 \mid \CF_i) = (T-\pi)^r(T+\pi)^s \in \CO_S[T].
\]
\setcounter{filler}{\value{enumi}}
\end{altenumerate}

The \emph{local model $M_I^\loc$} is the scheme-theoretic closure of the generic fiber in $M_I^\naive$.  We define $M_I$ to be the closed subscheme of $M_I^\naive$ defined by the additional conditions\footnote{Here conditions \eqref{LM wedge cond} and \eqref{LM str spin cond} make sense as written whenever $S$ is an $O_F$-scheme, and when $r = s$ they descend to conditions on $M_I^\naive$ over $\Spec O_E = \Spec O_{F_0}$.}
\begin{altenumerate}
\renewcommand{\theenumi}{\arabic{enumi}}
\setcounter{enumi}{\value{filler}}
\item\label{LM wedge cond} (\emph{wedge condition}) for all $i$, the operators
\[
   \sidewedge{_{\CO_S}^{s+1}} (\pi \otimes 1 - 1\otimes \pi \mid \CF_i ) = 0
	\quad\text{and}\quad
	\sidewedge{_{\CO_S}^{r+1}} (\pi \otimes 1 + 1\otimes \pi \mid \CF_i ) = 0;
\]
and
\item\label{LM str spin cond} for all $i$, the line bundle $\bigwedge_{\CO_S}^n \CF_i \subset  \tensor[^n]\Lambda{_i} \otimes_{O_F} \CO_S$ is contained in $L_{i,(-1)^r}^{r,s}(S)$.
\end{altenumerate}
\end{definition}

We will typically abbreviate the notation for points on $M_I^\naive$ to $(\CF_i)_{i \in I}$, since by conditions \eqref{LM periodic cond} and \eqref{LM perp cond} such a tuple determines the full tuple $(\CF_i)_{i \in \pm I + n\BZ}$.

In the generic fiber, the Kottwitz condition implies conditions \eqref{LM wedge cond} and \eqref{LM str spin cond}. Therefore there are inclusions of closed subschemes
\[
   M_I^\loc \subset M_I \subset M_I^\naive.
\]
On the other hand, \eqref{LM str spin cond} implies the Kottwitz condition in general by \cite[Lem.~5.1.2]{S}.  In the particular situation of Remark \ref{odd N_n crit} (which is for $n$ odd, $(r,s) = (n-1,1)$, and $I = \{m\}$), condition \eqref{LM str spin cond} also implies the wedge condition, but we do not know if this implication holds in general.  In all cases, the following is conjectured in \cite{S}.\footnote{Strictly speaking loc.~cit.~requires $I$ to have the property that if $n$ is even and $m - 1 \in I$, then $m \in I$, but here we drop this requirement. Note that on the other hand, Proposition \ref{lm isom} below allows one to view sets $I$ not satisfying this property as being redundant in some sense.}

\begin{conjecture}\label{str spin conj}
For any signature $(r,s)$ and nonempty $I \subset \{0,\dotsc,m\}$, the scheme $M_I$ is flat over $\Spec O_E$, or in other words $M_I^\loc = M_I$.
\end{conjecture}

\begin{remark}
Condition \eqref{LM str spin cond} can be regarded as a kind of common refinement of the Kottwitz condition and the \emph{spin condition} introduced in \cite{PR}.  Let us recall the latter.  Let $S$ be an $O_F$-scheme, and recall the decomposition $\tensor*[^n] V{} = \tensor*[^n] V{_1} \oplus \tensor*[^n] V{_{-1}}$ in \eqref{^nV decomp}.  For each $i \in \pm I + n\BZ$, in analogy with the definitions of $\tensor*[^n]\Lambda{_{\epsilon}^{r,s}}$ in \eqref{^nLambda_epsilon^r,s} and $L_{i,\epsilon}^{r,s}(S)$ in \eqref{L def}, define
\begin{equation}\label{^nLambda_epsilon}
   \tensor[^n]{(\Lambda_i)}{_\epsilon} := \tensor[^n]{(\Lambda_i)}{}\cap \tensor*[^n] V{_\epsilon}
	\quad\text{and}\quad
	L_{i,\epsilon}(S) := \im \bigl[ \tensor[^n]{(\Lambda_i)}{_\epsilon} \otimes_{O_F} \CO_S \to \tensor*[^n]\Lambda{_i} \otimes_{O_F} \CO_S \bigr].
\end{equation}
Then the \emph{spin condition} on an $S$-point $(\CF_i)_i$ of $M_I^\naive$ is that
\begin{equation}\label{LM spin cond}
	\text{\em for all $i$, the line bundle $\textstyle{\bigwedge_{\CO_S}^n} \CF_i \subset  \tensor[^n]\Lambda{_i} \otimes_{O_F} \CO_S$ is contained in $L_{i,(-1)^r}(S)$.}
\end{equation}
As in the formulation of conditions \eqref{LM wedge cond} and \eqref{LM str spin cond}, when $r = s$ the spin condition descends from $(M_I^\naive)_{O_F}$ to $M_I^\naive$.  Of course, the spin condition is trivially implied by condition \eqref{LM str spin cond}.
\end{remark}

\begin{remark}\label{I=m}
In the special case that $n$ is even and $I = \{m\}$, the above discussion can be simplified.  For $S$ an $O_E$-scheme, consider the $\CO_S$-bilinear form
\begin{equation*}
   \sform_m\colon (\Lambda_m \otimes_{O_{F_0}} \CO_S) \times (\Lambda_m \otimes_{O_{F_0}} \CO_S) \xra[\undertilde]{\id \times (\pi \otimes 1)} (\Lambda_m \otimes_{O_{F_0}} \CO_S) \times (\Lambda_{-m} \otimes_{O_{F_0}} \CO_S) \xra{\aform_m} \CO_S,
\end{equation*}
which is \emph{split symmetric}.  Then, using condition \eqref{LM periodic cond}, condition \eqref{LM perp cond} is equivalent to requiring that $\CF_m$ is Lagrangian for $\sform_m$.  Thus $M_{\{m\}}^\naive$ naturally embeds into the orthogonal Lagrangian Grassmannian $\OGr(n,\Lambda_m \otimes_{O_{F_0}} O_F)$.  Now, the generic fiber $(M_{\{m\}}^\naive)_E$ is connected (cf.~\cite[\S1.5.3]{PR}), and the spin condition is then that $\CF_m$ lies on the one of the two connected components of $\OGr(n,\Lambda_m \otimes_{O_{F_0}} O_F)$ marked by $(M_{\{m\}}^\naive)_E$; cf.~Rem.~2.32 and the paragraph following it in \cite{PRS}.  Thus the spin condition is a purely pointwise condition on $M_{\{m\}}^\naive$; after base change to $\Spec O_F$, it may also be characterized as the condition that the rank of $\pi \otimes 1 - 1\otimes \pi$ on $\CF_m$ at each point has the same parity as the common parity of $r$ and $s$.

The relevant signature in the context of Theorem \ref{wtCN'pm isom} is $(r,s) = (n-1,1)$.  In this case, in the presence of the wedge condition, the spin condition is simply that $\pi \otimes 1 - 1 \otimes \pi$ acts on $\CF_m$ with rank $1$ at each point.  Furthermore, the calculations in \cite[\S5.3]{PR} show that in this case, Conjecture \ref{str spin conj} holds true, and that in fact $M_{\{m\}}^\loc$ is smooth and is characterized just by conditions \eqref{LM rank cond}--\eqref{LM perp cond}, the condition $\bigwedge_{\CO_S}^2 (\pi \otimes 1 - 1\otimes \pi \mid \CF_m ) = 0$, and the spin condition.
\end{remark}

\begin{remark}\label{Yu flatness}
In the special case that $n$ is even, $I = \{m-1\}$, and $(r,s) = (n-1,1)$, Conjecture \ref{str spin conj} will be proved in the forthcoming paper \cite{Yu} of Yu.  Furthermore, she will show that in this case $M_{\{m-1\}}^\loc$ is characterized just by conditions \eqref{LM rank cond}--\eqref{LM perp cond} and \eqref{LM str spin cond}.
\end{remark}

We now return to our assumption that $n$ is even.
For $j \in \{m-1,m\}$, let $C_{\{j\}}$ be the closed subscheme of $\prod_{i \in \pm j + n\BZ} \Gr(n,\Lambda_i \otimes_{O_{F_0}} O_E)$ defined by conditions \eqref{LM rank cond}--\eqref{LM perp cond} in Definition \ref{LM def} and the spin condition \eqref{LM spin cond}.  Then projection onto the $j$th factor identifies $C_{\{j\}}$ with a closed subscheme in $\Gr(n,\Lambda_j\otimes_{O_{F_0}} O_E)$, and $M_{\{j\}}^\naive$ is naturally a closed subscheme of $C_{\{j\}}$.  Note that we do \emph{not} impose the Kottwitz condition on $C_{\{j\}}$, and therefore $C_{\{j\}}$ depends on the signature $(r,s)$ only through the common parity of $r$ and $s$ in the spin condition.

We are going to define a morphism $C_{\{m-1\}} \to C_{\{m\}}$ via the following lemma.  Quite generally, let $S$ be an $O_E$-scheme, and for any $i$, let
\begin{equation}\label{T_i}
   T_i\colon \Lambda_i \otimes_{O_{F_0}} \CO_S \to \Lambda_{i+1} \otimes_{O_{F_0}} \CO_S
\end{equation}
denote the natural map.

\begin{lemma}\label{LM mapping lem}
Let $\CF_{m-1} \subset \Lambda_{m-1} \otimes_{O_{F_0}} \CO_S$ be an $S$-point on $C_{\{m-1\}}$.  Then there exists a unique $\CO_S$-locally direct summand $\CF_m \subset \Lambda_m \otimes_{O_{F_0}} \CO_S$ which contains $T_{m-1}(\CF_{m-1})$, is Lagrangian for the symmetric form $\sform_m$ (cf.~Remark \ref{I=m}), and satisfies the spin condition. Furthermore, $\CF_m$ is an $S$-point on $C_{\{m\}}$, and $T_m(\CF_m) \subset \CF_{m+1}$.
\end{lemma}

\begin{proof}
By the uniqueness claim, it suffices to prove the lemma in the case that $S$ is the spectrum of a local ring $R$.  Let $\kappa$ denote the residue field of $R$, and let us systematically use a bar to denote base change from $R$ to $\kappa$.  Over $\kappa$, the map $\ov T_{m-1}$ has kernel of dimension $1$ or $0$ (according as $\varpi R$ is contained in the maximal ideal or not).  Either way, there exists an $(n-1)$-dimensional subspace in $\ov\CF_{m-1}$ mapped isomorphically by $\ov T_{m-1}$ to its image in $\Lambda_m \otimes_{O_{F_0}} \kappa$.  
Using Nakayama's lemma, it follows that we may choose a free basis $a_1,\dotsc,a_n$ of $\CF_{m-1}$ such that the images $b_1,\dotsc,b_{n-1}$ of the first $n-1$ basis elements under $T_{m-1}$ form a free basis for a summand $\CF$ of $\Lambda_m \otimes_{O_{F_0}} R$.

Now, for any $i$, it is obvious from the definition of the pairings in condition \eqref{LM perp cond} in Definition \ref{LM def} that there is an adjunction relation
\begin{equation}\label{adjunction}
   \bigl\la u, T_{-i-1}(v) \bigr\ra_i = \bigl\la T_i(u), v \bigr\ra_{i+1}
	\quad\text{for all}\quad
	u \in \Lambda_i \otimes_{O_{F_0}} R,\ v \in \Lambda_{-i-1} \otimes_{O_{F_0}} R.
\end{equation}
Applying this when $i = m-1$, and using condition \eqref{LM periodic cond} and the equality $\CF_{-(m-1)} = \CF_{m-1}^\perp$, it follows that $T_{m-1}(\CF_{m-1})$ is totally isotropic for $\sform_m$. Hence
\[
   \CF \subset T_{m-1}(\CF_{m-1}) \subset \CF^\perp.
\]
The quotient $\CF^\perp/\CF$ is then naturally made by $\sform_m$ into a free quadratic $R$-module of rank $2$.  Since $R$ is local, $2 \in R^\times$, $\CF$ is totally isotropic, and $\sform_m$ is split, it follows from Roy's cancellation theorem \cite[Th.~8.1]{Roy} that $\CF^\perp/\CF$ is split.  Hence there exist isotropic elements $c,d \in \CF^\perp$ such that $b_1,\dotsc,b_{n-1},c,d$ form a free basis of $\CF^\perp$, and
\begin{equation*}
   \spann_R\{b_1,\dotsc,b_{n-1},c\} \quad\text{and}\quad \spann_R\{b_1,\dotsc,b_{n-1},d\}
\end{equation*}
are the (only) two Lagrangian submodules of $\Lambda_m \otimes_{O_{F_0}} R$ containing $\CF$.  Since the intersection of these Lagrangians has odd corank in each of them, they are classified by points on different connected components of $\OGr(n,\Lambda_m \otimes_{O_{F_0}} O_F)$, cf.~\cite[\S7.1.4]{PR}.  Hence exactly one of them, say the first, satisfies the spin condition, and we define this to be $\CF_m$.  Note that this already proves the uniqueness claim for $\CF_m$ in the statement of the lemma.

To show that $\CF_m$ contains $T_{m-1}(\CF_{m-1})$, first note that since $\CF_{m-1}$ is spanned by $a_1,\dotsc,a_n$, $T_{m-1}(\CF_{m-1})$ is generated by
\[
	b_1,\dotsc,b_{n-1}, xc+yd
\]
for some $x,y \in R$. Let
\begin{align*}
   w &:= b_1 \wedge \dotsb \wedge b_{n-1} \wedge (xc +yd)\\
	 &\phantom{:}= x \cdot b_1 \wedge \dotsb \wedge b_{n-1} \wedge c + y \cdot b_1 \wedge \dotsb \wedge b_{n-1} \wedge d \in \tensor[^n]{\Lambda}{_m} \otimes_{O_F} R.
\end{align*}
Consider the commutative diagram
\[
   \xymatrix@R-3ex{
	   \tensor[^n]{(\Lambda_{m-1})}{_{(-1)^r}} \otimes_{O_F} R \ar[r] \ar[dd]_-\sim 
		   &  \tensor[^n]{(\Lambda_m)}{_{(-1)^r}} \otimes_{O_F} R \ar[dd]^-\sim \\
		\\
		L_{m-1,(-1)^r}(R) \ar@{}[d]|-*{\cap}  
		   &  L_{m,(-1)^r}(R) \ar@{}[d]|-*{\cap} \\
		\tensor[^n]{\Lambda}{_{m-1}} \otimes_{O_F} R \ar[r]^-{\bigwedge^n T_{m-1}} 
		   &  \tensor[^n]{\Lambda}{_m} \otimes_{O_F} R,
	}
\]
where we recall the modules $\tensor[^n]{({\Lambda_i})}{_{\pm 1}}$ and $L_{i,\pm 1}(R)$ from \eqref{^nLambda_epsilon}.  Then $w$ generates the image of $\bigwedge^n \CF_{m-1}$ under the bottom map.  Since $\bigwedge^n \CF_{m-1}$ is contained in $L_{m-1,(-1)^r}(R)$ by the spin condition, the diagram shows that $w \in L_{m,(-1)^r}(R)$.  Now, in the special case $i = m$, it is easy to verify from the definitions in \cite[\S7]{PR} or \cite[\S2.3]{S} that there is a direct sum decomposition
\[
   \tensor[^n]{{\Lambda_m}}{} = \tensor[^n]{({\Lambda_m})}{_1} \oplus \tensor[^n]{({\Lambda_m})}{_{-1}},
\]
and hence
\[
   \tensor[^n]{{\Lambda_m}}{} \otimes_{O_F} R = L_{m,1}(R) \oplus L_{m,-1}(R).
\]
Since $w$ lies in $L_{m,(-1)^r}(R)$, its component in the summand $L_{m,(-1)^{r+1}}(R)$ is zero.  Hence $y = 0$ and $T_{m-1}(\CF_{m-1}) \subset \CF_m$.

To complete the proof, it remains to show that $T_m(\CF_m) \subset \CF_{m+1}$ and that $\CF_m$ is $\pi \otimes 1$-stable.  The first of these is an easy consequence of the adjunction relations \eqref{adjunction} and conditions \eqref{LM periodic cond} and \eqref{LM perp cond} for $\CF_{m-1}$ and $\CF_{m+1}$.  For the second, note that the action of $\pi \otimes 1$ on $\Lambda_m \otimes_{O_{F_0}} R$ identifies with the composite
\[
   \xymatrix{
      \Lambda_m \otimes_{O_{F_0}} R \ar[r]^-{T_m}  
		   &  \Lambda_{m+1} \otimes_{O_{F_0}} R \ar[d]_-{\sim}^-{\pi \otimes 1} \\
	   &  \Lambda_{-m+1} \otimes_{O_{F_0}} R \ar[rrr]^-{T_{m-2}\circ \dotsb \circ T_{-m+1}}
		   & & &   \Lambda_{m-1} \otimes_{O_{F_0}} R \ar[r]^-{T_{m-1}} 
			&  \Lambda_m \otimes_{O_{F_0}} R.
	}
\]
Thus the containment $(\pi \otimes 1)(\CF_m) \subset \CF_m$ follows from the containment $T_m(\CF_m) \subset \CF_{m+1}$, from conditions \eqref{LM functoriality cond} and \eqref{LM periodic cond} on $C_{\{m-1\}}$, and from the containment $T_{m-1}(\CF_{m-1}) \subset \CF_m$.
\end{proof}

In the notation of the lemma, we now define
\[
   \nu\colon
   \xymatrix@R=0ex{
	   C_{\{m-1\}} \ar[r]  &  C_{\{m\}}\\
		\CF_{m-1} \ar@{|->}[r]  &  \CF_m.
	}
\]
Then $\nu$ is plainly an isomorphism between generic fibers, and it restricts to an isomorphism between the generic fibers of the closed subschemes $M_{\{m-1\}}^\naive$ and $M_{\{m\}}^\naive$ in the source and target, respectively.  Hence, passing to flat closures, $\nu$ restricts to a map
\begin{equation}\label{nu}
   \nu\colon M_{\{m-1\}}^\loc \to M_{\{m\}}^\loc.
\end{equation}
We now have the following.

\begin{proposition}\label{lm isom}
Suppose that $m - 1 \in I$ and $m \notin I$, and fix the signature $(r,s)$.
\begin{altenumerate}
\item
The natural forgetful morphism
\[
   \xymatrix@R=0ex{
      M_{I \cup \{m\}}^\loc \ar[r]  &  M_I^\loc\\
	   \bigl((\CF_i)_{i\in I},\CF_m\bigr) \ar@{|->}[r]  &  (\CF_i)_{i\in I}
	}
\] 
is an isomorphism.
\item\label{lm isom ii}
The analogous forgetful morphism $M_{I\cup \{m\}} \to M_I$ is an isomorphism when $(r,s) = (n-1,1)$.
\item\label{lm isom iii}
If Conjecture \ref{str spin conj} holds true for signature $(r,s)$ and the set $I = \{m-1\}$, then the analogous forgetful morphism $M_{I\cup \{m\}} \to M_I$ is an isomorphism for any $I$ as above.
\end{altenumerate}
\end{proposition}

\begin{proof}
By Lemma \ref{LM mapping lem}, the inverse in all cases is given by $(\CF_i)_{i\in I} \mapsto ((\CF_i)_{i\in I},\nu(\CF_{m-1}))$.  Note that in \eqref{lm isom iii}, flatness of $M_{\{m-1\}}$ ensures that $\nu$ carries $M_{\{m-1\}}$ into $M_{\{m\}}$, and hence that this inverse carries $M_I$ into $M_{I\cup \{m\}}$.  Part (\ref{lm isom ii}) then follows from (\ref{lm isom iii}) in light of Yu's forthcoming result (cf.\ Remark \ref{Yu flatness}), but let us also sketch a direct proof of (\ref{lm isom ii}).  It similarly suffices to show that $\nu$ carries $M_{\{m-1\}}$ into $M_{\{m\}}$.

As in Lemma \ref{L stability}, consider the automorphism scheme $\uAut(\Lambda_{\{m-1,m\}})$ of the polarized $O_F$-lattice chain $\Lambda_{\{m-1,m\}}$ over $\Spec O_{F_0}$.  Then $\uAut(\Lambda_{\{m-1,m\}})_{O_F}$ acts on $M_{\{m-1\}}$ and $M_{\{m\}}$, and $\nu$ is equivariant for these actions.  The $\ov k$-point $\CF := (\pi \otimes 1)(\Lambda_{m-1} \otimes_{O_{F_0}}\ov k) \subset \Lambda_{m-1} \otimes_{O_{F_0}} \ov k$ on $M_{\{m-1\}}$ (which is the unique $\ov k$-point on which $\pi \otimes 1$ acts as zero) is in the closure of every orbit for $\uAut(\Lambda_{\{m-1,m\}})_{\ov k}$ on the geometric special fiber, and therefore we reduce to considering points $\CF_{m-1}$ on $M_{\{m-1\}}$ in an affine chart around $\CF$.  For $j \in \{m-1,m\}$, we take the ordered $O_{F_0}$-basis for $\Lambda_{j}$,
\begin{equation}\label{basis}
   \pi\i e_1,\dotsc, \pi\i e_j, e_{j+1},\dotsc,e_n, e_1,\dotsc,e_j, \pi e_{j+1},\dotsc, \pi e_n.
\end{equation}
With respect to this basis in the case $j = m-1$, we look at the affine chart on $M_{\{m-1\}}$ of points $\CF_{m-1}$ of the form
\begin{equation}\label{CF_m-1}
   \CF_{m-1} = \colspan
   \begin{bmatrix}
		X\\
		1_n
	\end{bmatrix},
	\quad
	X = (x_{ij}),
\end{equation}
where the blocks are of size $n \times n$.  (Thus $\CF$ is the $\ov k$-point $X = 0$.)  Write $X$ in the block form
\[
   X =
	\left[
	\begin{array}{ccc}
		A  &  *  &  B\\
		R_1  &  x_{mm}  &  R_2\\
		C  &  *  &  D
	\end{array}
	\right],
\]
where $A$ has size $(m-1) \times (m-1)$, $B$ has size $(m-1) \times m$, $C$ has size $m \times (m-1)$, $D$ has size $m \times m$, $R_1$ has size $1 \times (m-1)$, $R_2$ has size $1 \times m$, and the blocks marked $*$ are columns of the appropriate sizes.  We claim that, with respect to the basis \eqref{basis} for $\Lambda_m$, we have
\begin{equation}\label{nu(CF_m-1)}
   \renewcommand{\arraystretch}{1.1}
   \nu(\CF_{m-1}) = \colspan
	\left[
	\begin{array}{c|c|c}
		A  &  &  B\\
		0  & \smash{\raisebox{.5\normalbaselineskip}{$R_2^\ad$}}  &  0\\
		\hline
		  &  1  &\\
		\smash{\raisebox{.5\normalbaselineskip}{$C$}}  & - R_1^\ad  &  \smash{\raisebox{.5\normalbaselineskip}{$D$}}\\
		\hline
		1_{m-1} &  &\\
		R_1  &  &  R_2\\
		  &  &  1_m
	\end{array}
	\right],
\end{equation}
where, defining
\[
   \setlength{\arraycolsep}{2.5pt}
   H_i :=
	\begin{bmatrix}
		  &  &  1\\
		  &  \smash{\iddots}\\
		1
	\end{bmatrix}
\]
to be the unit antidiagonal matrix of size $i \times i$, we set
\[
   R_1^\ad := H_{m-1}\tensor*[^t]{R}{_1}
	\quad\text{and}\quad
	R_2^\ad := H_m\tensor*[^t]{R}{_2}.
\] 
Indeed, in terms of our bases, the map $\Lambda_{m-1} \to \Lambda_m$ is given by the $2n \times 2n$ matrix
\[
   U :=
   \begin{bmatrix}
		1_{m-1}\\
		  &  &  &  \varpi\\
		  &  &  1_{n-1}\\
		  &  1\\
		  &  &  &  &  1_m
	\end{bmatrix},
\]
where the $\varpi$ is the $(m,n+m)$-entry, and the off-diagonal $1$ is the $(n+m,m)$-entry.  The first $m-1$ and last $m$ columns in \eqref{nu(CF_m-1)} are the image under multiplication by $U$ of the corresponding columns in \eqref{CF_m-1}; since these columns evidently span a direct summand of rank $n-1$, the proof of Lemma \ref{LM mapping lem} shows that $\nu(\CF_{m-1})$ is the unique Lagrangian subspace containing these columns and satisfying the spin condition.  To show that the right-hand side of \eqref{nu(CF_m-1)} satisfies these properties, first recall the symmetric form $\sform_m$ from Remark \ref{I=m}.  With respect to the basis \eqref{basis} for $\Lambda_m$, the matrix of $\sform_m$ is
\begin{equation}\label{pairing matrix}
   \begin{bmatrix}
		  &  &  H_m\\
		  &  -H_n\\
		H_m
	\end{bmatrix}.
\end{equation}
It follows that the $m$th column in the matrix in \eqref{nu(CF_m-1)} pairs to zero under $\sform_m$ with every column in this matrix.  Hence the right-hand side in \eqref{nu(CF_m-1)} is Lagrangian (recall from the proof of Lemma \ref{LM mapping lem} that the other $n-1$ columns in \eqref{nu(CF_m-1)}, being in the image of the point $\CF_{m-1}$ on $M_{\{m-1\}}$, automatically span a totally isotropic subspace).  Thus to prove the equality asserted in \eqref{nu(CF_m-1)}, it remains to show that the right-hand side satisfies the spin condition.  By Remark \ref{I=m}, both this and the fact that the right-hand side is a point on $M_{\{m\}}$ follow from the single claim that every column of the matrix in \eqref{nu(CF_m-1)} becomes a multiple of the $m$th one after applying the operator $\pi \otimes 1 - 1 \otimes \pi$ (note that the $m$th column obviously continues to span a rank one summand after applying this operator).

With respect to our basis for $\Lambda_m$, the operator $\pi \otimes 1 - 1 \otimes \pi$ is given by the matrix
\[
   \begin{bmatrix}
		-\pi 1_n  &  \varpi 1_n\\
		1_n  &  -\pi 1_n
	\end{bmatrix}.
\]
Writing the product of this with the matrix in \eqref{nu(CF_m-1)} in block form
$
   \begin{bmatrix}
		Y \\
		Z
	\end{bmatrix}
$
($n \times n$ blocks), we have
\[
   \renewcommand{\arraystretch}{1.1}
	Z =
	\left[
	\begin{array}{c|c|c}
		A - \pi 1_{m-1}  &  &  B \\
		-\pi R_1  & \smash{\raisebox{.5\normalbaselineskip}{$R_2^\ad$}}  &  -\pi R_2\\
		\hline
		  &  1  &\\
		\smash{\raisebox{.5\normalbaselineskip}{$C$}}  & - R_1^\ad  &  \smash{\raisebox{.5\normalbaselineskip}{$D- \pi 1_m$}}
	\end{array}
	\right]
	\quad\text{and}\quad
	Y = -\pi Z.
\]
Our problem is thus to show that every column in $Z$ is a multiple of its $m$th one.  In the case of the $j$th column for $j \neq m,m+1$, this means that we have to show that
\begin{equation}\label{want}
\begin{aligned}
	x_{ij} &= x_{m+1,j}x_{m,i^\vee},  &  &\quad i < m,\ i \neq j,\\
	x_{jj} - \pi &= x_{m+1,j} x_{m,j^\vee}  &  &\quad \text{if } j < m,\\
	-\pi x_{mj} &= x_{m+1,j} x_{m,m+1},\\
	x_{jj} - \pi &= -x_{m+1,j} x_{m,j^\vee},  &  &\quad \text{if } j > m+1,\\
	x_{ij} &= -x_{m+1,j}x_{m,i^\vee},  &  &\quad i > m+1,\ i \neq j,
\end{aligned}
\end{equation}
where for any $i$ we set
\[
   i^\vee := n+1-i.
\]
Similarly, in the case of the $(m+1)$th column in $Z$, we have to show that
\begin{equation}\label{m+1}
\begin{aligned}
   x_{i,m+1} &= (x_{m+1,m+1}-\pi)x_{m,i^\vee}  &  &\quad i < m,\\
	-\pi x_{m,m+1} &= (x_{m+1,m+1}-\pi)x_{m,m+1},\\
	x_{i,m+1} &= -(x_{m+1,m+1}-\pi)x_{m,i^\vee},  &  &\quad i > m + 1.
\end{aligned}
\end{equation}
We are going to deduce all of these relations from the fact that the columns in \eqref{nu(CF_m-1)} are pairwise orthogonal under $\sform_m$ and from condition (\ref{LM str spin cond}) in the definition of $M_{\{m-1\}}$.

Let us first make explicit the orthogonality relations we need.  For $i$ and $j$ distinct from $m$ and $m+1$, pairing the $i$th and $j$th columns in (\ref{nu(CF_m-1)}) with respect to (\ref{pairing matrix}), we obtain
\begin{equation}\label{orthog rel}
\begin{aligned}
   0 &= x_{m+1,i}x_{mj} + x_{j^\vee i} + x_{i^\vee j} + x_{mi}x_{m+1,j},  &  &\quad i,j < m,\\
	0 &= x_{j^\vee i} - x_{m+1,i}x_{m,j} - x_{i^\vee,j} - x_{mi}x_{m+1,j}  ,  &  &\quad i < m,\ m+1 < j,\\
	0 &= x_{j^\vee i} - x_{m+1,i}x_{mj} - x_{mi}x_{m+1,j} + x_{i^\vee j},  &  &\quad m+1 < i,j.
\end{aligned}
\end{equation}
Similarly, for $j \neq m,m+1$, pairing the $j$th column with the $(m+1)$th column, we obtain
\begin{equation}\label{orthog 2}
\begin{aligned}
   0 &= x_{m+1,j}x_{m,m+1} + x_{j^\vee,m+1} + x_{mj}x_{m+1,m+1},  &  & \quad j<m,\\
	0 &= -x_{m+1,j}x_{m,m+1} - x_{mj}x_{m+1,m+1} + x_{j^\vee,m+1},  &  &\quad j > m+1;
\end{aligned}
\end{equation}
and pairing the $(m+1)$th column with itself (and using that $2$ is a unit), we obtain
\begin{equation}\label{orthog 3}
	0 = x_{m+1,m+1}x_{m,m+1}.
\end{equation}

Now we turn to condition \eqref{LM str spin cond} in the definition of $M_{\{m-1\}}$.  We continue to use the notation of \S\ref{odd ram max}.  We closely follow the analysis in \cite{S}.  Similarly to \S4 in loc.\ cit., we introduce the basis elements in $V$,
\[
   g_i := e_i \otimes 1 + \pi e_i \otimes \pi\i,
	\quad g_{n+i} := \frac{e_i \otimes 1 - \pi e_i \otimes \pi\i}2,
	\quad
	i = 1,\dotsc,n.
\]
Then $g_1,\dotsc,g_n$ is a basis for $V_\pi$, and $g_{n+1},\dotsc,g_{2n}$ is a basis for $V_{-\pi}$.  For $S = \{i_1 < \dots < i_n\} \subset \{1,\dotsc,2n\}$ of cardinality $n$, we define
\[
   g_S := g_{i_1} \wedge \dots \wedge g_{i_n} \in \tensor*[^n]{V}{}.
\]
Furthermore, we say that $S$ has \emph{type $(r,s)$} if $S \cap \{1,\dotsc,n\}$ has $r$ elements and $S \cap \{n+1,\dotsc,2n\}$ has $s$ elements.  As $S$ varies through the sets of type $(n-1,1)$, the elements $g_S$ form a basis of $\tensor*[^n]{V}{^{n-1,1}}$, and the elements $g_S - \sgn(\sigma_S)g_{S^\perp}$ span $\tensor*[^n]{V}{_{-1}^{n-1,1}}$, cf.\ \cite[Lem.\ 4.2]{S}.  Here we set
\[
   S^* := \{\,2n+1-i \mid i \in S\,\}
	\quad\text{and}\quad
	S^\perp := \{1,\dotsc,2n\} \smallsetminus S^*,
\]
and $\sigma_S$ is the permutation on $\{1,\dotsc,2n\}$ sending the elements $1,\dotsc,n$ onto $S$ in increasing order, and $n+1,\dotsc,2n$ onto the complement of $S$ in increasing order.  By \cite[Lem.\ 2.8]{S}, $\sgn(\sigma_S) = (-1)^{\Sigma S + n/2}$, where $\Sigma S$ denotes the sum of the elements in $S$.  If $S$ is of type $(n-1,1)$, then $S = \{1,\dotsc,\wh\jmath,\dotsc,n,n+i\}$ for unique integers $1 \leq i,j \leq n$, where the hat means that the entry is omitted; and, since $n$ is even,
\[
   \sgn(\sigma_S) = (-1)^{\frac{n(n+1)}2 -j + n+i + \frac n 2} = (-1)^{i+j}.
\]

Now let $T = \{i_1 < \dotsb < i_n \}\subset \{1,\dotsc,2n\}$ be of cardinality $n$. Regarding the (images of the) basis elements \eqref{basis} in the case $j = m-1$ as an ordered $O_F$-basis for $\Lambda_{m-1} \otimes_{O_{F_0}} O_F$, define 
\[
   e_T := (i_1\text{th basis element}) \wedge \dotsb \wedge (i_n\text{th basis element}) \in \tensor*[^n]{\Lambda}{_{m-1}} \subset \tensor*[^n]{V}{}. 
\]
For $1 \leq i<j \leq n$ with $i,j \notin \{m,m+1\}$, consider the set
\[
   T_0:= \bigl\{m,m+1,n+1,\dotsc,\wh{n+i},\dotsc,\wh{n+j},\dotsc,2n\bigr\}.
\]
In taking the wedge product of the columns of the matrix in \eqref{CF_m-1} and expressing this as a linear combination of $e_T$'s for varying $T$, the coefficient $a_{T_0}$ of $e_{T_0}$ is $\pm(x_{mi}x_{m+1,j}-x_{m+1,i}x_{mj})$.  On the other hand, for $S$ of type $(n-1,1)$, when $g_S$ is written as a linear combination of $e_T$'s, the only $e_T$'s that occur are for $T$ containing at most one pair of the form $k,n+k$.  Since $T_0$ contains two such pairs (for $k = m$ and $m+1$), condition \eqref{LM str spin cond} on $\CF_{m-1}$ implies that $a_{T_0}$ must be zero.  We conclude that
\begin{equation}\label{wedge 2}
   x_{mi}x_{m+1,j} = x_{m+1,i}x_{mj}
	\quad\text{for all}\quad
	i,j \notin\{m,m+1\}.
\end{equation}

Now let us now show that the first relation in \eqref{want} holds in the case that $j < m$.  Consider the set
\[
   S := \{1,\dotsc,\wh\jmath,\dotsc,n,n+i\}.
\]
Then
\[
   S^\perp = \bigl\{1,\dotsc, \wh{i^\vee},\dotsc,n,n+j^\vee\bigr\}.
\]
We recall the notion of ``worst term'' from \cite[Def.\ 4.8]{S}, which we take with respect to the $e_T$-basis for $\tensor[^n]{V}{}$. We denote the worst term of a vector $v$ by $\WT(v)$.  Using that
\begin{equation}\label{double wedge}
   g_i \wedge g_{n+i} = (\pi\i e_i \otimes \pi) \wedge (e_i \otimes 1)
\end{equation}
for any $i$, we have
\begin{multline*}
   \WT(g_S) = (e_1 \otimes 1) \wedge \dotsb \wedge \wh{(e_j \otimes 1)} \wedge \dotsb \wedge (e_{m-1} \otimes 1)\\ \wedge (\pi e_m \otimes \pi\i) \wedge \dotsb \wedge (\pi e_n \otimes \pi\i) \wedge (-\pi\i e_i \otimes \pi)
\end{multline*}
and
\begin{multline*}
   \WT(g_{S^\perp}) = (e_1 \otimes 1) \wedge \dotsb \wedge (e_{m-1} \otimes 1)\\ \wedge (\pi e_m \otimes \pi\i) \wedge \dotsb \wedge \wh{(\pi e_{i^\vee} \otimes \pi\i)} \wedge \dotsb \wedge (\pi e_n \otimes \pi\i) \wedge (e_{j^\vee} \otimes 1).
\end{multline*}
Let
\[
   T_0 := \bigl\{i, n+1,\dotsc, \wh{n+j},\dotsc,2n\bigr\}
	\quad\text{and}\quad
	T_0' := \bigl\{ j^\vee, n+1, \dotsc, \wh{n+i^\vee},\dotsc,2n\bigr\}.
\]
Then the $e_{T_0}$-term and the $e_{T_0'}$-term in the wedge of the columns of \eqref{CF_m-1} are, respectively,
\[
   (e_1 \otimes 1) \wedge \dotsb \wedge \underbrace{(\pi\i e_i \otimes x_{ij})}_{\makebox[0ex][c]{$\scriptstyle \text{in place of } e_j \otimes 1$}} \wedge \dotsb \wedge (e_{m-1} \otimes 1) \wedge (\pi e_m \otimes 1) \wedge \dotsb \wedge (\pi e_n \otimes 1)
\]
and
\[
   (e_1 \otimes 1) \wedge \dotsb \wedge (e_{m-1} \otimes 1) \wedge (\pi e_m \otimes 1) \wedge \dotsb \wedge \underbrace{(e_{j^\vee} \otimes x_{j^\vee i^\vee})}_{\makebox[0ex][c]{$\scriptstyle \text{in place of } \pi e_{i^\vee} \otimes 1$}} \wedge \dotsb \wedge (\pi e_n \otimes 1).
\]
The sum of these terms is
\begin{align*}
   &(-1)^{n-j+1} x_{ij}\pi^m \WT(g_S) + (-1)^{n-i^\vee} x_{j^\vee i^\vee} \pi^m \WT(g_{S^\perp})\\
	   &\qquad \qquad = (-1)^{j+1} \pi^m \bigl[x_{ij}\WT(g_S) - (-1)^{i+j+1} x_{j^\vee i^\vee} \WT(g_{S^\perp})\bigr] \\
		&\qquad \qquad \qquad \qquad = (-1)^{j+1} \pi^m \bigl[ x_{ij}\WT(g_S) - (-x_{j^\vee i^\vee}) \sgn(\sigma_S)\WT(g_{S^\perp}) \bigr].
\end{align*}
Since $S$ is the only set of type $(n-1,1)$ for which $g_S$, when expressed in terms of the $e_T$-basis, involves $e_{T_0}$, and ditto for $S^\perp$ and $e_{T_0'}$, we conclude from condition \eqref{LM str spin cond} on $\CF_{m-1}$ that
\[
   x_{ij} = -x_{j^\vee i^\vee}.
\]
Combining this with \eqref{wedge 2} and the second orthogonality relation in \eqref{orthog rel} (where $j$ is replaced by $j^\vee$), and using that $2$ is a unit, we obtain the first relation in \eqref{want}.  The case that $j > m$ is handled in a similar way, as is the last relation in \eqref{want}.

We next show that the third relation in \eqref{want} holds.  We first need to obtain an analog of \eqref{wedge 2} in the case that $i = m+1$.  Assume that $j < m$, and consider the sets
\begin{align*}
	T_0 &:= \bigl\{m,n+1,\dotsc,\dotsc,\wh{n+j},\dotsc,2n\bigr\},\\
   T_0' &:= \bigl\{m,m+1,n+1,\dotsc,\wh{n+j},\dotsc,\wh{n+m+1},\dotsc,2n\bigr\}.
\end{align*}
When we express the wedge product of the columns in \eqref{CF_m-1} as a linear combination of $e_T$'s, the $e_{T_0}$-term is
\begin{equation}\label{e_T_0 term}
   (-1)^{j-1}x_{mj}e_{T_0},
\end{equation}
and the $e_{T_0'}$-term is
\[
   (-1)^{m-j}\det
	\begin{bmatrix}
		x_{mj}  &  x_{m,m+1}\\ 
		x_{m+1,j}  &  x_{m+1,m+1}
	\end{bmatrix}
	e_{T_0'}.
\]
On the other hand, the only set $S$ of type $(n-1,1)$ for which $e_{T_0}$ and $e_{T_0'}$ occur when we express $g_S$ as a linear combinator of $e_T$'s is
\[
   S = \{1,\dotsc,\wh\jmath,\dotsc,n,n+m\}.
\]
Using \eqref{double wedge} in the case $i = m$, the worst term of $g_S$ is its $e_{T_0}$-term,
\begin{equation}\label{e_T_0 term 2}
\begin{aligned}
   \WT(g_S) &= (e_1 \otimes 1) \wedge \dotsb \wedge \wh{(e_j \otimes 1)} \wedge \dotsb \wedge (e_{m-1} \otimes 1)\\ 
	   &\qquad \qquad\wedge (\pi e_m \otimes \pi\i) \wedge \dotsb \wedge (\pi e_n \otimes \pi\i) \wedge (e_m \otimes 1)\\
		&= - \pi^{-(m+1)} e_{T_0}.
\end{aligned}
\end{equation}
The $e_{T_0'}$-term in $g_S$ is
\begin{align*}
   &(e_1 \otimes 1)\wedge \dotsb \wedge \wh{(e_j \otimes 1)} \wedge \dotsb \wedge (e_{m-1} \otimes 1) \wedge (\pi e_m \otimes \pi\i) \\
	&\qquad\qquad\wedge (e_{m+1} \otimes 1) \wedge (\pi e_{m+2} \otimes \pi\i) \wedge \dotsb \wedge (\pi e_n \otimes \pi\i) \wedge (e_m \otimes 1)\\
 &\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad = (-1)^{m}\pi^{-m}e_{T_0'}.
\end{align*}
Condition \eqref{LM str spin cond} on $\CF_{m-1}$ then implies that
\[
   \det
	\begin{bmatrix}
		x_{mj}  &  x_{m,m+1}\\ 
		x_{m+1,j}  &  x_{m+1,m+1}
	\end{bmatrix}
	= \pi x_{mj}.
\]
If $j > m+1$, then one similarly finds that the same relation holds.  We conclude that
\begin{equation}\label{wedge 2'}
   x_{mj}x_{m+1,m+1} - x_{m+1,j}x_{m,m+1} = \pi x_{mj}, \quad j \neq m,m+1.
\end{equation}

To apply this to the third relation in \eqref{want}, suppose that $j < m$.  Combining \eqref{wedge 2'} and \eqref{orthog 2} (and again using that $2$ is a unit), it suffices to show that
\[
   \pi x_{mj} = x_{j^\vee,m+1}.
\]
We again consider the set $S = \{1,\dotsc,\wh\jmath,\dotsc,n,n+m\}$, and also its perp
\[
   S^\perp = \bigl\{ 1,\dotsc,\wh{m+1},\dotsc,n,n+j^\vee\bigr\}.
\]
Let
\[
   T_0'' := \bigl\{j^\vee,n+1,\dotsc, \wh{n+m+1},\dotsc,2n\bigr\}.
\]
The $e_{T_0''}$-term that occurs in the wedge product of the columns of \eqref{CF_m-1} is
\begin{equation}\label{e_T_0'' term}
   (-1)^m x_{j^\vee,m+1}e_{T_0''}.
\end{equation}
On the other hand, $S^\perp$ is the only set of type $(n-1,1)$ for which $g_{S^\perp}$ involves $e_{T_0''}$, and the $e_{T_0''}$-term in $g_S - \sgn(\sigma_S)g_{S^\perp} = g_S - (-1)^{j+m}g_{S^\perp}$ is then
\begin{align*}
   &(-1)^{j+m+1}(e_1 \otimes 1) \wedge \dotsb \wedge (e_{m-1} \otimes 1)\\ 
	   &\qquad \qquad \wedge (\pi e_m \otimes \pi\i) \wedge (\pi e_{m+2} \otimes \pi\i) \wedge \dotsb \wedge (\pi e_n \otimes \pi\i) \wedge (e_{j^\vee} \otimes 1)\\
		&\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad = (-1)^{j+m} \pi^{-m} e_{T_0''}.
\end{align*}
Since $\CF_{m-1}$ satisfies condition \eqref{LM str spin cond}, it follows from this, \eqref{e_T_0 term}, \eqref{e_T_0 term 2}, and \eqref{e_T_0'' term} that $\pi x_{mj} = x_{j^\vee,m+1}$, as desired.
A similar argument shows that the third relation in \eqref{want} holds when $j > m+1$.

We next show that the second and fourth relations in \eqref{want} hold.  Assume $j < m$.  By the second orthogonality relation in \eqref{orthog rel} (with $j$ in place of $i$ and $j^\vee$ in place of $j$) and by \eqref{wedge 2} (with $j^\vee$ in place of $i$), both of the desired relations follow (again using that $2$ is a unit) from showing that
\[
   x_{jj} - \pi = \pi - x_{j^\vee j^\vee}.
\]
For any $1 \leq i \leq n$, define
\[
   S_i := \{1,\dotsc,\wh\imath,\dotsc,n, n+i\}.
\]
Then $S_i^\perp = S_{i^\vee}$ and $\sgn(\sigma_S) = 1$.
By a similar calculation to the one in \cite[Lem.\ 4.11]{S}, for $i \leq m$,
\begin{align*}
   g_{S_i} - \sgn(\sigma_S)g_{S_i^\perp} 
	   &= g_{S_i} - g_{S_{i^\vee}}\\
	   &= (-1)^i g_1 \wedge \dotsb \wedge \wh g_i \wedge \dotsb \wedge \wh g_{i^\vee} \wedge \dotsb \wedge g_n\\
		&\qquad\qquad \wedge [(e_i \otimes 1) \wedge (e_{i^\vee} \otimes 1) - (\pi\i e_i \otimes 1) \wedge (\pi e_{i^\vee} \otimes 1)].
\end{align*}
It follows that $S_m$ and $S_{m+1}$ are the only sets $S$ of type $(n-1,1)$ for which $g_S - \sgn(\sigma_S)$ involves $e_{\{n+1,\dotsc,2n\}}$; and that for
\[
   T_j := \bigl\{j,n+1,\dotsc,\wh{n+j},\dotsc,2n\bigr\}
	\quad\text{and}\quad
	T_{j^\vee} := \bigl\{j^\vee,n+1,\dotsc,\wh{n+j^\vee},\dotsc,2n\bigr\},
\]
the sets $S_j,S_m,S_{m+1},S_{j^\vee}$ are the only sets $S$ of type $(n-1,1)$ for which $g_S - \sgn(\sigma_S)g_{S^\perp}$ involves $e_{T_j}$ (and ditto for $e_{T_{j^\vee}}$).  Furthermore, essentially the same argument as in the proof of \cite[Prop.\ 4.12]{S} (especially the last two paragraphs) shows that for $a_i \in F$,
\[
   \sum_{i = 1}^m a_i(g_{S_i}- g_{S_{i^\vee}}) \in \tensor*[^n]{\Lambda}{_{m-1}}
	\iff
	\ord_\pi(a_i) \geq m \text{ for all $i$, and $\ord_\pi(a_m) \geq m+1$}.
\]
Now note that the worst term in $g_{S_m}-g_{S_{m+1}}$ is its $e_{\{n+1,\dotsc,2n\}}$-term,
\begin{equation}\label{1}
   \WT(g_{S_m}-g_{S_{m+1}}) = (-1)^{m+1}\pi^{-(m+1)}e_{\{n+1,\dotsc,2n\}},
\end{equation}
and that the $e_{T_j}$- and $e_{T_{j^\vee}}$-terms in $g_{S_m}-g_{S_{m+1}}$ are, respectively,
\begin{equation}\label{2}
   (-1)^{m+1}\pi^{-m} (e\otimes 1) \wedge \dotsb \wedge \underbrace{(\pi\i e_j \otimes 1)}_{\makebox[0ex][c]{$\scriptstyle \text{in place of } e_j \otimes 1$}} \wedge \dotsb \wedge (e_{m-1}\otimes 1) \wedge (\pi e_m \otimes 1) \wedge \dotsb \wedge (\pi e_n \otimes 1)
\end{equation}
and
\begin{equation}\label{3}
	(-1)^{m+1}\pi^{-m} (e\otimes 1) \wedge \dotsb \wedge (e_{m-1}\otimes 1) \wedge (\pi e_m \otimes 1) \wedge \dotsb \wedge \underbrace{(e_{j^\vee} \otimes 1)}_{\makebox[0ex][c]{$\scriptstyle \text{in place of } \pi e_{j^\vee} \otimes 1$}} \wedge \dotsb \wedge (\pi e_n \otimes 1).
\end{equation}
Similarly, the $e_{T_j}$- and $e_{T_{j^\vee}}$-terms in $g_{S_j}-g_{S_{j^\vee}}$ are, respectively,
\begin{equation}\label{4}
   (-1)^{i+1}\pi^{-m} (e\otimes 1) \wedge \dotsb \wedge \underbrace{(\pi\i e_j \otimes 1)}_{\makebox[0ex][c]{$\scriptstyle \text{in place of } e_j \otimes 1$}} \wedge \dotsb \wedge (e_{m-1}\otimes 1) \wedge (\pi e_m \otimes 1) \wedge \dotsb \wedge (\pi e_n \otimes 1)
\end{equation}
and
\begin{equation}\label{5}
	(-1)^i\pi^{-m} (e\otimes 1) \wedge \dotsb \wedge (e_{m-1}\otimes 1) \wedge (\pi e_m \otimes 1) \wedge \dotsb \wedge \underbrace{(e_{j^\vee} \otimes 1)}_{\makebox[0ex][c]{$\scriptstyle \text{in place of } \pi e_{j^\vee} \otimes 1$}} \wedge \dotsb \wedge (\pi e_n \otimes 1).
\end{equation}
Note that the coefficients in (\ref{2}) and (\ref{3}) are $\pi$ times the coefficient in (\ref{1}), and that there is a relative sign of $-1$ between the coefficients in (\ref{4}) and (\ref{5}).  When we express the wedge product of the columns of (\ref{CF_m-1}) as a linear combination of $e_T$'s, since the coefficient of $e_{\{n+1,\dotsc,2n\}}$ is evidently $1$, and since $\CF_{m-1}$ satisfies condition \eqref{LM str spin cond}, it follows that
\[
   x_{jj} = \pi + c
	\quad\text{and}\quad x_{j^\vee j^\vee} = \pi - c
\]
for some scalar $c$.  Hence $x_{jj} - \pi = \pi - x_{j^\vee j^\vee}$, as desired.

To complete the proof, it remains to show that the relations \eqref{m+1} hold.  This is now very easy: the first and third relations are obvious from the third relation in \eqref{want} and from \eqref{orthog 2} (both with $i^\vee$ in place of $j$), and the second relation is obvious from the orthogonality relation \eqref{orthog 3}.
\end{proof}

\begin{remark}[$n=2$]\label{forgetful LM isom n=2}
Proposition \ref{lm isom} is a generalization of (part of) \cite[Rem. 2.35]{PRS}, which contains the case $n = 2$.
\end{remark}

\begin{remark}\label{not flat}
In the case that $(r,s) = (n-1,1)$, we remark that if one weakens the moduli problem defining $M_{\{m-1\}}$ by substituting the spin condition \eqref{LM spin cond} for condition \eqref{LM str spin cond}, then the resulting scheme can fail to be carried by $\nu$ into $M_{\{m\}}$, and hence can fail to be flat.  To give a simple example, take $R := O_F/\varpi O_F$, and let $\CF_{m-1} := (\pi \otimes 1)(\Lambda_{m-1} \otimes_{O_{F_0}} R) \subset \Lambda_{m-1} \otimes_{O_{F_0}} R$.  Then $\pi \otimes 1$ acts as $0$ on $\CF_{m-1}$.  If the characteristic of $k$ divides $n - 2$, then $\CF_{m-1}$ satisfies the Kottwitz condition, and it is easy to see that $\CF_{m-1}$ furthermore gives a point in $M_{\{m-1\}}^\naive(R)$ satisfying the wedge and spin conditions.  However, the corresponding point $\nu(\CF_{m-1}) \in C_{\{m\}}(R)$ is 
given by
\[
   \nu(\CF_{m-1}) = \spann_R\{e_1\otimes 1,\dotsc,e_{m-1}\otimes 1,e_{m+1}\otimes 1, \pi e_{m+1}\otimes 1,\dotsc, \pi e_n\otimes 1\},
\]
which does not satisfy the wedge condition.  This shows that for even $n = 2m$ and signature $(r,s) = (n-1,1)$, the statement of \cite[Conj.~7.3]{PR} can fail for $I = \{m-1\}$.  Now, strictly speaking, such an $I$ is not allowed in this conjecture (cf.~\S\S1.4, 7.2.1 in loc.~cit.), so this does not give an honest counterexample.  It would be interesting to see if this example sheds any light on the validity of this conjecture for those $I$ which are allowed.  (It is known that this conjecture can fail for odd $n$ and signature $(n-1,1)$, cf.~\cite{S}.)
\end{remark}









\part{The conjectures}\label{conjectures}

In this part of the paper, we formulate various arithmetic transfer conjectures arising from morphisms between the spaces we have defined previously.  Except where noted to the contrary, we denote by $S = S_n$ the scheme over $\Spec F_0$ defined in \eqref{S_n}.



\section{Arithmetic transfer conjecture, $F/F_0$ unramified, almost self-dual type}\label{s:ATunr}
In this section $F/F_0$ is unramified and $n\geq 2$, as in \S\ref{unram non-max}.  We take the special vectors $u_i\in W_i$ (cf.~\S\ref{setup homog}) to satisfy $(u_i, u_i)=\varpi$.  Recall the $p$-divisible group $\ov\CE$ from the Introduction, with its $O_F$-action $\iota_{\ov\CE}$, principal polarization $\lambda_{\ov\CE}$, and framing isomorphism $\rho_{\ov\CE}$.  Let
\[
   \ov\CE' := \ov{{\CE}},
	\quad
	\iota_{\ov\CE'} := \iota_{\ov\CE},
	\quad
	\lambda_{\ov\CE'} := \varpi\lambda_{\ov\CE},
	\quad\text{and}\quad
	\rho_{\ov\CE'} := \rho_{\ov\CE}\colon \ov\CE'_{\ov k} \isoarrow \ov\BE',
\]
where $\ov\BE'$ is defined in \eqref{ovBE'}.  Then $\rho_{\ov\CE'}$ is $O_F$-linear, and $\rho_{\ov\CE'}^*(\lambda_{\ov\BE'}) = (\lambda_{\ov\CE'})_{\ov k}$.  We define a closed embedding of formal schemes
\begin{equation*}
   \wt\delta_\CN \colon
	\xymatrix@R=0ex{
	   \CN_{n-1} \ar[r]  &  \wt\CN_n\\
		(X, \iota, \lambda, \rho) \ar@{|->}[r]
		   &  \bigl(X \times \ov\CE', \iota \times \iota_{\ov\CE'},
                 \lambda \times \lambda_{\ov\CE'}, \rho \times \rho_{\ov\CE'} \bigr) .
   }
\end{equation*}
Here the last entry is a framing to the constant object in the special fiber defined by $\wt\BX_n = \BX_{n-1} \times \ov\BE'$, cf.~\eqref{wtBX_n unram}.   We therefore obtain as in the case of the AFL a closed embedding
\begin{equation*}
   \wt\Delta_\CN \colon \CN_{n-1} \xra{(\id_{\CN_{n-1}},\wt\delta_\CN)} \wt\CN_{n-1,n} = \CN_{n-1}\times_{\Spf O_{\breve F}}\wt\CN_n,
\end{equation*}
whose image we denote by
\[
   \wt\Delta := \wt\Delta_\CN (\CN_{n-1}).
\]
Note that the canonical vector
\[
   u := (0,\id_{\ov\BE}) \in \BV\bigl(\wt\BX_n\bigr) = \BV(\BX_{n-1}) \oplus \BV\bigl(\ov\BE'\bigr)
\]
has norm $\varpi$.  Since $\BV(\BX_{n-1})$ is non-split, it follows from \eqref{chi decomp formula} that $\BV(\wt\BX_n)$ is split.  Thus we may identify the triple $(\BV(\wt\BX_n), u, \BV(\BX_{n-1}))$ with $(W_0,u_0,W_0^\flat)$. In this way $H_0(F_0)$ acts on $\CN_{n-1}$, $G_{W_0}$ acts on $\wt\CN_n$, and $\wt\Delta_\CN$ is equivariant for the embedding $H_0(F_0) \hookrightarrow G_{W_0}(F_0)$.

\begin{remark}
We note that the image of $\wt\delta_\CN$ is contained in the smooth locus of $\widetilde{\CN}_n$. Indeed, via the usual local model diagram argument, it suffices to prove the analogous claim for the corresponding map on local models.  Identifying the local model for $\wt\CN_n$ with the standard local model for $\GL_n$ as in the proof of Theorem \ref{wtCN_n semistable}, points  $(\CF_i' \subset (\Lambda_i \otimes_{O_{F_0}} \CO_S)')_{i=0,1}$ which lie in the image of this map have the property that the induced map $(\Lambda_0 \otimes_{O_{F_0}} \CO_S)'/\CF_0'\to (\Lambda_1\otimes_{O_{F_0}} \CO_S)'/\CF_1'$ is an isomorphism.  Such points are contained in the smooth locus, which is easy to deduce from the explicit description in \cite[\S4.4.5]{Goertz} (in the case $\kappa = 1$ and $r = n-1$).
\end{remark}

\begin{remark}\label{diag cycle}
As in the case of the formal scheme $\CN_n$ in Remark \ref{reltospecialunr}, one can define a special cycle $\wt\CZ(u)$ in $\wt\CN_n$ as the locus where the quasi-homomorphism $u\colon \ov\BE\to \BX_n$ lifts to a homomorphism from $\ov\CE$ to the universal object over $\wt\CN_n$.  When $n=2$, it is known that $\wt\CZ(u)$ is a relative divisor and that $\wt\delta_\CN$ induces an isomorphism $\CN_1\simeq \wt\CZ(u)$, cf.\ \cite[Th.~3.14]{San}. In this case
\[
   (1\times g)\wt\Delta = \wt\CZ(gu) , \quad g\in \U\bigl(\BV(\BX_2)\bigr) .
\]
Hence for $n=2$,  the intersection number $\Int(g)$ appearing in Conjecture \ref{conjunramified} below is  a special case of the intersection number of two \emph{unitary special divisors}, in the terminology of Sankaran.
\end{remark}

Now fix a self-dual lattice
\[
   \Lambda_1^\flat \subset W_1^\flat,
\]
which exists (and is unique up to $H_1(F_0)$-conjugacy) since $W_1^\flat$ is split by \eqref{chi decomp formula}. Let
\[
   \Lambda_1 := \Lambda_1^\flat \oplus O_F u_1 \subset W_1.
\]
Then $\Lambda_1$ is an almost self-dual $O_F$-lattice, i.e.~$\Lambda_1\subset^1 \Lambda_1^\vee\subset \varpi^{-1}{\Lambda}_1$.  Let
\[
   K_1^\flat \subset H_1(F_0)
\]
denote the stabilizer of $\Lambda_1^\flat$, and let
\[
	K_1 \subset G_1(F_0)
	\quad\text{and}\quad
	\fkk_1 \subset \fkg_1(F_0)
\]
denote the respective stabilizers of $\Lambda_1$.  Then $K_1^\flat$ and $K_1$ are both maximal parahoric subgroups. We normalize the Haar measure on $H_1(F_0)$ (and hence the product measure on $H_{W_1}(F_0) = H_1(F_0) \times H_1(F_0)$) by assigning $K_1^\flat$ volume $1$. We normalize the Haar measures on $H'_1 ({F_0})$ and $H'_2 ({F_0})$ as  in \S\ref{s:FL}, and we take the transfer factors $\omega_{G'}$ on $G'(F_0)_\rs$, $\omega_S$ on $S(F_0)_\rs$, and $\omega_\fks$ on $\fkg(F_0)_\rs$ as in \eqref{sign}.

Before stating the ATC in the present situtation, we first formulate a fundamental lemma conjecture; this will, in turn, motivate an AFL conjecture as part of the ATC. On the general linear group side, let
\begin{align*}
   K_0(\varpi) := \biggl\{\,g\in \GL_n(O_F) \biggm| g\equiv 
	\begin{bmatrix}
		*  &  0  \\
      *  &  *
   \end{bmatrix}  \bmod \varpi \,\biggr\}
\end{align*}
(diagonal blocks of respective sizes $(n-1) \times (n-1)$ and $1 \times 1$), and define
\begin{align}\label{eqn K' S}
   K' := S(O_{F_0})\cap K_0(\varpi)\subset S(F_0).
\end{align}
We also make the Lie algebra versions of these definitions,
\begin{align}\label{eqn fkk0}
   \fkk_0(\varpi) :=
	   \biggl\{\, y\in \gl_n(O_F) \biggm| y\equiv 
		\begin{bmatrix}
		   *  &  0  \\
         *  &  *
      \end{bmatrix}  \bmod \varpi \,\biggr\}
\end{align}
(same block sizes as before) and
\begin{align}\label{eqn fkk'}
   \fkk' := \fks(O_{F_0})\cap \fkk_0(\varpi).
\end{align}

\begin{conjecture}[Fundamental lemma]\label{FL almost self-dual}\hfill
\begin{altenumerate}
\renewcommand{\theenumi}{\alph{enumi}}
\item\label{FL almost self-dual homog}
\textup{(Homogeneous version)} The function $(-1)^{n-1}\frac{q^n-1}{q-1}\mathbf{1}_{\GL_{n-1}(O_F)\times K_0(\varpi)} \in C_c^\infty(G')$ transfers to the pair of functions $(0,\mathbf{1}_{K_1^\flat\times K_1}) \in C_c^\infty(G_{W_0}) \times C_c^\infty(G_{W_1})$. 
\item\label{FL almost self-dual inhomog}
\textup{(Inhomogeneous version)} The function $(-1)^{n-1}\mathbf{1}_{K'} \in C_c^\infty(S)$ transfers to the pair of functions $(0,\mathbf{1}_{K_1}) \in C_c^\infty(G_0)\times C_c^\infty(G_1)$.
\item\label{FL almost self-dual lie}
\textup{(Lie algebra version)} The function $(-1)^{n-1}\mathbf{1}_{\fkk'} \in  C_c^\infty(\fks)$ transfers to the pair of functions $(0,\mathbf{1}_{\fkk_1}) \in C_c^\infty(\fkg_0)\times C_c^\infty(\fkg_1)$.
\end{altenumerate}
\end{conjecture}

We will show in Theorem \ref{unram variant FL} below that part (\ref{FL almost self-dual lie}) of this conjecture is equivalent to the Lie algebra FL Conjecture \ref{FLconj}(\ref{FLconj lie}), and that parts (\ref{FL almost self-dual homog}) and (\ref{FL almost self-dual inhomog}) follow from these when $q \geq n$.

We now come to the ATC, as well as an AFL conjecture for the functions appearing on the general linear group side of Conjecture \ref{FL almost self-dual}. In analogy with \eqref{defintprod}, for $g \in G_{W_0}(F_0)_\rs$ we set
\[
   \Int(g) := \bigl\la \wt\Delta, g \wt\Delta \bigr\ra _{\wt\CN_{n-1, n}},
\]
and for $g \in G_0(F_0)_\rs$ we set
\[
   \Int(g) := \bigl\la \wt\Delta, (1 \times g) \wt\Delta \bigr\ra _{\wt\CN_{n-1, n}}.
\]
In the Lie algebra setting, for any quasi-endomorphism $x$ of $\wt\BX_n$, and in particular for $x \in \fkg_0(F_0) = \Lie \RU(\BV(\wt\BX_n))(F_0) \cong \{ x \in \End_{O_F}^\circ(\wt\BX_n) \mid x + \Ros_{\lambda_{\wt\BX_n}}(x) = 0 \}$, we define (abusing notation in the obvious way, as in \eqref{Delta_x})
\[
   \wt\Delta_x := \bigl\{\, (Y,X) \in \wt\CN_{n-1,n} \bigm| x\colon \wt\BX_n \rightarrow \wt\BX_n \text{ lifts to a homomorphism } Y \times \ov\CE' \rightarrow X \,\bigr\}.
\]
As in the case of \eqref{Delta_x}, when $g \in G_0(F_0)$ we have $\wt\Delta_g = (1 \times g)\wt\Delta$.
When $\wt\Delta \cap \wt\Delta_x$ is an artinian scheme, we define
\[
   \lInt(x) := \length\bigl(\wt\Delta \cap \wt\Delta_x\bigr).
\]



\begin{conjecture}[Arithmetic transfer conjecture and arithmetic fundamental lemma, almost self-dual case]\label{conjunramified} \hfill
\begin{altenumerate}
\renewcommand{\theenumi}{\alph{enumi}}
\item\label{conjunramified homog}
\textup{(Homogeneous version)}
Let $f' \in C^{\infty}_c (G')$ be a function transferring to the pair $(0, \mathbf{1}_{K_1^\flat \times K_1}) \in C_c^\infty(G_{W_0}) \times C_c^\infty(G_{W_1})$.  Then there exists a function $f'_\corr \in C^{\infty}_c (G')$ such that, for any $\gamma \in G'(F_0)_\rs$ matching an element $g \in G_{W_0}(F_0)_\rs$,
\begin{equation*}
   \omega_{G'} (\gamma)\del(\gamma, f') = - 2\Int(g)\cdot \log q + \omega (\gamma)\Orb(\gamma, f'_\corr).
\end{equation*}
Furthermore, for all such matching $\gamma$ and $g$, there is an AFL identity
\begin{equation*}
   \omega_{G'} (\gamma)\del\biggl(\gamma, (-1)^{n-1}\frac{q^n-1}{q-1} \cdot \mathbf{1}_{\GL_{n-1}(O_F)\times K_0(\varpi)} \biggr) = - 2\Int(g)\cdot \log q.
\end{equation*}
\item\label{conjunramified inhomog}
\textup{(Inhomogeneous version)}
Let $f' \in C^{\infty}_c(S)$ be a function transferring to the pair $(0, \mathbf{1}_{K_1}) \in C_c^\infty(G_0) \times C_c^\infty(G_1)$. Then there exists a function $f'_\corr \in C^{\infty}_c (S)$ such that, for any $\gamma \in S(F_0)_\rs$ matching an element $g \in G_0(F_0)_\rs$,
\begin{equation*}
   \omega_S (\gamma)\del(\gamma, f') = - \Int(g)\cdot \log q + \omega (\gamma)\Orb(\gamma, f'_\corr).
\end{equation*}
Furthermore, for all such matching $\gamma$ and $g$, there is an AFL identity
\begin{equation*}
   \omega_S (\gamma)\del\bigl(\gamma, (-1)^{n-1}\mathbf{1}_{K'}\bigr) = - \Int(g)\cdot \log q .
\end{equation*}
\item\label{conjunramified lie}
\textup{(Lie algebra version)}
Let $\phi' \in C^{\infty}_c (\fks)$ be a function transferring to the pair $(0, \mathbf{1}_{\fkk_1}) \in C_c^\infty(\fkg_0) \times C_c^\infty(\fkg_1)$. Then there exists a function $\phi'_\corr \in C^{\infty}_c (S)$ such that, for any $y \in \fks(F_0)_\rs$ matching an element $x \in \fkg_0(F_0)_\rs$ for which the intersection $\wt\Delta \cap \wt\Delta_x$ is an artinian scheme,
\begin{equation*}
   \omega_\fks (y)\del(y, \phi') = - \lInt(x)\cdot \log q + \omega (y)\Orb(y, \phi'_\corr).
\end{equation*}
Furthermore, for all such matching $y$ and $x$, there is an AFL identity
\begin{equation*}
   \omega_\fks (y)\del\bigl(y, (-1)^{n-1}\mathbf{1}_{\fkk'}\bigr) = - \lInt(x)\cdot \log q .
\end{equation*}
\end{altenumerate}
\end{conjecture}

In \S\ref{results atc afl} we will show that Conjecture \ref{conjunramified} reduces to the AFL in the self-dual case (i.e.\ Conjecture \ref{AFLconj}) in the case of a nondegenerate intersection.  In particular, this will show that the conjecture holds when $n = 2$ or $n = 3$. 





\section{Arithmetic transfer conjecture, $F/F_0$ ramified,  $n$ odd}\label{s:ATCodd}
In this section $F/F_0$ is ramified, $n \geq 3$ is odd, and we take the special vectors $u_i\in W_i$ to have norm $1$.  This case is the subject of \cite{RSZ}, to which we refer the reader for more details.  We continue to use the $p$-divisible group $\ov\CE$ and its attendant structure from the Introduction.  Recall from \S\ref{odd ram max} that we take $\CN_n=\CN^{(1)}_n$, i.e.~we require that the hermitian space $\BV(\BX_n)$ attached to the framing object $\BX_n = \BX_n^{(1)}$ is non-split. As in the case of the AFL, taking the product with $\ov\CE$ defines a closed embedding of formal schemes
\begin{equation*}
   \delta_\CN\colon
   \xymatrix@R=0ex{
	   \CN_{n-1} \ar[r]  &  {\CN}_n\\
		(X, \iota, \lambda, \rho) \ar@{|->}[r]  
		   &  \bigl(X \times \ov\CE, \iota \times \iota_{\ov\CE}, \lambda \times \lambda_{\ov\CE}, \rho \times \rho_{\ov\CE}\bigr).
	}
\end{equation*}
Here the last entry is a framing to the constant object over the special fiber defined by $\BX_n = \BX_{n-1} \times \ov{\BE}$.  We obtain as before a closed embedding
\begin{equation*}
   \Delta_\CN\colon \CN_{n-1} \xra{(\id_{\CN_{n-1}},\delta_\CN)} \CN_{n-1,n} = \CN_{n-1} \times_{\Spf O_{\breve F}} \CN_n,
\end{equation*}
whose image we again denote by
\[
   \Delta := \Delta_\CN(\CN_{n-1}).
\]
Let
\[
   u := (0,\id_{\ov\BE}) \in \BV(\BX_n) = \BV(\BX_{n-1}) \oplus \BV\bigr(\ov\BE\bigl),
\]
which is a vector of norm $1$.  Since $\BV(\BX_n)$ is non-split, we may therefore identify the triple $(\BV(\BX_n), u, \BV(\BX_{n-1}))$ with $(W_1,u_1,W_1^\flat)$.  In this way $\Delta_\CN$ is equivariant for the embedding $H_1(F_0) \hookrightarrow G_{W_1}(F_0)$ as before.

Now recall that in the ramified case, an $F/F_0$-hermitian space contains a $\pi$-modular lattice $\Lambda$ (i.e.~$\Lambda^\vee = \pi^{-1}\Lambda$) if and only if the space is split of even dimension (and all $\pi$-modular lattices are then conjugate under the unitary group). By \eqref{chi decomp formula} this is the case for $W_0^\flat$, and therefore we may fix a $\pi$-modular lattice
\[
   \Lambda_0^\flat \subset W_0^\flat.
\]
Let
\[
   \Lambda_0 := \Lambda_0^\flat \oplus O_Fu_0 \subset W_0.
\]
Then $\Lambda_0$ is almost $\pi$-modular, i.e.~$\Lambda_0 \subset \Lambda_0^\vee \subset^1 \pi^{-1}\Lambda_0$.  Let
\[
   K_0^\flat \subset H_0(F_0)
\]
denote the stabilizer of $\Lambda_0^\flat$, and let
\[
	K_0 \subset G_0(F_0)
	\quad\text{and}\quad
	\fkk_0 \subset \fkg_0(F_0)
\]
denote the respective stabilizers of $\Lambda_0$. Then $K_0^\flat $ is a special maximal parahoric subgroup, and $K_0$ contains a special maximal parahoric subgroup with index $2$, cf.~\cite[\S4.a]{PR-TLG}. We normalize the Haar measure on $H_0(F_0)$ (and hence the product measure on $H_{W_0}(F_0) = H_0(F_0) \times H_0(F_0)$) by assigning $K_0^\flat$ volume $1$. We normalize the Haar measures on $H'(F_0)$, $H'_1 ({F_0})$, and $H'_2 ({F_0})$ as in \S\ref{s:FL}.  We finally define the intersection number $\Int(g)$ for $g \in G_{W_1}(F_0)_\rs$ or $g \in G_1(F_0)_\rs$, and the formal locus $\Delta_x$ and the quantity $\lInt(x)$ for $x \in \fkg_1(F_0)_\rs$, as in \S\ref{s:AFL}.

\begin{conjecture}[Arithmetic transfer conjecture]\label{ATC ram odd}\hfill
\begin{altenumerate}
\renewcommand{\theenumi}{\alph{enumi}}
\item
\textup{(Homogeneous version)}
Let $f' \in C^{\infty}_c (G')$ be a function transferring to the pair $(\mathbf{1}_{K_0^\flat \times K_0}, 0) \in C_c^\infty(G_{W_0}) \times C_c^\infty(G_{W_1})$. Then there exists a function $f'_\corr \in C^{\infty}_c (G')$ such that, for any $\gamma \in G'(F_0)_\rs$ matching an element $g \in G_{W_1}(F_0)_\rs$,
\begin{equation*}
   \omega_{G'} (\gamma)\del(\gamma, f') = - \Int(g)\cdot \log q + \omega (\gamma)\Orb(\gamma, f'_\corr).
\end{equation*}
Furthermore, there exist such functions $f'$ for which $f'_\corr = 0$.
\item
\textup{(Inhomogeneous version)}
Let $f' \in C^{\infty}_c (S)$ be a function transferring to the pair $(\mathbf{1}_{K_0}, 0) \in C_c^\infty(G_0) \times C_c^\infty(G_1)$. Then there exists a function $f'_\corr \in C^\infty_c(S)$ such that, for any $\gamma \in S(F_0)_\rs$ matching an element $g \in G_1(F_0)_\rs$,
\begin{equation*}
   2 \omega_S (\gamma)\del(\gamma, f') = - \Int(g)\cdot \log q + \omega (\gamma)\Orb(\gamma, f'_\corr).
\end{equation*}
Furthermore, there exist such functions $f'$ for which $f'_\corr = 0$.
\item
\textup{(Lie algebra version)}
Let $\phi' \in C^{\infty}_c (\fks)$ be a function transferring to the pair $(\mathbf{1}_{\fkk_0},0) \in C_c^\infty(\fkg_0) \times C_c^\infty(\fkg_1)$. Then there exists a function $\phi'_\corr \in C^{\infty}_c (\fks)$ such that, for any $y \in \fks(F_0)_\rs$ matching an element $x \in \fkg_1(F_0)_\rs$ for which the intersection $\Delta \cap \Delta_x$ is an artinian scheme,
\begin{equation*}
   2\omega_\fks (y)\del(y, \phi') = - \lInt(x)\cdot \log q + \omega (y)\Orb(y, \phi'_\corr).
\end{equation*}
Furthermore, there exist such functions $\phi'$ for which $\phi'_\corr = 0$.
\end{altenumerate}
\end{conjecture}

A proof of this conjecture in the case $F_0 = \BQ_p$ and $n=3$ is contained in \cite{RSZ}.







\section{Arithmetic transfer conjecture, $F/F_0$ ramified, $n$ even}\label{s:ATCeven}
In this section $F/F_0$ is ramified, $n \geq 2$ is even, and we take the special vectors $u_i \in W_i$ to have norm $-1$.  We are going to formulate an AT conjecture analogous to the ones we have already encountered, but the setup this time is more complicated.  Indeed, in this case
``taking the product with $\ov\CE$'' defines a map on $\CN_{n-1}$ with values in the space $\CP_n$ defined in \S\ref{aux spaces}. Since $\CP_n$ is not regular, we cannot emulate the formulation of the previous AFL and AT conjectures in the most literal-minded fashion, with $\CP_n$ in the place of $\CN_n$.  Instead, we will use the results of \S\ref{aux spaces} to compose the morphism $\CN_{n-1} \to \CP_n$ with a morphism (in fact, two of them) from $\CP_n$ to $\CN_n$.

To make this precise, recall from Example \ref{CN_1} the universal object $(\CE,\iota_\CE,-\lambda_\CE,\rho_\CE)$ over $\CN_1$.
Taking the product with the conjugate of this object defines a closed embedding
\begin{equation}\label{wtdelta_CN}
	\begin{gathered}
   \wt\delta_\CN \colon
	\xymatrix@R=0ex{
	   \CN_{n-1} \ar[r]  &  \CP_n\\
		(X, \iota, \lambda, \rho) \ar@{|->}[r]  
		   &  \bigl(X \times \ov\CE, \iota \times \iota_{\ov\CE}, 
			       \lambda \times (-\lambda_{\ov\CE}), \rho \times \rho_{\ov\CE} \bigr),
	}
	\end{gathered}
\end{equation}
where the last entry is a framing to the constant object over the special fiber defined by $\wt\BX_n = \BX_{n-1} \times \ov\BX_1$, cf.~\eqref{wtBX_n^(1) def}.  Note that for $\wt\delta_\CN$ to be well-defined, it must produce quadruples satisfying the wedge condition and condition \eqref{even wtCN spin cond} on $\CP_n$.  It is straightforward, albeit tedious, to verify directly that this follows from the wedge condition and condition \eqref{odd spin cond} on $\CN_{n-1}$.  More conceptually, note that there is an obvious analog of the morphism $\wt\delta_\CN$ between the naive local models (cf.\ Definition \ref{LM def}) for $\CN_{n-1}$ and $\CP_n$; this is explicitly given by the formula for the first arrow in (\ref{LM delta_CN^pm}) below.  Since the (honest) local model for $\CN_{n-1}$ is flat, it is automatically carried into the (honest) local model for $\CP_n$, which proves that $\wt\delta_\CN$ is well-defined.

Now recall from \S\ref{aux spaces} the space $\CP_n'$, its tautological projections $\CP_n' \to \CP_n$ and $\CP_n' \xra\varphi \CN_n$, and its decomposition $\CP_n' = (\CP_n')^+ \amalg (\CP_n')^-$.  By Theorem \ref{wtCN'pm isom}, the projection to $\CP_n$ sends each of these summands isomorphically to $\CP_n$, and we denote by $\psi^\pm$ the inverse isomorphism $\CP_n \isoarrow (\CP_n')^\pm$.  We then define the composite morphism
\[
   \delta_\CN^\pm \colon 
	   \CN_{n-1} \xra{\wt\delta_\CN} 
		\CP_n \xra[\undertilde]{\psi^\pm}
		(\CP_n')^\pm \xra\varphi
		\CN_n.
\]

\begin{proposition}\label{delta^pm closed emb}
The morphism $\delta_\CN^\pm$ is a closed embedding.
\end{proposition}

\begin{proof}
Since $\CN_{n-1}$ is essentially proper over $\Spf O_{\breve F}$, it suffices to show that $\delta_\CN^\pm$ is universally injective and formally unramified.  For the first claim, for notational simplicity we just show that $\delta_\CN^\pm$ is an injection on $\ov k$-points; the argument for points in an arbitrary algebraically closed field is the same.  Let $\BN_n$, $\wt\BN_n$, $\BN_{n-1}$, and $\ov\BN_1$ denote the (covariant, as always) rational Dieudonn\'e modules of $\BX_n$, $\wt\BX_n$, $\BX_{n-1}$, and $\ov\BX_1$, respectively. We endow all of these with an $\breve F/\breve F_0$-hermitian structure as before.  In particular, $\ov\BN_1$ is a $1$-dimensional $\breve F$-vector space, and we choose a basis vector $e$ such that $O_{\breve F}e \subset \ov\BN_1$ is the (self-dual) Dieudonn\'e lattice of $\ov\BX_1$.  Identify $\BN_n$ with $\wt\BN_n = \BN_{n-1} \oplus \ov\BX_1$ via the isogeny $\phi_0$ in \eqref{phi_0}.  Let $(Y,\iota,\lambda,\rho) \in \CN_{n-1}(\ov k)$ with Dieudonn\'e module $L \subset \BN_{n-1}$. Our problem is to show that if $M$ is a $\pi$-modular Dieudonn\'e lattice in $\BN_n$ with $\pi L^\vee \oplus \pi O_{\breve F} e \subset^1 M \subset^1 L \oplus O_{\breve F} e$, then we can recover $L$ uniquely from $M$.  Since the image of $M$ in $(L \oplus O_{\breve F} e)/(\pi L^\vee \oplus \pi O_{\breve F} e)$ is an isotropic line and $e$ has non-zero norm modulo $\pi$, we have $e \notin M$.  Hence $M + O_{\breve F}e = L \oplus O_{\breve F} e$, from which we can indeed recover $L$. 

To show that $\delta_\CN^\pm$ is formally unramified, it suffices to show that the corresponding map on local models is a closed embedding; the conclusion then follows from the usual local model diagram argument.  We use (essentially) the notation of \S\ref{odd ram max} for lattices and related objects in $F^n$, and we use a $\flat$ to denote the analogous objects in $F^{n-1}$.  In particular, we denote by $e_1^\flat,\dotsc,e_{n-1}^\flat$ the standard basis in $F^{n-1}$, endowed with the standard split hermitian form \eqref{herm form}.  Consider a one-dimensional hermitian space $Fe$ with basis vector $e$ of norm $-1$, and let $\Lambda := O_F e \subset Fe$ denote the self-dual lattice.  We take the vectors
\[
   e_i := e_i^\flat, \quad 1 \leq i \leq m-1; \quad e_m := e_m^\flat - e; \quad e_{m+1} := \frac{e_m^\flat + e} 2;  \quad e_i := e_{i-1}^\flat, \quad m+2 \leq i \leq n
\]
as a basis for $F^{n-1} \oplus Fe$.  With respect to this basis, the orthogonal sum of the hermitian forms on $F^{n-1}$ and $Fe$ is the standard one \eqref{herm form}.  We define the lattices $\Lambda_i \subset F^{n-1} \oplus Fe$ with respect to $e_1,\dotsc,e_n$ as in \S\ref{odd ram max}.  In particular, we have $\Lambda_{m-1} = \Lambda_{m-1}^\flat \oplus \Lambda$.  Let $M_{\{m-1\}}$ and $M_{\{m\}}$ denote the schemes over $\Spec O_F$ defined in Definition \ref{LM def} in the case of signature $(r,s) = (n-1,1)$,\footnote{When $(r,s) = (1,1)$, these schemes are defined over $\Spec O_{F_0}$, and here we implicitly replace them with their base change to $\Spec O_F$.} and analogously let $M_{\{m-1\}}^\flat$ denote the scheme defined with respect to the basis $e_1^\flat,\dotsc,e_{n-1}^\flat$ in the case of signature $(r,s) = (n-2,1)$ and $I = \{\lfloor \frac{n-1}2 \rfloor\} = \{m-1\}$. Then $M_{\{m-1\}}^\flat$, $M_{\{m-1\}}$, and $M_{\{m\}}$ are the local models for $\CN_{n-1}$, $\CP_n$, and $\CN_n$, respectively.  The map between local models corresponding to $\delta_\CN^\pm$ is the composite
\begin{equation}\label{LM delta_CN^pm}
\begin{gathered}
	\xymatrix@R=0ex{
	   M_{\{m-1\}}^\flat \ar[r]  &  M_{\{m-1\}} \ar[r]^-\nu  &  M_{\{m\}}\\
		\CF_{m-1} \ar@{|->}[r]  &  \CF_{m-1} \oplus \CF
	}
\end{gathered},
\end{equation}
where, for $S$ a base scheme, $\CF$ is the rank one submodule $(e \otimes \pi + \pi e \otimes 1) \subset \Lambda \otimes_{O_{F_0}} \CO_S$, and $\nu$ is the morphism \eqref{nu} (here we use Proposition \ref{lm isom}(\ref{lm isom ii}) in the case $I = \{m-1\}$, which, as in the proof of this proposition, is equivalent to the fact that $\nu$ carries $M_{\{m-1\}}$ into $M_{\{m\}}$). Since the local models are proper, to show that the morphism \eqref{LM delta_CN^pm} is a closed embedding, we need only show that it is a monomorphism.  Let $\CF_{m-1}$ be an $S$-point on $M_{\{m-1\}}^\flat$. Note that the inclusions $\Lambda_{m-1}^\flat \subset \Lambda_{m-1} \subset \Lambda_m$ present $\Lambda_{m-1}^\flat$ as a direct summand of $\Lambda_m$.  Therefore, in the notation of \eqref{T_i}, $T_{m-1}(\Lambda_{m-1}^\flat \otimes_{O_{F_0}} \CO_S)$ is a direct summand of $\Lambda_m \otimes_{O_{F_0}} \CO_S$, and $T_{m-1}(\CF_{m-1})$ is a locally direct summand of rank $n-1$. The proof of Lemma \ref{LM mapping lem} then shows that $\nu(\CF_{m-1} \oplus \CF)$ is the unique Lagrangian submodule in $\Lambda_m \otimes_{O_{F_0}} \CO_S$ for the form $\sform_m$ (cf.~Remark \ref{I=m}) which contains $T_{m-1}(\CF_{m-1})$ and satisfies the spin condition.  Now, one sees readily that $\sform_m$ restricts to a nondegenerate split symmetric form on $T_{m-1}(\Lambda_{m-1}^\flat \otimes_{O_{F_0}} \CO_S)$, and hence $T_{m-1}(\CF_{m-1})$ is Lagrangian in $T_{m-1}(\Lambda_{m-1}^\flat \otimes_{O_{F_0}} \CO_S)$.  Hence
\[
   \nu(\CF_{m-1} \oplus \CF) \cap T_{m-1}(\Lambda_{m-1}^\flat \otimes_{O_{F_0}} \CO_S) = T_{m-1}(\CF_{m-1}),
\]
which shows that we can recover $\CF_{m-1}$ from its image in $M_{\{m\}}$.
\end{proof}

As usual, we take the graph morphism of $\delta_\CN^\pm$ to obtain a closed embedding
\begin{equation*}
   \Delta_\CN^\pm \colon \CN_{n-1} \xra{(\id_{\CN_{n-1}},\delta_\CN^\pm)} \CN_{n-1, n} 
	   = \CN_{n-1} \times_{\Spf O_{\breve F}} \CN_n.
\end{equation*}
Let $\Delta$ denote the (disjoint) union of the images of these embeddings,
\[
   \Delta := \Delta_\CN^+(\CN_{n-1}) \amalg \Delta_\CN^-(\CN_{n-1}).
\]
Of course, $\Delta$ can also be described as the image of the closed embedding
\[
   \Delta_\CN\colon \CN_{n-1} \times \{\pm 1\}
	   = \bigl(\CN_{n-1} \times \{+1\}\bigr) \amalg \bigl(\CN_{n-1} \times \{-1\}\bigr)
		\xra{\Delta_\CN^+ \amalg \Delta_\CN^-} \CN_{n-1,n}.
\]
Identifying $\BV(\BX_n)$ and $\BV(\wt\BX_n) = \BV(\BX_{n-1} \times \ov\BX_1)$ via the isogeny $\phi_0$ in \eqref{phi_0}, let
\begin{equation}\label{u}
   u := (0,\id_{\ov\BE}) \in \BV(\BX_n) \simeq \BV\bigl(\wt\BX_n\bigr) = \BV(\BX_{n-1}) \oplus \BV\bigl(\ov\BX_1\bigr).
\end{equation}
Then $u$ has norm $-1$, and therefore we may identify $(\BV(\BX_n),u,\BV(\BX_{n-1}))$ with $(W_1,u_1,W_1^\flat)$.  In this way $\Delta_\CN$ is equivariant for the embedding $H_1(F_0) \inj G_{W_1}(F_0)$, where $H_1(F_0)$ acts via the Kottwitz map on $\{\pm1\}$ and diagonally on the product $\CN_{n-1} \times \{\pm 1\}$.  (Note that the embeddings $\Delta_\CN^+$ and $\Delta_\CN^-$ are not separately $H_1(F_0)$-equivariant.)

\begin{example}[$n=2$]\label{CN_2 ATC eg}
Let us make the the above discussion ``concrete'' when $n = 2$.  Recall that $\CN_1 = \Spf O_{\breve F}$ is the universal deformation space for $\BE$ as a formal $O_F$-module, with universal object $(\CE,\iota_\CE,\rho_\CE)$, cf.~Example \ref{CN_1}; that $\CN_2$ identifies with two copies of the Lubin--Tate space $\CM_{\Spf O_{\breve F}}$, cf.~Example \ref{CN_2}; and that $\CP_2$ identifies with $(\CM_{\Gamma_0(\varpi)})_{\Spf O_{\breve F}}$, cf.~Remark \ref{CP_n diagram n=2}.  In terms of these identifications, we claim that $\wt\delta_\CN\colon \CN_1 \to \CP_2$ is the morphism
\[
   \xymatrix@R=0ex{
	   \Spf O_{\breve F} \ar[r]  &  (\CM_{\Gamma_0(\varpi)})_{\Spf O_{\breve F}}\\
		(\CE,\iota_\CE,\rho_\CE) \ar@{|->}[r]  &  (\CE,\CE,\iota_\CE(\pi),\rho_\CE).
	}
\]
Indeed, $\wt\delta_\CN$ sends $(\CE,\iota_\CE,\rho_\CE)$ to the point $(\CE \times \ov\CE, \iota_\CE \times \iota_{\ov\CE}, -(\lambda_\CE \times \lambda_{\ov\CE}), \rho_\CE \times \rho_{\ov\CE})$ on $\CP_2$; and the asserted value in $(\CM_{\Gamma_0(\varpi)})_{\Spf O_{\breve F}}$ identifies with the point $(\CE\times\CE, \iota, -2(\lambda_\CE \times \lambda_\CE), \psi_0\circ(\rho_\CE \times \rho_\CE))$ on $\CP_2$, where $\iota$ is defined by
\[
   \iota(\pi) =
	\begin{bmatrix}
		  &  \iota_\CE(\pi)\\
		\iota_\CE(\pi)
	\end{bmatrix},
\]
where $\psi_0$ is the isomorphism $\BX \isoarrow \wt\BX_2$ in \eqref{psi_0}, and where $\rho_\CE \times \rho_\CE$ is a framing to $\BX$.  It is obvious from the definition of $\psi_0$ that the isomorphism in the special fiber given by the framings lifts to an isomorphism between these two quadruples, which proves the claim.  Combining this with Example \ref{CP_n diagram n=2}, it follows that both morphisms $\delta_\CN^\pm$ identify with the embedding of $\CN_1$ in $\CM_{\Spf O_{\breve F}}$ sending $(\CE,\iota_\CE,\rho_\CE) \mapsto (\CE,\rho_\CE)$. Furthermore, the composition
\[
   \CN_1 \xra{\delta_\CN^\pm} \CM_{\Spf O_{\breve F}} \to \CM
\]
identifies with the canonical divisor in $\CM$ associated to the embedding $\iota_\BE\colon F \inj D$ in the sense of \cite{G} and \cite[Def.~1.2]{Wewers}.  Finally, note that $\Delta_\CN^\pm = \delta_\CN^\pm$ under the identification $\CN_{1,2}\cong \CN_2$.
\end{example}

Now fix an almost $\pi$-modular lattice
\[
   \Lambda_0^\flat \subset W_0^\flat;
\]
recall that when $F/F_0$ is ramified, such lattices exist in any odd-dimensional hermitian space and are all conjugate under the corresponding unitary group.
Then
\begin{equation}\label{Lambda^nat}
   \Lambda_0^\nat := \Lambda_0^\flat \oplus O_Fu_0
\end{equation}
is a vertex lattice of type $n-2$ in $W_0$, i.e.~$\Lambda_0^\nat \subset^{n-2} (\Lambda_0^\nat)^\vee \subset^2 \pi^{-1}\Lambda_0^\nat$.  Since $W_0$ is split, it follows that there are two $\pi$-modular lattices $\Lambda_0^+,\Lambda_0^-$ contained in $\Lambda_0^\nat$ (corresponding to the two isotropic lines in $\Lambda_0^\nat/\pi (\Lambda_0^\nat)^\vee$).  Let
\[
   K_0^\flat \subset H_0(F_0)
\]
denote the stabilizer of $\Lambda_0^\flat$, and let
\[
   K_0^\pm \subset G_0(F_0)
	\quad\text{and}\quad
	\fkk_0^\pm \subset \fkg_0(F_0)
\]
denote the respective stabilizers of $\Lambda_0^\pm$. 
Then $K_0^\flat$ is a maximal compact subgroup containing a special maximal parahoric subgroup with index $2$, and $K_0^\pm$ are special maximal parahoric subgroups, cf.~\cite[\S4.a]{PR-TLG}. Note that the two lattices $\Lambda_0^\pm$ are $K_0^\flat$-conjugate under the embedding $K_0^\flat \subset G_0(F_0)$, since, for example, $K_0^\flat$ contains elements of nontrivial Kottwitz invariant.

\begin{remark}\label{group theoretic}
The fact that we take $K_0^\flat$ to be the stabilizer of an almost $\pi$-modular lattice in $W_0^\flat$ reflects that we have almost $\pi$-modular polarizations in the moduli problem for $\CN_{n-1}$; and similarly, that $K_0^\pm$ are stabilizers of $\pi$-modular lattices reflects that the polarizations in the moduli problem for $\CN_n$ are $\pi$-modular.  The fact that $K_0^\flat \not\subset K_0^\pm$ under the embedding $H_0(F_0) \subset G_0(F_0)$ can then be regarded as a group-theoretic reflection of why $\delta_\CN$ cannot be defined as simply in the even ramified case as in the cases we have encountered previously.
\end{remark}

We normalize the Haar measure on $H_0(F_0)$ (and hence the product measure on $H_{W_0}(F_0) = H_0(F_0) \times H_0(F_0)$) by assigning $K_0^\flat$ volume $1$.  As before we normalize the Haar measures on $H'(F_0)$, $H'_1 ({F_0})$, and $H_2'(F_0)$ as in \S\ref{s:FL}.  For $g \in G_{W_1}(F_0)_\rs$ or $g \in G_1(F_0)_\rs$, we define the intersection number $\Int(g)$ with respect to the above cycle $\Delta$ as in \S\ref{s:AFL}.  For $x \in \fkg_1(F_0)_\rs$, we define (abusing notation in the usual obvious way)
\[
   \Delta_x := \biggl\{\, (Y,X) \in \CN_{n-1,n} \biggm| 
	   \begin{varwidth}{\linewidth}
		\centering
		Zariski-locally on the base, $x\colon \BX_n \rightarrow \BX_n$\\
		lifts to a homomorphism $\delta_\CN^+(Y) \rightarrow X$ or $\delta_\CN^-(Y) \rightarrow X$
		\end{varwidth} \,\biggr\}.
\]
As in the case of the AFL, this definition makes sense for any quasi-endomorphism $x$ of $\BX_n$, and for $g \in G_1(F_0)$ we have $\Delta_g = (1\times g)\Delta$. As usual, when $\Delta \cap \Delta_x$ is an artinian scheme, we define
\[
   \lInt(x) := \length(\Delta \cap \Delta_x).
\]

\begin{conjecture}[Arithmetic transfer conjecture]\label{conjram v3}\hfill
\begin{altenumerate}
\renewcommand{\theenumi}{\alph{enumi}}
\item\label{conjram v3 homog}
\textup{(Homogeneous version)} 
Let $f' \in C^\infty_c(G')$ be a function transferring to the pair of functions $(\mathbf{1}_{K_0^\flat \times K_0^+} + \mathbf{1}_{K_0^\flat \times K_0^-}, 0) \in C_c^\infty(G_{W_0}) \times C_c^\infty(G_{W_1})$.  Then there exists $f'_\corr \in C^{\infty}_c (G')$ such that, for any $\gamma \in G'(F_0)_\rs$ matching an element $g \in G_{W_1}(F_0)_\rs$,
\begin{equation*}
   \omega_{G'}(\gamma)\del(\gamma, f') 
	   = - \Int(g)\cdot\log q + \omega(\gamma) \Orb(\gamma, f'_\corr).
\end{equation*}
Furthermore, there exist such functions $f'$ for which $f'_\corr = 0$.
\item\label{conjram v3 inhomog}
\textup{(Inhomogeneous version)}
Let $f' \in C^{\infty}_c (S)$ be a function transferring to the pair of functions $(\mathbf{1}_{K_0^\flat K_0^+}+\mathbf{1}_{K_0^\flat K_0^-}, 0) \in C_c^\infty(G_0) \times C_c^\infty(G_1)$. Then there exists  $f'_\corr \in C^\infty_c(S)$ such that, for any $\gamma \in S(F_0)_\rs$ matching an element $g \in G_1(F_0)_\rs$,
\begin{equation*}
   2 \omega_S (\gamma)\del(\gamma, f') = - \Int(g)\cdot \log q + \omega (\gamma)\Orb(\gamma, f'_\corr).
\end{equation*}
Furthermore, there exist such functions $f'$ for which $f'_\corr = 0$.
\item\label{conjram v3 lie}
\textup{(Lie algebra version)}
Let $\phi' \in C^{\infty}_c (\fks)$ be a function transferring to the pair of functions $(\mathbf{1}_{\fkk_0^+}+\mathbf{1}_{\fkk_0^-},0) \in C_c^\infty(\fkg_0) \times C_c^\infty(\fkg_1)$. Then there exists $\phi'_\corr \in C^{\infty}_c (\fks)$ such that, for any $y \in \fks(F_0)_\rs$ matching an element $x \in \fkg_1(F_0)_\rs$ for which the intersection $\Delta \cap \Delta_x$ is an artinian scheme,
\begin{equation*}
   2\omega_\fks (y)\del(y, \phi') = - \lInt(x)\cdot \log q + \omega (y)\Orb(y, \phi'_\corr).
\end{equation*}
Furthermore, there exist such functions $\phi'$ for which $\phi'_\corr = 0$.
\end{altenumerate}
\end{conjecture}

\begin{remark}\label{remark S12}
Note that in the inhomogeneous version, we have 
\[
   \mathbf{1}_{K_0^\flat K_0^+}+\mathbf{1}_{K_0^\flat K_0^-}=\mathbf{1}_{ K_0^+ K_0^\flat }+\mathbf{1}_{K_0^- K_0^\flat}.
\]
Moreover, we may replace the test function  $\mathbf{1}_{K_0^\flat K_0^+}+\mathbf{1}_{K_0^\flat K_0^-}$ by $2\cdot \mathbf{1}_{K_0^\flat K_0^+}$ or $2 \cdot\mathbf{1}_{K_0^\flat K_0^-}$, since they all have the same orbital integrals (the two groups $K_0^\pm$ are conjugate under $H_0(F_0)$). Similarly, in the Lie algebra version, we may replace the test function $\mathbf{1}_{\fkk_0^+}+\mathbf{1}_{\fkk_0^-}$ by $2\cdot \mathbf{1}_{\fkk_0^+}$ or $2\cdot \mathbf{1}_{\fkk_0^-}$.
\end{remark}
The proof of Conjecture \ref{conjram v3} in the case $F_0 = \BQ_p$ and $n=2$ is contained in \S\ref{even ram proof}. 






\section{Arithmetic transfer theorems for $\wt\CN_2^{(0)}$ and $\wt\CN_2^{(1)}$}\label{s:ATC ram n=2}

In this final section of Part \ref{conjectures}, we state AT theorems attached to the spaces $\smash[t]{\wt\CN_2^{(0)}}$ and $\wt\CN_2^{(1)}$ defined in \S\ref{ram self-dual n=2} over $\Spf O_{\breve F_0}$.  To formulate the statements, we will define an embedding of $\CN_1$ into each of them, and then proceed in a way similar to before, albeit with a few differences.  In particular, we will only obtain statements in the inhomogeneous group and Lie algebra cases; and in order to intersect cycles in a regular space, it is crucial that we work over $O_{\breve F_0}$ instead of $O_{\breve F}$.  Let $F/F_0$ be ramified.


\subsection{The case of $\wt\CN_2^{(0)}$}\label{ATC wtCN_2^(0)}
Identify $F$ with its image in $D$ via $\iota_\BE$, and fix $\zeta \in O_D^\times$ such that $\zeta \pi = - \pi \zeta$.  Then the elements $\pi$ and $\zeta$ generate $O_D$ over $O_{F_0}$ since $p \neq 2$.  Furthermore, we have
\[
   \ep := \zeta^2 \in O_{F_0}^\times \smallsetminus \RN F^\times.
\]
We take the special vectors $u_i \in W_i$ to have norm $-\ep$.  Let
\[
   \bigl(\ov\BX_1^{(0)}, \iota_{\ov\BX_1^{(0)}}, \lambda_{\ov\BX_1^{(0)}}\bigr) := \bigl(\ov\BE, \iota_{\ov\BE}, -\ep\lambda_{\ov\BE}\bigr),
\]
which is the conjugate of the framing object $\BX_1^{(0)}$ for $\CN_1^{(0)}$, cf.\ \eqref{BX_1} and \eqref{BX_n^{(0)}}.  Taking the product with the conjugate of the corresponding universal object over $\CN_1^{(0)}$ then defines a closed embedding
\begin{equation*}
   \wt\delta^{(0)}_\CN \colon
	\xymatrix@R=0ex{
	   \CN_1 \ar[r]  &  (\wt\CN_2^{(0)})_{\Spf O_{\breve F}}\\
		(\CE, \iota_\CE, -\lambda_\CE, \rho_\CE) \ar@{|->}[r]  
		   &  \bigl(\CE \times \ov\CE, \iota_\CE \times \iota_{\ov\CE}, 
			       -(\lambda_\CE \times \ep\lambda_{\ov\CE}), \rho_\CE \times \rho_{\ov\CE} \bigr).
	}
\end{equation*}
Here the last entry $\rho_\CE \times \rho_{\ov\CE}$ is a framing to the constant object over the special fiber defined by
\begin{equation}\label{wtBX_2^(0)}
   \wt\BX^{(0)}_2 := \BX_1 \times \ov\BX_1^{(0)} = \bigl(\BE \times \ov\BE, \iota_\BE \times \iota_{\ov\BE}, 
			       -(\lambda_\BE \times \ep\lambda_{\ov\BE}) \bigr).
\end{equation}
Note that since $\BV(\BX_1) = \BV(\BX_1^{(1)})$ is non-split, $\BV(\wt\BX_2^{(0)})$ is indeed split by \eqref{chi decomp formula}.
We compose with the projection to the regular space $\wt\CN_2^{(0)}$ to obtain
\begin{equation*}
   \wt\Delta^{(0)}_\CN \colon \CN_1 \xra{\wt\delta_\CN^{(0)}} (\wt\CN_2^{(0)})_{\Spf O_{\breve F}} \to \wt\CN_2^{(0)}.
\end{equation*}
By inspection $\wt\Delta_\CN^{(0)}$ is again a closed embedding, and we denote its image by
\[
   \wt\Delta^{(0)} \subset \wt\CN_2^{(0)}.
\]
The canonical vector
\[
   u := (0,\id_{\ov\BE}) \in \BV\bigl(\wt\BX_2^{(0)}\bigr) = \BV(\BX_1) \oplus \BV\bigl(\ov\BX_1^{(0)}\bigr)
\]
has norm $-\ep$, and therefore we may identify the triple $(\BV(\wt\BX_2^{(0)}),u,\BV(\BX_1))$ with $(W_0,u_0,W_0^\flat)$. In this way $\wt\Delta_\CN^{(0)}$ is equivariant for the embedding $H_0(F_0) \inj G_0(F_0)$.

To express the above discussion in terms of the natural identifications we have previously noted for the spaces in play, recall from Example \ref{CN_1} that $\CN_1 = \Spf O_{\breve F}$ is the universal deformation space for $\BE$ as a formal $O_F$-module, with universal object $(\CE,\iota_\CE,\rho_\CE)$.  Further recall from \eqref{ramified Drinfeld isom} that $\wt\CN_2^{(0)}$ identifies with the Drinfeld space $(\wh\Omega_{F_0}^2)_{\Spf O_{\breve F_0}}$.  In fact, we will now use a slightly different description for the moduli problem for $(\wh\Omega_{F_0}^2)_{\Spf O_{\breve F_0}}$ than the one in \cite{KR-alt}, by changing the framing object.  Let
\[
   \BX_\Dr := \BE \times \ov\BE,
\]
endowed with its natural $O_F$-action $\iota_{\BX_\Dr}$ on the right-hand side, and extend this to an $O_D$-action by defining
\begin{equation}\label{iota(zeta) formula}
   \iota_{\BX_\Dr}(\zeta) :=
	\begin{bmatrix}
		  &  \ep\\
		1
	\end{bmatrix}.
\end{equation}
Then $\iota_{\BX_\Dr}(\zeta)\iota_{\BX_\Dr}(\pi) = - \iota_{\BX_\Dr}(\pi)\iota_{\BX_\Dr}(\zeta)$, as required, and we take $\BX_\Dr$ as the framing object for the Drinfeld moduli problem.  Now let
\[
   \lambda_{\BX_\Dr} := -(\lambda_\BE \times \ep \lambda_{\ov\BE}).
\]
It is easy to verify that
\[
   \Ros_{\lambda_{\BX_\Dr}}\bigl(\iota_{\BX_\Dr}(\pi)\bigr) = - \iota_{\BX_\Dr}(\pi)
	\quad\text{and}\quad
	\Ros_{\lambda_{\BX_\Dr}}\bigl(\iota_{\BX_\Dr}(\zeta)\bigr) = \iota_{\BX_\Dr}(\zeta).
\]
Hence by \cite[Th.~1.2]{KR-alt}, for any object $(X,\iota,\rho)$ of the Drinfeld moduli problem, there is a unique principal polarization $\lambda$ on $X$ lifting $\lambda_{\BX_\Dr}$, and $(X,\iota,\rho) \mapsto (X,\iota|_{O_F},\lambda,\rho)$ defines an isomorphism $(\wh\Omega_{F_0}^2)_{\Spf O_{\breve F_0}} \isoarrow \wt\CN_2^{(0)}$.  In terms of this identification, the map $\wt\Delta_\CN^{(0)}$ is therefore given by
\[
   \xymatrix@R=0ex{
	   \Spf O_{\breve F} \ar[r]  &  (\wh\Omega_{F_0}^2)_{\Spf O_{\breve F_0}}\\
		(\CE,\iota_\CE,\rho_\CE) \ar@{|->}[r]  &  (\CE \times \ov\CE, \iota, \rho_\CE \times \rho_{\ov\CE}),
	}
\]
where $\iota$ restricts to the natural $O_F$-action on $\CE \times \ov\CE$, and $\iota(\zeta)$ is defined as in \eqref{iota(zeta) formula}.

\begin{remark}\label{specialDr} Again, as in the case of Remark \ref{reltospecialunr}, one can introduce the special cycle $\CZ(u)$ in $\wt\CN_2^{(0)}$. 
However, according to Sankaran \cite{San-mail}, $\CZ(u)$ is not a divisor, but has embedded components. The divisor $\wt\Delta^{(0)}_\CN (\CN_1)$ is the \emph{purification} of $\CZ(u)$. 
\end{remark}

Now consider the one-dimensional space $W_1^\flat$, and let
\[
   \Lambda_1^\flat \subset W_1^\flat
\]
be the unique self-dual $O_F$-lattice. Let
\[
   \Lambda_1 := \Lambda_1^\flat \oplus O_Fu_1 \subset W_1,
\]
which is again self-dual.  Let 
\[
   \wt K_1 \subset G_1(F_0)
	\quad\text{and}\quad
	\wt \fkk_1 \subset \fkg_1(F_0)
\]
denote the respective stabilizers of $\Lambda_1$.  Then $\wt K_1$ contains the connected stabilizer of $\Lambda_1$ (which is the unique parahoric subgroup\footnote{After extension of scalars, this becomes an Iwahori subgroup.}) with index $2$. We normalize the Haar measure on $H_1(F_0) = F^1$ by assigning it volume $1$.  As usual we normalize the Haar measure on $H'(F_0)$ as in \S\ref{s:FL}.  For $g \in G_0(F_0)_\rs$, we define the intersection number $\Int(g)$ with respect to the cycle $\wt\Delta^{(0)} \subset \wt\CN_2^{(0)}$ in analogy with before,
\[
   \Int(g) := \bigl\la \wt\Delta^{(0)}, g\wt\Delta^{(0)} \bigr\ra_{\wt\CN_2^{(0)}}.
\]
Since $\wt\Delta^{(0)}\cap g\wt\Delta^{(0)}$ is an artinian scheme, this intersection number is simply given by the length 
\[
   \Int(g) =\length\bigl(\wt\Delta^{(0)} \cap g\wt\Delta^{(0)}\bigr) ,
\] 
cf.\ \cite[Prop.\ 8.10]{RSZ}.
For $x \in \fkg_0(F_0)_\rs$, we define (abusing notation as usual)
\[
   \wt\Delta_x^{(0)} := \bigl\{\, X \in \wt\CN_2^{(0)} \bigm| x\colon \wt\BX_2^{(0)} \rightarrow \wt\BX_2^{(0)} \text{ lifts to a homomorphism } \CE \times \ov\CE \rightarrow X \,\bigr\}.
\]
Then $\wt\Delta^{(0)} \cap \wt\Delta_x^{(0)}$ is an artinian scheme, and we define
\[
   \lInt(x) := \length(\wt\Delta^{(0)} \cap \wt\Delta_x^{(0)}).
\] 

\begin{theorem}[Arithmetic transfer theorem]\label{conjram i=0}
Let $F_0 = \BQ_p$.
\begin{altenumerate}
\renewcommand{\theenumi}{\alph{enumi}}
\item\label{conjram i=0 inhomog}
\textup{(Inhomogeneous version)}
Let $f' \in C^\infty_c (S)$ be a function transferring to the pair $(0,\mathbf{1}_{\wt K_1}) \in C_c^\infty(G_0) \times C_c^\infty(G_1)$. Then there exists a function $f'_\corr \in C^\infty_c(S)$ such that, for any $\gamma \in S(F_0)_\rs$ matching an element $g \in G_0(F_0)_\rs$,
\begin{equation*}
   2 \omega_S (\gamma)\del(\gamma, f') = - \Int(g)\cdot \log q + \omega (\gamma)\Orb(\gamma, f'_\corr).
\end{equation*}
Furthermore, there exist such functions $f'$ for which $f'_\corr = 0$.
\item\label{conjram i=0 lie}
\textup{(Lie algebra version)}
Let $\phi' \in C^{\infty}_c (\fks)$ be a function transferring to the pair $(0, \mathbf{1}_{\wt\fkk_1}) \in C_c^\infty(\fkg_0) \times C_c^\infty(\fkg_1)$. Then there exists a function $\phi'_\corr \in C^{\infty}_c (\fks)$ such that, for any $y \in \fks(F_0)_\rs$ matching an element $x \in \fkg_0(F_0)_\rs$,
\begin{equation*}
   2\omega_\fks (y)\del(y, \phi') = - \lInt(x)\cdot \log q + \omega (y)\Orb(y, \phi'_\corr).
\end{equation*}
Furthermore, there exist such functions $\phi'$ for which $\phi'_\corr = 0$.
\end{altenumerate}
\end{theorem}

We will prove Theorem \ref{conjram i=0} in \S\ref{proof wtCN_2^(0)}.



\subsection{The case of $\wt\CN_2^{(1)}$}\label{atc wtCN_2^(1)}
Now we take the special vectors $u_i \in W_i$ to have norm $-1$.
To obtain an analogous embedding of $\CN_1$ into $\wt\CN_2^{(1)}$, we simply use the morphism $\wt\delta_\CN$ defined in \eqref{wtdelta_CN}, followed by the natural projection to $\wt\CN_2^{(1)}$,
\[
   \wt\Delta_\CN^{(1)}\colon \CN_1 \xra{\wt\delta_\CN} \CP_2 \simeq (\wt\CN_2^{(1)})_{\Spf O_{\breve F}} \to \wt\CN_2^{(1)},
\]
where the isomorphism in the middle is the one in Example \ref{CP_n diagram n=2}.
Recall from Example \ref{CN_2 ATC eg} that in concrete terms we have $\CN_1 \cong \Spf O_{\breve F}$ and $\wt\CN_2^{(1)} \cong \CM_{\Gamma_0(\varpi)}$, and that $\wt\Delta_\CN^{(1)}$ then identifies with
\[
   \xymatrix@R=0ex{
	   \Spf O_{\breve F} \ar[r]  &  \CM_{\Gamma_0(\varpi)}\\
		(\CE,\iota_\CE,\rho_\CE) \ar@{|->}[r]  &  (\CE,\CE,\iota_\CE(\pi),\rho_\CE).
	}
\]

Now recall the framing object $\BX$ for $\wt\CN_2^{(1)}$, which is isomorphic to the framing object for $\CP_2$,
\begin{equation*}
   \wt\BX_2^{(1)} := \wt\BX_2 = \BX_1 \times \ov\BX_1 = \bigl(\BE \times \ov\BE, \iota_\BE \times \iota_{\ov\BE}, -(\lambda_\BE \times \lambda_{\ov\BE})\bigr),
\end{equation*}
via \eqref{psi_0}.  This gives us a canonical vector
\begin{equation}
   u := (0,\id_{\ov\BE}) \in \BV(\BX) \simeq \BV\bigl(\wt\BX_2^{(1)}\bigr) = \BV(\BX_1) \oplus \BV\bigl(\ov\BX_1\bigr)
\end{equation}
of norm $-1$, and therefore we may identify the triple $(\BV(\wt\BX_2^{(1)}),u,\BV(\BX_1))$ with $(W_1,u_1,W_1^\flat)$. In this way $\wt\Delta_\CN^{(1)}$ is equivariant for the embedding $H_1(F_0) \inj G_1(F_0)$.

\begin{remark} Again, as in the AFL case, one can introduce the special cycle $\CZ(u)$ in $\wt\CN_2^{(0)}$, cf.\ Remark \ref{reltospecialunr}. 
It seems likely that $\CZ(u)$ is not a divisor, but has embedded components \cite{KRbarc}, comp.\ Remark \ref{specialDr}. The divisor $\wt\Delta^{(0)}_\CN (\CN_1)$ is the \emph{purification} of $\CZ(u)$. 
\end{remark}


Now consider the one-dimensional space $W_0^\flat$, and let
\[
   \Lambda_0^\flat \subset W_0^\flat
\]
be the unique self-dual lattice.  Let
\[
   \Lambda_0 := \Lambda_0^\flat \oplus O_Fu_0 \subset W_0,
\]
which is again self-dual. Let 
\[
   \wt K_0 \subset G_0(F_0)
	\quad\text{and}\quad
	\wt\fkk_0 \subset \fkg_0(F_0)
\]
denote the respective stabilizers of $\Lambda_0$.  Then $\wt K_0$ contains an Iwahori subgroup with index $2$, cf.~\cite[\S4.a]{PR-TLG}. We normalize the Haar measure on $H_0(F_0) = F^1$ by assigning it volume $1$.  The other normalizations and transfer factors for $S$ and \fks are all as in the previous subsection.
Finally, as in the previous subsection, we define $\Int(g)$ and $\lInt(x)$ for $g\in G_1(F_0)_\rs$, resp.\ $x\in\fkg_{1}(F_0)_\rs$ (again, both are given by a length). 

\begin{theorem}[Arithmetic transfer theorem]\label{conjram i=1}
Let $F_0 = \BQ_p$.
\begin{altenumerate}
\renewcommand{\theenumi}{\alph{enumi}}
\item\label{conjram i=1 inhomog}
\textup{(Inhomogeneous version)}
Let $f' \in C^{\infty}_c (S)$ be a function transferring to the pair $(\mathbf{1}_{\wt K_0}, 0) \in C_c^\infty(G_0) \times C_c^\infty(G_1)$. Then there exists a function $f'_\corr \in C^\infty_c(S)$ such that, for any $\gamma \in S(F_0)_\rs$ matching an element $g \in G_1(F_0)_\rs$,
\begin{equation*}
   2 \omega_S (\gamma)\del(\gamma, f') = - \Int(g)\cdot \log q + \omega (\gamma)\Orb(\gamma, f'_\corr).
\end{equation*}
Furthermore, there exist such functions $f'$ for which $f'_\corr = 0$.
\item\label{conjram i=1 lie}
\textup{(Lie algebra version)}
Let $\phi' \in C^{\infty}_c (\fks)$ be a function transferring to the pair $(\mathbf{1}_{\wt\fkk_0},0) \in C_c^\infty(\fkg_0) \times C_c^\infty(\fkg_1)$. Then there exists a function $\phi'_\corr \in C^{\infty}_c (\fks)$ such that, for any $y \in \fks(F_0)_\rs$ matching an element $x \in \fkg_1(F_0)_\rs$,
\begin{equation*}
   2\omega_\fks (y)\del(y, \phi') = - \lInt(x)\cdot \log q + \omega (y)\Orb(y, \phi'_\corr).
\end{equation*}
Furthermore, there exist such functions $\phi'$ for which $\phi'_\corr = 0$.
\end{altenumerate}
\end{theorem}

We will prove Theorem \ref{conjram i=1} in \S\ref{proof wtCN_2^(1)}. 













\part{Results}
In this part of the paper we prove results on the conjectures formulated in Part \ref{conjectures} (except Conjecture \ref{ATC ram odd}, which is proved for $n = 3$ in \cite{RSZ}).  We continue to take $S = S_n$ as in \eqref{S_n}.




\section{On the ATC for $F/F_0$ unramified, almost self-dual type}
\label{unram proof}
We resume the setup of \S\ref{s:ATunr}, with $F/F_0$ unramified and $n \geq 2$. Recall that we have an orthogonal decomposition
\[
   W_i = W_i^\flat\oplus F u_i,\quad (u_i,u_i)=\varpi, \quad i \in \{0,1\},
\]
where $W_0$ is the split hermitian space of dimension $n$, and $W_1$ is the non-split hermitian space of dimension $n$; and, by \eqref{chi decomp formula}, $W_0^\flat$ is the non-split space of dimension $n-1$, and $W_1^\flat$ is the split space of dimension $n-1$. 


\subsection{On the FL Conjecture \ref{FL almost self-dual}}

In this subsection we prove the following theorem.

\begin{theorem}
\begin{altenumerate}
\item\label{fl equiv} 
The Lie algebra FL Conjectures \ref{FLconj}(\ref{FLconj lie}) and \ref{FL almost self-dual}(\ref{FL almost self-dual lie}) are equivalent to each other.
\item\label{fl equiv 2} 
The homogeneous and inhomogeneous FL Conjectures \ref{FL almost self-dual}(\ref{FL almost self-dual homog}) and \ref{FL almost self-dual}(\ref{FL almost self-dual inhomog}) are equivalent to each other.
\item\label{fl imply}
Assume $q \geq n$.  Then Conjecture \ref{FL almost self-dual}(\ref{FL almost self-dual lie}) implies Conjecture \ref{FL almost self-dual}(\ref{FL almost self-dual homog})(\ref{FL almost self-dual inhomog}).
\end{altenumerate}\label{unram variant FL}
\end{theorem}

In order to make the relation between the conjectures in part (\ref{fl equiv}), we first introduce some auxiliary spaces. 
Let
\[
   \wt W_i = \wt W_i^{\flat}\oplus F \wt u_i,\quad (\wt u_i, \wt u_i)=1, \quad i \in \{0,1\},
\]
where $\wt W_0$ is a split hermitian space and $\wt W_1$ is non-split. Thus $\wt W_i$ and $W_i$ are isometric, but we are choosing different special vectors in these spaces.  Let
\[
   \wt G_i := \U\bigl(\wt W_i\bigr),
	\quad
	\wt H_i := \U\bigl(\wt W_i^\flat\bigr),
	\quad\text{and}\quad
	\wt\fkg_i := \Lie \wt G.
\]
Recall from \S\ref{s:ATunr} the self-dual lattice $\Lambda_1^\flat \subset W_1^\flat$, the almost self-dual lattice $\Lambda_1 = \Lambda_1^\flat \oplus F u_1 \subset W_1$, and the Lie algebra stabilizer $\fkk_1 \subset \fkg_1(F_0)$ of $\Lambda_1$. We similarly fix an almost self-dual lattice $\Lambda_0^\flat \subset W_0^\flat$; we set $\Lambda_0 :=\Lambda_0^\flat\oplus O_F u_0$ (a vertex lattice of type $2$ in $W_0$); and we denote by $\fkk_0 \subset \fkg_0(F_0)$ the stabilizer of $\Lambda_0$.  We choose an identification $\wt W_i^\flat=W_{1-i}^\flat$, and we take
\[
   \wt \Lambda_i^\flat := \Lambda_{1-i}^\flat.
\]
We set $\wt\Lambda_i := \wt\Lambda_i^{\flat}\oplus O_F \wt u_i$, and we denote by $\wt\fkk_i \subset \wt\fkg_i(F_0)$ the stabilizer of $\wt\Lambda_i$. 

We next choose an $O_F$-basis of $\Lambda_i^\flat$ (and hence of $\wt\Lambda_{1-i}^\flat$) and extend it by adding $u_i$ (resp.~$\wt u_{1-i}$) to obtain an $F$-basis of $W_i$ (resp.~$\wt W_{1-i}$). In this way, all the groups under consideration identify with subgroups of $\GL_n(F)$, and all the Lie algebras identify with $F_0$-subspaces of $\RM_n(F)$. We define a $\GL_{n-1}(F)$-equivariant map
\[
  \theta\colon 
  \xymatrix@R=0ex{
     \RM_n(F) \ar[r]  &  \RM_n(F)\\
	  {\begin{bmatrix}
	 		 A &  b  \\
	       c  & d
	  \end{bmatrix}}
	  \ar@{|->}[r]  &
	  {\begin{bmatrix}
	  	  A &  \varpi^{-1} b  \\
	     c  & d
	  \end{bmatrix} },
  } 
\]
where as usual the diagonal blocks are of sizes $(n-1) \times (n-1)$ and $1 \times 1$, respectively.  Finally, we recall the compact open subgroup $\fkk' \subset \fks(O_{F_0})$ defined in \eqref{eqn fkk'}.

\begin{lemma}
\begin{altenumerate}
\item\label{lemtheta i} The restriction of $\theta$ to $\fks(F_0)$ gives a $\GL_{n-1}(F_0)$-equivariant bijection
\[
   \theta\colon \fks(F_0)\isoarrow \fks(F_0)
\]
such that
\[
   \theta (\fkk')=\fks(O_{F_0}).
\]
Furthermore, $\theta$ restricts to a bijection $\fks(F_0)_\rs \isoarrow \fks(F_0)_\rs$, and
\begin{align*}\label{eqn orb s}
   \omega_\fks (y) = (-1)^{n-1}\omega_\fks\bigl(\theta(y)\bigr) \quad\text{and}\quad
	\Orb(y, \mathbf{1}_{\fkk'}, s) = \Orb\bigl(\theta(y), \mathbf{1}_{\fks(O_{F_0})}, s\bigr), \quad y \in \fks(F_0)_\rs.
\end{align*}
\item\label{lemtheta ii} 
For $i \in \{0,1\}$, the restriction of $\theta$ to $\fkg_i(F_0)$ gives an $H_i(F_0) = \wt H_{1-i}(F_0)$-equivariant bijection
\[
   \theta\colon \fkg_i(F_0) \isoarrow \wt\fkg_{1-i}(F_0)
\]
such that
$$
\theta(\fkk_i)=\wt\fkk_{1-i}.
$$
In addition, $\theta$ further restricts to a bijection $\fkg_i(F_0)_\rs \isoarrow \wt\fkg_{1-i}(F_0)_\rs$, and
\begin{equation*}
   \Orb(x, \mathbf{1}_{\fkk_i}) = \Orb\bigl(\theta(x),\mathbf{1}_{\wt\fkk_{1-i}}\bigr), \quad x\in \fkg_i(F_0)_\rs .
\end{equation*} 
\end{altenumerate}
\label{lemtheta}
\end{lemma}

Here the final asserted equality of unitary orbital integrals when $i = 0$ is with respect to any fixed Haar measure on $H_0(F_0) = \wt H_1(F_0)$; the particular choice will not be important for us.

\begin{proof} 
We just prove the claim for the transfer factor; all of the other assertions are straightforward.  Let $y=\bigl[\begin{smallmatrix} A &  b \\ c  & d \end{smallmatrix}\bigr]\in \fks(F_0)_\rs$.  By \eqref{sign}, $\omega_\fks(y) = (-1)^{v(\det(y^i e)_{0 \leq i \leq n-1})} = (-1)^{v(\det(A^i b)_{0 \leq i \leq n-2})}$.  The claim now follows since applying $\theta$ to $y$ replaces $b$ by $\varpi\i b$.
\end{proof}	  


\begin{proof}[Proof of Theorem \ref{unram variant FL}(\ref{fl equiv})]
Noting that the lattice $\wt\Lambda_0 \subset \wt W_0$ defined above is self-dual, Conjecture \ref{FLconj}\eqref{FLconj lie} asserts that $\mathbf{1}_{\fks(O_{F_0})}\in  C_c^\infty(\fks)$ transfers to  $(\mathbf{1}_{\wt\fkk_0},0)\in C_c^\infty(\wt\fkg_0) \times C_c^\infty(\wt\fkg_1)$. The equivalence of this with Conjecture \ref{FL almost self-dual}(\ref{FL almost self-dual lie}) now follows immediately from Lemma \ref{lemtheta}.
\end{proof}
  
The key tool in proving part (\ref{fl imply}) of Theorem \ref{unram variant FL} will be the \emph{Cayley transform}.
For any $\xi\in F^1$ and $y \in \RM_n(F)$ with $\det(1-y) \neq 0$, the Cayley map $\fkc_\xi$ is defined by
\[
   \fkc_{\xi}(y) =  \xi \dfrac{1+y}{1-y} \in \RM_n(F).
\]
Its inverse is given by the formula
$$\fkc_\xi^{-1}(\gamma)=\frac{\gamma-\xi}{\gamma+\xi}.
$$
Note that both of these maps are equivariant for the conjugation action by $\GL_n(F)$. We introduce the following terminology.

\begin{definition}
\begin{altenumerate}
\item An element $\gamma\in S(F_0)$ is \emph{integral} if its characteristic polynomial has coefficients in $O_F$.  We make the same definition for $y\in \fks(F_0)$, for $g\in G_i(F_0)$, and for $x\in \fkg_i(F_0)$. 
\item An element $y\in \fks(F_0)$  is \emph{strongly integral} if it is integral and $\det(1-y)\in O_F^\times$. We make the same definition for $x\in \fkg_i(F_0)$.  We denote the subsets of strongly integral elements by $\fks(F_0)^\circ \subset \fks(F_0)$ and $\fkg_i(F_0)^\circ \subset \fkg_i(F_0)$.
\item Let $\xi\in F^1$. An element $\gamma\in S(F_0)$  is \emph{$\xi$-strongly integral} if it is integral and $\det(\gamma+\xi)\in O_F^\times$.  We make the same definition for $g\in G_i(F_0)$.  We denote the subsets of $\xi$-strongly integral elements by $S(F_0)_\xi^\circ \subset S(F_0)$ and $G_i(F_0)_\xi^\circ \subset G_i(F_0)$.
\end{altenumerate}
\end{definition}

Also recall the compact open subsets $K' \subset S(F_0)$ and $K_1 \subset G_1(F_0)$ from \S\ref{s:ATunr}, and define
\[
   \fkk^{\prime\circ} := \fkk' \cap \fks(F_0)^\circ,
	\quad
   K_\xi^{\prime \circ} := K' \cap S(F_0)_\xi^\circ,
	\quad
	\fkk_1^\circ := \fkk_1 \cap \fkg_1(F_0)^\circ,
	\quad
	K_{1,\xi}^\circ := K_1 \cap G_1(F_0)_\xi^\circ.
\]

\begin{lemma}\label{cayley}
Let $\xi \in F^1$.
\begin{altenumerate}
\item\label{cayley i} The Cayley transform $\fkc_\xi$ induces bijections
\[
   \fks(F_0)^\circ \isoarrow S(F_0)_\xi^\circ,
	\quad
	\fkg_0(F_0)^\circ \isoarrow G_0(F_0)_\xi^\circ,
	\quad\text{and}\quad
   \fkg_1(F_0)^\circ \isoarrow G_1(F_0)_\xi^\circ
\]
which are equivariant for the respective actions of $H'(F_0)$, $H_0(F_0)$, and $H_1(F_0)$.  These bijections respect the regular semi-simple sets on both sides, and they have the property that regular semi-simple elements $y \in \fks(F_0)^\circ$ and $x \in \fkg_i(F_0)^\circ$ match if and only if $\fkc_\xi(y) \in S(F_0)_\xi^\circ$ and $\fkc_\xi(x)\in G_i(F_0)_\xi^\circ$ match.
\item\label{cayley ii} Similarly, $\fkc_\xi$ induces bijections
\[
   \fkk^{\prime\circ} \isoarrow K_\xi^{\prime\circ}
	\quad\text{and}\quad
	\fkk_1^\circ \isoarrow K_{1,\xi}^\circ.
\]
\end{altenumerate}
\end{lemma}

\begin{proof}
The only claim that possibly requires proof is that the bijections in (\ref{cayley i}) respect the sets of regular semi-simple elements on both sides.  This follows by using that the Cayley--Hamilton theorem gives an equality of $F$-algebras $F[y] = F[\fkc_\xi(y)]$, and that an arbitrary $y \in \RM_n(F)$ is regular semi-simple if and only if the sets $\{y^i e\}_{i=0}^{n-1}$ and $\{\tensor[^t]{e}{}y^i\}_{i=0}^{n-1}$ are linearly independent; cf.\ the proofs of \cite[Lems.\ 8.7, 10.6]{RSZ}.
\end{proof}

\begin{lemma}\label{cayley orb}
Let $\xi \in F^1$.  Then for any regular semi-simple $y \in \fks(F_0)^\circ$,
\[
   \omega_\fks(y) = \omega_S\bigl(\fkc_\xi (y)\bigr)
	\quad\text{and}\quad
	\Orb(y, \mathbf{1}_{\fkk'}, s) = \Orb\bigl(\fkc_\xi(y), \mathbf{1}_{K'}, s\bigr) .
\]
Similarly, for any regular semi-simple $x \in \fkg_1(F_0)^\circ$,
\[
   \Orb(x, \mathbf{1}_{\fkk_1}) = \Orb\bigl(\fkc_\xi(x), \mathbf{1}_{K_1}\bigr).
\]
\end{lemma}

\begin{proof}
Since we take $y$ and $x$ to be strongly integral, the equalities for the orbital integrals follow from equivariance of the Cayley maps and from Lemma \ref{cayley} (especially part \eqref{cayley ii}).  The equality for the transfer factor is proved as for \cite[Lem.\ 11.9]{RSZ}. (Note that loc.~cit.\ considers the case that $F/F_0$ is ramified and $n$ is odd; when $F/F_0$ is unramified, the proof simplifies and is valid for any $n$.)
\end{proof}

Now we are ready to prove part (\ref{fl imply}) of the theorem.

\begin{proof}[Proof of Theorem \ref{unram variant FL}(\ref{fl imply})]
We show that part (\ref{FL almost self-dual lie}) of Conjecture \ref{FL almost self-dual} implies part (\ref{FL almost self-dual inhomog}); that this also implies (\ref{FL almost self-dual homog}) will follow from Theorem \ref{unram variant FL}(\ref{fl equiv 2}).  We must show that for all matching $\gamma \in S(F_0)_\rs$ and $g \in G_i(F_0)_\rs$,
\begin{align*}
   \omega_S(\gamma) \Orb\bigl(\gamma, (-1)^{n-1}\mathbf{1}_{K'}\bigr)=\begin{cases}0,&  g\in G_0(F_0)_\rs;\\
\Orb(g, \mathbf{1}_{K_1}),& g\in G_1(F_0)_\rs.
\end{cases}
\end{align*}

First assume that $\gamma$ is not integral. Then $\Orb(\gamma, \mathbf{1}_{K'}) = 0$, and we have to show that $\Orb(g,\mathbf{1}_{K_1}) = 0$ if $g \in G_1(F_0)$.  But since $\gamma$ and $g$ have identical characteristic polynomials, $g$ is also not integral, and hence $\Orb(g,\mathbf{1}_{K_1})$ vanishes.

Now assume that $\gamma$ is integral. Since we assume that $q\geq n$, there exist at least $n+1$ elements $\xi_0,\xi_1,\dotsc,\xi_n\in F^1$ with pairwise distinct residues mod $\varpi$ (since the kernel of the norm map $\BF_{q^2}^\times \to \BF_q^\times$ has $q+1$ elements). Hence there exists some $\xi = \xi_i$ such that $\det(\gamma+\xi)\in O_F^\times$, i.e.\ $\gamma$ is $\xi$-strongly integral. Since $\gamma$ and $g$ have the same characteristic polynomial, $g$ is $\xi$-strongly integral too.  Let $y := \fkc_\xi^{-1}(\gamma) \in \fks(F_0)^\circ$ and $x := \fkc_\xi^{-1}(g) \in \fkg_i(F_0)^\circ$.  Then $y$ and $x$ are matching regular semi-simple elements, and by Lemma \ref{cayley orb} and Conjecture \ref{FL almost self-dual}(\ref{FL almost self-dual lie}),
\begin{multline*}
   \omega_S(\gamma)\Orb\bigl(\gamma, (-1)^{n-1}\mathbf{1}_{K'}\bigr) = \omega_\fks(y)\Orb\bigl(y, (-1)^{n-1}\mathbf{1}_{\fkk'}\bigr)\\
	= 
	\begin{cases}
		0,  &  g \in G_0(F_0)_\rs;\\
		\Orb(x, \mathbf{1}_{\fkk_1}) = \Orb(g,\mathbf{1}_{K_1}),  &  g \in G_1(F_0)_\rs,
	\end{cases}
\end{multline*}
as desired.
\end{proof}

\begin{remark}
The idea to reduce the group statement to the Lie algebra statement via the Cayley transform also appears in \cite[Lem.\ 8.4, Lem.\ 11.1, Prop.\ 11.14]{RSZ}, and  in fact our situation is simpler than in loc.~cit.
If we assume that $q\geq n+2$, then we may show the converse to (\ref{fl imply}), i.e.\ the group version also implies the Lie algebra version, cf.\ \cite[Prop.\ 2.4]{M-AFL}.
\end{remark}

It remains to prove Theorem \ref{unram variant FL}(\ref{fl equiv 2}), which we will do by relating functions and orbital integrals on $G'(F_0)$ and $S(F_0)$ as in \cite[\S2.1]{Z14} and \cite[\S5.2]{RSZ}. 
We recall the map $r(g) = g \ov g\i$ from \eqref{Res GL_n -> S}, and we continue to normalize the Haar measures as in \S\ref{s:FL}.  Also recall that since we are in the unramified case, $\wt\eta$ is the natural extension $\wt\eta(x) = (-1)^{v(x)}$ of $\eta$ to $F^\times$.  For $g \in \GL_n(F)$, we write $\wt\eta(g) := \wt\eta(\det g)$.

\begin{lemma}\label{homog to inhomog}
Let $f'\in  C^\infty_c(G')$, and define the function $\wt f'$ on $S(F_0)$ by, for $g \in \GL_n(F)$,
\begin{equation*}
   \wt f'\bigl(r(g)\bigr) := \int_{\GL_{n-1}(F)\times \GL_n(F_0)}f'(h_1\i,h_1\i g h_2) \wt\eta(gh_2)^{n-1}\, dh_1\,dh_2.
\end{equation*}
\begin{altenumerate}
\item\label{all}
$\wt f'\in C^\infty_c(S)$, and every element in $C^\infty_c(S)$ arises in this way.  
\item\label{new}
We have
\[
   \frac{q^n-1}{q-1} \cdot \wt{\mathbf{1}}_{\GL_{n-1}(O_F) \times K_0(\varpi)} = \mathbf{1}_{K'}.
\]
\item\label{old}
For all $\gamma = (\gamma_1, \gamma_2)\in G'(F_0)_\rs$,
\begin{equation*}
   \Orb\bigl(r(\gamma_1\i\gamma_2),\wt f'\bigr) = \wt\eta(\gamma_1^{-1}\gamma_2)^{n-1}\Orb(\gamma,f').
\end{equation*}
\item\label{old 2}
If $f'$ transfers to $(0,f_1)$ for some $f_1\in  C^\infty_c(G_{W_1})$, then there exists a function $\phi_\corr' \in C_c^\infty(G')$ such that for any $\gamma$ matching an element in $G_{W_0}(F_0)_{\rs}$,
\[
   2 \del\bigl(r(\gamma_1\i\gamma_2),\wt f'\bigr) = \wt\eta(\gamma_1^{-1}\gamma_2)^{n-1} \bigl(\del(\gamma,f') +  \Orb(\gamma,\phi'_{\corr})\bigr).
\]
If furthermore the support of $f'$ is contained in the set $\{(\gamma_1,\gamma_2)\in G'(F_0) \mid \lv\det \gamma_1\rv = 1 \}$, then we may take $\phi_\corr' = 0$.
% Suppose that $f'$ transfers to $(0,f_1)$ for some $f_1\in  C^\infty_c(G_{W_1})$, and that the support of $f'$ is contained in $\{(\gamma_1,\gamma_2)\in G'(F_0) \mid \lv\det \gamma_1\rv = 1 \}$. Then for any $\gamma$ matching an element in $G_{W_0}(F_0)_{\rs}$,
% \begin{equation*}
%    \del\bigl(r(\gamma_1\i\gamma_2),\wt f'\bigr) = \wt\eta(\gamma_1^{-1}\gamma_2)^{n-1} \del(\gamma,f').
% \end{equation*}
\end{altenumerate}
\end{lemma}

\begin{proof}
Part (\ref{all}) is clear, and parts (\ref{old}) and (\ref{old 2}) are proved as in \cite[Lem.\ 5.7]{RSZ}.\footnote{Note that in loc.\ cit.\ $n$ is odd, which in the case of our $\wt\eta$ implies that $\wt\eta(\gamma_1^{-1}\gamma_2)^{n-1} = 1$; however the proof for arbitrary $n$ is analogous. The last statement in (\ref{old 2}) is immediate from the specific choice of $\phi_\corr'$ given in (5.13) in loc.\ cit.}  We prove (\ref{new}).  For $g \in \GL_n(F)$, we have
\begin{align}
   &\wt{\mathbf{1}}_{\GL_{n-1}(O_F) \times K_0(\varpi)}\bigl(r(g)\bigr)\notag\\ 
	   &\qquad\qquad\qquad = \int_{\GL_{n-1}(F)\times \GL_n(F_0)} \mathbf{1}_{\GL_{n-1}(O_F) \times K_0(\varpi)}(h_1\i,h_1\i g h_2) \wt\eta(gh_2)^{n-1}\, dh_1\,dh_2 \notag\\
		&\qquad\qquad\qquad= \int_{\GL_{n-1}(O_F)\times \GL_n(F_0)} \mathbf{1}_{K_0(\varpi)} (h_1\i g h_2) \wt\eta(gh_2)^{n-1}\, dh_1\,dh_2\notag\\
		&\qquad\qquad\qquad= \int_{\GL_n(F_0)} \mathbf{1}_{K_0(\varpi)} (g h_2) \wt\eta(gh_2)^{n-1}\, dh_2,\label{last}
\end{align}
where the last equality holds because $\GL_{n-1}(O_F) \subset K_0(\varpi)$.  We claim that
\begin{equation}\label{blah}
   r(g) \in K' \iff g \GL_n(F_0) \cap K_0(\varpi) \neq \emptyset.
\end{equation}
Before establishing this claim, let us show that it implies the conclusion of (\ref{new}).  If $r(g) \notin K'$, then $\wt{\mathbf{1}}_{\GL_{n-1}(O_F) \times K_0(\varpi)}(r(g)) = 0$ because, by (\ref{blah}), the integrand in (\ref{last}) is identically zero.  If $r(g) \in K'$, then by (\ref{blah}) we may assume that $g \in K_0(\varpi)$.  Since $\wt\eta$ is identically one on $K_0(\varpi)$, we conclude from (\ref{last}) that
\begin{multline*}
   \wt{\mathbf{1}}_{\GL_{n-1}(O_F) \times K_0(\varpi)}\bigl(r(g)\bigr) 
	   = \vol\bigl(\GL_n(F_0) \cap K_0(\varpi)\bigr)\\
	   = \frac 1{[\GL_n(O_{F_0}): \GL_n(O_{F_0})\cap K_0(\varpi)]}
		= \frac 1{\frac{q^n-1}{q-1}},
\end{multline*}
where in the last equality we use that the index in question equals $\#\BP_k^{n-1}(k)$ (note that $\GL_n(O_{F_0})$ acts transitively on the lines in $k^n$, and $\GL_n(O_{F_0})\cap K_0(\varpi)$ is the stabilizer of a line).  This proves (\ref{new}).

It remains to establish the equivalence (\ref{blah}).  The reverse implication is trivial.  To prove the forward implication, let $\Lambda := O_F^n$ and $\Lambda' := O_F^{n-1} \oplus \varpi\i O_F$.  Then $K_0(\varpi)$ is the stabilizer in $\GL_n(F)$ of the lattice chain $\Lambda \subset \Lambda'$.  Since $r(g) \in K'$, we have $\ov g\i \Lambda = g\i \Lambda$ and $\ov g\i \Lambda'= g\i \Lambda'$.  Hence these are Galois-stable lattices in $F^n$, so that they come from an $O_{F_0}$-lattice chain in $F_0$. Hence there exists $h \in \GL_n(F_0)$ such that $h \cdot (\Lambda \subset \Lambda') = g\i \cdot (\Lambda \subset \Lambda')$.  Hence $gh \in K_0(\varpi)$, as desired.
\end{proof}

\begin{proof}[Proof of Theorem \ref{unram variant FL}(\ref{fl equiv 2})]
By Lemma \ref{homog to inhomog}(\ref{new})(\ref{old}) and the definition of the transfer factors in \S\ref{trans factor},
\[
   \omega_{G'}(\gamma) \Orb\biggl(\gamma,\frac{q^n-1}{q-1}\cdot\mathbf{1}_{\GL_{n-1}(O_F)\times K_0(\varpi)}\biggr) = \omega_S\bigl(r(\gamma_1\i\gamma_2)\bigr) \Orb\bigl(r(\gamma_1\i\gamma_2), \mathbf{1}_{K'} \bigr)
\]
for all $\gamma = (\gamma_1,\gamma_2) \in G'(F_0)_\rs$.  On the other hand, it is easy to verify that
\[
   \Orb(g,\mathbf{1}_{K_1^\flat \times K_1}) = \Orb(g_1\i g_2,\mathbf{1}_{K_1})
\]
for all $g = (g_1,g_2) \in G_{W_1}(F_0)_\rs$.  Since the maps
\begin{equation}\label{maps}
   \begin{gathered}
		\xymatrix@R=0ex{
		   G'(F_0)_\rs \ar[r]  &  S(F_0)_\rs\\
			(\gamma_1,\gamma_2) \ar@{|->}[r]  &  r(\gamma_1\i \gamma_2)
		}
	\end{gathered}
	\qquad\text{and}\qquad
   \begin{gathered}
		\xymatrix@R=0ex{
		   G_{W_i}(F_0)_\rs \ar[r]  &  G_i(F_0)_\rs\\
			(g_1,g_2) \ar@{|->}[r]  &  g_1\i g_2
		}
	\end{gathered}
\end{equation}
are compatible with the matching relation, the theorem follows.
\end{proof}

Let us finally note that, in analogy with \cite[Lem.\ 2.5]{Z12} in the self-dual case, the transfer relations asserted in the FL Conjecture \ref{FL almost self-dual} are easy to verify in the case that the unitary matching elements are
attached to the split hermitian space.  For any $y \in \RM_n(F)$, define
\[
   \tensor*[^*]{y}{} := \diag(1,\dotsc,1,\varpi\i) \tensor[^t]{y}{} \diag(1,\dotsc,1,\varpi).
\]

\begin{lemma}
\begin{altenumerate}
\item\label{matching 0 homog}
Suppose that $f' \in C_c^\infty(G')$ satisfies $f'(\gamma_1,\gamma_2) = f'(\tensor*[^t]{\ov\gamma}{_1^{-1}},\tensor*[^*]{\ov\gamma}{_2^{-1}})$.  Then for all $\gamma \in G'(F_0)_\rs$ matching an element $g \in G_{W_0}(F_0)_\rs$,
\[
   \Orb(\gamma,f') = 0.
\]
In particular, $\Orb(\gamma,\mathbf{1}_{\GL_{n-1}(O_F) \times K_0(\varpi)}) = 0$ for such $\gamma$.
\item\label{matching 0 inhomog}
Suppose that $f' \in C_c^\infty(S)$ satisfies $f'(\gamma) = f'(\tensor*[^*]{\gamma}{})$.  Then for all $\gamma \in S(F_0)_\rs$ matching an element $g \in G_0(F_0)_\rs$,
\[
   \Orb(\gamma,f') = 0.
\]
In particular, $\Orb(\gamma,\mathbf{1}_{K'}) = 0$ for such $\gamma$.
\item\label{matching 0 lie}
Suppose that $\phi' \in C_c^\infty(\fks)$ satisfies $\phi'(y) = \phi'(\tensor*[^*]{y}{})$.  Then for all $y \in \fks(F_0)_\rs$ matching an element $x \in \fkg_0(F_0)_\rs$,
\[
   \Orb(y,\phi') = 0.
\]
In particular, $\Orb(\gamma,\mathbf{1}_{\fkk'}) = 0$ for such $y$.
\end{altenumerate}\label{matching 0}
\end{lemma}

\begin{proof}
The proofs of (\ref{matching 0 inhomog}) and (\ref{matching 0 lie}) are virtually identical to that of \cite[Lem.\ 2.5]{Z12}.  Part (\ref{matching 0 homog}) then follows from (\ref{matching 0 inhomog}) by the easily verified fact that if $f'$ satisfies the hypothesis in (\ref{matching 0 homog}), then $\wt f'$ satisfies the hypothesis in (\ref{matching 0 inhomog}); by the fact that the maps in \eqref{maps} respect the matching relation; and by Lemma \ref{homog to inhomog}(\ref{old}).
\end{proof}




\subsection{On the AT and AFL Conjecture \ref{conjunramified}}\label{results atc afl}
In this subsection we prove results related to Conjecture \ref{conjunramified}.  We retain the notation of the previous subsection.

\begin{theorem}\label{AFLtoAT1} 
The AFL identity in Conjecture \ref{conjunramified}(\ref{conjunramified lie})
holds true for an element $x\in \fkg_0(F_0)_\rs$ if and only if Conjecture \ref{AFLconj}(\ref{AFLconj lie}) holds true for $\theta(x)\in\fkg_1(F_0)_\rs$.
\end{theorem}

\begin{proof} Forgetting the polarizations, the framing objects $\BX_n$ of $\CN_n$ and $\wt\BX_n$ of $\wt\CN_n$ are identical, as are the objects $\ov\CE$ and $\ov\CE'$ used to define the respective embeddings $\delta_\CN\colon \CN_{n-1} \to \CN_n$ and $\wt\delta_\CN\colon \CN_{n-1} \to \wt\CN_n$. Hence for any $x\in\End_{O_F}^\circ(\wt\BX_n) = \End_{O_F}^\circ (\BX_n)$, we have an equality of closed formal subschemes of $\CN_{n-1}$, 
\[
   \wt\Delta\cap\wt\Delta_x=\Delta\cap\Delta_x . 
\]

Now let $x\in \fkg_0(F_0)$. We claim that 
\begin{equation*}
   \Delta\cap\Delta_x =\Delta\cap\Delta_{\theta(x)} .  
\end{equation*}
Indeed, with respect to the product decomposition $\wt\BX_n = \BX_n = \BX_{n-1} \times \ov \BE$, write
\[
   x = 
	\begin{bmatrix}
		 A &  b  \\
      c  & d
   \end{bmatrix},
\]  
where $A\in \End^\circ_{O_F}(\BX_{n-1})$, $b\in \Hom^\circ_{O_F}(\ov \BE,\BX_{n-1})$, $c \in \Hom_{O_F}^\circ(\BX_{n-1}, \ov\BE)$, and $d\in \End^\circ_{O_F}(\ov \BE)$.  Since $x + \Ros_{\lambda_{\wt\BX_n}}(x) = 0$, we have $b = - \varpi \tensor[^t]{c}{}$, where $\tensor[^t]{c}{} := \lambda_{\BX_{n-1}}\i \circ c^\vee \circ \lambda_{\ov\BE}$.  Hence
\[
   \theta(x) =
	\begin{bmatrix}
		A  &  -\tensor[^t]{c}{}\\
		c  &  d
	\end{bmatrix}.
\]
Given a point $Y$ on $\CN_{n-1}$, we see by inspection that $x$ lifts to an endomorphism of $Y \times \ov\CE$ if and only if $\theta(x)$ does, which proves the claim.
  
Of course, it follows from the claim that $\wt\Delta \cap \wt\Delta_x$ is artinian if and only if $\Delta \cap \Delta_{\theta(x)}$ is, and when they are,
$$
   \lInt(x)=\lInt\bigl(\theta(x)\bigr).
$$
On the orbital integral side, it follows from Lemma \ref{lemtheta}(\ref{lemtheta i}) that
\[
   \omega_\fks(y) \del\bigl(y, (-1)^{n-1}\mathbf{1}_{\fkk'}\bigr) = \omega_\fks\bigl(\theta(y)\bigr)\del\bigl(\theta(y), \mathbf{1}_{\fks(O_{F_0})}\bigr),\quad  y\in \fks(F_0)_\rs .
\]
This completes the proof.
\end{proof}

\begin{theorem} Assume $q\geq n$.
Then the AFL identities in Conjecture \ref{conjunramified}(\ref{conjunramified homog})(\ref{conjunramified inhomog}) hold true for all $g\in G_{W_0}(F_0)_\rs$, resp.\ $g\in G_0(F_0)_\rs$, for which the intersection is non-degenerate, provided that the AFL identity in
Conjecture \ref{conjunramified}(\ref{conjunramified lie})
holds true.
\end{theorem}

\begin{proof}
First note that homogeneous AFL identity reduces to the inhomogeneous one via Lemma \ref{homog to inhomog}(\ref{new})(\ref{old 2}), Lemma \ref{matching 0}(\ref{matching 0 homog}), and the easy fact that $\Int(g) = \Int(g_1\i g_2)$ for any $g = (g_1,g_2) \in G_{W_0}(F_0)_\rs$.  Thus we show that the inhomogeneous identity holds.	
The proof again uses Cayley maps
(cf.\ also the proof of \cite[Lem.\ 2.2]{M-AFL}). Let $g\in G_0(F_0)_\rs$ be such that the intersection is non-degenerate. Let $\gamma\in S(F_0)_\rs$ be a matching element. We need to show that
\begin{equation}\label{desired}
   \omega_S(\gamma) \del\bigl(\gamma, (-1)^{n-1}\mathbf{1}_{K'}\bigr)=-\Int(g)\cdot \log q.
\end{equation}

As in the proof of Theorem \ref{unram variant FL}(\ref{fl imply}), we consider cases based on the integrality of $\gamma$. If $\gamma$ is not integral, then the left-hand side of \eqref{desired} is obviously zero. But then $g$ is also not integral, and we claim this forces the intersection $\wt\Delta\cap (1\times g)\wt\Delta$ to be empty, so that the right-hand side of \eqref{desired} is also zero.  Indeed, if instead this intersection were nonempty, then it would contain a $\ov k$-point, and $g$ would stabilize the corresponding Dieudonn\'e module.  Hence the characteristic polynomial of $g$ would lie in $O_{\breve F}[T]$, contrary to the non-integrality of $g$.

Now assume that $\gamma$ is integral. Since $q\geq n$,  $\gamma$ is $\xi$-strongly integral for some $\xi\in F^1$, and hence so is the matching element $g$. Let $y:=\fkc_\xi^{-1}(\gamma) \in \fks(F_0)^\circ$ and $x:= \fkc_\xi\i(g) \in \fkg_0(F_0)^\circ$. Then $y$ and $x$ also match. By Lemma \ref{cayley orb},
$$
 \omega_\fks(y)\del(y, \mathbf{1}_{\fkk'})=\omega_S(\gamma)\del(\gamma, \mathbf{1}_{K'}) .
$$
To complete the proof, since we assume the AFL identity in Conjecture \ref{conjunramified}(\ref{conjunramified lie}), it suffices to show that $\wt\Delta \cap \wt\Delta_x$ is artinian if and only if $\wt\Delta \cap (1\times g)\wt\Delta = \wt\Delta \cap \wt\Delta_g$ is, and when they are, that
\begin{align}\label{idcayint}
   \lInt(x)=\Int(g).
\end{align}
Both of these statements follow from the equality 
of subschemes of $\wt\Delta$, for any strongly integral $x$ and $g=\fkc_\xi(x)$,
\begin{equation}\label{eqn int cayley u}
   \wt\Delta\cap\wt \Delta_x = \wt\Delta\cap\wt \Delta_g.
\end{equation}
Indeed, this implies \eqref{idcayint} because, when $\wt\Delta\cap\wt \Delta_g$ is artinian, 
its length is equal to $\Int(g)$, cf.\ \cite[Prop.\ 8.10]{RSZ}. Now, the two sides \eqref{eqn int cayley u} are the loci of points $Y$ in $\CN_{n-1}$ where, respectively, $x\colon \wt\BX_n \rightarrow \wt\BX_n$ and $g\colon \wt\BX_n \to \wt\BX_n$ lift to a homomorphism $Y \times \ov\CE \rightarrow Y\times \ov\CE$.  But by the Cayley--Hamilton theorem, for strongly integral $x$ we have $O_F[x] = O_F[\fkc_\xi(x)]$ as $O_F$-subalgebras of $\End_{O_F}^\circ(\wt\BX_n)$. Hence $x$ lifts if and only if $g$ does. This establishes \eqref{eqn int cayley u} and completes the proof.
\end{proof}


\begin{corollary}
Let $F_0 = \BQ_p$. Then Conjecture \ref{conjunramified} holds when   $n=2$ or $3$.
\end{corollary}
\begin{proof}
 Let us first consider the AFL identities in  Conjecture \ref{conjunramified}. In these cases the intersection is automatically non-degenerate.  Furthermore, $q\geq 3\geq n$. Thus by the two preceding theorems, these identities follow from the Lie algebra AFL Conjecture \ref{AFLconj}(\ref{AFLconj lie}) for $n = 2$ and $3$. This is proved in \cite{M-AFL}.
(When $q\geq 5$, the Lie algebra AFL for $n=3$ can also be deduced from the group version proved in \cite{Z12}; see \cite[Lem.\ 2.2]{M-AFL}.)

Now we consider the rest of Conjecture \ref{conjunramified}. By the same proof as for \cite[Lem.\ 5.18]{RSZ}, this follows from the density principle for our weighted orbital integrals, i.e.\ the analog in the unramified case of \cite[Conj.\ 5.16]{RSZ}. This conjectural density principle is known to hold for $n=2$ or $3$, cf.\ \cite[Th.\ 1.1]{Z12b} and \cite[Rem.\ 5.17]{RSZ}. 
\end{proof}

\begin{remark}
The AFL in the self-dual case (Conjecture \ref{AFLconj}) is known for arbitrary $n$ and $F_0 = \BQ_p$, provided that $g$ is minuscule in the sense of \cite{RTZ}, and $p\geq n/2+1$.
If $p \geq n+2$, then we may deduce from this the AFL identity in Conjecture \ref{conjunramified}(\ref{conjunramified inhomog}) in the almost self-dual case for certain $g$, by applying \cite[Th.\ 2.5]{M-AFL} and then passing through the Lie algebras as above.
\end{remark}







\section{On the ATC for $F/F_0$ ramified, $n=2$}\label{even ram proof}

In this section we prove Conjecture \ref{conjram v3} when $n=2$.

\subsection{The groups}\label{the groups}
On the symmetric space $S(F_0) = S_2(F_0)$, we write an element as
$$\gamma=
\begin{bmatrix}
		a &  b \\
         c  &  d
      \end{bmatrix}\in S(F_0).
$$
Then $\gamma$ is regular semi-simple if and only if $bc\neq 0$, in which case we may write $\gamma$ as
\begin{equation}\label{gamma(a,b)}
\begin{aligned}
\gamma=\gamma(a,b) &:=\begin{bmatrix}
		a &  b \\
         (1-\RN a)/\ov b &  -\ov ab/\ov b
      \end{bmatrix}\\
		&\phantom{:}=\begin{bmatrix}
		1&   \\
          &  -b/\ov b
      \end{bmatrix} \begin{bmatrix}
		a &  b \\
        - (1-\RN a)/ b &  \ov a
      \end{bmatrix} \in S(F_0)_\rs,
		\quad a \in F \smallsetminus F^1,\ b \in F^\times.
\end{aligned}
\end{equation}
We define the set of semi-simple but irregular elements
\[
A_{S} :=
	   \biggl\{\, 
		\begin{bmatrix}
		   a  &    \\
           &  d
      \end{bmatrix} 
		\in S(F_0) \biggm|  a,d \in F^1 \,\biggr\}.
\]
Similarly, in the ``Lie algebra'' $\fks(F_0) = \fks_2(F_0)$ we write an element as
\begin{equation}\label{y(a,b,c,d)}
   y=y(a, b, c, d)=\begin{bmatrix}
		   a  & b   \\
        c   &  d
      \end{bmatrix} \in \fks(F_0), \quad a,b,c,d\in \pi F_0.
\end{equation}
The set of semi-simple but irregular elements is 
\begin{align*}
\fka_{\fks} :=
	   \biggl\{\,
		\begin{bmatrix}
		   a  &    \\
		      &  d
		\end{bmatrix}
		\in \fks(F_0) \biggm|  a,d \in \pi F_0 \,\biggr\}.
\end{align*}

On the unitary side, we first look at objects attached to the split hermitian space.  Recall from \S\ref{s:ATCeven} that we have
\[
   W_0=W^\flat_0\oplus F u_0,\quad (u_0,u_0)=-1.
\]
By \eqref{chi decomp formula} the space $W_0^\flat$ is also split, and we choose a basis vector $u^\flat \in W_0^\flat$ with $(u^\flat, u^\flat) = 1$.  This choice determines a special embedding $G_0(F_0) = \U(W_0)(F_0) \inj \GL_2(F)$ as in \S\ref{setup inhomog}, which realizes $G_0$ as the unitary group associated to the diagonal hermitian matrix $\diag(1,-1)$. In this way, the set of irregular elements in $G_0(F_0)$ is 
\begin{equation}\label{eqn U_2 A}
A_{G_0} :=
	   \biggl\{\, 
		\begin{bmatrix}
		   a  &    \\
           &  d
      \end{bmatrix}
		\in \RM_2(F) \biggm| a,d \in F^1  \,\biggr\}.
\end{equation}
These elements are all semi-simple since the group $H_0 = \U(W_0^\flat)$ is anisotropic. Similarly, we embed the Lie algebra $\fkg_0(F_0) \inj \RM_2(F)$, and we denote its set of irregular semi-simple elements by 
\begin{align*}
\fka_{\fkg_0} :=
	   \biggl\{\, 
		\begin{bmatrix}
		   a  &    \\
		      &  d
		\end{bmatrix}
		\in \RM_2(F) \biggm|  a,d \in \pi F_0  \,\biggr\}.
\end{align*}

Now recall the lattice
$\Lambda_0^\nat=\Lambda_0^\flat\oplus O_F u_0$ from \eqref{Lambda^nat}, which is self-dual since $n = 2$. The two $\pi$-modular lattices lying between $\pi\Lambda_0^\nat$ and $\Lambda_0^\nat$ are given by
$$
\Lambda_0^\pm=\pi\Lambda_0^\nat+O_F\, (u_0\pm u^\flat).
$$
They are both stable under elements of $K_0^\flat = F^1$ with reduction $1 \bmod \pi$, and they are permuted by elements with reduction $-1 \bmod \pi$. Now let $\Lambda_0$ be either of them, and let $K_0 \subset G_0(F_0)$ and $\fkk_0 \subset \fkg_0(F_0)$ be the respective stabilizers of $\Lambda_0$. A subtle point is that 
$$
A_{G_0}\cap K_0=  \biggl\{\,  \begin{bmatrix}
		   a  &    \\
           &  d
      \end{bmatrix}\in G_0(F_0)\biggm|   a\equiv 1\bmod \pi   \,\biggr\}
$$
is a subgroup of $A_{G_0}$ of index $2$.  However, we do have 
\begin{equation}\label{A_G_0 intersect}
   A_{G_0}\cap K_0^\flat K_0= A_{G_0}.
\end{equation}
In the Lie algebra $\fkg_0(F_0)$, we have 
\begin{equation}\label{a_g_0 intersect}
   \fka_{\fkg_0} \cap \fkk_0= \biggl\{\, 
	\begin{bmatrix}
	   a  &    \\
	      &  d
	\end{bmatrix}
	\in \fkg_0(F_0) \biggm| a,d \in \pi O_{F_0}  \,\biggr\}.
\end{equation}

We now look at the non-quasi-split unitary group $G_1$. Recall from \eqref{u} that the hermitian space
\[
   W_1=\BV(\BX_2) \cong \BV\bigr(\wt\BX_2\bigl) 
	               = \Hom_{O_F}^\circ\bigl(\ov\BE,\BX_1 \times \ov\BX_1\bigr)
						= \BV(\BX_1)\oplus \BV\bigl(\ov \BX_1\bigr)
\]
has a special vector $u=(0,\id_{\ov \BE})$ with norm $-1$. Note that the rightmost space in the display is canonically $D=D^-\oplus F$ (as an $F_0$-vector space) with hermitian norm given by $(v,v)=-\RN v$ for $v\in D$, and the special vector $u$ corresponds to $1\in D$.
We identify 
$$
   \End_{O_{F_0}}^\circ \bigl(\wt\BX_2\bigr) = \End_{O_{F_0}}^\circ\bigl(\BE^2\bigr)=\RM_2(D),
$$ 
and the $O_F$-action is given by $\pi\mapsto \diag(\pi,-\pi)\in \RM_2(D)$. Then the $O_F$-linear quasi-endomorphism algebra is 
$$
\End_{O_F}^\circ\bigl(\wt\BX_2\bigr)= \biggl\{\,  \begin{bmatrix}
		   a  & b    \\
       c    &  d
      \end{bmatrix} \in \RM_2(D) \biggm|   a,d\in F,\ b,c\in D^-  \,\biggr\} .
$$
The Rosati involution is given by
$$
   \Ros_{\lambda_{\wt\BX_2}}(x)=x^\dagger= \tensor[^t]{\ov x}{},
$$
where $x\mapsto \ov x$ is the entry-wise main involution on $\RM_2(D)$.  We then have the unitary group 
$$
   G_1(F_0) = \bigl\{\, x\in \End_{O_F}^\circ\bigl(\wt\BX_2\bigr) \bigm|  x^\dagger x=1\,\bigr\} ,
$$
and its Lie algebra 
$$
\fkg_1(F_0)=\bigl\{\, x\in \End_{O_F}^\circ\bigl(\wt\BX_2\bigr) \bigm|  x^\dagger + x=0 \,\bigr\} .
$$
They may be explicitly presented as
\begin{equation}\label{G_1 pres}
   G_1(F_0)=\biggl\{\,  \begin{bmatrix}
		   1 &     \\
         &  \alpha
      \end{bmatrix}    \begin{bmatrix}
		   a  & b    \\
       b   &  a
      \end{bmatrix} \in \RM_2(D)  \biggm|  a\in F,\ b\in D^-,\ \RN a+\RN b=1,\ \alpha \in F^1 \,\biggr\}
\end{equation}
and 
\begin{equation}\label{fkg_1 pres}
\fkg_1(F_0)=\biggl\{\, \begin{bmatrix}
		   a  & b    \\
       b  &  d
      \end{bmatrix} \in \RM_2(D)  \biggm|  a,d\in \pi F_0,\ b\in D^-   \,\biggr\} .
\end{equation}
If we fix a basis element $\zeta \in D^-$, then we may also express these presentations in terms of special embeddings into $\RM_2(F)$,
\[
   \begin{bmatrix}
		   1 &     \\
         &  \alpha
   \end{bmatrix}
	\begin{bmatrix}
		   a  & b    \\
       b   &  a
   \end{bmatrix} \in G_1(F_0) \subset \RM_2(D)
	\quad\text{\emph{identifies with}}\quad
	\begin{bmatrix}
		   a  & b \zeta\i    \\
       \ov{\alpha b \zeta}  &  \ov{\alpha a}
   \end{bmatrix} \in \RM_2(F),
\]
and
\[
	\begin{bmatrix}
		 a  &  b    \\
       b  &  d
   \end{bmatrix} \in \fkg_1(F_0) \subset \RM_2(D)
	\quad\text{\emph{identifies with}}\quad
	\begin{bmatrix}
		 a  &  b \zeta\i   \\
       \ov{b \zeta}  &  -d
   \end{bmatrix} \in \RM_2(F).
\]
Similarly to before, the irregular semi-simple elements in $G_1(F_0)$ are given by the diagonal elements
\[
   A_{G_1} :=  \biggl\{\, 
		\begin{bmatrix}
		   a  &    \\
           &  d
      \end{bmatrix}
		\in \RM_2(D) \biggm| a,d \in F^1  \,\biggr\}
	=
	\biggl\{\, 
	\begin{bmatrix}
	   a  &    \\
        &  \ov d
   \end{bmatrix}
	\in \RM_2(F) \biggm| a,d \in F^1  \,\biggr\},
\]
and the irregular semi-simple elements in $\fkg_1(F_0)$ are given by
\[
   \fka_{\fkg_1} := \biggl\{\,
	   \begin{bmatrix}
		   a  &     \\
            &  d
      \end{bmatrix} \in \RM_2(D)  \biggm|  a,d\in \pi F_0  \,\biggr\} 
		= \biggl\{\,
	   \begin{bmatrix}
		   a  &     \\
            &  - d
      \end{bmatrix} \in \RM_2(F)  \biggm|  a,d\in \pi F_0  \,\biggr\}.
\]



\subsection{Orbit matching}\label{orbit matching}
Let us now indicate how regular semi-simple orbits match in terms of the presentations just given.  Recall from \cite[Prop.\ 6.2]{RS} that in the case $n = 2$, two regular semi-simple elements in $\RM_2(F)$ (cf.\ \S\ref{setup inhomog}) are $\GL_1(F)$-conjugate if and only if their diagonal entries are the same and the products of their off-diagonal entries are the same.  In the group setting, it is easy to verify from this that elements $\gamma\in S(F_0)_\rs$ and $g\in G_i(F_0)_{\rs}$ match if and only if, after regarding $g$ as an element of $\GL_2(F)$ via a special embedding, 
$
\det\gamma = \det g
$ and the upper-left entries of these matrices are equal.  Let $S_{\rs,i}$ denote the subset of $S(F_0)_\rs$ of elements matching with elements in $G_i(F_0)_\rs$.  It is easy to see that
\begin{equation}\label{S_rs,i cond}
   \gamma(a,b)\in S_{\rs,i} \iff \eta( \RN a - 1)=(-1)^i.
\end{equation}
Furthermore, in terms of the presentation \eqref{G_1 pres},
$$
   \gamma(a,b)\in S_{\rs, 1} \quad \text{\emph{matches}} \quad g=\begin{bmatrix}
		   1 &     \\
         &  \alpha
      \end{bmatrix}    \begin{bmatrix}
		   a'  & b'    \\
       b'   &  a'
      \end{bmatrix}\in G_1(F_0)_\rs
$$
if and only if $a=a'$ and $-b/\ov b=\det \gamma(a,b)=\det g = \ov\alpha$.

In the Lie algebra setting, we analogously denote by $\fks_{\rs,i}$ the subset of $\fks(F_0)_\rs$ of elements matching with elements in $\fkg_i(F_0)_\rs$. It is easy to see that
\[
   y(a,b,c,d)\in \fks_{\rs,i} \iff bc \neq 0 \text{ and } \eta(bc)=(-1)^i.
\]
In terms of the presentation \eqref{fkg_1 pres},
$$
   y(a,b,c,d) \in \fks_{\rs, 1}  \quad \text{\emph{matches}} \quad x= \begin{bmatrix}
		   a'  & b'    \\
       b'   &  d'
      \end{bmatrix}\in \fkg_1(F_0)_\rs
$$
if and only if  $a=a'$, $d= -d'$, and $bc=-\RN b'$.





\subsection{Harmonic analysis}\label{harm}
The harmonic analysis on $S(F_0)$ is done in Mihatsch's article \cite{M-ATC}. We briefly recall the results in loc.~cit.

The orbital integral for $\gamma = \gamma(a,b) \in S(F_0)_\rs$ and a function $f'\in C_c^\infty(S)$ is given by
$$
\Orb(\gamma,f',s)=\bigintssss_{F_0^\times} f'\biggl(\begin{bmatrix}
		   a  & b/x   \\
      x(1-\RN a)/\ov b &  -\ov ab/\ov b
      \end{bmatrix}\biggr) \eta(x)|x|^s \,dx.
$$
The transfer factor takes the form
\begin{equation}\label{omega_S n=2}
   \omega_S(\gamma)=\wt\eta\bigl(\ov b\bigr) = \wt\eta(b)\i,
\end{equation}
cf.\ \S\ref{trans factor}.  Similarly, the orbital integral for $f_i\in C_c^\infty(G_i)$, $i\in\{0,1\}$, is given by
$$
\Orb(g,f_i)=\int_{H_i(F_0)} f_i(h^{-1}gh ) \, dh.
$$
This is well-defined for all $g$, since $H_i(F_0) = F^1$ is compact. Recall that the Haar measure on $H_0(F_0)$ is chosen to give $K_0^\flat = H_0(F_0)$ volume one.  We similarly assign $H_1(F_0)$ volume one.
We also recall the orbital integrals for functions on the Lie algebras from \S\ref{setup lie}.




\begin{theorem}
\begin{altenumerate}
\item\label{germ i} Let $f'\in C_c^\infty(S)$ transfer to $(f_0,f_1)\in C_c^\infty(G_0)\times C_c^\infty(G_1)$, and let $\gamma_0=\diag(a_0,d_0)\in A_{S}$. If  $f_i=0$ for some $i\in\{0,1\}$, then there is the following germ expansion for $\gamma=\gamma(a,b)\in S_{\rs,i}$ in a neighborhood of $\gamma_0$,
$$
\omega_S(\gamma)\del(\gamma,f')=\frac{1}{2}\Orb\bigl(\diag(a_0,d_0),f_{1-i}\bigr)\log\lv 1-\RN a \rv + C,
$$
where $C$ is a constant depending on 
$\gamma_0$, $f'$, and $i$,
but not on $\gamma$. 
\item\label{germ ii} Let $f' \in C_c^\infty(\fks)$ transfer to $(f_0,f_1)\in C_c^\infty(\fkg_0)\times C_c^\infty(\fkg_1)$, and let $y_0=\diag (a_0,d_0)\in \fka_{\fks}$.  If $f_i=0$ for some $i\in\{0,1\}$, then there is the following germ expansion for $y=y(a, b, c, d) \in \fks(F_0)_{\rs,i}$ in a neighborhood of $y_0$,
$$
\omega_\fks(y)\del(y,f')=\frac{1}{2}\Orb\bigl(\diag(a_0,d_0),f_{1-i}\bigr)\log\lv bc \rv + C,
$$
where $C$ is again a constant which does not depend on $y$.
\end{altenumerate}\label{del germ s}
\end{theorem}

\begin{proof}
(\ref{germ i}) By \cite[Th.\ 3.5, Cor.\ 3.8]{M-ATC} and \eqref{omega_S n=2}, there is a germ expansion for regular semi-simple $\gamma = \gamma(a,b)$ in a neighborhood of $\gamma_0$,
\[
   \omega_S(\gamma)\Orb(\gamma,f',s) = 
	   \phi_+(\gamma_0,s)|b|^s 
		   +\phi_-(\gamma_0,s)\wt\eta\bigl(-\ov b\vphantom{b}^2\bigr) \eta(\RN a-1)\bigl\lv(1-\RN a)/\ov b\bigr\rv^{-s},
\]
where $\phi_\pm(\gamma_0,s)$ are Laurent polynomials in $q^{s}$ depending on $\gamma_0$ and $f'$.  Here $\lv\phantom{a}\rv$ denotes the natural extension of the normalized absolute value on $F_0$ to $F$.  For all $\gamma$ sufficiently near $\gamma_0$, the factor $\wt\eta(-\ov b\vphantom{b}^2) = \wt\eta(-\ov b/b)$ is constant-valued.  Hence, after possibly shrinking the neighborhood around $\gamma_0$ and replacing $\phi_-$ by a constant multiple of itself, we obtain
\begin{equation}\label{eqn germ s}
   \omega_S(\gamma)\Orb(\gamma,f',s) = \phi_+(\gamma_0,s)|b|^s +\phi_-(\gamma_0,s)\eta(\RN a-1)\bigl\lv(1-\RN a)/\ov b\bigr\rv^{-s}.
\end{equation}
Evaluation at $s=0$ yields
\begin{equation}\label{eqn germ s=0}
   \omega_S(\gamma)\Orb(\gamma,f') = \phi_+(\gamma_0)  +\phi_-(\gamma_0)\eta(\RN a-1),
\end{equation}
where $\phi_\pm(\gamma_0):=\phi_\pm(\gamma_0,0)$.

Similarly (and more simply), on the unitary side, the function $g \mapsto \Orb(g,f_i)$ is locally constant (and compactly supported) on $G_i(F_0)$.  In particular, for $g_0:=\diag(a_0, d_0)\in A_{G_i}$, there is a neighborhood of $g_0$ in $G_i(F_0)$ on which for all elements $g$,
$$
\Orb(g,f_i)=\Orb(g_0, f_i).
$$
Since $f'$ transfers to $(f_0,f_1)$, we obtain from this, \eqref{S_rs,i cond}, and \eqref{eqn germ s=0} that
\begin{equation}\label{eqn nil orb}
\begin{aligned}
   \Orb\bigl(\diag(a_0,d_0),f_0\bigr) &=\phi_+(\gamma_0)+\phi_-(\gamma_0),\\
	\Orb\bigl(\diag(a_0,d_0),f_1\bigr) &=\phi_+(\gamma_0)-\phi_-(\gamma_0).
\end{aligned}
\end{equation}


Now assume that $i=1$ in the statement of the theorem. Then by \eqref{eqn nil orb},
\begin{align}\label{eqn germ s u}
   \phi_+(\gamma_0) = \phi_-(\gamma_0) = \frac{1}{2}\Orb\bigl(\diag(a_0,d_0),f_0\bigr).
\end{align}
When $\gamma\in S_{\rs,1}$, i.e.\  $\eta(\RN a-1)=-1$, we may rewrite \eqref{eqn germ s} as
\[
   \omega_S(\gamma)\Orb(\gamma,f',s) =
	   |b|^s \bigl(\phi_+(\gamma_0,s)-\phi_-(\gamma_0,s)\bigr)+|b|^s\phi_-(\gamma_0,s)\bigl(1-|1-\RN a|^{-s}\bigr).
\]
Taking the derivative, we obtain
$$
\omega_S(\gamma)\del(\gamma,f')=C+\phi_-(\gamma_0)\log\lv 1-\RN a \rv,
$$
where $C:=\frac{d}{ds}\big|_{s=0}  (\phi_+(\gamma_0,s)-\phi_-(\gamma_0,s)) $ is a constant. The desired result now follows from \eqref{eqn germ s u}. The case $i=0$ is analogous.

(\ref{germ ii}) The proof is analogous to (\ref{germ i}).  Note that Th.\ 3.5 and Cor.\ 3.8 in \cite{M-ATC} are only stated in the group setting.  In the Lie algebra setting, one analogously proves that for all regular semi-simple $y = y(a,b,c,d)$ in a neighborhood of $y_0$,
\[
   \Orb(y,f',s) = \phi_+(y_0,s)\wt\eta(b)|b|^s + \phi_-(y_0,s)\wt\eta(c)\i |c|^{-s}
\]  
for some Laurent polynomials $\phi_\pm(y_0,s)$ in $q^s$ depending on $y_0$ and $f'$.  Also note that the Lie algebra transfer factor is given by $\omega_\fks(y) = \wt\eta(-b) = \wt\eta\bigl(\ov b\bigr)$.  With these remarks the proof of (\ref{germ i}) carries over in a straightforward way.
\end{proof}

For the specific test function $f_0=\mathbf{1}_{K_0^\flat K_0} \in C_c^\infty(G_0)$, the irregular orbital integrals are as follows. 

\begin{lemma}\label{lem nil orb int u}
The irregular orbital integrals  of $\mathbf{1}_{K_0^\flat K_0}$ are given by
$$
\Orb\bigl(\diag(a,d), \mathbf{1}_{K_0^\flat K_0}\bigr) = 1,\quad a,d\in F^1.
$$
The irregular orbital integrals  of $\mathbf{1}_{\fkk_0}$ are given by
$$
\Orb\bigl(\diag(a,d), \mathbf{1}_{\fkk_0}\bigr) = \begin{cases} 1,& a,d\in \pi O_{F_0},\\
0, &\mbox{otherwise}.
\end{cases}
$$
\end{lemma}

\begin{proof}
This is immediate from the fact that the conjugation action of $H_0(F_0)$ on diagonal matrices is trivial, from the normalization $\vol H_0(F_0) = 1$, and from \eqref{A_G_0 intersect} and \eqref{a_g_0 intersect}.
\end{proof}




\subsection{Intersection numbers}

We now record the values of the intersection numbers appearing in parts (\ref{conjram v3 inhomog}) and (\ref{conjram v3 lie}) of Conjecture \ref{conjram v3}.  Recall that $v$ denotes the normalized valuation on $F_0$.

\begin{proposition}\label{prop int(g) int(x)}
Let $g= \begin{bmatrix}
		   1 &     \\
         &  \alpha
      \end{bmatrix} 
\begin{bmatrix}
		   a  & b   \\
           b&  a
      \end{bmatrix}
\in G_1(F_0)_\rs$, expressed in the presentation (\ref{G_1 pres}). Then 
\[
   \Int(g)= 2v(\RN b) + 2.
\]
Similarly, for $x= 
\begin{bmatrix}
		   a  & b   \\
           b&  d
      \end{bmatrix}
\in \fkg_1(F_0)_\rs$ expressed in the presentation (\ref{fkg_1 pres}), 
\[
   \lInt(x)=
	\begin{cases}
      2v(\RN b) + 2,  &  a,d\in \pi O_{F_0} \text{ and } b\in O_D \cap D^-;\\
      0,  &  \text{otherwise}.
   \end{cases}
\]
\end{proposition}

\begin{proof}
We first consider the group version.  Note that under the parametrization \eqref{G_1 pres}, $a + b$ is a norm one element in $D$, and hence $a \in O_F$ and $b \in O_D \cap D^-$ are both integral.

The coordinates \eqref{G_1 pres} express $g$ naturally as a quasi-endomorphism of $\wt\BX_2$; the quasi-endo\-morphism of $\BX_2$ attached to $g$ is the conjugate $\phi_0\i g \phi_0$, where $\phi_0\colon \BX_2 \to \wt\BX_2$ is the isogeny \eqref{phi_0}.  With respect to the $O_{F_0}$-linear decompositions $\BX_2 = O_F \otimes_{O_{F_0}} \BE = (1 \otimes \BE) \oplus (\pi \otimes \BE)$ and $\wt\BX_2 = \BE^2$, the element $\phi_0 \in \Hom_{O_F}^\circ (\BX_2,\wt\BX_2) \subset \End_{O_{F_0}}^\circ(\BE^2) = \RM_2(D)$ identifies with the matrix
\[
   \begin{bmatrix}
		1  &  \pi\\
		1  &  -\pi
	\end{bmatrix}.
\]
Hence the conjugate $\phi_0\i g \phi_0$ identifies with the matrix
\begin{equation}\label{g conj}
   \begin{bmatrix}
		1  &  \pi\\
		1  &  -\pi
	\end{bmatrix}\i
	\begin{bmatrix}
		a  &  b\\
		\alpha b  &  \alpha a
	\end{bmatrix}
   \begin{bmatrix}
		1  &  \pi\\
		1  &  -\pi
	\end{bmatrix}
	=
   \frac 1 2
	\begin{bmatrix}
		(1 + \alpha)(a+b)  &  \pi(1-\alpha)(a+b)\\
		\pi\i(1-\alpha)(a+b)  &  (1+\alpha)(a+b)
	\end{bmatrix}.
\end{equation}

Now recall from Example \ref{CN_2 ATC eg} that $\CN_{1,2} \cong \CN_2 = \CN_2^+ \amalg \CN_2^-$, where each of the summands $\CN_2^\pm$ identifies with $\CM_{\Spf O_{\breve F}}$, and the cycle $\Delta$ identifies with the canonical divisor attached to the embedding $\iota_\BE\colon F \inj D$ in each copy of $\CM_{\Spf O_{\breve F}}$.  More precisely, under these identifications, the universal object over $\Delta \cap \CN_2^+$ is $\delta_\CN^+(\CE) = (O_F \otimes_{O_{F_0}} \CE, O_F \otimes \rho_\CE)$, and the universal object over $\Delta \cap \CN_2^-$ is $\delta_\CN^-(\CE) = (O_F \otimes_{O_{F_0}} \CE, \kappa_0 \circ(O_F \otimes \rho_\CE))$; here we have suppressed auxiliary structure in the obvious way, and
\[
   \kappa_0 :=
	\begin{bmatrix}
		  &  \pi\\
		\pi\i
	\end{bmatrix}
	\in \Aut_{O_F}^\circ (\BX_2) \subset \RM_2(D)
\]
is a self-quasi-isogeny of $\BX_2$ which lies in the unitary group $G_1(F_0)$ and has Kottwitz invariant $-1$ (so that the action of $\kappa_0$ on $\CN_2$ interchanges the components $\CN_2^\pm$).

Now we compute $\Int(g)$. First note that, as in \cite[Prop.\ 8.10]{RSZ}, there are no higher Tor terms in the calculation.  Thus $\Int(g)$ is simply the length of $\Delta \cap (1 \times g)\Delta$, which in turn is twice the length of $\Delta \cap (1\times g)\Delta \cap \CN_2^+$.  This last intersection is the locus in $\Spf O_{\breve F}$ where $\phi_0\i g \phi_0$ lifts to a homomorphism $\delta_\CN^+(\CE) \to \delta_\CN^+(\CE)$ or $\delta_\CN^-(\CE) \to \delta_\CN^+(\CE)$, or equivalently, where $\phi_0\i g \phi_0$ or $\phi_0\i g \phi_0 \kappa_0$ lifts to a homomorphism $\delta_\CN^+(\CE) \to \delta_\CN^+(\CE)$.  In other words, this is the locus where all the entries of the right-hand side of \eqref{g conj}, or all the entries of
\begin{equation}\label{g conj kappa}
   \phi_0\i g \phi_0 \kappa_0 = \frac 1 2
	\begin{bmatrix}
		(1-\alpha)(a-b)  &  \pi(1 + \alpha)(a-b)\\
		\pi\i(1+\alpha)(a-b)  &   (1-\alpha)(a-b)
	\end{bmatrix},
\end{equation}
lift to endomorphisms of the canonical lifting \CE.  In the group setting, only one of these matrices will have all entries integral to begin with; this is governed by the Kottwitz invariant of $g$, that is, by the residue class of the norm one element $\alpha$ mod $\pi$.  Indeed, suppose that $\alpha \equiv 1 \bmod \pi$.  Then $1+\alpha \in O_F^\times$ since $p \neq 2$.  Since $\RN(a - b) = \RN a + \RN b = 1$, we conclude that the lower left entry in \eqref{g conj kappa} is non-integral.  Continuing to assume $\alpha \equiv 1$, we evidently have that $\pi \mid 1 -\alpha$, and therefore the locus where the entries of \eqref{g conj} lift is the locus where $a + b$ lifts.  By Gross's formula \cite[Th.\ 2.1]{V1}, the length of this locus is $\ell + 1$, where $\ell$ is the nonnegative integer such that $a + b \in (O_F + \pi^\ell O_D)\smallsetminus (O_F + \pi^{\ell + 1}O_D)$;  comp.\ also \cite[Prop.\ 9.1]{RSZ}.  Since $a \in O_F$ and $b \in O_D \cap D^-$, the asserted formula for $\Int(g)$ follows.

If $\alpha \equiv -1 \bmod \pi$, then one similarly finds that the lower left entry of \eqref{g conj} is non-integral, and that the locus where the entries of \eqref{g conj kappa} lift is the locus where $a - b$ lifts, which has the same length as before.  This completes the proof in the group case.

The Lie algebra case is quite similar, and we only briefly outline the differences.  The matrices \eqref{g conj} and \eqref{g conj kappa} are replaced by
\[
   \frac 1 2
   \begin{bmatrix}
		a + d + 2b  &  \pi(a-d)\\
		\pi\i(a-d)  &  a + d + 2b
	\end{bmatrix}
	\quad\text{and}\quad
	\frac 1 2
	\begin{bmatrix}
		a-d  &  \pi(a+d-2b)\\
		\pi\i(a+d-2b)  &  a-d
	\end{bmatrix},
\]
respectively, and $\lInt(x)$ is twice the length of the locus where all the entries of at least one of these matrices lift to endomorphisms of \CE.  If any one of $a$, $b$, or $d$ is non-integral, then it is easy to see (again using that $p \neq 2$) that both of these matrices have a non-integral entry, and hence $\lInt(x) = 0$.  If all of them are integral, then the locus where the entries in the second matrix lift is contained in the locus where the entries in the first matrix lift, and the length of this latter locus is again given by Gross's formula as $v(\RN b) + 1$.
\end{proof}





\subsection{Proof of Conjecture \ref{conjram v3} for $F_0 = \BQ_p$ and $n=2$}\label{proof ram ATC n=2}
The homogeneous group version (\ref{conjram v3 homog}) reduces to the inhomogeneous version (\ref{conjram v3 inhomog}) as in \cite[Lem.\ 5.8]{RSZ} (using Lemma \ref{homog to inhomog}(\ref{all})(\ref{old})(\ref{old 2}), which is valid for arbitrary $n$ and arbitrary $F/F_0$, in place of \cite[Lem.\ 5.7]{RSZ} in the proof). Thus we show that (\ref{conjram v3 inhomog}) holds.  To prove the first assertion in (\ref{conjram v3 inhomog}), fix $\gamma_0=\diag(a_0,d_0) \in A_{S}=A_{G_0}$. It suffices to show that the sum
\begin{equation}\label{the sum}
   2\omega_S(\gamma)\del(\gamma,f')+\Int(g)\log q
\end{equation}
is constant when $\gamma\in S_{\rs,1}$ is in a neighborhood of $\gamma_0$ (and $g \in G_1(F_0)_\rs$ is any match of $\gamma$). It then follows from, for example, \cite[Cor.~3.8]{M-ATC} that \eqref{the sum} is an orbital integral function, which is what we have to show.

We have for $f_0=\mathbf{1}_{K_0^\flat K_0^+}+ \mathbf{1}_{K_0^\flat K_0^-}$ and $g \in G_0(F_0)$,
$$
\Orb(g,f_0)=2\Orb(g,\mathbf{1}_{K_0^\flat K_0^+})=2\Orb(g,\mathbf{1}_{K_0^\flat K_0^-}).
$$
We may therefore replace $f_0$ by $2\cdot \mathbf{1}_{K_0^\flat K_0}$, cf.\ Remark \ref{remark S12}. 
By Theorem \ref{del germ s} (in the case $i=1$) and Lemma \ref{lem nil orb int u}, there exists a neighborhood of $\gamma_0$ on which for all $\gamma = \gamma(a,b) \in S_{\rs,1}$,
$$
2\omega_S(\gamma)\del(\gamma,f')=2\log\lv 1-\RN a\rv +C=-2 v(1-\RN a)\log q+C
$$
for some constant $C$.  Proposition \ref{prop int(g) int(x)} then yields immediately that the sum 
\eqref{the sum}
is a constant for all such $\gamma$, as desired.  The second assertion in (\ref{conjram v3 inhomog}), namely that there exists an $f'$ transferring to $(\mathbf{1}_{K_0^\flat K_0^+}+ \mathbf{1}_{K_0^\flat K_0^-}, 0)$ for which $f_\corr' = 0$, now follows by the same argument as in \cite[Prop.\ 5.14]{RSZ}.

The Lie algebra version \eqref{conjram v3 lie} for $n=2$ follows similarly, by the corresponding statements in Theorem \ref{del germ s}, Lemma \ref{lem nil orb int u}, and  Proposition \ref{prop int(g) int(x)}.\qed






\section{Proofs of Theorems \ref{conjram i=0} and \ref{conjram i=1}}\label{s:ramifiedn=2}

\subsection{Proof of Theorem \ref{conjram i=0}}\label{proof wtCN_2^(0)}
We resume the setup of \S\ref{ATC wtCN_2^(0)}.  Let us recall the groups and their Lie algebras. 
The quasi-split unitary group $G_0$ is associated to the framing object $\wt\BX_2^{(0)}$ of $\wt\CN_2^{(0)}$, cf.\ \eqref{wtBX_2^(0)}. We identify 
\[
   \End_{O_{F_0}}^\circ\bigl(\wt\BX_2^{(0)}\bigr) = \End_{O_{F_0}}^\circ\bigl(\BE^2\bigr)=\RM_2(D),
\] 
and the $O_F$-action is given by $\pi\mapsto \diag(\pi,-\pi)\in \RM_2(D)$. Then the $O_F$-linear quasi-endomorphism algebra is 
$$
\End_{O_F}^\circ\bigl(\wt\BX_2^{(0)}\bigr)= \biggl\{\,  \begin{bmatrix}
		   a  & b    \\
       c    &  d
      \end{bmatrix} \in \RM_2(D) \biggm|   a,d\in F,\ b,c\in D^-  \,\biggr\} .
$$
The Rosati involution is given by 
$$
\Ros_{\lambda_{\wt\BX_2^{(0)}}}(x)=x^\dagger=  \begin{bmatrix}
		   1 &     \\
         &  \ep
      \end{bmatrix}  ^{-1}   \tensor[^t]{\ov x}{}   \begin{bmatrix}
		   1 &     \\
         &  \ep
      \end{bmatrix},
$$
where $x\mapsto \ov x$ is the entry-wise main involution on $\RM_2(D)$.  Recall that $\ep \in O_{F_0}^\times$ is a non-norm. We then have the unitary group 
$$
G_0(F_0)=\bigl\{\, x\in \End_{O_F}^\circ\bigl(\wt\BX_2^{(0)}\bigr) \bigm|  x^\dagger x=1 \,\bigr\},
$$
and its Lie algebra 
$$
\fkg_0(F_0)=\bigl\{\, x\in \End_{O_F}^\circ\bigl(\wt\BX_2^{(0)}\bigr) \bigm|  x^\dagger+ x=0\,\bigr\} .
$$
They may be explicitly presented as
$$G_0(F_0)=\biggl\{ \, \begin{bmatrix}
		   1 &     \\
         &  \alpha
      \end{bmatrix}    \begin{bmatrix}
		   a  & b    \\
          \ep^{-1}  b  &  a
      \end{bmatrix} \in \RM_2(D)  \biggm|  a\in F,\ b\in D^-,\ \RN a+\ep^{-1}\RN b=1,\ \alpha \in F^1\,\biggr\} ,
$$
and $$
\fkg_0(F_0)=\biggl\{\, \begin{bmatrix}
		   a  & b    \\
       \ep^{-1} b  &  d
      \end{bmatrix} \in \RM_2(D)  \biggm|  a,d\in \pi F_0,\ b\in D^-  \, \biggr\} .
$$

The matching of orbits is analogous to \S\ref{orbit matching}: in terms of the parametrization \eqref{gamma(a,b)} for elements in $S(F_0)_\rs$, we have
$$
   \gamma(a,b)\in S_{\rs, 0}  \quad \text{\emph{matches}} \quad g=\begin{bmatrix}
		   1 &     \\
         &  \alpha
      \end{bmatrix}    \begin{bmatrix}
		   a'  & b'    \\
      \ep^{-1} b'   &  a'
      \end{bmatrix}\in G_0(F_0)_\rs
$$
if and only if $a = a'$ and $-b/\ov b=\det\gamma(a,b) = \det g = \ov\alpha$. In the Lie algebras, in terms of the parametrization \eqref{y(a,b,c,d)} for elements in $\fks(F_0)$, we have 
$$
   y(a,b,c,d) \in \fks_{\rs, 0}
	\quad\text{\emph{matches}}\quad 
	x= \begin{bmatrix}
		   a'  & b'    \\
     \ep^{-1}  b'   &  d'
      \end{bmatrix}\in \fkg_0(F_0)_\rs
$$
if and only if  $a=a'$, $d = -d'$, and $bc=-\ep^{-1}\RN b'$.

The unitary group $G_1$ is associated to to the non-split hermitian space
\[
   W_1=W_1^\flat \oplus F u_1,\quad  (u_1,u_1)=-\ep.
\]
By \eqref{chi decomp formula} the space $W_1^\flat$ is split, and we choose a basis vector $u^\flat \in W_1^\flat$ with $(u^\flat, u^\flat) = 1$.  In this way we view $G_1$ and its Lie algebra $\fkg_1$ as attached to the diagonal hermitian form $\diag(1,-\ep)$.
The irregular elements in the $F_0$-points of each then consist of the diagonal matrices contained in each.
  Now recall from \S\ref{ATC wtCN_2^(0)} the self-dual lattice $\Lambda_1 \subset W_1$ and its respective stabilizers $\wt K_1 \subset G_1(F_0)$ and $\wt\fkk_1 \subset \fkg_1(F_0)$.

\begin{lemma}\label{lem nil orb int u 0}
The irregular orbital integrals  of $\mathbf{1}_{\wt K_1}$ are given by
$$
\Orb\bigl(\diag(a,d), \mathbf{1}_{\wt K_1}\bigr)=1,\quad a,d\in F^1.
$$
The irregular orbital integrals  of $\mathbf{1}_{\wt\fkk_1}$ are given by
$$
\Orb\bigl(\diag(a,d), \mathbf{1}_{\wt\fkk_1}\bigr)=\begin{cases} 1,& a,d\in \pi O_{F_0},\\
0, &\mbox{otherwise}.
\end{cases}
$$
\end{lemma}

\begin{proof}
This is the same as the proof of Lemma \ref{lem nil orb int u}, noting that $\wt K_1$ contains the irregular group elements, and that the intersection of $\wt\fkk_1$ with the irregular Lie algebra elements is the set $\{\diag(a,d) \mid a,d \in \pi O_{F_0}\}$.
\end{proof}

\begin{proposition}\label{prop int(g) int(x) 0}
Let $g= \begin{bmatrix}
		   1 &     \\
         &  \alpha
      \end{bmatrix} 
\begin{bmatrix}
		   a  & b   \\
             \ep^{-1}  b&  a
      \end{bmatrix}
$ be an element in $G_0(F_0)_\rs$. Then 
\[
   \Int(g)=
	\begin{cases}
      v(\RN b) + 1,  &  a\in O_F \text{ and } b\in O_D \cap D^-;\\
      0,  &  \text{otherwise}.
   \end{cases}
\]
Similarly,  for an element $x= 
\begin{bmatrix}
		   a  & b   \\
              \ep^{-1} b&  d
      \end{bmatrix}
$  in $\fkg_0(F_0)_\rs$, 
\[
   \lInt(x)=
	\begin{cases}
      v(\RN b) + 1,  &  a,d\in \pi O_{F_0} \text{ and } b\in O_D \cap D^-;\\
      0,  &  \text{otherwise}.
   \end{cases}
\]
\end{proposition}
\begin{proof}
The method of proof is the same as that of Proposition \ref{prop int(g) int(x)}, except this time the details are much simpler.  In the group case, $\Int(g)$ is the length of the locus in $\Spf O_{\breve F}$ where $\bigl[\begin{smallmatrix} a  &  b\\ \alpha \ep\i b &  \alpha a \end{smallmatrix}\bigr]$ lifts from an endomorphism of $\BE \times \ov\BE$ to an endomorphism of $\CE \times \ov\CE$, or in other words, where each of the entries lifts to an endomorphism of $\CE$.  If $a$ or $b$ is non-integral, then this locus is empty and we obtain $\Int(g) = 0$.  If $a$ and $b$ are integral,  then $a,\alpha,\ep\i \in O_F$ lift without constraint, and the length in question is again given by Gross's formula as $v(\RN b) + 1$.  The Lie algebra case is analogous.  We remind the reader that the factor of $2$ in Proposition \ref{prop int(g) int(x)} is due to the fact that there are two copies of $\CM$ involved there.
\end{proof}

Now we complete the proof of the theorem.

\begin{proof}[Proof of Theorem \ref{conjram i=0}] 
We first prove the group version (\ref{conjram i=0 inhomog}); the argument is formally the same as the proof of Conjecture \ref{conjram v3}(\ref{conjram v3 inhomog}) for $n=2$ in \S\ref{proof ram ATC n=2}. To prove the first assertion in (\ref{conjram i=0 inhomog}),
fix $\gamma_0=\diag(a_0,d_0)\in A_S$, which we also regard as an irregular element in $G_1(F_0)$. It again suffices to show that the sum
\begin{equation}\label{sum eq0}
   2\omega_S(\gamma)\del(\gamma,f')+\Int(g)\log q
\end{equation}
is  constant when $\gamma\in S_{\rs,0}$ is in a neighborhood of $\gamma_0$ (and $g \in G_0(F_0)_\rs$ is any match of $\gamma$). 
By Theorem \ref{del germ s} (in the case $i=0$) and Lemma \ref{lem nil orb int u 0}, there exists such a neighborhood on which for all $\gamma = \gamma(a,b) \in S_{\rs,0}$,
$$
2\omega_S(\gamma)\del(\gamma,f')=\log\lv 1-\RN a\rv +C=-v(1-\RN a)\log q+C
$$
for some constant $C$.
Proposition \ref{prop int(g) int(x) 0} then yields that \eqref{sum eq0}
is constant for such $\gamma$, as desired.  The second assertion in (\ref{conjram i=0 inhomog}) again follows by the argument in \cite[Prop.\ 5.14]{RSZ}.

The Lie algebra version (\ref{conjram i=0 lie}) follows similarly, by the corresponding statements in Theorem \ref{del germ s}, Lemma \ref{lem nil orb int u 0}, and  Proposition \ref{prop int(g) int(x) 0}.
\end{proof}




\subsection{Proof of Theorem \ref{conjram i=1}}\label{proof wtCN_2^(1)}
Now we resume the setup of \S\ref{atc wtCN_2^(1)}.  This case is very similar to the $\pi$-modular case in \S\ref{even ram proof}.
The groups are the same as in \S\ref{even ram proof}. 
In particular, the irregular elements in $G_0(F_0)$ are the subset $A_{G_0}$ \eqref{eqn U_2 A}.
Recall that the compact open subgroups $\wt K_0 \subset G_0(F_0)$ and $\wt\fkk_0 \subset \fkg_0(F_0)$ are the respective stabilizers of the self-dual lattice $\Lambda_0 \subset W_0$.  By the same argument as in the proofs of Lemmas \ref{lem nil orb int u} and \ref{lem nil orb int u 0}, we obtain the following.

\begin{lemma}\label{lem nil orb int u 1}
The irregular orbital integrals  of $\mathbf{1}_{\wt K_0}$ are given by
$$
\Orb\bigl(\diag(a,d), \mathbf{1}_{\wt K_0}\bigr)=1,\quad a,d\in F^1.
$$The irregular orbital integrals  of $\mathbf{1}_{\wt\fkk_0}$ are given by
\begin{flalign*}
	\phantom{\qed} & &
	\Orb\bigl(\diag(a,d), \mathbf{1}_{\wt\fkk_0}\bigr)=\begin{cases} 1,& a,d\in \pi O_{F_0},\\
	0, &\text{otherwise}.
	\end{cases}
	& & \qed
\end{flalign*}
\end{lemma}

\begin{proposition}\label{prop int(g) int(x) 1}
Let $g= \begin{bmatrix}
		   1 &     \\
         &  \alpha
      \end{bmatrix} 
\begin{bmatrix}
		   a  & b   \\
           b&  a
      \end{bmatrix}
\in G_1(F_0)_\rs$, expressed in the presentation (\ref{G_1 pres}). Then 
\[
   \Int(g)= v(\RN b) + 1.
\]
Similarly, for $x= 
\begin{bmatrix}
		   a  & b   \\
           b&  d
      \end{bmatrix}
\in \fkg_1(F_0)_\rs$ expressed in the presentation (\ref{fkg_1 pres}),
\[
   \lInt(x)=
	\begin{cases}
      v(\RN b) + 1,  &  a,d\in \pi O_{F_0} \text{ and } b\in O_D \cap D^-;\\
      0,  &  \text{otherwise}.
\end{cases}
\]
\end{proposition}
\begin{proof}
The proof is virtually identical to that of Proposition \ref{prop int(g) int(x) 0}.  Note that in the group case, as in Proposition \ref{prop int(g) int(x)}, the entries $a$ and $b$ are automatically integral.
\end{proof}

Now we complete the proof of the theorem.

\begin{proof}[Proof of Theorem \ref{conjram i=1}]
The proof is essentially the same as the proofs of Conjecture \ref{conjram v3}(\ref{conjram v3 inhomog})(\ref{conjram v3 lie}) when $n=2$ and Theorem \ref{conjram i=0}. We first prove the group version (\ref{conjram i=1 inhomog}).
For the first assertion, fix $\gamma_0=\diag(a_0,d_0)\in A_{S}$, which we also regard as an irregular element in $G_0(F_0)$. As before, it suffices to show that the sum
\begin{equation}\label{sum eq}
2\omega_S(\gamma)\del(\gamma,f')+\Int(g)\log q
\end{equation}
is  constant when $\gamma\in S_{\rs,1}$ is in a neighborhood of $\gamma_0$ (and $g$ matches $\gamma$). 
By Theorem \ref{del germ s} (in the case $i = 1$) and Lemma \ref{lem nil orb int u 1}, there exists such a neighborhood on which for all $\gamma = \gamma(a,b) \in S_{\rs,1}$,
$$
2\omega_S(\gamma)\del(\gamma,f')=\log\lv 1-\RN a\rv+C=-v(1-\RN a)\log q+C
$$
for some constant $C$. Proposition \ref{prop int(g) int(x) 1} then yields that \eqref{sum eq}
is constant for such $\gamma$, as desired.  The second assertion in (\ref{conjram i=1 inhomog}) again follows by the argument in \cite[Prop.\ 5.14]{RSZ}.


The Lie algebra version (\ref{conjram i=1 lie}) follows similarly, by the corresponding statements in Theorem \ref{del germ s}, Lemma \ref{lem nil orb int u 1}, and  Proposition \ref{prop int(g) int(x) 1}.
\end{proof}





\begin{thebibliography}{99}

\bibitem{ACZ}{T. Ahsendorf, C. Cheng, and Th. Zink, \textit{$\mathcal O$-displays and $\pi$-divisible formal $\mathcal O$-modules}, J. Algebra \textbf{457} (2016), 129--193.}

\bibitem{ARGOS}{\textit{ARGOS seminar on intersections of modular correspondences}, Ast\'erisque \textbf{312}
(2007).}

\bibitem{A}{K. Arzdorf, \textit{On local models with special parahoric level structure}, Michigan Math. J. \textbf{58} (2009), no. 3, 683--710.}

\bibitem{D}{V. G. Drinfeld, \textit{Coverings of $p$-adic symmetric domains}, Funkcional. Anal. i Prilo\v zen. \textbf{10} (1976), no. 2, 29--40 (Russian).}

\bibitem{F}{L. Fargues, \textit{Cohomologie des espaces de modules de groupes $p$-divisibles et correspondances de Langlands locales}, Ast\'erisque \textbf{291} (2004), 1--199.}

\bibitem{Goertz}{U. G\"ortz, \textit{On the flatness of models of certain Shimura varieties of PEL-type}, Math. Ann. \textbf{321} (2001), no. 3, 689--727.}

\bibitem{Goertz-He}{U. G\"ortz and X. He, \textit{Basic loci in Shimura varieties of Coxeter type},  Camb. J. Math. \textbf{3} (2015), no. 3, 323--353.}

\bibitem{Go}{J. Gordon, \textit{Transfer to characteristic zero}, appendix to \cite{Y}.}

\bibitem{G}{B. Gross, \textit{On canonical and quasicanonical liftings}, Invent. Math.  \textbf{84}  (1986),  no. 2, 321--326.}

\bibitem{JR}{H. Jacquet and S. Rallis, \textit{On the Gross-Prasad conjecture for unitary
groups}.  In \textit{On certain $L$-functions}, Clay Math. Proc., 13, Amer. Math. Soc., Providence, RI, 2011, pp. 205--264.}

\bibitem{KR-U1}{S. Kudla and M. Rapoport, \textit{Special cycles on unitary
Shimura varieties I. Unramified local theory}, Invent. Math. \textbf{184} (2011), no. 3, 629--682.}

\bibitem{KR-alt}{\bysame, \textit{An alternative description of the Drinfeld $p$-adic half-plane}, Ann. Inst. Fourier (Grenoble) \textbf{64} (2014), no. 3, 1203--1228.}

\bibitem{KRbarc}{\bysame, \textit{Special cycles on the $\Gamma_0(p^n)$-moduli curve}, unpublished. }

\bibitem{Lau}{E. Lau, \textit{Smoothness of the truncated display functor}, J. Amer. Math. Soc. \textbf{26} (2013), no.~1, 129--165.}

\bibitem{M-ATC}{A. Mihatsch, \textit{An arithmetic transfer identity}, Manuscripta Math. \textbf{150} (2016), no.~1, 1--19.}

\bibitem{M-AFL}{\bysame, \textit{On the arithmetic fundamental lemma conjecture through Lie algebras}, to appear in Math. Z.}

\bibitem{M-Th}{\bysame, \textit{Relative unitary RZ-spaces and the Arithmetic Fundamental Lemma}, preprint, 2016, \href{https://arxiv.org/abs/1611.06520}{\texttt{arXiv:1611.06520 [math.AG]}}.}

\bibitem{P}{G. Pappas, \textit{On the arithmetic moduli schemes of PEL Shimura varieties}, J. Algebraic Geom. \textbf{9} (2000), no. 3, 577--605.}

\bibitem{PR-TLG}{G. Pappas and M. Rapoport, \textit{Twisted loop groups and their affine flag varieties}, Adv. Math. \textbf{219} (2008), no. 1, 118--198.}

\bibitem{PR}{\bysame, \textit{Local models in the ramified case. III. Unitary groups}, J. Inst. Math. Jussieu \textbf{8} (2009), no. 3, 507--564.}

\bibitem{PRS}{G. Pappas, M. Rapoport, and B. Smithling, \textit{Local models of Shimura varieties, I. Geometry and combinatorics}. In \textit{Handbook of Moduli. Vol. III}, Adv. Lect. Math. (ALM), vol. \textbf{26}, Int. Press, Somerville, MA, 2013, pp. 135--217.}

\bibitem{PZ}{G. Pappas and X. Zhu, \textit{Local models of Shimura varieties and a conjecture of Kottwitz}, 
Invent. Math. \textbf{194} (2013), no. 1, 147--254.} 

\bibitem{RS}{S. Rallis and G. Schiffmann, \textit{Multiplicity one conjectures}, preprint, 2007, \href{http://arxiv.org/abs/0705.2168}{\texttt{arXiv:0705.2168 [math.NT]}}.}

\bibitem{RSZ}{M. Rapoport, B. Smithling,  and W. Zhang, \textit{On the arithmetic transfer conjecture for exotic smooth formal moduli spaces}, to appear in Duke Math. J.} 

\bibitem{RSZglob}{\bysame, \textit{Arithmetic diagonal cycles on unitary Shimura varieties}, in preparation.}

\bibitem{RTW}{M. Rapoport, U. Terstiege, and S. Wilson, \textit{The supersingular locus of the Shimura variety for ${\rm GU}(1, n - 1)$ over a ramified prime}, Math. Z. \textbf{276} (2014), no. 3--4, 1165--1188.}

\bibitem{RTZ}{M. Rapoport, U. Terstiege, and W. Zhang, \textit{On the arithmetic fundamental lemma in the minuscule case}, Compos. Math. \textbf{149} (2013), no. 10, 1631--1666.}

\bibitem{RZ}{M. Rapoport and Th. Zink, \textit{Period spaces for $p$-divisible groups}, Annals of Mathematics Studies, vol. \textbf{141}, Princeton University Press, Princeton, NJ, 1996.}

\bibitem{Roy}{A. Roy, \textit{Cancellation of quadratic forms over commutative rings}, J. Algebra \textbf{10} (1968), 286--298.}
 
\bibitem{San}{S. Sankaran, \textit{Unitary cycles on Shimura curves and the Shimura lift I}, Documenta Math. \textbf{18} (2013), 1403--1464.}

\bibitem{San-mail}{\bysame, e-mail to Rapoport, 11 April 2015.}
 
\bibitem{S}{B. Smithling, \textit{On the moduli description of local models for ramified unitary groups}, Int. Math. Res. Not. \textbf{2015} (2015), no. 24, 13493--13532.}

\bibitem{V1}{I. Vollaard, \textit{Endomorphisms of quasi-canonical lifts}, in \cite{ARGOS},  pp. 105--112.}

\bibitem{V2}{\bysame, \textit{The supersingular locus of the Shimura variety for $GU(1,s)$}, Can. J. Math.
\textbf{62} (2010), 668--720.}

\bibitem{VW}{I. Vollaard and T. Wedhorn, \textit{The supersingular locus of the Shimura variety for $\mathrm{GU}(1,n- 1)$ II}, Invent. Math. \textbf{184} (2011), no. 3, 591--627.}

\bibitem{Wewers}{S. Wewers, \textit{Canonical and quasi-canonical liftings}, in \cite{ARGOS}, pp. 67--86.}

\bibitem{Wu}{H. Wu, \textit{The supersingular locus of unitary Shimura varieties with exotic good reduction}, preprint, 2016, \href{https://arxiv.org/abs/1609.08775}{\texttt{arXiv:1609.08775 [math.AG]}}.}

\bibitem{Yu}{S. Yu, in preparation.}

\bibitem{Y}{Z. Yun, \textit{The fundamental lemma of Jacquet--Rallis in positive
characteristics},  Duke Math. J. \textbf{156} (2011), no. 2, 167--228.}

\bibitem{Y12}{\bysame, \textit{An arithmetic fundamental lemma for function fields}, in preparation.}

\bibitem{Z12}{W. Zhang, \textit{On arithmetic fundamental lemmas}, Invent. Math. \textbf{188} (2012), no. 1, 197--252.}

\bibitem{Z12b}{\bysame, \textit{On the smooth transfer conjecture of Jacquet--Rallis for $n=3$}, Ramanujan J. \textbf{29} (2012), no. 1--3, 225--256.}

\bibitem{Z14}{\bysame, \textit{Fourier transform and the global Gan--Gross--Prasad conjecture for unitary groups}, Ann. of Math. (2) \textbf{180} (2014), no. 3, 971--1049.}

\end{thebibliography}
\end{document}
pgfcalendar.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/utilities/pgfcalendar.code.tex,v 1.11 2007/07/23 21:23:14 tantau Exp $


% Translation stuff

\ifx\translate\@undefined
  \def\translate#1{#1}
\fi

% Load month dictionary, if possible

\ifx\usedictionary\@undefined
\else
  \usedictionary{translator-months-dictionary}
\fi




% Typeset a calendar
%
% #1 = prefix for the calendar nodes
% #2 = begin date in ISO format
% #3 = end date in ISO format
% #4 = date rendering code
%
% Description:
%
% First note that this macro need not be called inside a pgfpicture
% (even though it often will be). You can use it to typeset
% calendars also using packages other than pgf. You do not even need
% to load pgf to use this file.
%
% A calendar is typeset as follows: You specify a range of dates (by
% providing a begin and an end date). Then, for each date the code #4
% is executed. When the code is called, lots of information about the
% current date (like its day of week) is available. The job of
% #4 is to render the date. Typically, this is done by placing nodes
% somewhere, but the function could do other things as well. 
% It is also the job of #4 to position the calendar correctly.
%
% The different calls of #4 are not surrounded by TeX groups (though
% you can do so yourself, of course). This means that settings can
% accumulate between different calls, which is often desirable and
% useful. 
%
% Inside #4 code, different macros can be access:
%
% \pgfcalendarprefix
% The parameter #1. This prefix is recomended for nodes inside the
% calendar, but you have to use it yourself explicitly.
%
% \pgfcalendarbeginiso
% Start date of range being typeset in ISO format (like 2006-01-10)
%
% \pgfcalendarbeginjulian
% Julian day number of start date begin typeset
%
% \pgfcalendarendiso
% End date of range begin typeset
%
% \pgfcalendarendjulian
% Same as Julian day number
%
% \pgfcalendarcurrentjulian (a TeX-count)
% Julian day number of day to be rendered/considered
%
% \pgfcalendarcurrentweekday
% Weekday (0 = Monday) of day to be checked
%
% \pgfcalendarcurrentyear
% Year of day to be checked
%
% \pgfcalendarcurrentmonth
% Month of day to be chjeck
%
% \pgfcalendarcurrentday
% Day of monath of day to be checked
%
%
% Inside the \pgfcalendar macro the macro \ifdate is available, which
% has the same effect as \pgfcalendarifdate{\pgfcalendarcurrentjulian}
% (only faster). This means that you
% can write, say, \ifdate{Monday}{current date is a Monday}{Not a Monday}.
%
% Example:
%
% \begin{tikzpicture}
%   \pgfcalendar{cal}{2007-01-20}{2007-02-10}
%     {\node[anchor=base] {\pgfcalendaronday}; \pgftransformyshift{-1.5em}}
% \end{tikzpicture}
%
% \pgfcalendar{cal}{2007-01-20}{2007-02-10}{ \pgfcalendaronday\ }

\long\def\pgfcalendar#1#2#3#4{%
  \begingroup%
    % Setup local \ifdate
    \let\ifdate=\pgfcalendar@local@ifdate%
    % Let's start with computing start and end dates... 
    \def\pgfcalendarprefix{#1}%
    \pgfcalendardatetojulian{#2}{\pgfcalendarcurrentjulian}%
    \edef\pgfcalendarbeginjulian{\the\pgfcalendarcurrentjulian}%
    \edef\pgfcalendarbeginiso{#2}%
    \pgfcalendardatetojulian{#3}{\pgfutil@tempcnta}%
    \edef\pgfcalendarendjulian{\the\pgfutil@tempcnta}%
    \advance\pgfutil@tempcnta by1\relax%
    \edef\pgfcalendarendjulianplus{\the\pgfutil@tempcnta}%
    \edef\pgfcalendarendiso{#3}%
    %
    % Start main loop
    %
    \loop%
    \ifnum\pgfcalendarcurrentjulian<\pgfcalendarendjulianplus\relax%
      % Setup information about current date
      \pgfcalendarjuliantodate{\pgfcalendarcurrentjulian}%
      {\pgfcalendarcurrentyear}{\pgfcalendarcurrentmonth}{\pgfcalendarcurrentday}%
      \pgfcalendarjuliantoweekday{\pgfcalendarcurrentjulian}{\pgfutil@tempcntb}%
      \edef\pgfcalendarcurrentweekday{\the\pgfutil@tempcntb}%
      % Render:
      #4%
      % Advance day:
      \advance\pgfcalendarcurrentjulian by1\relax%
    \repeat%
  \endgroup%
}

\newcount\pgfcalendarcurrentjulian

\def\pgfcalendar@local@ifdate{%
  \let\pgfcalendarifdatejulian=\pgfcalendarcurrentjulian%
  \let\pgfcalendarifdateyear=\pgfcalendarcurrentyear%
  \let\pgfcalendarifdatemonth=\pgfcalendarcurrentmonth%
  \let\pgfcalendarifdateday=\pgfcalendarcurrentday%
  \let\pgfcalendarifdateweekday=\pgfcalendarcurrentweekday%
  \pgfcalendar@launch@ifdate%
}



% Execute on specific kinds of dates
%
% #1 = ISO-format date
% #2 = date specification
% #3 = code
%
% Description:
%
% The given code #3 is execute on every day that matches the date
% specification #2. This specification is a comma-separated list of
% key-value pairs with the path /pgf/calendar. The code for a
% key-value should check whether the given day matches its
% specification. If so, it should set \pgfcalendarmatches to true.
%
% When the key-value code is executed, the following macros will have
% been setup:
%
% \pgfcalendarifdatejulian 
% Julian day number of day to be checked
%
% \pgfcalendarifdateweekday
% Weekday (0 = Monday) of day to be checked
%
% \pgfcalendarifdateyear
% Year of day to be checked
%
% \pgfcalendarifdatemonth
% Month of day to be chjeck
%
% \pgfcalendarifdateday
% Day of month of day to be checked
%
% The setting of these macros will persist after the call, so a
% sideeffect of callling this macro is to setup these macros.
%
% By setting \ifpgfcalendar@do@not@recompute to false, the computation
% of the year, month etc. is suppressed.
%
% Examples:
%
% \pgfcalendarifdate{2007-01-10}{all}{}
% % Simply setup the macros
%
% \pgfcalendarifdate{2007-01-10}{mondays}{Is a monday}
%
% \pgfcalendarifdate{\mydate}{date=05-01}{\mydate is a Worker's Day}

\def\pgfcalendarifdate#1#2#3#4{%
  \pgfcalendardatetojulian{#1}{\pgfutil@tempcnta}%
  \pgfcalendarjuliantodate{\pgfutil@tempcnta}
    {\pgfcalendarifdateyear}{\pgfcalendarifdatemonth}{\pgfcalendarifdateday}%
  \edef\pgfcalendarifdatejulian{\the\pgfutil@tempcnta}%
  % Compute info about date
  \pgfcalendarjuliantoweekday{\pgfutil@tempcnta}{\pgfutil@tempcntb}%
  \edef\pgfcalendarifdateweekday{\the\pgfutil@tempcntb}%
  %
  \pgfcalendar@launch@ifdate{#2}{#3}{#4}%
}


\long\def\pgfcalendar@launch@ifdate#1#2#3{%
  % When this macro is called, the pgfcalendarifdatexxxx macros must
  % be setup correctly
  %
  % Set match to false
  \pgfcalendarmatchesfalse%
  \pgfqkeys{/pgf/calendar}{#1}% 
  \ifpgfcalendarmatches%
    #2%
  \else%
    #3%
  \fi%
}

\newif\ifpgfcalendarmatches


% Keys for matching

\pgfkeys{/pgf/calendar/all/.code=\pgfcalendarmatchestrue}

\pgfkeys{/pgf/calendar/Monday/.code={\ifnum\pgfcalendarifdateweekday=0\relax\pgfcalendarmatchestrue\fi}}
\pgfkeys{/pgf/calendar/Tuesday/.code={\ifnum\pgfcalendarifdateweekday=1\relax\pgfcalendarmatchestrue\fi}}
\pgfkeys{/pgf/calendar/Wednesday/.code={\ifnum\pgfcalendarifdateweekday=2\relax\pgfcalendarmatchestrue\fi}}
\pgfkeys{/pgf/calendar/Thursday/.code={\ifnum\pgfcalendarifdateweekday=3\relax\pgfcalendarmatchestrue\fi}}
\pgfkeys{/pgf/calendar/Friday/.code={\ifnum\pgfcalendarifdateweekday=4\relax\pgfcalendarmatchestrue\fi}}
\pgfkeys{/pgf/calendar/Saturday/.code={\ifnum\pgfcalendarifdateweekday=5\relax\pgfcalendarmatchestrue\fi}}
\pgfkeys{/pgf/calendar/Sunday/.code={\ifnum\pgfcalendarifdateweekday=6\relax\pgfcalendarmatchestrue\fi}}

\pgfkeys{/pgf/calendar/workday/.code={\ifnum\pgfcalendarifdateweekday<5\relax\pgfcalendarmatchestrue\fi}}
\pgfkeys{/pgf/calendar/weekend/.code={\ifnum\pgfcalendarifdateweekday>4\relax\pgfcalendarmatchestrue\fi}}

\pgfkeys{/pgf/calendar/equals/.cd,.value required,.code={%
  \pgfcalendar@special@datetojulian{#1}%
  \ifnum\pgfcalendarifdatejulian=\pgfutil@tempcnta\relax%
    \pgfcalendarmatchestrue%
  \fi}%
}

\pgfkeys{/pgf/calendar/day of month/.cd,.value required,.code={\ifnum#1=\pgfcalendarifdateday\relax\pgfcalendarmatchestrue\fi}}
\pgfkeys{/pgf/calendar/end of month/.cd,.default=1,.code={%
  % Tricky and expensive ... do only if necessary
  \ifpgfcalendarmatches%
  \else% sigh
    {%
      \pgfutil@tempcnta=\pgfcalendarifdatejulian\relax%
      \advance\pgfutil@tempcnta by#1\relax%
      \pgfcalendarjuliantodate{\pgfutil@tempcnta}{\pgf@dummy}{\pgf@dummy}{\pgf@cal@temp}%
      \global\let\pgf@cal@temp=\pgf@cal@temp%
    }%
    \ifnum\pgf@cal@temp=1\relax\pgfcalendarmatchestrue\fi%
  \fi}%
}

\pgfkeys{/pgf/calendar/at least/.cd,.value required,.code={%
  \pgfcalendar@special@datetojulian{#1}%
  \ifnum\pgfcalendarifdatejulian<\pgfutil@tempcnta\relax%
  \else%
    \pgfcalendarmatchestrue%
  \fi%
}}

\pgfkeys{/pgf/calendar/at most/.cd,.value required,.code={%
  \pgfcalendar@special@datetojulian{#1}%
  \ifnum\pgfcalendarifdatejulian>\pgfutil@tempcnta\relax%
  \else%
    \pgfcalendarmatchestrue%
  \fi%
}}

\pgfkeys{/pgf/calendar/between/.cd,.value required,.code args={#1and#2}{%
  \pgfcalendar@special@datetojulian{#1}%
  \ifnum\pgfcalendarifdatejulian<\pgfutil@tempcnta\relax%
  \else%
    \pgfcalendar@special@datetojulian{#2}%
    \ifnum\pgfcalendarifdatejulian>\pgfutil@tempcnta\relax%
    \else%
      \pgfcalendarmatchestrue%
    \fi%
  \fi%
}}

\def\pgfcalendar@special@datetojulian#1{%
  \edef\pgf@temp{#1}%
  \expandafter\pgfcalendar@special@split@test\pgf@temp-\relax{#1}%  
}

\def\pgfcalendar@special@split@test#1-#2-#3\relax#4{%
  \def\pgf@temp{#3}%
  \ifx\pgf@temp\pgfutil@empty%
    \def\pgf@temp{\pgfcalendarifdateyear-#1-#2}%
  \else%
    \def\pgf@temp{#4}%
  \fi%
  \pgfcalendardatetojulian{\pgf@temp}{\pgfutil@tempcnta}%
}


% Suggested name for nodes inside a calendar
%
% Description:
%
% It is suggested that (main) nodes (if present) in a calendar should
% get this name.
%
% Example:
%
% \pgfcalendar{cal}{2007-01-20}{2007-02-10}{}
% { \node[anchor=base] (\pgfcalendarsuggestedname) {\pgfcalendarifdateday};
%   \pgftransformyshift{-1.5em} }
%
% \draw (cal-2007-01-30) -- (cal-2007-02-08);

\def\pgfcalendarsuggestedname{%
  \ifx\pgfcalendarprefix\pgfutil@empty\else\pgfcalendarprefix-%
  \pgfcalendarcurrentyear-\pgfcalendarcurrentmonth-\pgfcalendarcurrentday\fi%
}



%
%
% Date conversion functions
%
%



% Convert a date to the Julian day number (number of days since
% January 1st, -4712)
%
% #1 = date specification
% #2 = counter that should be set to the number of days
%
% Description:
%
% The conversion is taken from the Wikipedia entry on Julian days. 
%
% The date specification works as follows:
%
% - It starts with a year. Use \year for the current year (the year
%   the file is being typeset).
% - Next comes a hyphen.
% - Next comes a month (number). Use \month for the current month.
% - Next comes a hyphen.
% - Next comes either a day of month (number, use \day for current
%   day) or "last". The keyword "last" refers the last day of the
%   month. Thus, 2006-01-last is the same as 2006-01-31 and
%   2000-02-last is the same as 2002-02-29.
% - Next may come a plus sign, followed by a number (positive or
%   negative). This will adjust the date by the given number of
%   days. Thus, 2006-01-31+1 is the same as 2006-02-01 and
%   2006-02-01+-2 is the same as 2006-01-30. And \year-\month-day+1 is
%   tomorrow. You may add a space before the +.
%
% Example:
%
% \pgfcalendardatetojulian{2006-01-10}{\mycount}

\def\pgfcalendardatetojulian#1#2{\edef\pgf@temp{#1}\expandafter\pgfcalendar@datetojulian\pgf@temp+/{#2}}
\def\pgfcalendar@datetojulian#1-#2-#3+#4/#5{%
  {%
    %
    % Store year, month and days.
    % 
    \count1=#1\relax%
    \count2=#2\relax%
    % If #3=="last", then calculate first day of next month
    \edef\pgf@temp{#3}%
    \ifx\pgf@temp\pgfcalendar@last@text%
      \advance\count2 by1\relax%
      \count3=1\relax%
    \else%
      \count3=#3\relax%
    \fi%
    %
    % Store offset
    %
    \edef\pgf@@temp{#4}%
    \ifx\pgf@@temp\pgfutil@empty%
      \count8=0\relax%
    \else%
      \pgfcalendar@unpack#4%
    \fi%
    %
    %
    % 4) a = \lfloor (14-month) /12 \rfloor
    %
    \ifnum\count2<3\relax%
      \count4=1\relax%
    \else%
      \count4=0\relax%
    \fi%
    %
    % 5) y = year + 4800 - a
    %
    \count5=\count1\relax%
    \advance\count5 by 4800\relax%
    \advance\count5 by-\count4\relax%
    %
    % 6) m = month + 12a - 3
    %
    \count6=\count2\relax%
    \count0=\count4\relax%
    \multiply\count0 by12\relax
    \advance\count6 by\count0\relax%
    \advance\count6 by-3\relax%
    %
    % 7) jdn = day + \floor{(153 m+2)/5} + 365y + \floor{y/4} -
    % \floor{y/100} + \florr{y/400} - 32045
    %
    \count7=\count3\relax%
    % + \floor{(153 m+2)/5} :
    \count0=\count6\relax%
    \multiply\count0 by 153\relax%
    \advance\count0 by 2\relax%
    \divide\count0 by 5\relax%
    \advance\count7 by \count0\relax%
    % + 365y :
    \count0=\count5%
    \multiply\count0by365\relax%
    \advance\count7 by\count0\relax%
    % + \floor{y/4}
    \count0=\count5\relax%
    \divide\count0 by 4\relax%
    \advance\count7 by\count0%
    % - \floor{y/100}
    \count0=\count5\relax%
    \divide\count0 by 100\relax%
    \advance\count7 by-\count0\relax%
    % + \floor{y/400}
    \count0=\count5\relax%
    \divide\count0 by 400\relax%
    \advance\count7 by\count0%
    %  - 32045
    \advance\count7 by-32045\relax%
    %
    % Undo "last" advance
    \ifx\pgf@temp\pgfcalendar@last@text%
      \advance\count7by-1\relax%
    \fi%
    % Add offset  
    \advance\count7by\count8\relax%
    \expandafter%
  }%
  \expandafter#5\the\count7\relax%  
}
\def\pgfcalendar@last@text{last}
\def\pgfcalendar@unpack#1+{%
  \count8=#1\relax%
}

% Convert Julian day number date. 
%
% #1 = the number of Julian days
% #2 = a macro in which the year should be stored.
% #3 = a macro in which the month should be stored.
% #4 = a macro in which the day should be stored.
%
% Formula used:
%
% 1) J = Julian day number
% 2) j = J + 32044
% 3) g = j div 146097
% 4) dg = j mod 146097
% 5) c = (dg div 36524 + 1) * 3 div 4
% 6) dc = dg - c * 36524
% 7) b = dc div 1461
% 8) db = dc mod 1461
% 9) a = (db div 365 + 1) * 3 div 4
% 10)da = db - a * 365
% 11)y = g * 400 + c * 100 + b * 4 + a
% 12)m = (da * 5 + 308) div 153 - 2
% 13)d = da - (m + 4) * 153 div 5 + 122
% 14)Y = y - 4800 + (m + 2) div 12
% 15)M = (m + 2) mod 12 + 1
% 16)D = d + 1
%
% Example
%
% \pgfcalendarjuliantodate{\mynumber}{\myyear}{\mymonth}{\myday}

\def\pgfcalendarjuliantodate#1#2#3#4{%
  {%
    % 1) J = Julian day number
    \count1=#1\relax%
    % 2) j = J + 32044     
    \count2=\count1\relax%
    \advance\count2 by 32044\relax%
    % 3) g = j div 146097  
    \count3=\count2\relax%
    \divide\count3 by 146097\relax%
    % 4) dg = j mod 146097 
    \count4=\count3\relax%
    \multiply\count4 by-146097\relax%
    \advance\count4 by\count2\relax%
    % 5) c = (dg div 36524 + 1) * 3 div 4 
    \count5=\count4\relax%
    \divide\count5 by36524\relax%
    \advance\count5 by1\relax%
    \multiply\count5 by3\relax%
    \divide\count5 by4\relax%
    % 6) dc = dg - c * 36524 
    \count6=\count4\relax%
    \count0=\count5\relax%
    \multiply\count0 by-36524\relax%
    \advance\count6 by\count0\relax%
    % 7) b = dc div 1461
    \count7=\count6\relax%
    \divide\count7 by1461\relax%
    % 8) db = dc mod 1461
    \count8=\count7\relax%
    \multiply\count8 by-1461\relax%
    \advance\count8 by\count6\relax%
    % 9) a = (db div 365 + 1) * 3 div 4
    \count9=\count8\relax%
    \divide\count9 by 365\relax%
    \advance\count9 by 1\relax%
    \multiply\count9 by3\relax%
    \divide\count9 by4\relax%
    % 10)da = db - a * 365
    \count10=\count8\relax%
    \count0=\count9\relax%
    \multiply\count0 by-365\relax%
    \advance\count10 by\count0\relax%
    % 11)y = g * 400 + c * 100 + b * 4 + a
    \count11=\count3\relax%
    \multiply\count11 by400\relax%
    \count0=\count5\relax%
    \multiply\count0 by100\relax%
    \advance\count11 by\count0\relax%
    \count0=\count7\relax%
    \multiply\count0 by4\relax%
    \advance\count11 by\count0\relax%
    \advance\count11 by\count9\relax%
    % 12)m = (da * 5 + 308) div 153 - 2
    \count12=\count10\relax%
    \multiply\count12 by5\relax%
    \advance\count12 by 308\relax%
    \divide\count12 by 153\relax%
    \advance\count12 by -2\relax%
    % 13)d = - (m + 4) * 153 div 5 + 122 + da
    \count13=\count12\relax%
    \advance\count13 by 4\relax%
    \multiply\count13 by153\relax%
    \divide\count13 by5\relax%
    \count13=-\count13\relax%
    \advance\count13 by 122\relax%
    \advance\count13 by \count10\relax%
    % 14)Y =  (m + 2) div 12 + y - 4800
    \count14=\count12\relax%
    \advance\count14 by 2\relax%
    \divide\count14 by12\relax%
    \advance\count14 by\count11\relax%
    \advance\count14 by-4800\relax%
    % 15)M = (m + 2) mod 12 + 1
    \count15=\count12\relax%
    \advance\count15 by2\relax%
    \count0=\count15\relax%
    \divide\count0 by12\relax%
    \multiply\count0 by12\relax%
    \advance\count15 by-\count0\relax%
    \advance\count15 by1\relax%
    % 16)D = d + 1
    \count16=\count13%
    \advance\count16by 1\relax%    
    %
    \xdef\pgf@temp@year{\the\count14}%
    \xdef\pgf@temp@month{\ifnum\count15<10 0\fi\the\count15}%
    \xdef\pgf@temp@day{\ifnum\count16<10 0\fi\the\count16}%
  }%
  \let#2=\pgf@temp@year%
  \let#3=\pgf@temp@month%  
  \let#4=\pgf@temp@day%  
}



% Returns the day of week as a number between 0 = Monday and 6 =
% Sunday
%
% #1 = a Julian day number
% #2 = a counter into which the weekday should be put.
%
% Example:
%
% \pgfcalendardatetojulian{2006-01-10}{\mycount}
% \pgfcalendarjuliantoweekday{\mycount}{\myweekday}

\def\pgfcalendarjuliantoweekday#1#2{%
  {%
    \pgfutil@tempcnta=#1\relax%
    #2=\pgfutil@tempcnta%
    \divide#2by7\relax%
    \multiply#2by-7\relax%
    \advance#2by\pgfutil@tempcnta\relax%
    \expandafter%
  }%
  \expandafter#2\the#2\relax%
}



% Converts a day of week into a weekday name (long or short)
%
% #1 = a number representing a weekday (0=Monday)
%
% Example:
%
% \pgfcalendardatetojulian{2006-01-10}{\mycount}
% \pgfcalendarjuliantoweekday{\mycount}{\myweekday}
% October 1st, 2006 was a \pgfcalendarweekdayname{\myweekday}

\def\pgfcalendarweekdayname#1{%
  \translate{\ifcase#1Monday\or Tuesday\or Wednesday\or Thursday\or Friday\or Saturday\or Sunday\fi}%
}

\def\pgfcalendarweekdayshortname#1{%
  \translate{\ifcase#1Mon\or Tue\or Wed\or Thu\or Fri\or Sat\or Sun\fi}%
}


% Converts a month of year number into a month name (long or short)
%
% #1 = a number representing a month (1=January)
%
% Example:
%
% \pgfcalendarmonthname

\def\pgfcalendarmonthname#1{%
  \translate{\ifcase#1\or January\or February\or March\or April\or
    May\or June\or July\or August\or September\or October\or
    November\or December\fi}%
}

\def\pgfcalendarmonthshortname#1{%
  \translate{\ifcase#1\or Jan\or Feb\or Mar\or Apr\or
    May\or Jun\or Jul\or Aug\or Sep\or Oct\or
    Nov\or Dec\fi}%
}






% Macro for easy typesetting of days, etc.
%
% #1 = kind selection
% #2 = length and representation selection
%
% Description:
%
% Replaces the shorthand according to the following rules: The
% first letter of the shorthand describes the kind of
% shorthand. Possible kinds are:
%
% d = day of current date (in an invocation of \pgfcalendar)
% m = month of current date
% y = year of current date
% w = week day of current date
%
% The second parameter determines how the kind is represented:
%
% - = shortest possible numerical way (allowed only for d, m, y)
% = = same, but always of the same length (padded with blanks as
%     needed, allowed only for d, m, y)
% 0 = numerical representation for d and m padded with leading zeros.
% t = textual representation (allowed only for d, m, w)
% . = abbreviated textual representation (allowed only for d, m, w)
%
% It is adivsed that you say, for example,
% \let\%=\pgfcalendarshorthand.
%
% With this setting, you can typeset an ISO-date by saying \%y0-\%m0-\%d0.
% For another example, on 2007-02-09, which is a
% Friday, you can write "\%wt, \%mt \%d-, \%y0" to get "Friday, February 9, 2007"

\def\pgfcalendarshorthand#1#2{\csname pgfcalendar@shorthand@#1#2\endcsname}
\expandafter\def\csname pgfcalendar@shorthand@d-\endcsname{%
  {\pgfutil@tempcnta=\pgfcalendarcurrentday\relax\the\pgfutil@tempcnta}}
\expandafter\def\csname pgfcalendar@shorthand@d=\endcsname{%
  {\pgfutil@tempcnta=\pgfcalendarcurrentday\relax\ifnum\pgfutil@tempcnta<10\relax\setbox0=\hbox{1}\kern\wd0\relax\fi\the\pgfutil@tempcnta}}
\expandafter\def\csname pgfcalendar@shorthand@d0\endcsname{%
  \pgfcalendarcurrentday}
\expandafter\def\csname pgfcalendar@shorthand@m-\endcsname{%
  {\pgfutil@tempcnta=\pgfcalendarcurrentmonth\relax\the\pgfutil@tempcnta}}
\expandafter\def\csname pgfcalendar@shorthand@m=\endcsname{%
  {\pgfutil@tempcnta=\pgfcalendarcurrentmonth\relax\ifnum\pgfutil@tempcnta<10\relax\setbox0=\hbox{1}\kern\wd0\relax\fi\the\pgfutil@tempcnta}}
\expandafter\def\csname pgfcalendar@shorthand@m0\endcsname{%
  \pgfcalendarcurrentmonth}
\expandafter\def\csname pgfcalendar@shorthand@y-\endcsname{%
  \pgfcalendarcurrentyear}
\expandafter\def\csname pgfcalendar@shorthand@y=\endcsname{%
  \pgfcalendarcurrentyear}
\expandafter\def\csname pgfcalendar@shorthand@y0\endcsname{%
  \pgfcalendarcurrentyear}
\expandafter\def\csname pgfcalendar@shorthand@w.\endcsname{%
  \pgfcalendarweekdayshortname{\pgfcalendarcurrentweekday}}
\expandafter\def\csname pgfcalendar@shorthand@wt\endcsname{%
  \pgfcalendarweekdayname{\pgfcalendarcurrentweekday}}
\expandafter\def\csname pgfcalendar@shorthand@m.\endcsname{%
  \pgfcalendarmonthshortname{\pgfcalendarcurrentmonth}}
\expandafter\def\csname pgfcalendar@shorthand@mt\endcsname{%
  \pgfcalendarmonthname{\pgfcalendarcurrentmonth}}


\endinput

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

pgfexternal.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.
%
% In addition to the above licenses, this particular file may also be
% directly inlined into other documents and this copyright notice may
% be removed. Additionally, when you inline this file, you may modify
% it as needed and you may remove comments.
%
% This file is intended to be distributed or even inlined into a file
% when a document needs to be typeset on a system that does not have
% pgf/TikZ installed. 

% "environment" for reading an external graphic. Note that there are
% no (!) braces around the "name" of the environment
%
% #1 = name of the graphics file
%
% Example:
%
% \beginpgfgraphicnamed{mygraph}
%   \begin{tikzpicture}
%     ...
%   \end{tikzpicture}
% \endpgfgraphicnamed

\long\def\beginpgfgraphicnamed#1#2\endpgfgraphicnamed{\includegraphics{#1}}

pgfexternalwithdepth.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.
%
% In addition to the above licenses, this particular file may also be
% directly inlined into other documents and this copyright notice may
% be removed. Additionally, when you inline this file, you may modify
% it as needed and you may remove comments.
%
% This file is intended to be distributed or even inlined into a file
% when a document needs to be typeset on a system that does not have
% pgf/TikZ installed. 

% "environment" for reading an external graphic. Note that there are
% no (!) braces around the "name" of the environment
%
% #1 = name of the graphics file
%
% Example:
%
% \beginpgfgraphicnamed{mygraph}
%   \begin{tikzpicture}
%     ...
%   \end{tikzpicture}
% \endpgfgraphicnamed

\long\def\beginpgfgraphicnamed#1#2\endpgfgraphicnamed{%
	\begingroup
	\setbox1=\hbox{\includegraphics{#1}}%
	\openin1=#1.dpth
	\ifeof1	\box1 
	\else
		\read1 to\pgfincludeexternalgraphicsdp	\closein1
		\dimen0=\pgfincludeexternalgraphicsdp\relax
		\hbox{\lower\dimen0 \box1 }%
	\fi
	\endgroup
}

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

pgflibraryarrows.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/pgflibraryarrows.code.tex,v 1.16 2013/09/23 18:04:35 tantau Exp $


% A square bracket shaped arrow

\pgfarrowsdeclare{square bracket}{square bracket}
{
  \pgfutil@tempdima=1pt%
  \advance\pgfutil@tempdima by1.25\pgflinewidth%
  \pgfarrowsleftextend{+-\pgfutil@tempdima}
  \pgfarrowsrightextend{+.5\pgflinewidth}
}
{
  \pgfutil@tempdima=2pt%
  \advance\pgfutil@tempdima by1.5\pgflinewidth%
  \pgfutil@tempdimb=\pgfutil@tempdima%
  \advance\pgfutil@tempdimb by\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetmiterjoin
  \pgfsetbuttcap
  \pgfpathmoveto{\pgfqpoint{-.5\pgfutil@tempdimb}{-1\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{0pt}{-1\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{0pt}{\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{-.5\pgfutil@tempdimb}{\pgfutil@tempdima}}
  \pgfusepathqstroke
}
\pgfdeclarearrow{name=[-], means=square bracket}

\pgfarrowsdeclarereversed{]}{[}{[}{]}


% A round bracket shaped arrow

\pgfarrowsdeclare{(}{)}
{
  \pgfutil@tempdima=2pt%
  \advance\pgfutil@tempdima by1.5\pgflinewidth%
  \pgfutil@tempdimb=0.0625\pgfutil@tempdima\advance\pgfutil@tempdimb by.5\pgflinewidth%
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
  \pgfutil@tempdimb=0.5\pgfutil@tempdima\advance\pgfutil@tempdimb by.5\pgflinewidth%
  \pgfarrowsleftextend{+-\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=2pt%
  \advance\pgfutil@tempdima by1.5\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetroundcap
  \pgfpathmoveto{\pgfqpoint{-.5\pgfutil@tempdima}{-1\pgfutil@tempdima}}
  \pgfpathcurveto
  {\pgfqpoint{.25\pgfutil@tempdima}{-.5\pgfutil@tempdima}}
  {\pgfqpoint{.25\pgfutil@tempdima}{.5\pgfutil@tempdima}}
  {\pgfqpoint{-.5\pgfutil@tempdima}{\pgfutil@tempdima}}
  \pgfusepathqstroke
}

\pgfarrowsdeclarereversed{)}{(}{(}{)}




% A pointed bracket shaped arrow

\pgfarrowsdeclare{angle 90}{angle 90}
{
  \pgfutil@tempdima=0.3pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfutil@tempdimb=5.5\pgfutil@tempdima\advance\pgfutil@tempdimb by.5\pgflinewidth%
  \pgfarrowsleftextend{+-\pgfutil@tempdimb}
  \pgfutil@tempdimb=.5\pgfutil@tempdima\advance\pgfutil@tempdimb by0.707\pgflinewidth%
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.3pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetroundcap
  \pgfsetmiterjoin
  \pgfpathmoveto{\pgfqpoint{-5.5\pgfutil@tempdima}{-6\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{0.5\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{-5.5\pgfutil@tempdima}{6\pgfutil@tempdima}}
  \pgfusepathqstroke
}

\pgfarrowsdeclarereversed{angle 90 reversed}{angle 90 reversed}{angle 90}{angle 90}


\pgfarrowsdeclare{angle 60}{angle 60}
{
  \pgfutil@tempdima=0.3pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfutil@tempdimb=7.29\pgfutil@tempdima\advance\pgfutil@tempdimb by.5\pgflinewidth%
  \pgfarrowsleftextend{+-\pgfutil@tempdimb}
  \pgfutil@tempdimb=.5\pgfutil@tempdima\advance\pgfutil@tempdimb by\pgflinewidth%
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.3pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetroundcap
  \pgfsetmiterjoin
  \pgfpathmoveto{\pgfpointadd{\pgfqpoint{0.5\pgfutil@tempdima}{0pt}}{\pgfqpointpolar{150}{9\pgfutil@tempdima}}}
  \pgfpathlineto{\pgfqpoint{0.5\pgfutil@tempdima}{0pt}}
  \pgfpathlineto{\pgfpointadd{\pgfqpoint{0.5\pgfutil@tempdima}{0pt}}{\pgfqpointpolar{-150}{9\pgfutil@tempdima}}}
  \pgfusepathqstroke
}

\pgfarrowsdeclarereversed{angle 60 reversed}{angle 60 reversed}{angle 60}{angle 60}



\pgfarrowsdeclare{angle 45}{angle 45}
{
  \pgfutil@tempdima=0.3pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfutil@tempdimb=8.705\pgfutil@tempdima\advance\pgfutil@tempdimb by.5\pgflinewidth%
  \pgfarrowsleftextend{+-\pgfutil@tempdimb}
  \pgfutil@tempdimb=.5\pgfutil@tempdima\advance\pgfutil@tempdimb by1.28\pgflinewidth%
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.3pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetroundcap
  \pgfsetmiterjoin
  \pgfpathmoveto{\pgfpointadd{\pgfqpoint{0.5\pgfutil@tempdima}{0pt}}{\pgfqpointpolar{157}{10\pgfutil@tempdima}}}
  \pgfpathlineto{\pgfqpoint{0.5\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathlineto{\pgfpointadd{\pgfqpoint{0.5\pgfutil@tempdima}{0pt}}{\pgfqpointpolar{-157}{10\pgfutil@tempdima}}}
  \pgfusepathqstroke
}

\pgfarrowsdeclarereversed{angle 45 reversed}{angle 45 reversed}{angle 45}{angle 45}



% A dot shaped arrow

\pgfarrowsdeclare{*}{*}
{
  \pgfutil@tempdima=0.4pt%
  \advance\pgfutil@tempdima by.2\pgflinewidth%
  \pgfutil@tempdimb=7.5\pgfutil@tempdima\advance\pgfutil@tempdimb by.5\pgflinewidth
  \pgfarrowsleftextend{+-\pgfutil@tempdimb}
  \pgfutil@tempdimb=1.5\pgfutil@tempdima\advance\pgfutil@tempdimb by.5\pgflinewidth
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.4pt%
  \advance\pgfutil@tempdima by.2\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfpathcircle{\pgfqpoint{-3\pgfutil@tempdima}{0pt}}{+4.5\pgfutil@tempdima}
  \pgfusepathqfillstroke
}


% An open dot shaped arrow

\pgfarrowsdeclare{o}{o}
{
  \pgfarrowsleftextend{+-.5\pgflinewidth}
  \pgfutil@tempdima=0.4pt%
  \advance\pgfutil@tempdima by.2\pgflinewidth%
  \pgfutil@tempdimb=9\pgfutil@tempdima\advance\pgfutil@tempdimb by.5\pgflinewidth
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.4pt%
  \advance\pgfutil@tempdima by.2\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfpathcircle{\pgfqpoint{4.5\pgfutil@tempdima}{0bp}}{4.5\pgfutil@tempdima}
  \pgfusepathqstroke
}



% A diamond shaped arrow

\pgfarrowsdeclare{diamond}{diamond}
{
  \pgfutil@tempdima=0.4pt%
  \advance\pgfutil@tempdima by.275\pgflinewidth%
  \pgfutil@tempdimb=13\pgfutil@tempdima\advance\pgfutil@tempdimb by.5\pgflinewidth
  \pgfarrowsleftextend{+-\pgfutil@tempdimb}
  \pgfutil@tempdimb=1\pgfutil@tempdima\advance\pgfutil@tempdimb by.5\pgflinewidth
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.4pt%
  \advance\pgfutil@tempdima by.275\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetroundjoin
  \pgfpathmoveto{\pgfqpoint{1\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{-6\pgfutil@tempdima}{4\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{-13\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{-6\pgfutil@tempdima}{-4\pgfutil@tempdima}}
  \pgfpathclose
  \pgfusepathqfillstroke
}

\pgfarrowsdeclare{open diamond}{open diamond}%{{-.5bp}{14.5bp}}
{
  \pgfutil@tempdima=0.4pt%
  \advance\pgfutil@tempdima by.275\pgflinewidth%
  \pgfarrowsleftextend{+-.5\pgflinewidth}
  \pgfutil@tempdimb=14\pgfutil@tempdima\advance\pgfutil@tempdimb by.5\pgflinewidth
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.4pt%
  \advance\pgfutil@tempdima by.275\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetroundjoin
  \pgfpathmoveto{\pgfqpoint{14\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{7\pgfutil@tempdima}{4\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{0\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{7\pgfutil@tempdima}{-4\pgfutil@tempdima}}
  \pgfpathclose
  \pgfusepathqstroke
}


% A square shaped arrow
\newdimen\arrowsize
\pgfarrowsdeclare{square}{square}
{
 \arrowsize=0.4pt
 \advance\arrowsize by.275\pgflinewidth%
 \pgfarrowsleftextend{-7\arrowsize-.5\pgflinewidth}
 \advance\arrowsize by.5\pgflinewidth
 \pgfarrowsrightextend{+\arrowsize}
}
{
 \arrowsize=0.4pt
 \advance\arrowsize by.275\pgflinewidth%
 \pgfsetdash{}{+0pt}
 \pgfsetroundjoin
 \pgfpathmoveto{\pgfqpoint{1\arrowsize}{4\arrowsize}}
 \pgfpathlineto{\pgfqpoint{-7\arrowsize}{4\arrowsize}}
 \pgfpathlineto{\pgfqpoint{-7\arrowsize}{-4\arrowsize}}
 \pgfpathlineto{\pgfqpoint{1\arrowsize}{-4\arrowsize}}
 \pgfpathclose
 \pgfusepathqfillstroke
}
% A open square shaped arrow

\pgfarrowsdeclare{open square}{open square}%{{-.5bp}{8.5bp}}
{
 \arrowsize=0.4pt
 \advance\arrowsize by.275\pgflinewidth%
 \pgfarrowsleftextend{+-.5\pgflinewidth}
 \advance\arrowsize by7\arrowsize
 \advance\arrowsize by.5\pgflinewidth
 \pgfarrowsrightextend{+\arrowsize}
}
{
 \arrowsize=0.4pt
 \advance\arrowsize by.275\pgflinewidth%
 \pgfsetdash{}{+0pt}
 \pgfsetroundjoin
 \pgfpathmoveto{\pgfqpoint{8\arrowsize}{4\arrowsize}}
 \pgfpathlineto{\pgfqpoint{0\arrowsize}{4\arrowsize}}
 \pgfpathlineto{\pgfqpoint{0\arrowsize}{-4\arrowsize}}
 \pgfpathlineto{\pgfqpoint{8\arrowsize}{-4\arrowsize}}
 \pgfpathclose
 \pgfusepathqstroke
}



% A triangle shaped arrow

\pgfarrowsdeclare{triangle 90}{triangle 90}
{
  \pgfutil@tempdima=0.5pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfutil@tempdimb=5.5\pgfutil@tempdima\advance\pgfutil@tempdimb by.5\pgflinewidth%
  \pgfarrowsleftextend{+-\pgfutil@tempdimb}
  \pgfutil@tempdimb=.5\pgfutil@tempdima\advance\pgfutil@tempdimb by0.707\pgflinewidth%
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.5pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetmiterjoin
  \pgfpathmoveto{\pgfqpoint{-5.5\pgfutil@tempdima}{-6\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{0.5\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{-5.5\pgfutil@tempdima}{6\pgfutil@tempdima}}
  \pgfpathclose
  \pgfusepathqfillstroke
}

\pgfarrowsdeclarereversed{triangle 90 reversed}{triangle 90 reversed}{triangle 90}{triangle 90}


\pgfarrowsdeclare{triangle 60}{triangle 60}
{
  \pgfutil@tempdima=0.5pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfutil@tempdimb=7.29\pgfutil@tempdima\advance\pgfutil@tempdimb by.5\pgflinewidth%
  \pgfarrowsleftextend{+-\pgfutil@tempdimb}
  \pgfutil@tempdimb=.5\pgfutil@tempdima\advance\pgfutil@tempdimb by\pgflinewidth%
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.5pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetmiterjoin
  \pgfpathmoveto{\pgfpointadd{\pgfqpoint{0.5\pgfutil@tempdima}{0pt}}{\pgfqpointpolar{150}{9\pgfutil@tempdima}}}
  \pgfpathlineto{\pgfqpoint{0.5\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathlineto{\pgfpointadd{\pgfqpoint{0.5\pgfutil@tempdima}{0pt}}{\pgfqpointpolar{-150}{9\pgfutil@tempdima}}}
  \pgfpathclose
  \pgfusepathqfillstroke
}

\pgfarrowsdeclarereversed{triangle 60 reversed}{triangle 60 reversed}{triangle 60}{triangle 60}




\pgfarrowsdeclare{triangle 45}{triangle 45}
{
  \pgfutil@tempdima=0.5pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfutil@tempdimb=8.705\pgfutil@tempdima\advance\pgfutil@tempdimb by.5\pgflinewidth%
  \pgfarrowsleftextend{+-\pgfutil@tempdimb}
  \pgfutil@tempdimb=.5\pgfutil@tempdima\advance\pgfutil@tempdimb by1.28\pgflinewidth%
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.5pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetmiterjoin
  \pgfpathmoveto{\pgfpointadd{\pgfqpoint{0.5\pgfutil@tempdima}{0pt}}{\pgfqpointpolar{157}{10\pgfutil@tempdima}}}
  \pgfpathlineto{\pgfqpoint{0.5\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathlineto{\pgfpointadd{\pgfqpoint{0.5\pgfutil@tempdima}{0pt}}{\pgfqpointpolar{-157}{10\pgfutil@tempdima}}}
  \pgfpathclose
  \pgfusepathqfillstroke
}

\pgfarrowsdeclarereversed{triangle 45 reversed}{triangle 45 reversed}{triangle 45}{triangle 45}




\pgfarrowsdeclare{open triangle 90}{open triangle 90}
{
  \pgfutil@tempdima=0.5pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfarrowsleftextend{+-.5\pgflinewidth}
  \pgfutil@tempdimb=6\pgfutil@tempdima\advance\pgfutil@tempdimb by0.707\pgflinewidth%
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.5pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetmiterjoin
  \pgfpathmoveto{\pgfqpoint{0\pgfutil@tempdima}{-6\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{6\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{0\pgfutil@tempdima}{6\pgfutil@tempdima}}
  \pgfpathclose
  \pgfusepathqstroke
}

\pgfarrowsdeclare{open triangle 90 reversed}{open triangle 90 reversed}
{
  \pgfutil@tempdima=0.5pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfarrowsleftextend{+-.707\pgflinewidth}
  \pgfutil@tempdimb=6\pgfutil@tempdima\advance\pgfutil@tempdimb by0.5\pgflinewidth%
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.5pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetmiterjoin
  \pgfpathmoveto{\pgfqpoint{6\pgfutil@tempdima}{-6\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{0\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{6\pgfutil@tempdima}{6\pgfutil@tempdima}}
  \pgfpathclose
  \pgfusepathqstroke
}



\pgfarrowsdeclare{open triangle 60}{open triangle 60}
{
  \pgfutil@tempdima=0.5pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfarrowsleftextend{+-.5\pgflinewidth}
  \pgfutil@tempdimb=7.794\pgfutil@tempdima\advance\pgfutil@tempdimb by\pgflinewidth%
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.5pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetmiterjoin
  \pgfpathmoveto{\pgfpointadd{\pgfqpoint{7.794\pgfutil@tempdima}{0pt}}{\pgfqpointpolar{150}{9\pgfutil@tempdima}}}
  \pgfpathlineto{\pgfqpoint{7.794\pgfutil@tempdima}{0pt}}
  \pgfpathlineto{\pgfpointadd{\pgfqpoint{7.794\pgfutil@tempdima}{0pt}}{\pgfqpointpolar{-150}{9\pgfutil@tempdima}}}
  \pgfpathclose
  \pgfusepathqstroke
}



\pgfarrowsdeclare{open triangle 60 reversed}{open triangle 60 reversed}
{
  \pgfutil@tempdima=0.5pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfarrowsleftextend{+-\pgflinewidth}
  \pgfutil@tempdimb=7.794\pgfutil@tempdima\advance\pgfutil@tempdimb by0.5\pgflinewidth%
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.5pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetmiterjoin
  \pgfpathmoveto{\pgfqpointpolar{30}{9\pgfutil@tempdima}}
  \pgfpathlineto{\pgfpointorigin}
  \pgfpathlineto{\pgfqpointpolar{-30}{9\pgfutil@tempdima}}
  \pgfpathclose
  \pgfusepathqstroke
}



\pgfarrowsdeclare{open triangle 45}{open triangle 45}
{
  \pgfutil@tempdima=0.5pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfarrowsleftextend{+-.5\pgflinewidth}
  \pgfutil@tempdimb=9.205\pgfutil@tempdima\advance\pgfutil@tempdimb by1.28\pgflinewidth%
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.5pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetmiterjoin
  \pgfpathmoveto{\pgfpointadd{\pgfqpoint{9.205\pgfutil@tempdima}{0pt}}{\pgfqpointpolar{157}{10\pgfutil@tempdima}}}
  \pgfpathlineto{\pgfqpoint{9.205\pgfutil@tempdima}{0pt}}
  \pgfpathlineto{\pgfpointadd{\pgfqpoint{9.205\pgfutil@tempdima}{0pt}}{\pgfqpointpolar{-157}{10\pgfutil@tempdima}}}
  \pgfpathclose
  \pgfusepathqstroke
}



\pgfarrowsdeclare{open triangle 45 reversed}{open triangle 45 reversed}
{
  \pgfutil@tempdima=0.5pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfarrowsleftextend{+-1.28\pgflinewidth}
  \pgfutil@tempdimb=9.205\pgfutil@tempdima\advance\pgfutil@tempdimb by0.5\pgflinewidth%
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.5pt%
  \advance\pgfutil@tempdima by.25\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetmiterjoin
  \pgfpathmoveto{\pgfqpointpolar{23}{10\pgfutil@tempdima}}
  \pgfpathlineto{\pgfpointorigin}
  \pgfpathlineto{\pgfqpointpolar{-23}{10\pgfutil@tempdima}}
  \pgfpathclose
  \pgfusepathqstroke
}



% A less fleshy variant of LaTeX's orginal arrow type

\pgfarrowsdeclare{latex'}{latex'}
{
  \pgfutil@tempdima=0.28pt%
  \advance\pgfutil@tempdima by.3\pgflinewidth%
  \pgfarrowsleftextend{+-4\pgfutil@tempdima}
  \pgfarrowsrightextend{+6\pgfutil@tempdima}
}
{
  \pgfutil@tempdima=0.28pt%
  \advance\pgfutil@tempdima by.3\pgflinewidth%
  \pgfpathmoveto{\pgfqpoint{6\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathcurveto
  {\pgfqpoint{3.5\pgfutil@tempdima}{.5\pgfutil@tempdima}}
  {\pgfqpoint{-1\pgfutil@tempdima}{1.5\pgfutil@tempdima}}
  {\pgfqpoint{-4\pgfutil@tempdima}{3.75\pgfutil@tempdima}}
  \pgfpathcurveto
  {\pgfqpoint{-1.5\pgfutil@tempdima}{1\pgfutil@tempdima}}
  {\pgfqpoint{-1.5\pgfutil@tempdima}{-1\pgfutil@tempdima}}
  {\pgfqpoint{-4\pgfutil@tempdima}{-3.75\pgfutil@tempdima}}
  \pgfpathcurveto
  {\pgfqpoint{-1\pgfutil@tempdima}{-1.5\pgfutil@tempdima}}
  {\pgfqpoint{3.5\pgfutil@tempdima}{-.5\pgfutil@tempdima}}
  {\pgfqpoint{6\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathclose
  \pgfusepathqfill
}

\pgfarrowsdeclarereversed{latex' reversed}{latex' reversed}{latex'}{latex'}


% A rounded variant of the stealth arrow

\pgfarrowsdeclare{stealth'}{stealth'}
{
  \pgfutil@tempdima=0.28pt%
  \advance\pgfutil@tempdima by.3\pgflinewidth%
  \pgfutil@tempdimb=6\pgfutil@tempdima\advance\pgfutil@tempdimb by.5\pgflinewidth%
  \pgfarrowsleftextend{+-\pgfutil@tempdimb}
  \pgfutil@tempdimb=2\pgfutil@tempdima\advance\pgfutil@tempdimb by0.5\pgflinewidth%
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.28pt%
  \advance\pgfutil@tempdima by.3\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetroundjoin
  \pgfpathmoveto{\pgfqpoint{2\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathcurveto
  {\pgfqpoint{-.5\pgfutil@tempdima}{.5\pgfutil@tempdima}}
  {\pgfqpoint{-3\pgfutil@tempdima}{1.5\pgfutil@tempdima}}
  {\pgfqpoint{-6\pgfutil@tempdima}{3.25\pgfutil@tempdima}}
  \pgfpathcurveto
  {\pgfqpoint{-3\pgfutil@tempdima}{1\pgfutil@tempdima}}
  {\pgfqpoint{-3\pgfutil@tempdima}{-1\pgfutil@tempdima}}
  {\pgfqpoint{-6\pgfutil@tempdima}{-3.25\pgfutil@tempdima}}
  \pgfpathcurveto
  {\pgfqpoint{-3\pgfutil@tempdima}{-1.5\pgfutil@tempdima}}
  {\pgfqpoint{-.5\pgfutil@tempdima}{-.5\pgfutil@tempdima}}
  {\pgfqpoint{2\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathclose
  \pgfusepathqfillstroke
}

\pgfarrowsdeclarereversed{stealth' reversed}{stealth' reversed}{stealth'}{stealth'}



% The two half of the $\to$ arrow

\pgfarrowsdeclare{left to}{left 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{0.55\pgfutil@tempdima}{-0.125\pgflinewidth}}
  {\pgfqpoint{0.5\pgfutil@tempdima}{-0.125\pgflinewidth}}
  {\pgfqpoint{0.5\pgfutil@tempdima}{-0.125\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{0pt}{-0.125\pgflinewidth}}
  \pgfusepathqstroke
}


\pgfarrowsdeclare{right to}{right 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{0.55\pgfutil@tempdima}{0.125\pgflinewidth}}
  {\pgfqpoint{0.5\pgfutil@tempdima}{0.125\pgflinewidth}}
  {\pgfqpoint{0.5\pgfutil@tempdima}{0.125\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{0pt}{0.125\pgflinewidth}}
  \pgfusepathqstroke
}



% The halfs of the $\to$ arrow reversed

\pgfarrowsdeclare{left to reversed}{left to reversed}
{
  \pgfutil@tempdima=0.28pt%
  \advance\pgfutil@tempdima by.3\pgflinewidth%
  \pgfarrowsleftextend{+-.1\pgflinewidth}
  \pgfutil@tempdimb=3.75\pgfutil@tempdima\advance\pgfutil@tempdimb by0.9\pgflinewidth%
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.28pt%
  \advance\pgfutil@tempdima by.3\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetroundjoin
  \pgfsetbuttcap
  \pgfpathmoveto{\pgfqpoint{0.5\pgflinewidth}{0pt}}
  \pgfpathlineto{\pgfqpoint{-0.1\pgflinewidth}{0pt}}
  \pgfusepathqstroke
  \pgfsetroundcap
  \pgfsetlinewidth{.8\pgflinewidth}
  {\pgftransformxshift{0.625\pgflinewidth}
    \pgfpathmoveto{\pgfqpoint{3.75\pgfutil@tempdima}{4\pgfutil@tempdima}}
    \pgfpathcurveto{\pgfqpoint{3.5\pgfutil@tempdima}{2.5\pgfutil@tempdima}}{\pgfqpoint{0.75\pgfutil@tempdima}{0.25\pgfutil@tempdima}}{\pgfqpoint{0pt}{0.125\pgflinewidth}}
    \pgfpathmoveto{\pgfqpoint{3.75\pgfutil@tempdima}{4\pgfutil@tempdima}}
    \pgfpathcurveto{\pgfqpoint{3.5\pgfutil@tempdima}{2.5\pgfutil@tempdima}}{\pgfqpoint{0.75\pgfutil@tempdima}{0.25\pgfutil@tempdima}}{\pgfqpoint{0pt}{-0.125\pgflinewidth}}
  }
  \pgfusepathqstroke%
}

\pgfarrowsdeclare{right to reversed}{right to reversed}
{
  \pgfutil@tempdima=0.28pt%
  \advance\pgfutil@tempdima by.3\pgflinewidth%
  \pgfarrowsleftextend{+-.1\pgflinewidth}
  \pgfutil@tempdimb=3.75\pgfutil@tempdima\advance\pgfutil@tempdimb by0.9\pgflinewidth%
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.28pt%
  \advance\pgfutil@tempdima by.3\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetroundjoin
  \pgfsetbuttcap
  \pgfpathmoveto{\pgfqpoint{0.5\pgflinewidth}{0pt}}
  \pgfpathlineto{\pgfqpoint{-0.1\pgflinewidth}{0pt}}
  \pgfusepathqstroke
  \pgfsetroundcap
  \pgfsetlinewidth{.8\pgflinewidth}
  {\pgftransformxshift{0.625\pgflinewidth}
    \pgfpathmoveto{\pgfqpoint{3.75\pgfutil@tempdima}{-4\pgfutil@tempdima}}
    \pgfpathcurveto{\pgfqpoint{3.5\pgfutil@tempdima}{-2.5\pgfutil@tempdima}}{\pgfqpoint{0.75\pgfutil@tempdima}{-0.25\pgfutil@tempdima}}{\pgfqpoint{0pt}{-0.125\pgflinewidth}}
    \pgfpathmoveto{\pgfqpoint{3.75\pgfutil@tempdima}{-4\pgfutil@tempdima}}
    \pgfpathcurveto{\pgfqpoint{3.5\pgfutil@tempdima}{-2.5\pgfutil@tempdima}}{\pgfqpoint{0.75\pgfutil@tempdima}{-0.25\pgfutil@tempdima}}{\pgfqpoint{0pt}{0.125\pgflinewidth}}
  }
  \pgfusepathqstroke%
}



% A left hook

\pgfarrowsdeclare{left hook}{left hook}
{
  \pgfutil@tempdima=0.4pt%
  \advance\pgfutil@tempdima by.2\pgflinewidth%
  \pgfarrowsleftextend{+-.5\pgflinewidth}
  \pgfutil@tempdimb=3.75\pgfutil@tempdima\advance\pgfutil@tempdimb by0.5\pgflinewidth%
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.4pt%
  \advance\pgfutil@tempdima by.2\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetroundcap
  \pgfpathmoveto{\pgfqpoint{0\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{0.75\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathcurveto{\pgfqpoint{2.415\pgfutil@tempdima}{0\pgfutil@tempdima}}{\pgfqpoint{3.75\pgfutil@tempdima}{1.665\pgfutil@tempdima}}{\pgfqpoint{3.75\pgfutil@tempdima}{3\pgfutil@tempdima}}
  \pgfpathcurveto{\pgfqpoint{3.75\pgfutil@tempdima}{4.665\pgfutil@tempdima}}{\pgfqpoint{2.415\pgfutil@tempdima}{6\pgfutil@tempdima}}{\pgfqpoint{0.75\pgfutil@tempdima}{6\pgfutil@tempdima}}
  \pgfusepathqstroke%
}

\pgfarrowsdeclarereversed{left hook reversed}{left hook reversed}{left hook}{left hook}



% A right hook

\pgfarrowsdeclare{right hook}{right hook}
{
  \pgfutil@tempdima=0.4pt%
  \advance\pgfutil@tempdima by.2\pgflinewidth%
  \pgfarrowsleftextend{+-.5\pgflinewidth}
  \pgfutil@tempdimb=3.75\pgfutil@tempdima\advance\pgfutil@tempdimb by0.5\pgflinewidth%
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.4pt%
  \advance\pgfutil@tempdima by.2\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetroundcap
  \pgfpathmoveto{\pgfqpoint{0\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{0.75\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathcurveto{\pgfqpoint{2.415\pgfutil@tempdima}{0\pgfutil@tempdima}}{\pgfqpoint{3.75\pgfutil@tempdima}{-1.665\pgfutil@tempdima}}{\pgfqpoint{3.75\pgfutil@tempdima}{-3\pgfutil@tempdima}}
  \pgfpathcurveto{\pgfqpoint{3.75\pgfutil@tempdima}{-4.665\pgfutil@tempdima}}{\pgfqpoint{2.415\pgfutil@tempdima}{-6\pgfutil@tempdima}}{\pgfqpoint{0.75\pgfutil@tempdima}{-6\pgfutil@tempdima}}
  \pgfusepathqstroke%
}

\pgfarrowsdeclarereversed{right hook reversed}{right hook reversed}{right hook}{right hook}


% Hooks in both directions

\pgfarrowsdeclare{hooks}{hooks}
{
  \pgfutil@tempdima=0.4pt%
  \advance\pgfutil@tempdima by.2\pgflinewidth%
  \pgfarrowsleftextend{+-.5\pgflinewidth}
  \pgfutil@tempdimb=3.75\pgfutil@tempdima\advance\pgfutil@tempdimb by0.5\pgflinewidth%
  \pgfarrowsrightextend{+\pgfutil@tempdimb}
}
{
  \pgfutil@tempdima=0.4pt%
  \advance\pgfutil@tempdima by.2\pgflinewidth%
  \pgfsetdash{}{+0pt}
  \pgfsetroundcap
  \pgfpathmoveto{\pgfqpoint{0\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{0.75\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathcurveto{\pgfqpoint{2.415\pgfutil@tempdima}{0\pgfutil@tempdima}}{\pgfqpoint{3.75\pgfutil@tempdima}{1.665\pgfutil@tempdima}}{\pgfqpoint{3.75\pgfutil@tempdima}{3\pgfutil@tempdima}}
  \pgfpathcurveto{\pgfqpoint{3.75\pgfutil@tempdima}{4.665\pgfutil@tempdima}}{\pgfqpoint{2.415\pgfutil@tempdima}{6\pgfutil@tempdima}}{\pgfqpoint{0.75\pgfutil@tempdima}{6\pgfutil@tempdima}}
  \pgfpathmoveto{\pgfqpoint{0.75\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathcurveto{\pgfqpoint{2.415\pgfutil@tempdima}{0\pgfutil@tempdima}}{\pgfqpoint{3.75\pgfutil@tempdima}{-1.665\pgfutil@tempdima}}{\pgfqpoint{3.75\pgfutil@tempdima}{-3\pgfutil@tempdima}}
  \pgfpathcurveto{\pgfqpoint{3.75\pgfutil@tempdima}{-4.665\pgfutil@tempdima}}{\pgfqpoint{2.415\pgfutil@tempdima}{-6\pgfutil@tempdima}}{\pgfqpoint{0.75\pgfutil@tempdima}{-6\pgfutil@tempdima}}
  \pgfusepathqstroke%
}

\pgfarrowsdeclarereversed{hooks reversed}{hooks reversed}{hooks}{hooks}


% An arrow that looks like a serif of the computer modern font

\pgfarrowsdeclare{serif cm}{serif cm}
{
  \pgfutil@tempdima=0.4pt%
  \advance\pgfutil@tempdima by.45\pgflinewidth%
  \pgfarrowsleftextend{+-.75\pgfutil@tempdima}
  \pgfarrowsrightextend{+.04\pgflinewidth}
}
{
  \pgfutil@tempdima=0.4pt%
  \advance\pgfutil@tempdima by.45\pgflinewidth%
  \pgftransformxshift{.04\pgflinewidth}
  \pgfpathmoveto{\pgfqpoint{-.75\pgfutil@tempdima}{.5\pgflinewidth}}
  \pgfpathcurveto
    {\pgfqpoint{-.375\pgfutil@tempdima}{.5\pgflinewidth}}
    {\pgfqpoint{-.375\pgfutil@tempdima}{.7\pgflinewidth}}
    {\pgfqpoint{-.375\pgfutil@tempdima}{1.95\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{0pt}{1.95\pgfutil@tempdima}}
  \pgfpathcurveto
    {\pgfqpoint{-.04\pgflinewidth}{.5\pgfutil@tempdima}}
    {\pgfqpoint{-.04\pgflinewidth}{-.5\pgfutil@tempdima}}
    {\pgfqpoint{0pt}{-1.95\pgfutil@tempdima}}  
  \pgfpathlineto{\pgfqpoint{-.375\pgfutil@tempdima}{-1.95\pgfutil@tempdima}}  
  \pgfpathcurveto
    {\pgfqpoint{-.375\pgfutil@tempdima}{-.7\pgflinewidth}}
    {\pgfqpoint{-.375\pgfutil@tempdima}{-.5\pgflinewidth}}
    {\pgfqpoint{-.75\pgfutil@tempdima}{-.5\pgflinewidth}}
  \pgfpathclose
  \pgfusepathqfill
}



% Round cap

\pgfarrowsdeclare{round cap}{round cap}
{\pgfarrowsleftextend{+0pt}\pgfarrowsrightextend{+\pgflinewidth}}
{
  \pgfsetdash{}{+0pt}
  \pgfsetroundcap
  \pgfpathmoveto{\pgfpointorigin}
  \pgfpathlineto{\pgfqpoint{0.5\pgflinewidth}{0pt}}
  \pgfusepathqstroke
}


% Butt cap

\pgfarrowsdeclare{butt cap}{butt cap}
{\pgfarrowsleftextend{+-.1\pgflinewidth}\pgfarrowsrightextend{+.5\pgflinewidth}}
{
  \pgfsetdash{}{+0pt}
  \pgfsetbuttcap
  \pgfpathmoveto{\pgfqpoint{-.1\pgflinewidth}{0pt}}
  \pgfpathlineto{\pgfqpoint{0.5\pgflinewidth}{0pt}}
  \pgfusepathqstroke
}



% 90 degrees cap

\pgfarrowsdeclare{triangle 90 cap}{triangle 90 cap}
{\pgfarrowsleftextend{+-.1\pgflinewidth}\pgfarrowsrightextend{+\pgflinewidth}}
{
  \pgfpathmoveto{\pgfqpoint{-.1\pgflinewidth}{0.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{.5\pgflinewidth}{.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{\pgflinewidth}{0pt}}
  \pgfpathlineto{\pgfqpoint{.5\pgflinewidth}{-.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{-.1\pgflinewidth}{-0.5\pgflinewidth}}
  \pgfpathclose
  \pgfusepathqfill
}


% reversed 90 degrees cap

\pgfarrowsdeclare{triangle 90 cap reversed}{triangle 90 cap reversed}
{\pgfarrowsleftextend{+-.1\pgflinewidth}\pgfarrowsrightextend{+\pgflinewidth}}
{
  \pgfpathmoveto{\pgfqpoint{1\pgflinewidth}{0.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{-.1\pgflinewidth}{.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{-.1\pgflinewidth}{-.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{1\pgflinewidth}{-.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{0.5\pgflinewidth}{0\pgflinewidth}}
  \pgfpathclose
  \pgfusepathqfill
}



% fast

\pgfarrowsdeclare{fast cap}{fast cap}
{\pgfarrowsleftextend{+-.1\pgflinewidth}\pgfarrowsrightextend{+2\pgflinewidth}}
{
  \pgfpathmoveto{\pgfqpoint{-.1\pgflinewidth}{0.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{.5\pgflinewidth}{.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{1\pgflinewidth}{0\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{.5\pgflinewidth}{-.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{-.1\pgflinewidth}{-0.5\pgflinewidth}}
  \pgfpathclose
  \pgfpathmoveto{\pgfqpoint{1\pgflinewidth}{0.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{1.5\pgflinewidth}{0.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{2\pgflinewidth}{0\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{1.5\pgflinewidth}{-.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{1\pgflinewidth}{-0.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{1.5\pgflinewidth}{0\pgflinewidth}}
  \pgfpathclose
  \pgfusepathqfill
}


\pgfarrowsdeclare{fast cap reversed}{fast cap reversed}
{\pgfarrowsleftextend{+-.1\pgflinewidth}\pgfarrowsrightextend{+2\pgflinewidth}}
{
  \pgfpathmoveto{\pgfqpoint{-.1\pgflinewidth}{0.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{1\pgflinewidth}{.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{.5\pgflinewidth}{0\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{1\pgflinewidth}{-.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{-.1\pgflinewidth}{-0.5\pgflinewidth}}
  \pgfpathclose
  \pgfpathmoveto{\pgfqpoint{1.5\pgflinewidth}{0.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{2\pgflinewidth}{0.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{1.5\pgflinewidth}{0\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{2\pgflinewidth}{-.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{1.5\pgflinewidth}{-0.5\pgflinewidth}}
  \pgfpathlineto{\pgfqpoint{1\pgflinewidth}{0\pgflinewidth}}
  \pgfpathclose
  \pgfusepathqfill
}





% Mathematical arrows


% The arrow tip of an \implies arrow, to be used with an inner line.
%
% Example:
%
% \pgfsetarrow{-implies}
% \pgfsetlinewidth{1.8pt}
% \pgfsetinnerlinewidth{1pt}

\pgfarrowsdeclare{implies}{implies}
{
  \pgfmathsetlength{\pgfutil@tempdima}{.25\pgflinewidth+.25*\pgfinnerlinewidth}%
  \pgfmathsetlength{\pgfutil@tempdimb}{.5\pgflinewidth-.5*\pgfinnerlinewidth}%
  \pgfarrowsrightextend{2.06\pgfutil@tempdima+.5\pgfutil@tempdimb}
  \pgfarrowsleftextend{-1.36\pgfutil@tempdima-.5\pgfutil@tempdimb}
}
{
  \pgfmathsetlength{\pgfutil@tempdima}{.25\pgflinewidth+.25*\pgfinnerlinewidth}%
  \pgfmathsetlength{\pgfutil@tempdimb}{.5\pgflinewidth-.5*\pgfinnerlinewidth}%
  \pgftransformxshift{.06\pgfutil@tempdima}
  \pgfsetlinewidth{\pgfutil@tempdimb}
  \pgfsetdash{}{+0pt}
  \pgfsetroundcap
  \pgfsetroundjoin
  \pgfpathmoveto{\pgfpoint{-1.4\pgfutil@tempdima}{2.65\pgfutil@tempdima}}
  \pgfpathcurveto
  {\pgfpoint{-0.75\pgfutil@tempdima}{1.25\pgfutil@tempdima}}
  {\pgfpoint{1\pgfutil@tempdima}{0.05\pgfutil@tempdima}}
  {\pgfpoint{2\pgfutil@tempdima}{0pt}}
  \pgfpathcurveto
  {\pgfpoint{1\pgfutil@tempdima}{-0.05\pgfutil@tempdima}}
  {\pgfpoint{-.75\pgfutil@tempdima}{-1.25\pgfutil@tempdima}}
  {\pgfpoint{-1.4\pgfutil@tempdima}{-2.65\pgfutil@tempdima}}
  \pgfusepathqstroke
}



\endinput

pgflibraryarrows.meta.code.tex
% Copyright 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[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/libraries/pgflibraryarrows.meta.code.tex,v 1.12 2013/12/13 15:11:58 tantau Exp $



% 
% 
% Meta keys 
% 
%


\newdimen\pgfarrowinset
\newdimen\pgfarrowlength
\newdimen\pgfarrowwidth
\newdimen\pgfarrowlinewidth
\newif\ifpgfarrowroundcap
\newif\ifpgfarrowroundjoin

\pgfarrowsaddtolengthscalelist\pgfarrowlength
\pgfarrowsaddtolengthscalelist\pgfarrowinset
\pgfarrowsaddtowidthscalelist\pgfarrowwidth


\pgfkeys{
  /pgf/arrow keys/.cd,
  length/.code={%
    \pgfarrowsthreeparameters{#1}%
    \expandafter\pgfarrowsaddtooptions\expandafter{\expandafter\pgfarrowslinewidthdependent\pgfarrowstheparameters\pgfarrowlength\pgf@x}%
  },
  inset/.code={%
    \pgfarrowsthreeparameters{#1}%
    \expandafter\pgfarrowsaddtolateoptions\expandafter{\expandafter\pgfarrowslinewidthdependent\pgfarrowstheparameters\pgfarrowinset\pgf@x}%
  },
  inset'/.code={
    \pgfarrowsthreeparameters{#1}%
    \expandafter\pgfarrowsaddtolateoptions\expandafter{\expandafter\pgfarrowslengthdependent\pgfarrowstheparameters\pgfarrowinset}%
  },
  line width/.code={%
    \pgfarrowsthreeparameters{#1}%
    \expandafter\pgfarrowsaddtolateoptions\expandafter{\expandafter\pgfarrowslinewidthdependent\pgfarrowstheparameters\pgfarrowlinewidth\pgf@x}%
  },
  line width'/.code={
    \pgfarrowsthreeparameters{#1}%
    \expandafter\pgfarrowsaddtolateoptions\expandafter{\expandafter\pgfarrowslengthdependent\pgfarrowstheparameters\pgfarrowlinewidth}%
  },
  width/.code={%
    \pgfarrowsthreeparameters{#1}%
    \expandafter\pgfarrowsaddtolateoptions\expandafter{\expandafter\pgfarrowslinewidthdependent\pgfarrowstheparameters\pgfarrowwidth\pgf@x}%
  },
  width'/.code={%
    \pgfarrowsthreeparameters{#1}%
    \expandafter\pgfarrowsaddtolateoptions\expandafter{\expandafter\pgfarrowslengthdependent\pgfarrowstheparameters\pgfarrowwidth}%
  },
  angle/.code={%
    \pgfarrowsfourparameters{#1}%
    \expandafter\pgfarrowsaddtooptions\expandafter{\expandafter\pgfarrows@angle@setup\pgfarrowstheparameters}%
  },
  angle'/.code={
    \pgfarrowsaddtolateoptions{\pgfarrows@angle@setup@prime{#1}}%
  },
  % 
  line cap/.is choice,
  line cap/butt/.code=\pgfarrowsaddtooptions{\pgfarrowroundcapfalse},
  line cap/round/.code=\pgfarrowsaddtooptions{\pgfarrowroundcaptrue},
  line join/.is choice,
  line join/miter/.code=\pgfarrowsaddtooptions{\pgfarrowroundjoinfalse},
  line join/round/.code=\pgfarrowsaddtooptions{\pgfarrowroundjointrue},
  round/.style={line cap=round,line join=round},
  sharp/.style={line cap=butt,line join=miter},
}




%
%
% Classificaiton of arrow tips:
%
%
% Barbs
% -----
%
% These arrow tips consisting of stroked lines starting at the tip,
% typically going backward. They cannot be filled, only stroked
%
% A special case are the arrows mimicking the tip at the end of a
% \rightarrow command. 
%
%
% Geometric
% ---------
%
% The arrow tips have a geometric form like a triangle or a
% "stealth" fighter or a kite. They can be filled and/or stroked.
%
%
% Caps
% ----
%
% These arrow tips have their width fixed to the line width and
% provide different ways of adding a "cap" to the end of a line. This
% allows one to use more than just the standard "round cap", "butt
% cap" and "rect cap" and, additionally, one can one kind of cap at
% one end and another at the other end.
%
%
% Other
% -----
%
% Special purpose arrow tips.
%



%
%
% Barbs arrow tips
%
%


% An Straight Barb yields a simple angle

\pgfdeclarearrow{
  name = Straight Barb,
  defaults = {
    length = +1.5pt 2,
    width'  = +0pt 2,
    line width = +0pt 1 1,
  },
  setup code = {
    % Compute front miter length:
    \pgfmathdivide@\pgfarrowlength\pgfarrowwidth%
    \let\pgf@temp@quot\pgfmathresult%
    \pgf@x\pgfmathresult pt%
    \pgf@x\pgfmathresult\pgf@x%
    \pgf@x4\pgf@x%
    \advance\pgf@x by1pt%
    \pgfmathsqrt@\pgf@x%
    \pgf@xc\pgfmathresult\pgfarrowlinewidth% xc is front miter
    \pgf@xc.5\pgf@xc
    \pgf@xa\pgf@temp@quot\pgfarrowlinewidth% xa is extra harpoon miter
    % Set ends
    \ifpgfarrowroundjoin
      \pgfarrowssettipend{\pgfarrowlength\advance\pgf@x by.5\pgfarrowlinewidth}    
    \else
      \pgfarrowssettipend{\pgfarrowlength\advance\pgf@x by\pgf@xc\ifpgfarrowharpoon\advance\pgf@x by\pgf@xa\fi}
    \fi
    \pgfarrowssetvisualbackend{\pgfarrowlength\advance\pgf@x by.5\pgfarrowlinewidth}
    \pgfarrowssetbackend{-.5\pgfarrowlinewidth}
    % harpoon miter correction
    \ifpgfarrowreversed
      \pgfarrowssetlineend{\pgfarrowlength\ifpgfarrowharpoon\advance\pgf@x by.5\pgfarrowlinewidth\fi}
    \else
      \pgfarrowssetlineend{\pgfarrowlength\advance\pgf@x by-.5\pgfarrowlinewidth}
    \fi
    % The hull:
    \ifpgfarrowroundjoin
      \pgfarrowshullpoint{\pgfarrowlength\advance\pgf@x by.5\pgfarrowlinewidth}{\ifpgfarrowharpoon-.5\pgfarrowlinewidth\else0pt\fi}%
    \else%
      \ifpgfarrowharpoon
        \pgfarrowshullpoint{\pgfarrowlength\advance\pgf@x by\pgf@xc\advance\pgf@x by\pgf@xa}{-.5\pgfarrowlinewidth}%
      \else
        \pgfarrowshullpoint{\pgfarrowlength\advance\pgf@x by\pgf@xc\advance\pgf@x by\pgf@xa}{0pt}%
      \fi%
    \fi
    \pgfarrowsupperhullpoint{.5\pgfarrowlinewidth}{.5\pgfarrowwidth\advance\pgf@y by.5\pgfarrowlinewidth}%
    \pgfarrowsupperhullpoint{-.5\pgfarrowlinewidth}{.5\pgfarrowwidth\advance\pgf@y by.5\pgfarrowlinewidth}%
    \ifpgfarrowharpoon
      \pgfarrowshullpoint{-.5\pgfarrowlinewidth}{-.5\pgfarrowlinewidth}%
    \fi
    % The following are needed in the code:
    \pgfarrowssavethe\pgfarrowlinewidth
    \pgfarrowssavethe\pgfarrowlength
    \pgfarrowssavethe\pgfarrowwidth
  },
  drawing code = {
    \pgfsetdash{}{+0pt}
    \ifpgfarrowroundjoin\pgfsetroundjoin\else\pgfsetmiterjoin\fi
    \ifpgfarrowroundcap\pgfsetroundcap\else\pgfsetbuttcap\fi
    \ifdim\pgfarrowlinewidth=\pgflinewidth\else\pgfsetlinewidth{+\pgfarrowlinewidth}\fi
    \pgfpathmoveto{\pgfqpoint{0pt}{.5\pgfarrowwidth}}
    \pgfpathlineto{\pgfqpoint{\pgfarrowlength}{0pt}}
    \ifpgfarrowharpoon
      \pgfpathlineto{\pgfqpoint{\pgfarrowlength\advance\pgf@x by\ifpgfarrowreversed\else-\fi\pgfarrowlinewidth}{0pt}}
    \else
      \pgfpathlineto{\pgfqpoint{0pt}{-.5\pgfarrowwidth}}
    \fi
    \pgfusepathqstroke
  },
  parameters = {
    \the\pgfarrowlinewidth,%
    \the\pgfarrowlength,%
    \the\pgfarrowwidth,%
    \ifpgfarrowharpoon h\fi%
    \ifpgfarrowroundjoin j\fi%
    \ifpgfarrowroundcap c\fi%
  },
}



% Hooks are barbs that consist of an arc going forward from the line
% end and curving back by a given angle speficied using the |arc|
% key.

\pgfkeys{
  /pgf/arrow keys/.cd,
  arc/.code={%
    \pgfmathparse{#1}%
    \expandafter\pgfarrowsaddtooptions\expandafter{\expandafter\def\expandafter\pgfarrowarc\expandafter{\pgfmathresult}}
  }
}

\def\pgfarrowarc{180}

\pgfdeclarearrow{
  name = Hooks,
  defaults = {
    length = +0.75pt 1.25,
    width'  = +0pt 4 -1,
    line width = +0pt 1 1,
  },
  setup code = {
    \ifpgfarrowharpoon
      \pgfarrowshullpoint{.5\pgfarrowlength}{-.5\pgfarrowlinewidth}
      \pgfarrowshullpoint{\pgfarrowlength}{-.5\pgfarrowlinewidth\advance\pgf@y by.125\pgfarrowwidth}
    \fi
    \ifdim\pgfarrowarc pt<90.1pt
      \pgfarrowsupperhullpoint{0pt}{.25\pgfarrowwidth\ifpgfarrowroundcap\else\advance\pgf@y by-.25\pgfarrowlinewidth\fi}
      \pgfarrowsupperhullpoint{\pgfarrowlength}{.25\pgfarrowwidth\ifpgfarrowroundcap\else\advance\pgf@y by-.25\pgfarrowlinewidth\fi}
    \else%
      \pgfarrowsupperhullpoint{\pgfarrowlength}{.375\pgfarrowwidth}
      \pgfarrowsupperhullpoint{.5\pgfarrowlength}{.5\pgfarrowwidth}
      \ifdim\pgfarrowarc pt>180pt
        \pgfarrowsupperhullpoint{-.5\pgfarrowlength}{.5\pgfarrowwidth}
        \pgfarrowsupperhullpoint{-\pgfarrowlength}{.375\pgfarrowwidth}
        \pgfarrowsupperhullpoint{-\pgfarrowlength}{.25\pgfarrowwidth}
      \else
        \pgfarrowsupperhullpoint{\ifpgfarrowroundcap-.5\pgfarrowlinewidth\else0pt\fi}{.25\pgfarrowwidth}
        \pgfarrowsupperhullpoint{\ifpgfarrowroundcap-.5\pgfarrowlinewidth\else0pt\fi}{.5\pgfarrowwidth}      
      \fi
    \fi
    % Adjust width and length: Take line thickness into account:
    \advance\pgfarrowlength by-.5\pgfarrowlinewidth
    \advance\pgfarrowwidth by-\pgfarrowlinewidth
    \ifpgfarrowreversed
      \ifpgfarrowroundjoin
        \pgfarrowssetbackend{-.5\pgfarrowlinewidth}
      \fi
    \fi
    % There are four different intervals for the values of
    % \pgfarrowsarc that give rise to four different settings of tip
    % ends and so on:
    % 
    % Case 1: 0 <= Angle < 90 
    % 
    \ifdim\pgfarrowarc pt<90pt%
      % Tip end is given by sin(pgfarrowarc)*length
      \pgfmathsin@{\pgfarrowarc}
      \pgfarrowssettipend{\pgfmathresult\pgfarrowlength\advance\pgf@x by.5\pgfarrowlinewidth}%
    \else\ifdim\pgfarrowarc pt<180pt%
      \pgfarrowssettipend{\pgfarrowlength\advance\pgf@x by.5\pgfarrowlinewidth}%
      \ifpgfarrowroundcap\pgfarrowssetbackend{-.5\pgfarrowlinewidth}\fi%
    \else\ifdim\pgfarrowarc pt<270pt%
      \pgfarrowssettipend{\pgfarrowlength\advance\pgf@x by.5\pgfarrowlinewidth}%
      \ifdim\pgfarrowarc pt>180pt
        % Back end is given by sin(pgfarrowarc)*length
        \pgfmathsin@{\pgfarrowarc}
        \pgfarrowssetbackend{\pgfmathresult\pgfarrowlength\advance\pgf@x by-.5\pgfarrowlinewidth}%
      \else
        \ifpgfarrowroundcap\pgfarrowssetbackend{-.5\pgfarrowlinewidth}\fi%
      \fi%
    \else%  
      \pgfarrowssettipend{\pgfarrowlength\advance\pgf@x by.5\pgfarrowlinewidth}%
      \pgfarrowssetbackend{-\pgfarrowlength\advance\pgf@x by-.5\pgfarrowlinewidth}%
    \fi\fi\fi%
    \ifpgfarrowreversed
      \pgfarrowssetlineend{.5\pgfarrowlinewidth}
    \else%
      \ifpgfarrowharpoon
        \pgfarrowssetlineend{0pt}
      \else 
        \pgfarrowssetlineend{.25\pgfarrowlinewidth}
      \fi
    \fi
    % Adjust arc:
    \pgf@x\pgfarrowarc pt%
    \advance\pgf@x by-90pt%
    \edef\pgfarrowarc{\pgf@sys@tonumber\pgf@x}%    
    % The following are needed in the code:
    \pgfarrowssavethe\pgfarrowlinewidth
    \pgfarrowssavethe\pgfarrowlength
    \pgfarrowssavethe\pgfarrowwidth
    \pgfarrowssave\pgfarrowarc
  },
  drawing code = {
    \pgfsetdash{}{+0pt}
    \ifpgfarrowroundjoin\pgfsetroundjoin\else\pgfsetmiterjoin\fi
    \ifpgfarrowroundcap\pgfsetroundcap\else\pgfsetbuttcap\fi
    \ifdim\pgfarrowlinewidth=\pgflinewidth\else\pgfsetlinewidth{+\pgfarrowlinewidth}\fi
    {%
      \pgftransformxscale{+\pgfarrowlength}
      \pgftransformyscale{+.25\pgfarrowwidth}
      \pgfpathmoveto{\pgfpointpolar{+\pgfarrowarc}{+1pt}\advance\pgf@y by1pt}
      \pgfpatharc{\pgfarrowarc}{+-90}{+1pt}
      \ifpgfarrowharpoon
      \else
        \pgfpatharc{+90}{+-\pgfarrowarc}{+1pt}
      \fi
    }
    \ifpgfarrowharpoon\ifpgfarrowreversed
    \pgfpathlineto{\pgfqpoint{\pgflinewidth}{0pt}}
    \fi\fi
    \pgfusepathqstroke
  },
  parameters = {
    \the\pgfarrowlinewidth,%
    \the\pgfarrowlength,%
    \the\pgfarrowwidth,%
    \pgfarrowarc,%
    \ifpgfarrowharpoon h\fi%
    \ifpgfarrowroundjoin j\fi%
    \ifpgfarrowroundcap c\fi%
  },
}


\pgfdeclarearrow{
  name = Arc Barb,
  defaults = {
    length = +1.5pt 2,
    width'  = +0pt 2,
    line width = +0pt 1 1,
  },
  setup code = {
    % Adjust arc:
    \pgf@x\pgfarrowarc pt%
    \pgf@x.5\pgf@x%
    \edef\pgfarrowarc{\pgf@sys@tonumber\pgf@x}%
    % The tips:
    \pgfarrowssettipend{\pgfarrowlength}
    \pgfarrowssetvisualbackend{\pgfarrowlength}
    \pgfarrowssetlineend{\pgfarrowlength\advance\pgf@x by-.5\pgfarrowlinewidth}
    % The hull:
    \pgfarrowsupperhullpoint{\pgfarrowlength}{.25\pgfarrowwidth}
    \ifpgfarrowharpoon\pgfarrowshullpoint{\pgfarrowlength}{-.5\pgflinewidth}\fi
    \pgfmathsincos@{\pgfarrowarc}%
    \pgf@xa.5\pgfarrowwidth%
    \pgfarrowsupperhullpoint{\pgfmathresultx\pgfarrowlength}{\pgfmathresulty\pgf@xa}
    \ifdim\pgfarrowarc pt>60pt
      \pgfarrowsupperhullpoint{.5\pgfarrowlength}{\ifdim\pgfarrowarc pt<90pt\pgfmathresulty\pgf@xa\else.5\pgfarrowwidth\fi}
    \fi
    \ifdim\pgfarrowarc pt>90pt
      \ifdim\pgfarrowarc pt<120pt
        \pgfarrowsupperhullpoint{\pgfmathresultx\pgfarrowlength}{.5\pgfarrowwidth}
      \else  
        \pgfarrowsupperhullpoint{-.5\pgfarrowlength}{.5\pgfarrowwidth}
        \ifdim\pgfarrowarc pt>150pt
          \pgfarrowsupperhullpoint{-\pgfarrowlength}{.25\pgfarrowwidth}
        \fi
      \fi
    \fi
    \pgfutil@tempswafalse
    \ifdim\pgfarrowarc pt<90pt
      \pgfutil@tempswatrue
    \fi
    \ifpgfarrowharpoon
      \pgfutil@tempswatrue
    \fi
    \ifpgfutil@tempswa  
      \pgf@xa.5\pgfarrowwidth\advance\pgf@xa by-\pgfarrowlinewidth%
      \pgf@ya\pgfarrowlength\advance\pgf@ya by-\pgfarrowlinewidth%
      \pgfarrowsupperhullpoint{\pgfmathresultx\pgf@ya}{\pgfmathresulty\pgf@xa}
    \fi
    % Compute back end
    \ifpgfarrowroundcap
      \pgf@y\pgfarrowlength
      \advance\pgf@y by-.5\pgfarrowlinewidth
      \pgf@x\pgfmathresultx\pgf@y%
    \else
      \ifdim\pgfarrowarc pt<90pt
        \pgf@y\pgfarrowlength
        \advance\pgf@y by-\pgfarrowlinewidth
        \pgf@x\pgfmathresultx\pgf@y%
      \else
        \pgf@x\pgfmathresultx\pgfarrowlength%
      \fi
    \fi
    \pgfarrowssetbackend{\pgf@x\ifpgfarrowroundcap\advance\pgf@x by-.5\pgfarrowlinewidth\fi}
    % Adjust width and length: Take line thickness into account:
    \advance\pgfarrowlength by-.5\pgfarrowlinewidth
    \advance\pgfarrowwidth by-\pgfarrowlinewidth
    % The following are needed in the code:
    \pgfarrowssavethe\pgfarrowlinewidth
    \pgfarrowssavethe\pgfarrowlength
    \pgfarrowssavethe\pgfarrowwidth
    \pgfarrowssave\pgfarrowarc
  },
  drawing code = {
    \pgfsetdash{}{+0pt}
    \ifpgfarrowroundcap\pgfsetroundcap\else\pgfsetbuttcap\fi
    \ifpgfarrowroundjoin\pgfsetroundjoin\else\pgfsetmiterjoin\fi
    \ifdim\pgfarrowlinewidth=\pgflinewidth\else\pgfsetlinewidth{+\pgfarrowlinewidth}\fi
    {%
      \pgftransformxscale{+\pgfarrowlength}
      \pgftransformyscale{+.5\pgfarrowwidth}
      \pgfpathmoveto{\pgfpointpolar{+\pgfarrowarc}{+1pt}}
      \ifpgfarrowharpoon
        \pgfpatharc{+\pgfarrowarc}{0pt}{+1pt}
      \else
        \pgfpatharc{+\pgfarrowarc}{+-\pgfarrowarc}{+1pt}
      \fi
    }
    \ifpgfarrowharpoon
      \pgfpathlineto{\pgfqpoint{\pgfarrowlength\advance\pgf@x by\ifpgfarrowreversed\else-\fi.5\pgflinewidth}{0pt}}
    \fi
    \pgfusepathqstroke
  },
  parameters = {
    \the\pgfarrowlinewidth,%
    \the\pgfarrowlength,%
    \the\pgfarrowwidth,%
    \pgfarrowarc,%
    \ifpgfarrowharpoon h\fi%
    \ifpgfarrowroundcap c\fi%
    \ifpgfarrowroundjoin j\fi%
  },
}



% Tee Barb are barb arrows heads that look like a T

\pgfdeclarearrow{
  name = Tee Barb,
  defaults = {
    length = +1.5pt 2,
    width = +3pt 4,
    inset' = +0pt .5,
    line width = +0pt 1 1,
  },
  bending mode=polar,
  setup code = {
    % Two useful numbers... 
    \pgfutil@tempswafalse%
    \pgfutil@tempswbfalse%
    \pgfutil@tempdima\pgfarrowlength\advance\pgfutil@tempdima by-\pgfarrowinset\ifdim\pgfutil@tempdima<.5\pgfarrowlinewidth\pgfutil@tempdima.5\pgfarrowlinewidth\pgfutil@tempswatrue\fi%
    \pgfutil@tempdimb-\pgfarrowinset\ifdim\pgfutil@tempdimb>-.5\pgfarrowlinewidth\pgfutil@tempdimb-.5\pgfarrowlinewidth\pgfutil@tempswbtrue\fi
    % The following are needed in the code:
    \pgfarrowssavethe\pgfarrowwidth
    \pgfarrowssavethe\pgfutil@tempdima
    \pgfarrowssavethe\pgfutil@tempdimb
    % Infos:
    \pgfarrowssettipend{\pgfutil@tempdima\ifpgfarrowroundcap\ifpgfutil@tempswa\else\advance\pgf@x by.5\pgfarrowlinewidth\fi\fi}
    \pgfarrowssetvisualbackend{.5\pgfarrowlinewidth}
    \pgfarrowssetbackend{\pgfutil@tempdimb\ifpgfarrowroundcap\ifpgfutil@tempswb\else\advance\pgf@x by-.5\pgfarrowlinewidth\fi\fi}
    \pgfarrowssetlineend{\ifpgfarrowreversed\else-\fi.25\pgfarrowlinewidth}%
    % The hull:
    \pgfarrowsupperhullpoint{\pgfutil@tempdima\ifpgfarrowroundcap\ifpgfutil@tempswa\else\advance\pgf@x by.5\pgfarrowlinewidth\fi\fi}{.5\pgfarrowwidth}%
    \pgfarrowsupperhullpoint{\pgfutil@tempdimb\ifpgfarrowroundcap\ifpgfutil@tempswb\else\advance\pgf@x by-.5\pgfarrowlinewidth\fi\fi}{.5\pgfarrowwidth}%
    \ifpgfarrowharpoon
      \pgfarrowshullpoint{.5\pgfarrowlinewidth}{-.5\pgfarrowlinewidth}%
    \fi
  },
  drawing code = {
    \pgfsetdash{}{+0pt}
    \pgf@yc\pgflinewidth% save...
    \ifdim\pgflinewidth=\pgfarrowlinewidth\else\pgfsetlinewidth{+\pgfarrowlinewidth}\fi
    \ifpgfarrowroundcap\pgfsetroundcap\else\pgfsetbuttcap\fi
    \ifpgfarrowroundjoin\pgfsetroundjoin\else\pgfsetmiterjoin\fi
    \pgf@x\pgfutil@tempdima\advance\pgf@x by-.5\pgfarrowlinewidth%
    \pgf@y\pgfutil@tempdimb\advance\pgf@y by.5\pgfarrowlinewidth%
    % Case 1: No bar atop the I:
    \ifdim\pgf@x=\pgf@y%
      \pgfpathmoveto{\pgfqpoint{0pt}{.5\pgfarrowwidth}}
      \pgfpathlineto{\pgfqpoint{0pt}{\ifpgfarrowharpoon-.5\pgfarrowlinewidth\else-.5\pgfarrowwidth\fi}}
    \else
      % Case 2: Bar, but only in one direction:
      \ifdim\pgfutil@tempdima=.5\pgfarrowlinewidth%
        \pgfpathmoveto{\pgfqpoint{\pgfutil@tempdimb}{.5\pgfarrowwidth\advance\pgf@y by-.5\pgfarrowlinewidth}}
        \pgfpathlineto{\pgfqpoint{0pt}{.5\pgfarrowwidth\advance\pgf@y by-.5\pgfarrowlinewidth}}
        \ifpgfarrowharpoon%
          \pgfpathlineto{\pgfqpoint{0pt}{-.5\pgf@yc}}%
        \else%
          \pgfpathlineto{\pgfqpoint{0pt}{-.5\pgfarrowwidth\advance\pgf@y by.5\pgfarrowlinewidth}}
          \pgfpathlineto{\pgfqpoint{\pgfutil@tempdimb}{-.5\pgfarrowwidth\advance\pgf@y by.5\pgfarrowlinewidth}}
        \fi
      \else% Case 3: Complete I:
        \pgfpathmoveto{\pgfqpoint{\pgfutil@tempdimb}{.5\pgfarrowwidth\advance\pgf@y by-.5\pgfarrowlinewidth}}
        \pgfpathlineto{\pgfqpoint{\pgfutil@tempdima}{.5\pgfarrowwidth\advance\pgf@y by-.5\pgfarrowlinewidth}}
        \pgfpathmoveto{\pgfqpoint{0pt}{.5\pgfarrowwidth\advance\pgf@y by-.5\pgfarrowlinewidth}}
        \ifpgfarrowharpoon%
          \pgfpathlineto{\pgfqpoint{0pt}{-.5\pgf@yc}}%
        \else%
          \pgfpathlineto{\pgfqpoint{0pt}{-.5\pgfarrowwidth\advance\pgf@y by.5\pgfarrowlinewidth}}
          \pgfpathmoveto{\pgfqpoint{\pgfutil@tempdimb}{-.5\pgfarrowwidth\advance\pgf@y by.5\pgfarrowlinewidth}}
          \pgfpathlineto{\pgfqpoint{\pgfutil@tempdima}{-.5\pgfarrowwidth\advance\pgf@y by.5\pgfarrowlinewidth}}
        \fi
      \fi
    \fi
    \pgfusepathqstroke
  },
  parameters = {
    \the\pgfarrowwidth,%
    \the\pgfarrowlength,%
    \the\pgfarrowinset,%
    \the\pgfarrowlinewidth,%
    \ifpgfarrowharpoon h\fi%
    \ifpgfarrowroundjoin j\fi%
    \ifpgfarrowroundcap c\fi%
  },
}


% Math barbs that resemble \rightarrow in different fonts:



% The original default arrow head used in TikZ. It is modeled on an
% old version of the \rightarrow head of the *old* Computer Modern
% fonts. 

\pgfdeclarearrow{
  name = Classical TikZ Rightarrow,
  defaults = {
    length  = +1.05pt 1.925,
    width'  = +0pt 1.9237,
    line width = 0pt 0.8 1,
    round
  },
  setup code = 
  {
    \ifpgfarrowharpoon\pgfarrowroundjointrue\fi
    % inner length:
    \pgfutil@tempdima\pgfarrowlength
    \advance\pgfutil@tempdima by-\pgfarrowlinewidth
    \pgfutil@tempdimb\pgfarrowwidth
    \advance\pgfutil@tempdimb by-\pgfarrowlinewidth
    \ifpgfarrowroundjoin%
    \else%
      \pgfmathdivide@\pgfutil@tempdima\pgfutil@tempdimb%
      \let\pgf@temp@quot\pgfmathresult%
      \pgf@x\pgfmathresult pt%
      \pgf@x\pgfmathresult\pgf@x%
      \pgf@x40.96\pgf@x%
      \advance\pgf@x by1pt%  \pgflinewidth^2 + (6.4 \pgftempdim@a / \pgfutil@tempdimb) \pgflinewidth^2
      \pgfmathsqrt@\pgf@x%
      \pgf@xc\pgfmathresult\pgfarrowlinewidth% xc is front miter
      \pgf@xc.5\pgf@xc
    \fi%
     % The following are needed in the code:
    \pgfarrowssavethe\pgfutil@tempdima
    \pgfarrowssavethe\pgfutil@tempdimb
    % The extend:
    \pgfarrowssettipend{\pgfutil@tempdima\ifpgfarrowroundjoin\advance\pgf@x by.5\pgfarrowlinewidth\else\advance\pgf@x by\pgf@xc\fi}%
    \pgfarrowssetvisualbackend{\pgfutil@tempdima\advance\pgf@x by.5\pgfarrowlinewidth}%
    \ifpgfarrowreversed%
      \ifpgfarrowharpoon%
        % A reversed arrow needs a slightly different line end:
        \pgfarrowssetlineend{\pgfutil@tempdima\advance\pgf@x by.5\pgflinewidth}%
      \else%
        % A reversed arrow needs a slightly different line end:
        \pgfarrowssetlineend{\pgfutil@tempdima\advance\pgf@x by-.25\pgflinewidth}%
      \fi%
    \else%
      \pgfarrowssetlineend{\pgfutil@tempdima\advance\pgf@x by-.6\pgflinewidth}%
    \fi%
    \pgfarrowssetbackend{-.5\pgfarrowlinewidth}%
    % The hull:
    %  Tip:
    \pgfarrowshullpoint{\pgfutil@tempdima\ifpgfarrowroundjoin\advance\pgf@x by.5\pgfarrowlinewidth\else\advance\pgf@x by\pgf@xc\fi}{.5\pgfarrowlinewidth}%
    \pgfarrowshullpoint{\pgfutil@tempdima\ifpgfarrowroundjoin\advance\pgf@x by.5\pgfarrowlinewidth\else\advance\pgf@x by\pgf@xc\fi}{-.5\pgfarrowlinewidth}%
    %  Upper end:
    \pgfarrowsupperhullpoint{.5\pgfarrowlinewidth}{.5\pgfutil@tempdimb\advance\pgf@y by.5\pgfarrowlinewidth}%
    \pgfarrowsupperhullpoint{-.5\pgfarrowlinewidth}{.5\pgfutil@tempdimb\advance\pgf@y by.5\pgfarrowlinewidth}%
    %  Lower end:
    \ifpgfarrowharpoon
      \pgfarrowshullpoint{\pgfutil@tempdima\advance\pgf@x by-\pgflinewidth}{-.5\pgflinewidth}%    
      \pgfarrowshullpoint{-.5\pgfarrowlinewidth}{.5\pgfutil@tempdimb\advance\pgf@y by-.5\pgflinewidth}%
    \fi
  },
  drawing code = 
  {
    \pgfsetdash{}{+0pt}
    \edef\pgf@orig@linewidth{\the\pgflinewidth}
    \ifdim\pgfarrowlinewidth=\pgflinewidth\else\pgfsetlinewidth{+\pgfarrowlinewidth}\fi
    \ifpgfarrowharpoon\pgfarrowroundjointrue\fi
    \ifpgfarrowroundcap\pgfsetroundcap\else\pgfsetbuttcap\fi
    \ifpgfarrowroundjoin\pgfsetroundjoin\else\pgfsetmiterjoin\fi
    \pgfpathmoveto
          {\pgfqpoint{0pt}{.5\pgfutil@tempdimb}}
    \ifpgfarrowharpoon
      \pgf@arrows@old@tikz@harpoon
    \else
      \pgfpathcurveto
          {\pgfqpoint{0.066666\pgfutil@tempdima}{0.3125\pgfutil@tempdimb}}
          {\pgfqpoint{.8\pgfutil@tempdima}{0.03125\pgfutil@tempdimb}}
          {\pgfqpoint{\pgfutil@tempdima}{0pt}} 
      \pgfpathcurveto
          {\pgfqpoint{.8\pgfutil@tempdima}{-.03125\pgfutil@tempdimb}}
          {\pgfqpoint{0.066666\pgfutil@tempdima}{-.3125\pgfutil@tempdimb}}
          {\pgfqpoint{0pt}{-.5\pgfutil@tempdimb}}
      \pgfsetlinewidth{+\pgfarrowlinewidth}
      \pgfusepathqstroke
    \fi
  },
  parameters = {
    \the\pgfarrowlinewidth,%
    \the\pgfarrowlength,%
    \the\pgfarrowwidth,%
    \ifpgfarrowharpoon h\fi%
    \ifpgfarrowroundjoin j\fi%
    \ifpgfarrowroundcap c\fi%
  },
}

\def\pgf@arrows@old@tikz@harpoon{
  \ifpgfarrowreversed
    \pgf@arrows@old@tikz@harpoon@reversed
  \else
    \pgfpathcurveto
      {\pgfqpoint{0.066666\pgfutil@tempdima}{0.3125\pgfutil@tempdimb}}
      {\pgfqpoint{.8\pgfutil@tempdima}{0.03125\pgfutil@tempdimb}}
      {\pgfqpoint{\pgfutil@tempdima}{0pt}}
    \pgfpathcurveto
      {\pgfqpoint{0.95\pgfutil@tempdima}{-0.125\pgflinewidth}}
      {\pgfqpoint{0.933333\pgfutil@tempdima}{-0.125\pgflinewidth}}
      {\pgfqpoint{0.933333\pgfutil@tempdima}{-0.125\pgflinewidth}}
    \pgfpathlineto
      {\pgfqpoint{0.8\pgfutil@tempdima\advance\pgf@x by-.5\pgflinewidth}{-0.125\pgflinewidth}}
    \pgfusepathqstroke
  \fi
}
\def\pgf@arrows@old@tikz@harpoon@reversed{
    \pgfpathcurveto
      {\pgfqpoint{0.066666\pgfutil@tempdima}{0.3125\pgfutil@tempdimb}}
      {\pgfqpoint{.8\pgfutil@tempdima}{0.03125\pgfutil@tempdimb}}
      {\pgfqpoint{\pgfutil@tempdima}{0.125\pgflinewidth}}
    \pgfpathmoveto
      {\pgfqpoint{0pt}{.5\pgfutil@tempdimb}}
    \pgfpathcurveto
      {\pgfqpoint{0.066666\pgfutil@tempdima}{0.3125\pgfutil@tempdimb}}
      {\pgfqpoint{.8\pgfutil@tempdima}{0.03125\pgfutil@tempdimb}}
      {\pgfqpoint{\pgfutil@tempdima}{-0.125\pgflinewidth}}
    \pgfusepathqstroke
    \pgfsetlinewidth{+\pgf@orig@linewidth}
    \pgfsetroundcap
    \pgfpathmoveto{\pgfqpoint{\pgfutil@tempdima\advance\pgf@x by0.6\pgflinewidth}{0pt}}
    \pgfpathlineto{\pgfqpoint{\pgfutil@tempdima}{0pt}}
    \pgfusepathqstroke
}


% An approximation to the new (past 1992) Computer Modern math arrow
% heads. This would be a better version of "to", so consider saying
% to/.tips=Computer Modern Rightarrow

\pgfdeclarearrow{
  name = Computer Modern Rightarrow,
  defaults = {
    length = +1.6pt 2.2, % 0pt 5.2
    width' = +0pt 2.096774,
    line width = 0pt 1 1,
    round
  },
  setup code = 
  {
    % inner length:
    \pgfutil@tempdima\pgfarrowlength
    \advance\pgfutil@tempdima by-\pgfarrowlinewidth
    \pgfutil@tempdimb\pgfarrowwidth
    \advance\pgfutil@tempdimb by-\pgfarrowlinewidth
    % The following are needed in the code:
    \pgfarrowssavethe\pgfutil@tempdima
    \pgfarrowssavethe\pgfutil@tempdimb
    % Front miter:
    \ifpgfarrowroundjoin%
    \else%
      \pgfmathdivide@\pgfutil@tempdima\pgfutil@tempdimb%
      \let\pgf@temp@quot\pgfmathresult%
      \pgf@x\pgfmathresult pt%
      \pgf@x\pgfmathresult\pgf@x%
      \pgf@x49.44662\pgf@x%
      \advance\pgf@x by1pt%  \pgfarrowlinewidth^2 + (0.41019/0.0583333 \pgftempdim@a / \pgfutil@tempdimb) \pgfarrowlinewidth^2
      \pgfmathsqrt@\pgf@x%
      \pgf@xc\pgfmathresult\pgfarrowlinewidth% xc is front miter
      \pgf@xc.5\pgf@xc
      \pgf@xa\pgf@temp@quot\pgfarrowlinewidth% xa is extra harpoon miter
      \pgf@xa3.51591\pgf@xa% xa is extra harpoon miter
    \fi%
    % The extend:
    \pgfarrowssettipend{\ifpgfarrowroundjoin.5\pgfarrowlinewidth\else\pgf@xc\ifpgfarrowharpoon\advance\pgf@x by\pgf@xa\fi\fi}%
    \pgfarrowssetvisualbackend{.5\pgfarrowlinewidth}%
    \ifpgfarrowreversed%
      \ifpgfarrowharpoon%
        \pgfarrowssetlineend{.5\pgfarrowlinewidth}%
      \else%
        \pgfarrowssetlineend{-.5\pgfarrowlinewidth}%
      \fi%
    \else%
      \pgfarrowssetlineend{-.5\pgfarrowlinewidth}%
    \fi%
    \pgfarrowssetbackend{-\pgfutil@tempdima\advance\pgf@x by-.5\pgfarrowlinewidth}%
    % The hull:
    %  Tip:
    \pgfarrowshullpoint{\ifpgfarrowroundjoin.5\pgfarrowlinewidth\else\pgf@xc\ifpgfarrowharpoon\advance\pgf@x by\pgf@xa\fi\fi}{.5\pgfarrowlinewidth}%
    \pgfarrowshullpoint{\ifpgfarrowroundjoin.5\pgfarrowlinewidth\else\pgf@xc\ifpgfarrowharpoon\advance\pgf@x by\pgf@xa\fi\fi}{-.5\pgfarrowlinewidth}%
    %  Upper end:
    \pgfarrowsupperhullpoint{-\pgfutil@tempdima\advance\pgf@x by.5\pgfarrowlinewidth}{.5\pgfutil@tempdimb\advance\pgf@y by.5\pgfarrowlinewidth}%
    \pgfarrowsupperhullpoint{-\pgfutil@tempdima\advance\pgf@x by-.5\pgfarrowlinewidth}{.5\pgfutil@tempdimb\advance\pgf@y by.5\pgfarrowlinewidth}%
    %  Lower end:
    \ifpgfarrowharpoon
      \pgfarrowshullpoint{-\pgfarrowlinewidth}{-.5\pgfarrowlinewidth}%    
      \pgfarrowshullpoint{-\pgfutil@tempdima\advance\pgf@x by-.5\pgfarrowlinewidth}{.5\pgfutil@tempdimb\advance\pgf@y by-.5\pgfarrowlinewidth}%
    \fi
  },
  drawing code = 
  {
    \pgfsetdash{}{+0pt}
    \ifpgfarrowroundcap\pgfsetroundcap\else\pgfsetbuttcap\fi
    \ifpgfarrowroundjoin\pgfsetroundjoin\else\pgfsetmiterjoin\fi
    \ifdim\pgfarrowlinewidth=\pgflinewidth\else\pgfsetlinewidth{+\pgfarrowlinewidth}\fi
    \pgfpathmoveto
        {\pgfqpoint{-\pgfutil@tempdima}{.5\pgfutil@tempdimb}}
    \pgfpathcurveto
        {\pgfqpoint{-0.81731\pgfutil@tempdima}{.2\pgfutil@tempdimb}}
        {\pgfqpoint{-0.41019\pgfutil@tempdima}{0.05833333\pgfutil@tempdimb}}
        {\pgfpointorigin}
    \ifpgfarrowharpoon
      \pgfpathlineto
        {\pgfqpoint{\ifpgfarrowreversed.5\else-\fi\pgfarrowlinewidth}{0pt}}
    \else    
      \pgfpathcurveto
        {\pgfqpoint{-0.41019\pgfutil@tempdima}{-0.05833333\pgfutil@tempdimb}}
        {\pgfqpoint{-0.81731\pgfutil@tempdima}{-.2\pgfutil@tempdimb}}
        {\pgfqpoint{-\pgfutil@tempdima}{-.5\pgfutil@tempdimb}}
    \fi
    \pgfusepathqstroke
  },
  parameters = {
    \the\pgfarrowlinewidth,%
    \the\pgfarrowlength,%
    \the\pgfarrowwidth,%
    \ifpgfarrowharpoon h\fi
    \ifpgfarrowharpoon r\fi
    \ifpgfarrowroundjoin j\fi%
    \ifpgfarrowroundcap c\fi%
  },
}



% The arrow tip of an \implies arrow, to be used with an inner
% line. Cannot be configured otherwise.

\pgfdeclarearrow{
  name = Implies,
  setup code = {
    \pgf@xa\pgfinnerlinewidth
    \pgfutil@tempdima.25\pgflinewidth
    \advance\pgfutil@tempdima by.25\pgf@xa%
    \pgfutil@tempdimb.5\pgflinewidth
    \advance\pgfutil@tempdimb by-.5\pgf@xa%
    \pgfarrowssettipend{2.06\pgfutil@tempdima\advance\pgf@x by.5\pgfutil@tempdimb}
    \pgfarrowssetbackend{-1.36\pgfutil@tempdima\advance\pgf@x by.5\pgfutil@tempdimb}
    \pgfarrowsupperhullpoint{-1.4\pgfutil@tempdima}{2.8\pgfutil@tempdima}
    \pgfarrowsupperhullpoint{2\pgfutil@tempdima}{.5\pgfutil@tempdimb}
    \pgfarrowssavethe\pgfutil@tempdima
    \pgfarrowssavethe\pgfutil@tempdimb
  },
  drawing code = {
    \pgftransformxshift{.06\pgfutil@tempdima}
    \pgfsetlinewidth{\pgfutil@tempdimb}
    \pgfsetdash{}{+0pt}
    \pgfsetroundcap
    \pgfsetroundjoin
    \pgfpathmoveto{\pgfpoint{-1.4\pgfutil@tempdima}{2.65\pgfutil@tempdima}}
    \pgfpathcurveto
    {\pgfpoint{-0.75\pgfutil@tempdima}{1.25\pgfutil@tempdima}}
    {\pgfpoint{1\pgfutil@tempdima}{0.05\pgfutil@tempdima}}
    {\pgfpoint{2\pgfutil@tempdima}{0pt}}
    \pgfpathcurveto
    {\pgfpoint{1\pgfutil@tempdima}{-0.05\pgfutil@tempdima}}
    {\pgfpoint{-.75\pgfutil@tempdima}{-1.25\pgfutil@tempdima}}
    {\pgfpoint{-1.4\pgfutil@tempdima}{-2.65\pgfutil@tempdima}}
    \pgfusepathqstroke
  },
  parameters = {\the\pgfarrowlength}
}




%
%
% Geomatric arrow tips
%
%


% Generic "latex-like" arrow tip. This is the basic arrow tip used in
% latex's picture environment. You can configure its length and width.  

\pgfdeclarearrow{
  name = Latex,
  defaults = {
    length  = +3pt 4.5 .8,% +2.8pt 3 0.8,
    width' = +0pt .75,
    line width = +0pt 1 1,
  },
  setup code = {
    % Cap the line width at 1/4th distance from inset to tip
    \pgf@x.2\pgfarrowlength
    \ifdim\pgf@x<\pgfarrowlinewidth
      \pgfarrowlinewidth\pgf@x
    \fi
    \pgfarrowssavethe\pgfarrowlinewidth%
    % Compute front miter length:
    \pgfmathdivide@\pgfarrowlength\pgfarrowwidth%
    \let\pgf@temp@quot\pgfmathresult%
    \pgf@x\pgfmathresult pt%
    \pgf@x\pgfmathresult\pgf@x%
    \pgf@x9\pgf@x%
    \advance\pgf@x by1pt%
    \pgfmathsqrt@\pgf@x%
    \pgf@xc\pgfmathresult\pgfarrowlinewidth%
    \pgf@xa\pgf@temp@quot\pgfarrowlinewidth
    % Inner length (pgfutil@tempdima) is now arrowlength - front miter
    % - 0.5 linewidth (back thickness)
    \pgfutil@tempdima\pgfarrowlength%
    \advance\pgfutil@tempdima by-.5\pgf@xc%
    \advance\pgfutil@tempdima by-.5\pgfarrowlinewidth%
    % harpoon miter correction
    \pgfarrowssetbackend{-.5\pgfarrowlinewidth}
    \ifpgfarrowreversed
      \ifdim\pgfinnerlinewidth>0pt
        \pgfarrowssetlineend{0pt}
      \else
        \pgfarrowssetlineend{\pgfutil@tempdima\advance\pgf@x by-.5\pgflinewidth}
      \fi
    \else
      \pgfarrowssetlineend{0pt}
    \fi
    \ifpgfarrowroundjoin
      \pgfarrowssettipend{\pgfutil@tempdima\advance\pgf@x by.5\pgfarrowlinewidth}    
    \else
      \pgfarrowssettipend{\pgfarrowlength\advance\pgf@x by-.5\pgfarrowlinewidth\ifpgfarrowharpoon\advance\pgf@x  by1.5\pgf@xa\fi}
    \fi
    % The following are needed in the code:
    \pgfarrowssavethe\pgfutil@tempdima
    % Now, compute back tip miter limit:
    \pgf@process{\pgfpointnormalised{\pgfqpoint{.3\pgfarrowlength}{.2333333\pgfarrowwidth}}}%
    \advance\pgf@y by1pt%
    \pgf@yc\pgf@y\pgf@xc\pgf@x%
    \pgfmathdivide@\pgf@yc\pgf@xc%
    \pgfutil@tempdimb\pgfmathresult\pgfarrowlinewidth%
    \pgfutil@tempdimb-.5\pgfutil@tempdimb%
    \advance\pgfutil@tempdimb by.5\pgfarrowwidth%
    \pgfarrowssavethe\pgfutil@tempdimb%
    % The hull:
    \pgfarrowshullpoint{\pgfarrowlength\advance\pgf@x by-.5\pgfarrowlinewidth\ifpgfarrowroundjoin\else\ifpgfarrowharpoon\advance\pgf@x  by1.5\pgf@xa\fi\fi}{\ifpgfarrowharpoon-.5\pgfarrowlinewidth\else0pt\fi}%
    \pgfarrowshullpoint{-.5\pgfarrowlinewidth}{.5\pgfarrowwidth\ifpgfarrowharpoon\advance\pgf@y by-.5\pgfarrowlinewidth\fi}%
    \pgfarrowshullpoint{-.5\pgfarrowlinewidth}{\ifpgfarrowharpoon-.5\pgfarrowlinewidth\else-.5\pgfarrowwidth\fi}%
  },
  drawing code = {
    \pgfsetdash{}{+0pt}
    \ifpgfarrowroundjoin\pgfsetroundjoin\else\pgfsetmiterjoin\fi
    \ifdim\pgfarrowlinewidth=\pgflinewidth\else\pgfsetlinewidth{+\pgfarrowlinewidth}\fi
    \pgfpathmoveto    {\pgfqpoint{\pgfutil@tempdima}{0pt}}
    \pgfpathcurveto   {\pgfqpoint{.877192\pgfutil@tempdima}{.077922\pgfutil@tempdimb}}
                      {\pgfqpoint{.337381\pgfutil@tempdima}{.519480\pgfutil@tempdimb}}
                      {\pgfqpoint{0pt}{\pgfutil@tempdimb}}
    \ifpgfarrowharpoon
      \pgfpathlineto  {\pgfpointorigin}
    \else  
      \pgfpathlineto  {\pgfqpoint{0pt}{-\pgfutil@tempdimb}}
      \pgfpathcurveto {\pgfqpoint{.337381\pgfutil@tempdima}{-.519480\pgfutil@tempdimb}}
                      {\pgfqpoint{.877192\pgfutil@tempdima}{-.077922\pgfutil@tempdimb}}
                      {\pgfqpoint{\pgfutil@tempdima}{0pt}}
    \fi
    \pgfpathclose
    \ifpgfarrowopen\pgfusepathqstroke\else\ifdim\pgfarrowlinewidth>0pt\pgfusepathqfillstroke\else\pgfusepathqfill\fi\fi
  },
  parameters = {
    \the\pgfarrowlinewidth,%
    \the\pgfarrowlength,%
    \the\pgfarrowwidth,%
    \ifpgfarrowharpoon h\fi%
    \ifpgfarrowopen o\fi%
    \ifpgfarrowroundjoin j\fi%
  },
}



% A basic stealth-fighter-like pointed arrow

\pgfdeclarearrow{
  name = Stealth,
  defaults = {
    length  = +3pt 4.5 .8,
    width'  = +0pt .75,
    inset'  = +0pt 0.325,
    line width = +0pt 1 1,
  },
  setup code = {
    % Cap the line width at 1/4th distance from inset to tip
    \pgf@x\pgfarrowlength
    \advance\pgf@x by-\pgfarrowinset
    \pgf@x.25\pgf@x
    \ifdim\pgf@x<\pgfarrowlinewidth
      \pgfarrowlinewidth\pgf@x
    \fi
    % Compute front miter length:
    \pgfmathdivide@\pgfarrowlength\pgfarrowwidth%
    \let\pgf@temp@quot\pgfmathresult%
    \pgf@x\pgfmathresult pt%
    \pgf@x\pgfmathresult\pgf@x%
    \pgf@x4\pgf@x%
    \advance\pgf@x by1pt%
    \pgfmathsqrt@\pgf@x%
    \pgf@xc\pgfmathresult\pgfarrowlinewidth% xc is front miter
    \pgf@xc.5\pgf@xc
    \pgf@xa\pgf@temp@quot\pgfarrowlinewidth% xa is extra harpoon miter
    % Compute back miter length:
    \pgf@ya.5\pgfarrowwidth%
    \csname pgfmathatan2@\endcsname{\pgfmath@tonumber\pgfarrowlength}{\pgfmath@tonumber\pgf@ya}%
    \pgf@yb\pgfmathresult pt%
    \csname pgfmathatan2@\endcsname{\pgfmath@tonumber\pgfarrowinset}{\pgfmath@tonumber\pgf@ya}%
    \pgf@ya\pgfmathresult pt%
    \advance\pgf@yb by-\pgf@ya%
    \pgf@yb.5\pgf@yb% half angle in yb
    \pgfmathtan@{\pgf@yb}%
    \pgfmathreciprocal@{\pgfmathresult}%
    \pgf@yc\pgfmathresult\pgfarrowlinewidth%
    \pgf@yc.5\pgf@yc%
    \advance\pgf@ya by\pgf@yb%
    \pgfmathsincos@{\pgf@ya}%
    \pgf@ya\pgfmathresulty\pgf@yc% ya is the back miter
    \pgf@yb\pgfmathresultx\pgf@yc% yb is the top miter
    \ifdim\pgfarrowinset=0pt%
      \pgf@ya.5\pgfarrowlinewidth% easy: back miter is half linewidth
    \fi
    % Compute inset miter length:
    \pgfmathdivide@\pgfarrowinset\pgfarrowwidth%
    \let\pgf@temp@quot\pgfmathresult%
    \pgf@x\pgfmathresult pt%
    \pgf@x\pgfmathresult\pgf@x%
    \pgf@x4\pgf@x%
    \advance\pgf@x by1pt%
    \pgfmathsqrt@\pgf@x%
    \pgf@yc\pgfmathresult\pgfarrowlinewidth% yc is inset miter
    \pgf@yc.5\pgf@yc% 
    % Inner length (pgfutil@tempdima) is now arrowlength - front miter - back miter
    \pgfutil@tempdima\pgfarrowlength%
    \advance\pgfutil@tempdima by-\pgf@xc%
    \advance\pgfutil@tempdima by-\pgf@ya%
    \pgfutil@tempdimb.5\pgfarrowwidth%
    \advance\pgfutil@tempdimb by-\pgf@yb%
    % harpoon miter correction
    \ifpgfarrowroundjoin
      \pgfarrowssetbackend{\pgf@ya\advance\pgf@x by-.5\pgfarrowlinewidth}    
    \else
      \pgfarrowssetbackend{0pt}
    \fi
    \ifpgfarrowharpoon
      \pgfarrowssetlineend{\pgfarrowinset\advance\pgf@x
        by\pgf@yc\advance\pgf@x by.5\pgfarrowlinewidth}
    \else
      \pgfarrowssetlineend{\pgfarrowinset\advance\pgf@x by\pgf@yc\advance\pgf@x by-.25\pgfarrowlinewidth}
      \ifpgfarrowreversed
        \ifdim\pgfinnerlinewidth>0pt
          \pgfarrowssetlineend{\pgfarrowinset}
        \else
          \pgfarrowssetlineend{\pgfutil@tempdima\advance\pgf@x by\pgf@ya\advance\pgf@x by-.25\pgfarrowlinewidth}
        \fi
      \fi
    \fi
    \ifpgfarrowroundjoin
      \pgfarrowssettipend{\pgfutil@tempdima\advance\pgf@x by\pgf@ya\advance\pgf@x by.5\pgfarrowlinewidth}    
    \else
      \pgfarrowssettipend{\pgfarrowlength\ifpgfarrowharpoon\advance\pgf@x by\pgf@xa\fi}
    \fi
    % The hull:
    \pgfarrowshullpoint{\pgfarrowlength\ifpgfarrowroundjoin\else\ifpgfarrowharpoon\advance\pgf@x by\pgf@xa\fi\fi}{\ifpgfarrowharpoon-.5\pgfarrowlinewidth\else0pt\fi}%
    \pgfarrowsupperhullpoint{0pt}{.5\pgfarrowwidth}%
    \pgfarrowshullpoint{\pgfarrowinset}{\ifpgfarrowharpoon-.5\pgfarrowlinewidth\else 0pt\fi}%
    % Adjust inset
    \pgfarrowssetvisualbackend{\pgfarrowinset}
    \advance\pgfarrowinset by\pgf@yc%
    % The following are needed in the code:
    \pgfarrowssavethe\pgfutil@tempdima
    \pgfarrowssavethe\pgfutil@tempdimb
    \pgfarrowssavethe\pgfarrowlinewidth
    \pgfarrowssavethe\pgf@ya
    \pgfarrowssavethe\pgfarrowinset
  },
  drawing code = {
    \pgfsetdash{}{+0pt}
    \ifpgfarrowroundjoin\pgfsetroundjoin\else\pgfsetmiterjoin\fi
    \ifdim\pgfarrowlinewidth=\pgflinewidth\else\pgfsetlinewidth{+\pgfarrowlinewidth}\fi
    \pgfpathmoveto{\pgfqpoint{\pgfutil@tempdima\advance\pgf@x by\pgf@ya}{0pt}}
    \pgfpathlineto{\pgfqpoint{\pgf@ya}{\pgfutil@tempdimb}}
    \pgfpathlineto{\pgfqpoint{\pgfarrowinset}{0pt}}
    \ifpgfarrowharpoon \else
    \pgfpathlineto{\pgfqpoint{\pgf@ya}{-\pgfutil@tempdimb}}
    \fi
    \pgfpathclose
    \ifpgfarrowopen\pgfusepathqstroke\else\ifdim\pgfarrowlinewidth>0pt\pgfusepathqfillstroke\else\pgfusepathqfill\fi\fi
  },
  parameters = {
    \the\pgfarrowlinewidth,%
    \the\pgfarrowlength,%
    \the\pgfarrowwidth,%
    \the\pgfarrowinset,%
    \ifpgfarrowharpoon h\fi%
    \ifpgfarrowopen o\fi%
    \ifpgfarrowroundjoin j\fi%
  },
}



% A Kite is like a Stealth, only the inset counts in the other direction

\pgfdeclarearrow{
  name = Kite,
  defaults = {
    length  = +3.6pt +5.4,
    width'  = +0pt +0.5,   
    inset'  = +0pt 0.25,
    line width = +0pt 1 1,
  },
  setup code = {
    % Cap the line width at 1/4th of the length
    \pgf@x.4\pgfarrowlength
    \ifdim\pgf@x<\pgfarrowlinewidth
      \pgfarrowlinewidth\pgf@x
    \fi
    \pgf@x.4\pgfarrowwidth
    \ifdim\pgf@x<\pgfarrowlinewidth
      \pgfarrowlinewidth\pgf@x
    \fi
    % Compute front miter length:
    \pgf@xa\pgfarrowlength%
    \advance\pgf@xa by-\pgfarrowinset%
    \pgfmathdivide@\pgf@xa\pgfarrowwidth%
    \let\pgf@temp@quot\pgfmathresult%
    \pgf@x\pgfmathresult pt%
    \pgf@x\pgfmathresult\pgf@x%
    \pgf@x4\pgf@x%
    \advance\pgf@x by1pt%
    \pgfmathsqrt@\pgf@x%
    \pgf@xc\pgfmathresult\pgfarrowlinewidth% xc is front miter
    \pgf@xc.5\pgf@xc
    \pgf@xa\pgf@temp@quot\pgfarrowlinewidth% xa is extra harpoon miter
    % Compute back miter length:
    \pgfmathdivide@\pgfarrowinset\pgfarrowwidth%
    \let\pgf@temp@quot\pgfmathresult%
    \pgf@x\pgfmathresult pt%
    \pgf@x\pgfmathresult\pgf@x%
    \pgf@x4\pgf@x%
    \advance\pgf@x by1pt%
    \pgfmathsqrt@\pgf@x%
    \pgf@yc\pgfmathresult\pgfarrowlinewidth% yc is back miter
    \pgf@yc.5\pgf@yc
    \pgf@ya\pgf@temp@quot\pgfarrowlinewidth% ya is extra harpoon miter
    % Compute top miter length:
    {%
      \pgfutil@tempdimb.5\pgfarrowwidth%
      \pgfutil@tempdima\pgfarrowlength\advance\pgfutil@tempdima by-\pgfarrowinset%
      \csname pgfmathatan2@\endcsname{\pgfmath@tonumber\pgfutil@tempdima}{\pgfmath@tonumber\pgfutil@tempdimb}%
      \pgf@yb\pgfmathresult pt%
      \csname pgfmathatan2@\endcsname{\pgfmath@tonumber\pgfarrowinset}{\pgfmath@tonumber\pgfutil@tempdimb}%
      \pgf@ya\pgfmathresult pt%
      \advance\pgf@yb by\pgf@ya%
      \pgf@yb.5\pgf@yb% half angle in yb
      \ifdim\pgf@yb=45pt%
        \def\pgfmathresult{1.414213}%
      \else%
        \pgfmathsin@{\pgf@yb}%
        \pgfmathreciprocal@{\pgfmathresult}%
      \fi%
      \pgf@yc\pgfmathresult\pgfarrowlinewidth%
      \pgf@yc.5\pgf@yc%
      \pgf@ya-\pgf@ya%
      \advance\pgf@ya by-90pt%
      \advance\pgf@ya by\pgf@yb%
      \pgfmathsincos@{\pgf@ya}%
      \pgf@xb\pgfmathresultx\pgf@yc% ya is the back miter
      \pgf@yb\pgfmathresulty\pgf@yc% yb is the top miter
      \expandafter\expandafter\expandafter%
    }\expandafter\expandafter\expandafter\pgf@xb\expandafter\the\expandafter\pgf@xb\expandafter\pgf@yb\the\pgf@yb%
    % Inner length (pgfutil@tempdima) is now arrowlength - front miter - back miter
    \pgfutil@tempdima\pgfarrowlength%
    \advance\pgfutil@tempdima by-\pgf@xc%
    \pgfutil@tempdimb.5\pgfarrowwidth%
    \advance\pgfutil@tempdimb by\pgf@yb%
    % Set back end
    \ifpgfarrowroundjoin
      \pgfarrowssetbackend{\pgf@ya\advance\pgf@x by-.5\pgfarrowlinewidth}    
    \else
      \pgfarrowssetbackend{0pt}
    \fi
    % harpoon miter correction
    \ifpgfarrowreversed
      \pgfarrowssetlineend{\pgfutil@tempdima\advance\pgf@x by-\pgflinewidth\advance\pgf@x by\pgfarrowlinewidth}
    \else
      \pgfarrowssetlineend{\pgf@yc\advance\pgf@x by\pgflinewidth\advance\pgf@x by-\pgfarrowlinewidth}
    \fi
    \ifpgfarrowroundjoin
      \pgfarrowssettipend{\pgfutil@tempdima\advance\pgf@x by.5\pgfarrowlinewidth}    
    \else
      \pgfarrowssettipend{\pgfarrowlength\ifpgfarrowharpoon\advance\pgf@x by\pgf@xa\fi}
    \fi
    % The hull:
    \pgfarrowshullpoint{\pgfarrowlength\ifpgfarrowroundjoin\else\ifpgfarrowharpoon\advance\pgf@x by\pgf@xa\fi\fi}{\ifpgfarrowharpoon-.5\pgfarrowlinewidth\else0pt\fi}%
    \pgfarrowsupperhullpoint{\pgfarrowinset}{.5\pgfarrowwidth}%
    \pgfarrowshullpoint{0pt}{\ifpgfarrowharpoon-.5\pgfarrowlinewidth\else0pt\fi}%
    % Adjust the inset:
    \advance\pgfarrowinset by\pgf@xb%
    % The following are needed in the code:
    \pgfarrowssavethe\pgfutil@tempdima
    \pgfarrowssavethe\pgfutil@tempdimb
    \pgfarrowssavethe\pgfarrowlinewidth
    \pgfarrowssavethe\pgf@yc
    \pgfarrowssavethe\pgfarrowinset
  },
  drawing code = {
    \pgfsetdash{}{+0pt}
    \ifpgfarrowroundjoin\pgfsetroundjoin\else\pgfsetmiterjoin\fi
    \ifdim\pgfarrowlinewidth=\pgflinewidth\else\pgfsetlinewidth{\pgfarrowlinewidth}\fi
    \pgfpathmoveto{\pgfqpoint{\pgfutil@tempdima}{0pt}}
    \pgfpathlineto{\pgfqpoint{\pgfarrowinset}{\pgfutil@tempdimb}}
    \pgfpathlineto{\pgfqpoint{\pgf@yc}{0pt}}
    \ifpgfarrowharpoon \else
    \pgfpathlineto{\pgfqpoint{\pgfarrowinset}{-\pgfutil@tempdimb}}
    \fi
    \pgfpathclose
    \ifpgfarrowopen\pgfusepathqstroke\else\ifdim\pgfarrowlinewidth>0pt\pgfusepathqfillstroke\else\pgfusepathqfill\fi\fi
  },
  parameters = {
    \the\pgfarrowlinewidth,%
    \the\pgfarrowlength,%
    \the\pgfarrowwidth,%
    \the\pgfarrowinset,%
    \ifpgfarrowharpoon h\fi%
    \ifpgfarrowopen o\fi%
    \ifpgfarrowroundjoin j\fi%
  },
}




% A simple rectangle shape

\pgfdeclarearrow{
  name = Square,
  defaults = {
    length  = +2.12132pt +2.828427,
    width'  = +0pt +1,
    line width = +0pt +1 +1,
  },
  setup code = {
    % Cap the line width at 1/2th of the length
    \pgf@x.5\pgfarrowlength
    \ifdim\pgf@x<\pgfarrowlinewidth
      \pgfarrowlinewidth\pgf@x
    \fi
    \ifpgfarrowreversed
      \pgfarrowssetlineend{\pgfarrowlength\advance\pgf@x by-.5\pgfarrowlinewidth}
    \else
      \pgfarrowssetlineend{.5\pgfarrowlinewidth}
    \fi
    \pgfarrowssettipend{\pgfarrowlength}
    % The hull:
    \pgfarrowshullpoint{\pgfarrowlength}{.5\pgfarrowwidth}
    \pgfarrowshullpoint{0pt}{.5\pgfarrowwidth}
    \pgfarrowshullpoint{\pgfarrowlength}{\ifpgfarrowharpoon-.5\pgfarrowlinewidth\else-.5\pgfarrowwidth\fi}
    \pgfarrowshullpoint{0pt}{\ifpgfarrowharpoon-.5\pgfarrowlinewidth\else-.5\pgfarrowwidth\fi}
    % The following are needed in the code:
    \pgfarrowssavethe\pgfarrowlinewidth
    \pgfarrowssavethe\pgfarrowlength
    \pgfarrowssavethe\pgfarrowwidth
  },
  drawing code = {
    \pgfsetdash{}{+0pt}
    \ifpgfarrowroundjoin\pgfsetroundjoin\else\pgfsetmiterjoin\fi
    \ifdim\pgfarrowlinewidth=\pgflinewidth\else\pgfsetlinewidth{+\pgfarrowlinewidth}\fi
    \pgfpathmoveto{\pgfqpoint{\pgfarrowlength\advance\pgf@x by-.5\pgfarrowlinewidth}{.5\pgfarrowwidth\advance\pgf@y by-.5\pgfarrowlinewidth}}
    \pgfpathlineto{\pgfqpoint{.5\pgfarrowlinewidth}{.5\pgfarrowwidth\advance\pgf@y by-.5\pgfarrowlinewidth}}
    \pgfpathlineto{\pgfqpoint{.5\pgfarrowlinewidth}{\ifpgfarrowharpoon0pt\else-.5\pgfarrowwidth\advance\pgf@y by.5\pgfarrowlinewidth\fi}}
    \pgfpathlineto{\pgfqpoint{\pgfarrowlength\advance\pgf@x by-.5\pgfarrowlinewidth}{\ifpgfarrowharpoon0pt\else-.5\pgfarrowwidth\advance\pgf@y by.5\pgfarrowlinewidth\fi}}
    \pgfpathclose
    \ifpgfarrowopen\pgfusepathqstroke\else\ifdim\pgfarrowlinewidth>0pt\pgfusepathqfillstroke\else\pgfusepathqfill\fi\fi
  },
  parameters = {
    \the\pgfarrowlinewidth,%
    \the\pgfarrowlength,%
    \the\pgfarrowwidth,%
    \ifpgfarrowharpoon h\fi%
    \ifpgfarrowopen o\fi%
    \ifpgfarrowroundjoin j\fi%
  },
}


% A simple rectangle shape

\pgfdeclarearrow{
  name = Circle,
  defaults = {
    length  = +2.39365pt +3.191538,
    width'  = +0pt 1,
    line width = +0pt 1 1,
  },
  setup code = {
    % Cap the line width at 1/2th of the length
    \pgf@x.5\pgfarrowlength
    \ifdim\pgf@x<\pgfarrowlinewidth
      \pgfarrowlinewidth\pgf@x
    \fi
    \ifpgfarrowreversed
      \pgfarrowssetlineend{\pgfarrowlength\advance\pgf@x by-.5\pgfarrowlinewidth}
    \else
      \pgfarrowssetlineend{.5\pgfarrowlinewidth}
    \fi
    \pgfarrowssettipend{\pgfarrowlength}
    % The hull:
    \pgfarrowsupperhullpoint{\pgfarrowlength}{.25\pgfarrowwidth}
    \pgfarrowsupperhullpoint{.75\pgfarrowlength}{.5\pgfarrowwidth}
    \pgfarrowsupperhullpoint{.25\pgfarrowlength}{.5\pgfarrowwidth}
    \pgfarrowsupperhullpoint{0pt}{.25\pgfarrowwidth}
    \ifpgfarrowharpoon%
      \pgfarrowshullpoint{0pt}{-.5\pgfarrowlinewidth}
      \pgfarrowshullpoint{\pgfarrowlength}{-.5\pgfarrowlinewidth}
    \fi%
    % The following are needed in the code:
    \pgfarrowssavethe\pgfarrowlinewidth
    \pgfarrowssavethe\pgfarrowlength
    \pgfarrowssavethe\pgfarrowwidth
  },
  drawing code = {
    \pgfsetdash{}{+0pt}
    \ifpgfarrowroundjoin\pgfsetroundjoin\else\pgfsetmiterjoin\fi
    \ifdim\pgfarrowlinewidth=\pgflinewidth\else\pgfsetlinewidth{+\pgfarrowlinewidth}\fi
    \ifpgfarrowharpoon
      \pgfpathmoveto{\pgfqpoint{\pgfarrowlength\advance\pgf@x
          by-.5\pgfarrowlinewidth}{0pt}}
      {%
        \pgf@xa.5\pgfarrowlength
        \advance\pgf@xa by-.5\pgfarrowlinewidth
        \pgftransformxscale{+\the\pgf@xa}
        \pgf@xa.5\pgfarrowwidth
        \advance\pgf@xa by-.5\pgfarrowlinewidth
        \pgftransformyscale{+\the\pgf@xa}
        \pgfpatharc{0}{180}{1pt}
      }
      \pgfpathclose
    \else%
      \pgfpathellipse{\pgfqpoint{.5\pgfarrowlength}{0pt}}{\pgfqpoint{.5\pgfarrowlength\advance\pgf@x
          by-.5\pgfarrowlinewidth}{0pt}}{\pgfqpoint{0pt}{.5\pgfarrowwidth\advance\pgf@y
          by-.5\pgfarrowlinewidth}}
    \fi
    \ifpgfarrowopen\pgfusepathqstroke\else\ifdim\pgfarrowlinewidth>0pt\pgfusepathqfillstroke\else\pgfusepathqfill\fi\fi
  },
  parameters = {
    \the\pgfarrowlinewidth,%
    \the\pgfarrowlength,%
    \the\pgfarrowwidth,%
    \ifpgfarrowharpoon h\fi%
    \ifpgfarrowopen o\fi%
    \ifpgfarrowroundjoin j\fi%
  },
}

% Round cap

\pgfdeclarearrow{
  name = Round Cap,
  defaults = {
    length = +0pt .5
  },
  setup code = {
    \ifpgfarrowreversed
      \pgfarrowssettipend{\pgfarrowlength}
      \pgfarrowssetlineend{\pgfarrowlength\advance\pgf@x by.5\pgflinewidth}
    \else
      \pgfarrowssettipend{\pgfarrowlength}
      \pgfarrowssetlineend{-.5\pgflinewidth}
    \fi
    \pgfarrowssavethe\pgfarrowlength
    \pgfarrowsupperhullpoint{0pt}{.5\pgflinewidth}
    \pgfarrowsupperhullpoint{\pgfarrowlength}{.5\pgflinewidth}
  },
  drawing code = {
    \ifpgfarrowreversed
      \pgftransformxscale{-1}
      \pgftransformxshift{-\pgfarrowlength}
    \fi
    \pgfutil@tempdima.5\pgflinewidth
    \pgfpathmoveto   {\pgfqpoint{-0.75\pgflinewidth}{\pgfutil@tempdima}}
    \pgfpathlineto   {\pgfqpoint{0pt}{\pgfutil@tempdima}}
    \ifpgfarrowreversed
      \pgfpathlineto {\pgfqpoint{\pgfarrowlength}{\pgfutil@tempdima}}
      \begingroup
      \pgftransformxshift{\pgfarrowlength}
      \pgftransformxscale{-1}
    \fi
    \pgfpathcurveto  {\pgfqpoint{0.55228475\pgfarrowlength}{\pgfutil@tempdima}}
                     {\pgfqpoint{\pgfarrowlength}{0.55228475\pgfutil@tempdima}}
                     {\pgfqpoint{\pgfarrowlength}{0pt}}
    \pgfpathcurveto  {\pgfqpoint{\pgfarrowlength}{-0.55228475\pgfutil@tempdima}}
                     {\pgfqpoint{0.55228475\pgfarrowlength}{-\pgfutil@tempdima}}
                     {\pgfqpoint{0pt}{-\pgfutil@tempdima}}
    \ifpgfarrowreversed
      \endgroup
    \fi
    \pgfpathlineto   {\pgfqpoint{-.75\pgflinewidth}{-\pgfutil@tempdima}}
    \pgfpathclose
    \pgfusepathqfill
  },
  parameters = {\the\pgfarrowlength}
}



\pgfdeclarearrow{
  name = Butt Cap,
  defaults = {
    length = +0pt .5
  },
  setup code = {
    \pgfarrowssettipend{\pgfarrowlength}
    \pgfarrowssetlineend{-.5\pgflinewidth}
    \pgfarrowssavethe\pgfarrowlength
    \pgfarrowsupperhullpoint{0pt}{.5\pgflinewidth}
    \pgfarrowsupperhullpoint{\pgfarrowlength}{.5\pgflinewidth}
  },
  drawing code = {
    \pgfutil@tempdima.5\pgflinewidth
    \pgfpathmoveto   {\pgfqpoint{-0.75\pgflinewidth}{\pgfutil@tempdima}}
    \pgfpathlineto   {\pgfqpoint{0pt}{\pgfutil@tempdima}}
    \pgfpathlineto   {\pgfqpoint{\pgfarrowlength}{\pgfutil@tempdima}}
    \pgfpathlineto   {\pgfqpoint{\pgfarrowlength}{-\pgfutil@tempdima}}
    \pgfpathlineto   {\pgfqpoint{-.75\pgflinewidth}{-\pgfutil@tempdima}}
    \pgfpathclose
    \pgfusepathqfill
  },
  parameters = {\the\pgfarrowlength}
}



\pgfkeys{
  /pgf/arrow keys/.cd,
  cap angle/.code={%
    \pgfmathsetlength\pgf@x{#1}%
    \pgf@x.5\pgf@x
    \pgfmathtan@{\pgf@x}%
    \pgfmathreciprocal@{\pgfmathresult}%
    \pgf@x\pgfmathresult pt%
    \pgf@x.5\pgf@x%
    \edef\pgf@marshal{\noexpand\pgfarrowsaddtooptions{\noexpand\pgfarrowslinewidthdependent{+0pt}{\pgf@sys@tonumber\pgf@x}{0}\pgfarrowlength\pgf@x}}
    \pgf@marshal
  }
}


\pgfdeclarearrow{
  name = Triangle Cap,
  defaults = {
    length = +0pt .5
  },
  setup code = {
    \ifpgfarrowreversed
      \pgfarrowssettipend{\pgfarrowlength}
      \pgfarrowssetlineend{\pgfarrowlength\advance\pgf@x by.5\pgflinewidth}
    \else
      \pgfarrowssettipend{\pgfarrowlength}
      \pgfarrowssetlineend{-.5\pgflinewidth}
    \fi
    \pgfarrowssavethe\pgfarrowlength
    \pgfarrowsupperhullpoint{0pt}{.5\pgflinewidth}
    \pgfarrowshullpoint{\pgfarrowlength}{0pt}
  },
  drawing code = {
    \ifpgfarrowreversed
      \pgftransformxscale{-1}
      \pgftransformxshift{-\pgfarrowlength}
    \fi
    \pgfutil@tempdima.5\pgflinewidth
    \pgfpathmoveto   {\pgfqpoint{-0.75\pgflinewidth}{\pgfutil@tempdima}}
    \pgfpathlineto   {\pgfqpoint{0pt}{\pgfutil@tempdima}}
    \ifpgfarrowreversed
      \pgfpathlineto {\pgfqpoint{\pgfarrowlength}{\pgfutil@tempdima}}
      \begingroup
      \pgftransformxshift{\pgfarrowlength}
      \pgftransformxscale{-1}
    \fi
    \pgfpathlineto   {\pgfqpoint{\pgfarrowlength}{0pt}}
    \ifpgfarrowreversed
      \endgroup
      \pgfpathlineto {\pgfqpoint{\pgfarrowlength}{-\pgfutil@tempdima}}
    \fi
    \pgfpathlineto   {\pgfqpoint{0pt}{-\pgfutil@tempdima}}
    \pgfpathlineto   {\pgfqpoint{-.75\pgflinewidth}{-\pgfutil@tempdima}}
    \pgfpathclose
    \pgfusepathqfill
  },
  parameters = {\the\pgfarrowlength}
}



\pgfdeclarearrow{
  name = Fast Triangle,
  defaults = {
    length = +0pt .5,
    inset = +0pt .5,
  },
  setup code = {
    \pgfarrowssettipend{\pgfarrowlength\advance\pgf@x by\pgfarrowinset}
    \ifpgfarrowreversed\pgfarrowssetlineend{\pgfarrowlength\advance\pgf@x by\pgfarrowinset}\fi
    \pgfarrowssavethe\pgfarrowlength
    \pgfarrowssavethe\pgfarrowinset
    \pgfarrowsupperhullpoint{0pt}{.5\pgflinewidth}
    \pgfarrowsupperhullpoint{\pgfarrowinset}{.5\pgflinewidth}
    \pgfarrowshullpoint{\pgfarrowlength\advance\pgf@x by\pgfarrowinset}{0pt}
  },
  drawing code = {
    \pgfutil@tempdima.5\pgflinewidth
    \pgfpathmoveto   {\pgfqpoint{0pt}{\pgfutil@tempdima}}
    \pgfpathlineto   {\pgfqpoint{\pgfarrowinset}{\pgfutil@tempdima}}
    \pgfpathlineto   {\pgfqpoint{\pgfarrowinset\advance\pgf@x by\pgfarrowlength}{0pt}}
    \pgfpathlineto   {\pgfqpoint{\pgfarrowinset}{-\pgfutil@tempdima}}
    \pgfpathlineto   {\pgfqpoint{0pt}{-\pgfutil@tempdima}}
    \pgfpathlineto   {\pgfqpoint{\pgfarrowlength}{0pt}}
    \pgfpathclose
    \pgfusepathqfill
  },
  parameters = {\the\pgfarrowlength,\the\pgfarrowinset}
}


\pgfdeclarearrow{
  name = Fast Round,
  defaults = {
    length = +0pt .5,
    inset = +0pt .5,
  },
  setup code = {
    \pgfarrowssettipend{\pgfarrowlength\advance\pgf@x by\pgfarrowinset}
    \ifpgfarrowreversed\pgfarrowssetlineend{\pgfarrowlength\advance\pgf@x by\pgfarrowinset}\fi
    \pgfarrowssavethe\pgfarrowlength
    \pgfarrowssavethe\pgfarrowinset
    \pgfarrowsupperhullpoint{0pt}{.5\pgflinewidth}
    \pgfarrowsupperhullpoint{\pgfarrowlength\advance\pgf@x by\pgfarrowinset}{.5\pgflinewidth}
  },
  drawing code = {
    \pgfutil@tempdima.5\pgflinewidth
    \pgfpathmoveto   {\pgfqpoint{0pt}{\pgfutil@tempdima}}
    \pgfpathlineto   {\pgfqpoint{\pgfarrowinset}{\pgfutil@tempdima}}
    {
      \pgftransformxshift{\pgfarrowinset}
      \pgfpathcurveto{\pgfqpoint{0.55228475\pgfarrowlength}{\pgfutil@tempdima}}
                     {\pgfqpoint{\pgfarrowlength}{0.55228475\pgfutil@tempdima}}
                     {\pgfqpoint{\pgfarrowlength}{0pt}}
      \pgfpathcurveto{\pgfqpoint{\pgfarrowlength}{-0.55228475\pgfutil@tempdima}}
                     {\pgfqpoint{0.55228475\pgfarrowlength}{-\pgfutil@tempdima}}
                     {\pgfqpoint{0pt}{-\pgfutil@tempdima}}
    }
    \pgfpathlineto   {\pgfqpoint{0pt}{-\pgfutil@tempdima}}
    \pgfpathcurveto  {\pgfqpoint{0.55228475\pgfarrowlength}{-\pgfutil@tempdima}}
                     {\pgfqpoint{\pgfarrowlength}{-0.55228475\pgfutil@tempdima}}
                     {\pgfqpoint{\pgfarrowlength}{0pt}}
    \pgfpathcurveto  {\pgfqpoint{\pgfarrowlength}{0.55228475\pgfutil@tempdima}}
                     {\pgfqpoint{0.55228475\pgfarrowlength}{\pgfutil@tempdima}}
                     {\pgfqpoint{0pt}{\pgfutil@tempdima}}
    \pgfpathclose
    \pgfusepathqfill
  },
  parameters = {\the\pgfarrowlength,\the\pgfarrowinset}
}




%
%
% Other arrow tips.
%
%


\pgfkeys{
  /pgf/arrow keys/.cd,
  n/.code={%
    \pgfmathparse{#1}%
    \expandafter\pgf@lib@meta@strip@dot\pgfmathresult.\relax%
  }
}
\def\pgf@lib@meta@strip@dot#1.#2\relax{%
  \pgfarrowsaddtooptions{\def\pgfarrown{#1}}%
}

\def\pgfarrown{4}

\pgfdeclarearrow{
  name = Rays,
  defaults = {
    length = +3pt 4,
    width'  = +0pt 1,
    line width = +0pt 1 1,
  },
  setup code = {
    \pgfmathdivide@{360}{\pgfarrown}%
    \let\pgfarrow@inc\pgfmathresult%
    % Compute tips:
    \pgf@xa\pgfarrow@inc pt%
    \ifodd\pgfarrown\pgf@ya.25\pgf@xa\else\pgf@ya.5\pgf@xa\fi%
    \pgfmathsincos@\pgf@ya%
    \pgf@x.5\pgfarrowlength%    
    \pgf@xa\pgfmathresultx\pgf@x%
    \ifpgfarrowroundcap
      \advance\pgf@xa by.5\pgfarrowlinewidth
    \else
      \pgf@process{\pgfpointnormalised{\pgfqpoint{\pgfmathresultx\pgfarrowlength}{\pgfmathresulty\pgfarrowwidth}}}%
      \pgf@x.5\pgfarrowlinewidth%
      \advance\pgf@xa by\pgf@sys@tonumber{\pgf@y}\pgf@x%
    \fi%
    \pgfarrowssettipend{\pgf@xa}
    \pgfarrowssetbackend{-\pgf@xa}
    % Hull is alwyas 8-point hull, except for tip
    % The following are needed in the code:
    \pgfarrowsupperhullpoint{\pgf@xa}{.25\pgfarrowwidth}
    \pgfarrowsupperhullpoint{.25\pgfarrowlength}{.5\pgfarrowwidth\ifpgfarrowroundcap\advance\pgf@y by.5\pgfarrowlinewidth\fi}
    \pgfarrowsupperhullpoint{-.25\pgfarrowlength}{.5\pgfarrowwidth\ifpgfarrowroundcap\advance\pgf@y by.5\pgfarrowlinewidth\fi}
    \pgfarrowsupperhullpoint{-\pgf@xa}{.25\pgfarrowwidth}
    \ifpgfarrowharpoon
      \pgfarrowshullpoint{-.5\pgfarrowlength\ifpgfarrowroundcap\advance\pgf@x by-.5\pgfarrowlinewidth\fi}{-.5\pgfarrowlinewidth}
      \pgfarrowshullpoint{.5\pgfarrowlength\ifpgfarrowroundcap\advance\pgf@x by.5\pgfarrowlinewidth\fi}{-.5\pgfarrowlinewidth}
    \fi
    \pgfarrowssavethe\pgfarrowlinewidth
    \pgfarrowssavethe\pgfarrowlength
    \pgfarrowssavethe\pgfarrowwidth
    \pgfarrowssave\pgfarrow@inc
    \pgfarrowssave\pgfarrown
  },
  drawing code = {
    \pgfsetdash{}{+0pt}
    \ifpgfarrowroundcap\pgfsetroundcap\else\pgfsetbuttcap\fi
    \ifdim\pgfarrowlinewidth=\pgflinewidth\else\pgfsetlinewidth{+\pgfarrowlinewidth}\fi
    {%
      \pgfgettransform\pgf@temp@trans
      \pgftransformxscale{+.5\pgfarrowlength}
      \pgftransformyscale{+.5\pgfarrowwidth}
      \pgf@xa\pgfarrow@inc pt%
      \ifodd\pgfarrown\pgf@ya.25\pgf@xa\else\pgf@ya.5\pgf@xa\fi%
      \ifpgfarrowharpoon\pgf@yb180pt\else\pgf@yb360pt\fi
      \pgfutil@loop%
      \ifdim\pgf@ya<\pgf@yb%
        \pgfpathmoveto{\pgfpointpolar{+\pgf@ya}{+1pt}}
        \pgfpathlineto{\pgfpointorigin}
        \ifpgfarrowharpoon\ifdim\pgf@ya>\pgf@xa\else{\pgfsettransform\pgf@temp@trans\pgfpathlineto{\pgfqpoint{-.5\pgflinewidth}{0pt}}}\fi\fi
        \advance\pgf@ya by\pgf@xa\relax%
      \pgfutil@repeat%  
    }
    \pgfusepathqstroke
  },
  parameters = {
    \the\pgfarrowlinewidth,%
    \the\pgfarrowlength,%
    \the\pgfarrowwidth,%
    \pgfarrown,%
    \ifpgfarrowharpoon h\fi%
    \ifpgfarrowroundcap c\fi%
  }
}



% Shorthands and Aliases:

\pgfkeys{
  LaTeX /.tip         = {Latex},
  Triangle /.tip      = {Stealth[inset=+0pt, angle=+60:+2.7pt +3.6]},
  Rectangle /.tip     = {Square[length=+3pt +4.5,width'=+0pt +.5]},
  Ellipse /.tip       = {Circle[length=+3.3pt +4.95, width'=+0pt +0.5]},
  Diamond /.tip       = {Kite[inset'=+0pt .5]},
  Turned Square /.tip = {Kite[length=+3pt 4,width'= +0pt 1,inset'= +0pt 0.5]},
  To /.tip            = {Computer Modern Rightarrow},
  Bar /.tip           = {Tee Barb[length=+0pt]},
  Bracket /.tip       = {Tee Barb[inset'=+0pt +1,length=+0.75pt +1]},
  Parenthesis /.tip   = {Arc Barb[arc=+120,length=+1.725pt +2.3]}
}




\endinput

pgflibraryarrows.spaced.code.tex
% Copyright 2012 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/pgflibraryarrows.spaced.code.tex,v 1.3 2013/09/23 18:04:36 tantau Exp $


\usepgflibrary{arrows}


% This library offers "spaced" versions of existing arrows, where a
% bit of additional space is inserted at the tip. This often looks
% better than the normal arrow.
%
% These arrows are called "spaced whatever" where "whatever" is the
% original name of the arrow.


\pgfarrowsdeclarecombine*{spaced to}{spaced to}{to}{to}{space}{space}
\pgfarrowsdeclarecombine*{spaced to reversed}{spaced to reversed}{to reversed}{to reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced implies}{spaced implies}{implies}{implies}{space}{space}
\pgfarrowsdeclarecombine*{spaced latex}{spaced latex}{latex}{latex}{space}{space}
\pgfarrowsdeclarecombine*{spaced latex reversed}{spaced latex reversed}{latex reversed}{latex reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced latex'}{spaced latex'}{latex'}{latex'}{space}{space}
\pgfarrowsdeclarecombine*{spaced latex' reversed}{spaced latex' reversed}{latex' reversed}{latex' reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced stealth}{spaced stealth}{stealth}{stealth}{space}{space}
\pgfarrowsdeclarecombine*{spaced stealth reversed}{spaced stealth reversed}{stealth reversed}{stealth reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced stealth'}{spaced stealth'}{stealth'}{stealth'}{space}{space}
\pgfarrowsdeclarecombine*{spaced stealth' reversed}{spaced stealth' reversed}{stealth' reversed}{stealth' reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced triangle 90}{spaced triangle 90}{triangle 90}{triangle 90}{space}{space}
\pgfarrowsdeclarecombine*{spaced triangle 90 reversed}{spaced triangle 90 reversed}{triangle 90 reversed}{triangle 90 reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced triangle 60}{spaced triangle 60}{triangle 60}{triangle 60}{space}{space}
\pgfarrowsdeclarecombine*{spaced triangle 60 reversed}{spaced triangle 60 reversed}{triangle 60 reversed}{triangle 60 reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced triangle 45}{spaced triangle 45}{triangle 45}{triangle 45}{space}{space}
\pgfarrowsdeclarecombine*{spaced triangle 45 reversed}{spaced triangle 45 reversed}{triangle 45 reversed}{triangle 45 reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced open triangle 90}{spaced open triangle 90}{open triangle 90}{open triangle 90}{space}{space}
\pgfarrowsdeclarecombine*{spaced open triangle 90 reversed}{spaced open triangle 90 reversed}{open triangle 90 reversed}{open triangle 90 reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced open triangle 60}{spaced open triangle 60}{open triangle 60}{open triangle 60}{space}{space}
\pgfarrowsdeclarecombine*{spaced open triangle 60 reversed}{spaced open triangle 60 reversed}{open triangle 60 reversed}{open triangle 60 reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced open triangle 45}{spaced open triangle 45}{open triangle 45}{open triangle 45}{space}{space}
\pgfarrowsdeclarecombine*{spaced open triangle 45 reversed}{spaced open triangle 45 reversed}{open triangle 45 reversed}{open triangle 45 reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced angle 90}{spaced angle 90}{angle 90}{angle 90}{space}{space}
\pgfarrowsdeclarecombine*{spaced angle 90 reversed}{spaced angle 90 reversed}{angle 90 reversed}{angle 90 reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced angle 60}{spaced angle 60}{angle 60}{angle 60}{space}{space}
\pgfarrowsdeclarecombine*{spaced angle 60 reversed}{spaced angle 60 reversed}{angle 60 reversed}{angle 60 reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced angle 45}{spaced angle 45}{angle 45}{angle 45}{space}{space}
\pgfarrowsdeclarecombine*{spaced angle 45 reversed}{spaced angle 45 reversed}{angle 45 reversed}{angle 45 reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced hooks}{spaced hooks}{hooks}{hooks}{space}{space}
\pgfarrowsdeclarecombine*{spaced hooks reversed}{spaced hooks reversed}{hooks reversed}{hooks reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced o}{spaced o}{o}{o}{space}{space}
\pgfarrowsdeclarecombine*{spaced *}{spaced *}{*}{*}{space}{space}
\pgfarrowsdeclarecombine*{spaced diamond}{spaced diamond}{diamond}{diamond}{space}{space}
\pgfarrowsdeclarecombine*{spaced open diamond}{spaced open diamond}{open diamond}{open diamond}{space}{space}
\pgfarrowsdeclarecombine*{spaced square}{spaced square}{square}{square}{space}{space}
\pgfarrowsdeclarecombine*{spaced open square}{spaced open square}{open square}{open square}{space}{space}
\pgfarrowsdeclarecombine*{spaced serif cm}{spaced serif cm}{serif cm}{serif cm}{space}{space}
\pgfarrowsdeclarecombine*{spaced left to}{spaced left to}{left to}{left to}{space}{space}
\pgfarrowsdeclarecombine*{spaced left to reversed}{spaced left to reversed}{left to reversed}{left to reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced right to}{spaced right to}{right to}{right to}{space}{space}
\pgfarrowsdeclarecombine*{spaced right to reversed}{spaced right to reversed}{right to reversed}{right to reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced left hook}{spaced left hook}{left hook}{left hook}{space}{space}
\pgfarrowsdeclarecombine*{spaced left hook reversed}{spaced left hook reversed}{left hook reversed}{left hook reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced right hook}{spaced right hook}{right hook}{right hook}{space}{space}
\pgfarrowsdeclarecombine*{spaced right hook reversed}{spaced right hook reversed}{right hook reversed}{right hook reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced round cap}{spaced round cap}{round cap}{round cap}{space}{space}
\pgfarrowsdeclarecombine*{spaced butt cap}{spaced butt cap}{butt cap}{butt cap}{space}{space}
\pgfarrowsdeclarecombine*{spaced triangle 90 cap}{spaced triangle 90 cap}{triangle 90 cap}{triangle 90 cap}{space}{space}
\pgfarrowsdeclarecombine*{spaced triangle 90 cap reversed}{spaced triangle 90 cap reversed}{triangle 90 cap reversed}{triangle 90 cap reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced fast cap}{spaced fast cap}{fast cap}{fast cap}{space}{space}
\pgfarrowsdeclarecombine*{spaced fast cap reversed}{spaced fast cap reversed}{fast cap reversed}{fast cap reversed}{space}{space}
\pgfarrowsdeclarecombine*{spaced (}{spaced )}{(}{)}{space}{space}
\pgfarrowsdeclarecombine*{spaced )}{spaced (}{)}{(}{space}{space}
\pgfarrowsdeclarecombine*{spaced |}{spaced |}{|}{|}{space}{space}

\pgfdeclarearrow{
  name = spaced [-spaced ],
  means = square bracket[].space
} 

\pgfdeclarearrow{
  name = spaced ]-spaced [,
  means = square bracket[reversed].space
} 



\endinput

pgflibrarycurvilinear.code.tex
% Copyright 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[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/libraries/pgflibrarycurvilinear.code.tex,v 1.3 2013/10/07 15:51:46 tantau Exp $

%
% This file defines commands for computing points in curvilinear
% coordinate systems. 
%


%
% Curvilinear coordinate systems defined in terms of a Bezier curve.
%
% For the following coordinate systems, you must first provide a
% Bezier curve (using, as always, four points), which will be set for
% the current scope. When the curve is "installed" some expensive
% precomputations are done; subsequent calls to
% \pgfpointcurvilinearxxx based on this Bezier curve will be
% relatively quick.
% 



% Install a Bezier curve
%
% #1 = start point
% #2 = first control point
% #3 = second control point
% #4 = end point
%
% Description:
%
% Subsequent calls to functions like
% \pgfpointcurvilinearbezierorthogonal will be relative to the curve
% installed using this command. The main job of this macro is a
% precomputation for computing length along the curve.
% All lengths along the Bezier curve are approximated using a lookup table
% of four time/length points. For this, an approximate time for length
% 1pt is computed first, and then the length for twice this time, four
% times this time, and eight times this time are approximated. A
% distance-to-time conversion is then done by a linear interpolation
% of distance-to-time for these four points. Note that all of these
% computations are not particularly precise, but a compromise trading
% speed against precision. Also note that the results will only be
% best near the start of the curve and may be far off near the end if
% that end is degenerate (second control point very near to end
% point). 
%
% Example:
%
% \pgfsetcurvilinearbeziercurve
% {\pgfpoint{0mm}{10mm}}
% {\pgfpoint{5.5mm}{10mm}}
% {\pgfpoint{10mm}{5.5mm}}
% {\pgfpoint{10mm}{0mm}} % nearly a quarter circle
% \pgfpointcurvilinearbezierorthogonal{5mm}{5mm} 
%   % should be 5mm along the circle, put at
%   % distance 15mm from the origin (5mm from the circle line).

\def\pgfsetcurvilinearbeziercurve#1#2#3#4{%
  \pgf@process{#1}%
  \edef\pgf@curvilinear@line@a{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
  \pgf@xa=-\pgf@x%
  \pgf@ya=-\pgf@y%
  \pgf@process{#2}%
  \edef\pgf@curvilinear@line@b{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
  \pgf@xb=-\pgf@x%
  \pgf@yb=-\pgf@y%
  \advance\pgf@x by\pgf@xa%
  \advance\pgf@y by\pgf@ya%
  \pgfmathveclen@{\pgf@x}{\pgf@y}%
  \let\pgf@curvilinear@lenab\pgfmathresult%
  \pgf@process{#3}%
  \edef\pgf@curvilinear@line@c{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
  \pgf@xc=-\pgf@x%
  \pgf@yc=-\pgf@y%
  \advance\pgf@x by\pgf@xb%
  \advance\pgf@y by\pgf@yb%
  \pgfmathveclen@{\pgf@x}{\pgf@y}%
  \let\pgf@curvilinear@lenbc\pgfmathresult%
  \pgf@process{#4}%
  \edef\pgf@curvilinear@line@d{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
  \advance\pgf@x by\pgf@xc%
  \advance\pgf@y by\pgf@yc%
  \pgfmathveclen@{\pgf@x}{\pgf@y}%
  \let\pgf@curvilinear@lencd\pgfmathresult
  %
  \pgf@x=\pgf@curvilinear@lenab pt%
  \advance\pgf@x by\pgf@curvilinear@lenbc pt%
  \advance\pgf@x by\pgf@curvilinear@lencd pt%
  \pgfmathreciprocal@{\pgf@x}%
  \pgf@curvilinear@time@a\pgfmathresult pt%
  \pgf@process{\pgfpointcurveattime{\pgf@curvilinear@time@a}{\pgf@curvilinear@line@a}{\pgf@curvilinear@line@b}{\pgf@curvilinear@line@c}{\pgf@curvilinear@line@d}}%
  \pgf@xb=-\pgf@x%
  \pgf@yb=-\pgf@y%
  \advance\pgf@x by\pgf@xa%
  \advance\pgf@y by\pgf@ya%
  \pgfmathveclen@{\pgf@x}{\pgf@y}%
  \pgf@curvilinear@length@a\pgfmathresult pt%
  \ifdim\pgf@curvilinear@length@a>1pt\relax%
    % Ok, too large, let us make this smaller
    \pgfmathdivide@{\pgf@curvilinear@time@a}{\pgf@curvilinear@length@a}%
    \pgf@curvilinear@time@a\pgfmathresult pt%
    \pgf@process{\pgfpointcurveattime{\pgf@curvilinear@time@a}{\pgf@curvilinear@line@a}{\pgf@curvilinear@line@b}{\pgf@curvilinear@line@c}{\pgf@curvilinear@line@d}}
    \pgf@xb=-\pgf@x%
    \pgf@yb=-\pgf@y%
    \advance\pgf@x by\pgf@xa%
    \advance\pgf@y by\pgf@ya%
    \pgfmathveclen@{\pgf@x}{\pgf@y}%
    \pgf@curvilinear@length@a\pgfmathresult pt%
  \fi%
  % Compute three positions:
  \pgf@process{\pgfpointcurveattime{2\pgf@curvilinear@time@a}{\pgf@curvilinear@line@a}{\pgf@curvilinear@line@b}{\pgf@curvilinear@line@c}{\pgf@curvilinear@line@d}}
  \pgf@xa=-\pgf@x%
  \pgf@ya=-\pgf@y%
  \advance\pgf@x by\pgf@xb%
  \advance\pgf@y by\pgf@yb%
  \pgfmathveclen@{\pgf@x}{\pgf@y}%
  \pgf@curvilinear@length@b\pgfmathresult pt%
  \advance\pgf@curvilinear@length@b by\pgf@curvilinear@length@a%
  \pgf@process{\pgfpointcurveattime{4\pgf@curvilinear@time@a}{\pgf@curvilinear@line@a}{\pgf@curvilinear@line@b}{\pgf@curvilinear@line@c}{\pgf@curvilinear@line@d}}
  \pgf@xb=-\pgf@x%
  \pgf@yb=-\pgf@y%
  \advance\pgf@x by\pgf@xa%
  \advance\pgf@y by\pgf@ya%
  \pgfmathveclen@{\pgf@x}{\pgf@y}%
  \pgf@curvilinear@length@c\pgfmathresult pt%
  \advance\pgf@curvilinear@length@c by\pgf@curvilinear@length@b%
  \pgf@process{\pgfpointcurveattime{8\pgf@curvilinear@time@a}{\pgf@curvilinear@line@a}{\pgf@curvilinear@line@b}{\pgf@curvilinear@line@c}{\pgf@curvilinear@line@d}}
  \advance\pgf@x by\pgf@xb%
  \advance\pgf@y by\pgf@yb%
  \pgfmathveclen@{\pgf@x}{\pgf@y}%
  \pgf@curvilinear@length@d\pgfmathresult pt%
  \advance\pgf@curvilinear@length@d by\pgf@curvilinear@length@c%
  \let\pgf@curvilinear@comp@a\pgf@curvilinear@comp@a@initial%
  \let\pgf@curvilinear@comp@b\pgf@curvilinear@comp@b@initial%
  \let\pgf@curvilinear@comp@c\pgf@curvilinear@comp@c@initial%
  \let\pgf@curvilinear@comp@d\pgf@curvilinear@comp@d@initial%
  \let\pgf@curvilinear@comp@e\pgf@curvilinear@comp@e@initial%
  \let\pgf@curvilinear@point\pgf@curvilinear@curve@point%
}
\newdimen\pgf@curvilinear@time@a
\newdimen\pgf@curvilinear@length@a
\newdimen\pgf@curvilinear@length@b
\newdimen\pgf@curvilinear@length@c
\newdimen\pgf@curvilinear@length@d


\def\pgf@curvilinear@comp@a@initial{%
  \pgfmathdivide@\pgf@curvilinear@time@a\pgf@curvilinear@length@a%
  \let\pgf@curvilinear@quot@a\pgfmathresult%
  \let\pgf@curvilinear@comp@a\pgf@curvilinear@comp@a@cont%
  \pgf@curvilinear@comp@a@cont%
}
\def\pgf@curvilinear@comp@a@cont{%
  \pgf@x\pgf@curvilinear@quot@a\pgf@x%
}

\def\pgf@curvilinear@comp@b@initial{%
  \pgf@y=\pgf@curvilinear@length@b%
  \advance\pgf@y by-\pgf@curvilinear@length@a%
  \pgfmathdivide@\pgf@curvilinear@time@a\pgf@y%
  \let\pgf@curvilinear@quot@b\pgfmathresult%
  \pgf@y\pgfmathresult\pgf@curvilinear@length@a%
  \pgf@y-\pgf@y%
  \advance\pgf@y by\pgf@curvilinear@time@a%
  \edef\pgf@curvilinear@correct@b{\pgf@sys@tonumber\pgf@y}%
  \let\pgf@curvilinear@comp@b\pgf@curvilinear@comp@b@cont%
  \pgf@curvilinear@comp@b@cont%
}
\def\pgf@curvilinear@comp@b@cont{%
  \pgf@x\pgf@curvilinear@quot@b\pgf@x%
  \advance\pgf@x by\pgf@curvilinear@correct@b pt%
}

\def\pgf@curvilinear@comp@c@initial{%
  \pgf@y=\pgf@curvilinear@length@c%
  \advance\pgf@y by-\pgf@curvilinear@length@b%
  \pgf@y.5\pgf@y%
  \pgfmathdivide@\pgf@curvilinear@time@a\pgf@y%
  \let\pgf@curvilinear@quot@c\pgfmathresult%
  \pgf@y\pgf@curvilinear@quot@c\pgf@curvilinear@length@b%
  \pgf@y-\pgf@y%
  \advance\pgf@y by2\pgf@curvilinear@time@a%
  \edef\pgf@curvilinear@correct@c{\pgf@sys@tonumber\pgf@y}%
  \let\pgf@curvilinear@comp@c\pgf@curvilinear@comp@c@cont%
  \pgf@curvilinear@comp@c@cont%
}
\def\pgf@curvilinear@comp@c@cont{%
  \pgf@x\pgf@curvilinear@quot@c\pgf@x%
  \advance\pgf@x by\pgf@curvilinear@correct@c pt%
}

\def\pgf@curvilinear@comp@d@initial{%
  \pgf@y=\pgf@curvilinear@length@d%
  \advance\pgf@y by-\pgf@curvilinear@length@c%
  \pgf@y.25\pgf@y%
  \pgfmathdivide@\pgf@curvilinear@time@a\pgf@y%
  \let\pgf@curvilinear@quot@d\pgfmathresult%
  \pgf@y\pgf@curvilinear@quot@d\pgf@curvilinear@length@c%
  \pgf@y-\pgf@y%
  \advance\pgf@y by4\pgf@curvilinear@time@a%
  \edef\pgf@curvilinear@correct@d{\pgf@sys@tonumber\pgf@y}%
  \let\pgf@curvilinear@comp@d\pgf@curvilinear@comp@d@cont%
  \pgf@curvilinear@comp@d@cont%
}
\def\pgf@curvilinear@comp@d@cont{%
  \pgf@x\pgf@curvilinear@quot@d\pgf@x%
  \advance\pgf@x by\pgf@curvilinear@correct@d pt%
}

\def\pgf@curvilinear@comp@e@initial{%
  \pgfmathdivide@{8\pgf@curvilinear@time@a}{\pgf@curvilinear@length@d}%
  \let\pgf@curvilinear@quot@e\pgfmathresult%
  \let\pgf@curvilinear@comp@e\pgf@curvilinear@comp@e@cont%
  \pgf@curvilinear@comp@e@cont%
}
\def\pgf@curvilinear@comp@e@cont{%
  \pgf@x\pgf@curvilinear@quot@e\pgf@x%
}


% Convert a distance into a time
% 
% #1 = a distance
% 
% Description:
%
% After having called \pgfsetcurvilinearbeziercurve, you can use this
% macro to convert a distance into a time along the curve set in that 
% command. The result will be stored in \pgf@x. It will only be
% reasonably precise for small nonnegative #1 (in particular, #1
% should not be more than about half the length of the curve).

\def\pgfcurvilineardistancetotime#1{%
  \pgfmathsetlength{\pgf@x}{#1}%
  \ifdim\pgf@x<\pgf@curvilinear@length@c\relax%
    \ifdim\pgf@x<\pgf@curvilinear@length@a\relax%
      \pgf@curvilinear@comp@a%
    \else\ifdim\pgf@x<\pgf@curvilinear@length@b\relax%
      \pgf@curvilinear@comp@b%
    \else%
      \pgf@curvilinear@comp@c%
    \fi\fi%
  \else\ifdim\pgf@x<\pgf@curvilinear@length@d\relax%
    \pgf@curvilinear@comp@d%
  \else%
    \pgf@curvilinear@comp@e%
  \fi\fi%
}



% Compute a "Bezier-orthogonal" point for use in a nonlinear transformation.
%
% #1 = x
% #2 = y
%
% Description:
%
% In this coordinate system, the x-axis "goes along" the Bezier curve
% installed using \pgfsetcurvilinearbeziercurve
% and the y-axis is always perpendicular to the (Bezier) curve at the
% given x-coordinate. Formally, given a pair (x,y), let B(x) be the point on
% the Bezier curve B at distance x from the start of the curve. Let
% T(x) be the tangent of B at B(x) and let P(x) be the (normalized)
% vector perpendicular to T(x). Then (x,y) would be mapped to B(x) +
% y*P(x). As an example, if B is a circle, then the corresponding
% curvilinear coordinate system is (essentially, except for an offset in
% the y value) the polar coordinate system.
%
% In addition to setting \pgf@x and \pgf@y, \pgf@xa/ya will be set to
% a tangent along the curve at the given point and \pgf@xb/yb to a
% tanget orthogonal to the curve.

\def\pgfpointcurvilinearbezierorthogonal#1#2{%
  \pgfmathsetmacro\pgf@curvilinear@yfactor{#2}%
  \pgfcurvilineardistancetotime{#1}%
  \pgfpointcurveattime{\pgf@x}{\pgf@curvilinear@line@a}{\pgf@curvilinear@line@b}{\pgf@curvilinear@line@c}{\pgf@curvilinear@line@d}
  \pgf@xc\pgf@x% save
  \pgf@yc\pgf@y% save
  % compute normal:
  \advance\pgf@xb by-\pgf@xa%
  \advance\pgf@yb by-\pgf@ya%
  \ifdim\pgf@xb<0.0001pt\ifdim\pgf@xb>-0.0001pt\ifdim\pgf@yb<0.0001pt\ifdim\pgf@yb>-0.0001pt\pgf@diff@curvi@ac\fi\fi\fi\fi
  \pgf@process{\pgfpointnormalised{\pgf@x=\pgf@yb\pgf@y=-\pgf@xb}}
  \pgf@x\pgf@curvilinear@yfactor\pgf@x%
  \pgf@y\pgf@curvilinear@yfactor\pgf@y%
  \advance\pgf@x by\pgf@xc%
  \advance\pgf@y by\pgf@yc%
}

\def\pgf@diff@curvi@ac{%
  \pgf@curvilinear@line@a%
  \pgf@xa\pgf@x\pgf@ya\pgf@y%
  \pgf@curvilinear@line@c%
  \pgf@xb\pgf@x\pgf@yb\pgf@y%
  \advance\pgf@xb by-\pgf@xa%
  \advance\pgf@yb by-\pgf@ya%
  \ifdim\pgf@xb<0.0001pt\ifdim\pgf@xb>-0.0001pt\ifdim\pgf@yb<0.0001pt\ifdim\pgf@yb>-0.0001pt% still degenerate!
    \pgf@curvilinear@line@d%
    \pgf@xb\pgf@x\pgf@yb\pgf@y%
    \advance\pgf@xb by-\pgf@xa%
    \advance\pgf@yb by-\pgf@ya%
  \fi\fi\fi\fi%
  \pgf@xb-\pgf@xb%
  \pgf@yb-\pgf@yb%
}



% Compute a "Bezier-polar" point.
%
% #1 = x
% #2 = y
%
% Description:
%
% Let (r:d) be the point (x,y) in polar coordinates, that is, r is the
% angle and d the distance of (x,y) to the origin. The point returned
% by \pgfpointcurvilinearbezierpolar is now defined as follows: First,
% we compute that point at distance d along the Bezier curve B. Let
% B(d) be this point. Then, we rotate this point around the start of
% the curve (B(0)) by r degrees.
% 
% As an example, consider a triangle with one tip at the origin and
% the other tips as (4cm,3cm) and (4cm,-3cm). Then this triangle would be
% transformed as follows: We take the first 5cm of the Bezier curve
% and rotate it by roughly 37 degrees to the left and by 37 degrees to
% the right.
% 
% Note that this command is pretty expensive.

\def\pgfpointcurvilinearbezierpolar#1#2{%
  \pgfmathsetlength\pgfutil@tempdima{#1}%
  \pgfmathsetlength\pgfutil@tempdimb{#2}%
  % Compute angle:
  \pgfpointnormalised{\pgfqpoint{\pgfutil@tempdima}{\pgfutil@tempdimb}}%
  \ifdim\pgfutil@tempdimb=0pt\relax\ifdim\pgfutil@tempdima=0pt\pgf@x1pt\pgf@y0pt\fi\fi%
  \ifdim\pgfutil@tempdima<0pt%
    \pgf@x-\pgf@x%
    \pgf@y-\pgf@y%
  \fi%
  \pgf@ya=-\pgf@y%
  \pgfsettransformentries%
    {\pgf@sys@tonumber\pgf@x}{\pgf@sys@tonumber\pgf@y}%
    {\pgf@sys@tonumber\pgf@ya}{\pgf@sys@tonumber\pgf@x}{0pt}{0pt}%
  \pgftransformshift{\pgfpointscale{-1}{\pgf@curvilinear@line@a}}%
  \pgfmathveclen@{\pgfutil@tempdima}{\pgfutil@tempdimb}%
  \ifdim\pgfutil@tempdima<0pt%
    \edef\pgfmathresult{-\pgfmathresult}%
  \fi%
  \pgfcurvilineardistancetotime{\pgfmathresult}%
  % Now, transform:
  \pgf@process{%
    \pgfpointadd{%
      \pgfpointtransformed{%
        \pgfpointcurveattime%
          {\pgf@x}%
          {\pgf@curvilinear@line@a}%
          {\pgf@curvilinear@line@b}%
          {\pgf@curvilinear@line@c}%
          {\pgf@curvilinear@line@d}%
      }%
    }%
    \pgf@curvilinear@line@a%
  }%
}


\endinput

pgflibrarydatavisualization.barcharts.code.tex
% Copyright 2008 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/datavisualization/pgflibrarydatavisualization.barcharts.code.tex,v 1.3 2008/11/12 23:39:37 tantau Exp $

\usepgfmodule{datavisualization}


%
% This file defines additional data visualization classes.
%


\pgfooclass{candle stick visualizer}
{
  \attribute attribute;
  \attribute offset;
  \attribute use path rise=\pgfsetfillcolor{white}\pgfusepath{fill,stroke};
  \attribute use path fall=\pgfsetfillcolor{black}\pgfusepath{fill,stroke};
  \attribute use path wick=\pgfusepath{stroke};
  
  \method candle stick visualizer(#1) {
    \pgfooeset{attribute}{#1}
    \pgfoothis.set stick width(4pt)
  }

  \method default connects() {
    \pgfoothis.get handle(\pgf@dv@me)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\pgf@dv@me,visualize,visualize datapoint signal)
  }

  \method set stick width(#1) {
    \pgfmathparse{#1}
    \pgfmathdivide{\pgfmathresult}{2}
    \let\pgf@dv@lib@w=\pgfmathresult
    % Compute the normalized vector:
    \pgfkeyssetvalue{/data point/\pgfoovalueof{attribute}}{1}
    \pgfcanvaspositionofdatapoint%
    \pgfsettocanvasposition\pgf@dv@lib@lower%
    \pgfkeyssetvalue{/data point/\pgfoovalueof{attribute}}{10}
    \pgfcanvaspositionofdatapoint%
    \pgfsettocanvasposition\pgf@dv@lib@upper%
    \pgf@process{\pgfpointnormalised{\pgfpointdiff{\pgf@dv@lib@upper}{\pgf@dv@lib@lower}}}%
    % Rotate by 90 degrees
    \pgf@xa=\pgf@x%
    \pgf@x=-\pgf@dv@lib@w\pgf@y%
    \pgf@y=\pgf@dv@lib@w\pgf@xa%
    \edef\pgf@dv@lib@temp{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
    \pgfoolet{offset}\pgf@dv@lib@temp
  }

  \method set use path rise(#1) {
    \pgfooset{use path rise}{#1}
  }

  \method set use path fall(#1) {
    \pgfooset{use path fall}{#1}
  }

  \method visualize() {
    {
      \pgfooget{attribute}\pgf@lib@attribute%
      \pgfkeysgetvalue{/data point/\pgf@lib@attribute/low}\pgf@lib@low
      \pgfkeysgetvalue{/data point/\pgf@lib@attribute/high}\pgf@lib@high
      \pgfkeysgetvalue{/data point/\pgf@lib@attribute/entry}\pgf@lib@entry
      \pgfkeysgetvalue{/data point/\pgf@lib@attribute/exit}\pgf@lib@exit
      \ifx\pgf@lib@low\pgfutil@empty\pgf@dv@lib@cs@skiptrue\fi
      \ifx\pgf@lib@low\relax\pgf@dv@lib@cs@skiptrue\fi
      \ifx\pgf@lib@high\pgfutil@empty\pgf@dv@lib@cs@skiptrue\fi
      \ifx\pgf@lib@high\relax\pgf@dv@lib@cs@skiptrue\fi
      \ifx\pgf@lib@entry\pgfutil@empty\pgf@dv@lib@cs@skiptrue\fi
      \ifx\pgf@lib@entry\relax\pgf@dv@lib@cs@skiptrue\fi
      \ifx\pgf@lib@exit\pgfutil@empty\pgf@dv@lib@cs@skiptrue\fi
      \ifx\pgf@lib@exit\relax\pgf@dv@lib@cs@skiptrue\fi
      \ifpgf@dv@lib@cs@skip%
      \else%
        \begin{pgfscope}
          % Ok, compute low point
          \pgfkeyssetvalue{/data point/\pgf@lib@attribute}\pgf@lib@low
          \pgfcanvaspositionofdatapoint%
          \pgfsettocanvasposition\pgf@dv@lib@lowpoint%
          % Ok, compute hight point
          \pgfkeyssetvalue{/data point/\pgf@lib@attribute}\pgf@lib@high
          \pgfcanvaspositionofdatapoint%
          \pgfsettocanvasposition\pgf@dv@lib@highpoint%
          % Compute entry and exit
          \pgfkeyssetvalue{/data point/\pgf@lib@attribute}\pgf@lib@entry
          \pgfcanvaspositionofdatapoint%
          \pgfsettocanvasposition\pgf@dv@lib@entrypoint%
          \pgfkeyssetvalue{/data point/\pgf@lib@attribute}\pgf@lib@exit
          \pgfcanvaspositionofdatapoint%
          \pgfsettocanvasposition\pgf@dv@lib@exitpoint%
          \ifdim\pgf@lib@entry pt<\pgf@lib@exit pt\relax%
            \pgf@dv@lib@risetrue%
          \fi%
          \ifpgf@dv@lib@rise
            \let\pgf@dv@lib@a=\pgf@dv@lib@entrypoint
            \let\pgf@dv@lib@b=\pgf@dv@lib@exitpoint
          \else
            \let\pgf@dv@lib@a=\pgf@dv@lib@exitpoint
            \let\pgf@dv@lib@b=\pgf@dv@lib@entrypoint
          \fi
          % Start drawing...
          \pgfpathmoveto{\pgf@dv@lib@lowpoint}
          \pgfpathlineto{\pgf@dv@lib@a}
          \pgfpathmoveto{\pgf@dv@lib@highpoint}
          \pgfpathlineto{\pgf@dv@lib@b}
          \pgfoovalueof{use path wick}
          \pgfpathmoveto{\pgfpointadd{\pgf@dv@lib@a}{\pgfoovalueof{offset}}}
          \pgfpathlineto{\pgfpointadd{\pgf@dv@lib@b}{\pgfoovalueof{offset}}}
          \pgfpathlineto{\pgfpointadd{\pgf@dv@lib@b}{\pgfpointscale{-1}{\pgfoovalueof{offset}}}}
          \pgfpathlineto{\pgfpointadd{\pgf@dv@lib@a}{\pgfpointscale{-1}{\pgfoovalueof{offset}}}}
          \pgfpathclose
          \ifpgf@dv@lib@rise
            \pgfoovalueof{use path rise}
          \else
            \pgfoovalueof{use path fall}
          \fi
        \end{pgfscope}
      \fi
    }
  }

  \newif\ifpgf@dv@lib@cs@skip
  \newif\ifpgf@dv@lib@rise
}


\endinput

pgflibrarydatavisualization.formats.functions.code.tex
% Copyright 2008 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/datavisualization/pgflibrarydatavisualization.formats.functions.code.tex,v 1.4 2011/03/14 23:17:52 tantau Exp $

\usepgfmodule{datavisualization}




% Function evaluator
%
% (This uses TeX evaluation and is slow. *You have been warned*.)
%
% Description:
%
% The data contains the description of variables and functions.
%
% The format for the variables is
%
%   var <name> : interval "["<start>:<end>"]" [ step <steps> | samples <samples>];
%
% (The first two [ and ] are "real", the second pair means "optional",
% see the examples.)
%
%
% The format for the functions is
%
%   func <name> = <body>;
%
% Additionally, the variables and functions stored in the keys
% /pgf/data/vars and /pgf/data/funcs will also be used, the format for
% them is the same as above. 
%
% The <name> is always the name of a (data point) attribute. Inside
% the <body> it can be accessed using the \value macro, which is
% defined locally, here.
%
% Newlines are not importants, everything is gathered into a single
% line, the semicolons are used to detect the beginnings and ends of
% declarations.
%
% With everything setup in this way, for each variable, the variable
% ranges throught the values between start and end, either with the
% given step or the given number of samples. If neither is given, the
% current value of /pgf/data visualization/samples is used. If there
% are multiple variables, they all range over their respective
% intervals independently. Thus, "var x = [0,1]; var y = [0:1];", 
% assuming samples=25, gives you 625 data points.
%
% As the variables range over their respective values, the functions
% are evaluated using the function stored in /pgf/data/evaluator. By
% default this is set to \pgfmathparse, but 
% you can use a different parser, if you like.
%
% Example:
%
% data [format=function] {
%
%   % This is a parametric plot with the parameter called t.
%   var t : interval [0:360] samples 60;
%
%   % Let's draw a circle:
%   func x = sin(\value t);
%   func y = cos(\value t);
% }
%
% data [format=function] {
%
%   % This a surface plot data...
%   var x : interval [0:1];
%   var y : interval [0:1];
%
%   % Let's draw a circle:
%   func height = \value x*\value x + \value y*\value y;
% }

\pgfdeclaredataformat{function}
{ % no catcode code
}
{ % Startup
  % Init collectors
  \let\value=\relax% avoid expansion
  \pgfkeysgetvalue{/pgf/data/vars}\pgf@lib@dv@collector
}
{% Line arguments
  #1%
}
{ % Line action
  \edef\pgf@lib@dv@collector{\pgf@lib@dv@collector\space #1}%
}
{% Ignore empty lines
}
{%
  \edef\pgf@lib@dv@collector{\pgf@lib@dv@collector\space \pgfkeysvalueof{/pgf/data/funcs}}%
  \let\pgf@lib@dv@parsed\pgfutil@empty%
  % launch parser on the result
  \expandafter\pgf@lib@dv@func@parse \pgf@lib@dv@collector\pgf@stop%
  \let\value\pgf@lib@dv@getval
  \pgf@lib@dv@parsed\pgfdatapoint\pgfutil@gobble\pgf@stop%
}

\pgfkeys{
  /pgf/data/vars/.initial=,
  /pgf/data/funcs/.initial=,
  /pgf/data/evaluator/.initial=\pgfmathparse,
  /pgf/data/samples/.initial=25}

\def\pgf@lib@dv@getval#1{\pgfkeysvalueof{/data point/#1}}

\def\pgf@lib@dv@func@parse{%
  \pgfutil@ifnextchar\pgf@stop{% done
    \pgfutil@gobble%
  }
  {%
    \pgfutil@ifnextchar v{% variable
      \pgf@lib@dv@var%
    }{%
      \pgf@lib@dv@func%
    }%
  }%
}

\def\pgf@lib@dv@func func #1 =#2;{%
  \expandafter\def\expandafter\pgf@lib@dv@parsed\expandafter{\pgf@lib@dv@parsed\pgf@lib@dv@eval@func{#1}{#2}}
  \pgf@lib@dv@func@parse%
}
\def\pgf@lib@dv@var var #1 :{\pgfutil@ifnextchar\bgroup{\pgf@lib@dv@var@group{#1}}{\pgf@lib@dv@var@int{#1}}}
\def\pgf@lib@dv@var@group#1#2;{%
  \expandafter\def\expandafter\pgf@lib@dv@parsed\expandafter{\pgf@lib@dv@parsed\pgf@lib@dv@group@var{#1}{#2}}%
  \pgf@lib@dv@func@parse%
}
\def\pgf@lib@dv@var@int#1#2[#3:#4]{%
  \pgfutil@ifnextchar s{%
    \pgf@lib@dv@samplesorsteps{#1}{#3}{#4}%
  }{%
    \expandafter\def\expandafter\pgf@lib@dv@parsed\expandafter{%
      \pgf@lib@dv@parsed\pgf@lib@dv@samples@var{#1}{#3}{#4}{\pgfkeysvalueof{/pgf/data/samples}}}%
    \expandafter\pgf@lib@dv@func@parse\pgfutil@gobble%
  }
} 
\def\pgf@lib@dv@samplesorsteps#1#2#3s{%
  \pgfutil@ifnextchar t{% step
    \pgf@lib@dv@step{#1}{#2}{#3}%
  }{% sample
    \pgf@lib@dv@samples{#1}{#2}{#3}%
  }%
}
\def\pgf@lib@dv@step#1#2#3tep#4;{%
  \expandafter\def\expandafter\pgf@lib@dv@parsed\expandafter{\pgf@lib@dv@parsed\pgf@lib@dv@step@var{#1}{#2}{#3}{#4}}%
  \pgf@lib@dv@func@parse%
}
\def\pgf@lib@dv@samples#1#2#3amples#4;{%
  \expandafter\def\expandafter\pgf@lib@dv@parsed\expandafter{\pgf@lib@dv@parsed\pgf@lib@dv@samples@var{#1}{#2}{#3}{#4}}%
  \pgf@lib@dv@func@parse%
}

%
% Executer...
%
\def\pgf@lib@dv@samples@var#1#2#3#4{%
  \pgfmathparse{#3}%
  \let\pgf@lib@dv@temp=\pgfmathresult%
  \pgfmathparse{#2}%
  \pgfmathparse{\pgf@lib@dv@temp-\pgfmathresult}%
  \pgfmathparse{\pgfmathresult/(#4-1)}%
  \let\pgf@lib@dv@temp=\pgfmathresult%
  \pgf@lib@dv@step@var{#1}{#2}{#3}{\pgf@lib@dv@temp}%
}

\def\pgf@lib@dv@step@var#1#2#3#4#5\pgf@stop{%
  {%
    \def\pgf@loop@body{#5}%
    \pgfmathparse{#2}%
    \pgfkeyslet{/data point/#1}{\pgfmathresult}%
    \pgfmathparse{#3}%
    \let\pgf@loop@end\pgfmathresult%
    \pgfmathparse{#4}%
    \let\pgf@loop@step\pgfmathresult%
    \pgfmathloop%
      \pgfmathlessthan{\pgf@loop@end}{\pgfkeysvalueof{/data point/#1}}
    \ifdim\pgfmathresult pt<1pt\relax%
      \pgf@loop@body\pgf@stop%
      \pgfmathparse{\pgfkeysvalueof{/data point/#1}+\pgf@loop@step}%
      \pgfkeyslet{/data point/#1}{\pgfmathresult}%
    \repeatpgfmathloop%%
  }%
}

\def\pgf@lib@dv@group@var#1#2#3\pgf@stop{%
  \foreach \pgf@lib@dv@iterator in {#2} {%
    \pgfkeyslet{/data point/#1}{\pgf@lib@dv@iterator}%
    #3\pgf@stop%
  }%
}

\def\pgf@lib@dv@eval@func#1#2{%
  \pgfkeysvalueof{/pgf/data/evaluator}{#2}%
  \pgfkeyslet{/data point/#1}{\pgfmathresult}%  
}


\endinput

pgflibrarydatavisualization.polar.code.tex
% Copyright 2008 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/datavisualization/pgflibrarydatavisualization.polar.code.tex,v 1.4 2011/02/22 22:07:24 tantau Exp $

\usepgfmodule{datavisualization}

% This file defines code for doing plots involving polar
% coordinates. This includes not only standard polar plots, but also
% pie charts. 



\pgfooclass{polar transformer}
{
  % Class plor mapper
  %
  % A polar mapper is used to transform attributes given as (2d) polar
  % coordinates to canvas coordinates. Note that no special ranges
  % can be specified and that the angle must be given in degrees. You
  % can, however, use a standard mapper to change these things.
  
  \attribute angle;
  % The attribute from which the angle is read.
  
  \attribute radius;
  % The attribute from which the radius is read.
  
  \attribute unit vector 0 degrees;
  % The unit vector 0 degrees
  
  \attribute unit vector 90 degrees;
  % The unit vector 90 degrees



  % Constructor
  %
  % #1 = angle attribute. Example: rotation.
  % #2 = radius attribute. Example: height.
  % #3 = unit vector 0 degrees
  % #4 = unit vector 90 degrees
  %
  \method polar transformer(#1,#2,#3,#4) {
    \pgfooset{angle}{#1}
    \pgfooset{radius}{#2}
    \pgfooset{unit vector 0 degrees}{#3}
    \pgfooset{unit vector 90 degrees}{#4}
  } 

  % Method
  \method default connects() {
    \pgfoothis.get handle(\pgf@dv@me)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\pgf@dv@me,transform,transform datapoint signal)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\pgf@dv@me,path,path signal)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\pgf@dv@me,direction,direction signal)
  }

  % Getters
  \method get angle attribute(#1) {
    \pgfooget{angle}{#1}
  }

  \method get radius attribute(#1) {
    \pgfooget{radius}{#1}
  }

  
  % Slot
  %
  % This slot should be connected to the transform datapoint
  % signal. When this signal is emitted, the coordinate system will be
  % shifted according to the current value of the attribute.
  \method transform() {
    \pgfkeysgetvalue{/data point/\pgfoovalueof{angle}/const}\pgf@dv@angle%
    \ifx\pgf@dv@angle\relax
      \pgfkeysgetvalue{/data point/\pgfoovalueof{angle}}\pgf@dv@angle%
    \fi
    \ifx\pgf@dv@angle\relax\else%
      \ifx\pgf@dv@angle\pgfutil@empty\else%
        \pgfkeysgetvalue{/data point/\pgfoovalueof{radius}/const}\pgf@dv@radius%
        \ifx\pgf@dv@radius\relax
          \pgfkeysgetvalue{/data point/\pgfoovalueof{radius}}\pgf@dv@radius%
        \fi
        \ifx\pgf@dv@radius\pgfutil@empty\else%
          \ifx\pgf@dv@radius\relax\else%
            \pgfdvmathenter{\pgf@dv@val}{\pgf@dv@angle}%
            \pgfdvmathexitbyscientificformat{\pgf@dv@angle}{\pgf@dv@val}%
            \pgfdvmathenter{\pgf@dv@val}{\pgf@dv@radius}%
            \pgfdvmathexitbyscientificformat{\pgf@dv@radius}{\pgf@dv@val}%
            \pgfmathsincos{\pgf@dv@angle}%
            \pgfmathmultiply{\pgfmathresultx}{\pgf@dv@radius}%
            \let\pgf@dv@polar@temp=\pgfmathresult
            \pgftransformshift{\pgfpointscale{\pgf@dv@polar@temp}{\pgfoovalueof{unit vector 0 degrees}}}%
            \pgfmathmultiply{\pgfmathresulty}{\pgf@dv@radius}%
            \let\pgf@dv@polar@temp=\pgfmathresult
            \pgftransformshift{\pgfpointscale{\pgf@dv@polar@temp}{\pgfoovalueof{unit vector 90 degrees}}}%
          \fi%
        \fi%
      \fi%
    \fi%
  }


  
  % Reaction to the path signal
  %
  % Here is what we do: When a pgfdvpathmoveto is done, the radius and
  % the angle are recorded. When a pgfdvpathlineto is done, the saved
  % radius and angle are compared with the new angle and radius. If,
  % and only if, the radius is the same, but the angle is different,
  % the lineto is caught and replaced by an arc from the previous
  % position to the new position.

  \attribute prev angle;
  \attribute prev radius;
  
  \method path(#1) {%
    \ifpgfdvhandled%
    \else%
      \ifx#1\pgfdvpathlinetotoken
        % Ok, let us have a look...
        \pgfooget{prev radius}\pgf@dv@prev@rad
        \pgfkeysgetvalue{/data point/\pgfoovalueof{radius}}\pgf@dv@current@rad
        \ifx\pgf@dv@current@rad\relax
        \else
          \ifx\pgf@dv@current@rad\pgf@dv@prev@rad%
            \pgfooget{prev angle}\pgf@dv@prev@angle
            \pgfkeysgetvalue{/data point/\pgfoovalueof{angle}}\pgf@dv@current@angle
            \ifx\pgf@dv@current@angle\relax
            \else
              \ifx\pgf@dv@current@angle\pgf@dv@prev@angle%
              % do nothing
              \else%
                % Do arc:
                \pgfdvmathenter{\pgf@dv@val}{\pgf@dv@prev@angle}%
                \pgfdvmathexitbyscientificformat{\pgf@dv@prev@angle}{\pgf@dv@val}%
                \pgfdvmathenter{\pgf@dv@val}{\pgf@dv@prev@rad}%
                \pgfdvmathexitbyscientificformat{\pgf@dv@prev@rad}{\pgf@dv@val}%
                \pgfdvmathenter{\pgf@dv@val}{\pgf@dv@current@angle}%
                \pgfdvmathexitbyscientificformat{\pgf@dv@current@angle}{\pgf@dv@val}%
                \pgfdvmathenter{\pgf@dv@val}{\pgf@dv@current@rad}%
                \pgfdvmathexitbyscientificformat{\pgf@dv@current@rad}{\pgf@dv@val}%
                \pgfpatharcaxes{\pgf@dv@prev@angle}{\pgf@dv@current@angle}
                  {\pgfpointscale{\pgf@dv@current@rad}{\pgfoovalueof{unit vector 0 degrees}}}
                  {\pgfpointscale{\pgf@dv@current@rad}{\pgfoovalueof{unit vector 90 degrees}}}%
                \pgfdvhandledtrue%
              \fi%
            \fi%
          \fi%
        \fi%
      \fi%
    \fi%
    % No matter what, record the current position
    \pgfooeset{prev angle}{\pgfkeysvalueof{/data point/\pgfoovalueof{angle}}}
    \pgfooeset{prev radius}{\pgfkeysvalueof{/data point/\pgfoovalueof{radius}}}
  }

  % Method
  %
  % React to direction signals. See pgfpointdvdirection for an
  % explanation
  %
  \method direction(#1) {%
    \ifx#1\pgfdvdirectionfromtoken
      % Record from angle and radius
      \xdef\pgf@dv@polar@from@angle{\pgfkeysvalueof{/data point/\pgfoovalueof{angle}}}
      \xdef\pgf@dv@polar@from@radius{\pgfkeysvalueof{/data point/\pgfoovalueof{radius}}}
    \else\ifx#1\pgfdvdirectiontotoken%
      % Record to angle and radius
      \xdef\pgf@dv@polar@to@angle{\pgfkeysvalueof{/data point/\pgfoovalueof{angle}}}
      \xdef\pgf@dv@polar@to@radius{\pgfkeysvalueof{/data point/\pgfoovalueof{radius}}}
    \else%
      \ifx\pgf@dv@polar@from@radius\pgf@dv@polar@to@radius%
        \pgfdvmathenter{\pgf@dv@a}{\pgf@dv@polar@from@angle}%
        \pgfdvmathenter{\pgf@dv@b}{\pgf@dv@polar@to@angle}%
        \pgfdvmathifless{\pgf@dv@a}{\pgf@dv@b}{\def\pgf@dv@temp@sign{+}}{\def\pgf@dv@temp@sign{-}}%
        \pgfkeysgetvalue{/data point/\pgfoovalueof{angle}}\pgf@temp%
        \ifx\pgf@temp\relax%
        \else%
          \pgfdvmathenter{\pgf@dv@val}{\pgf@temp}%
          \pgfdvmathexitbyscientificformat{\pgf@dv@polar@angle}{\pgf@dv@val}%
          \pgf@process{\pgfpointpolar{\pgf@dv@polar@angle\pgf@dv@temp@sign90}{1pt}}%
          \pgfdvhandledtrue%
        \fi%
      \fi%
    \fi\fi%
  }
}


\endinput

  

pgflibrarydecorations.footprints.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}


% Parameters
\pgfset{
  % Length of a footprint:
  /pgf/decoration/foot length/.initial=10pt,
  % Distance between two footprints on the same side of the path
  /pgf/decoration/stride length/.initial=30pt,
  % Double distance between footprint and input path
  /pgf/decoration/foot sep/.initial=4pt,
  % Rotate feet by this much
  /pgf/decoration/foot angle/.initial=10,
  % What animal?
  /pgf/decoration/foot of/.initial=human,
}



\pgfdeclaredecoration{footprints}{left}
{
  \state{left}[width=\pgfkeysvalueof{/pgf/decoration/stride length}/2,next state=right]
  {
    \pgftransformyshift{\pgfkeysvalueof{/pgf/decoration/foot sep}/2}
    \pgfmathparse{\pgfkeysvalueof{/pgf/decoration/foot length}}
    \pgftransformscale{\pgfmathresult}
    \pgftransformrotate{\pgfkeysvalueof{/pgf/decoration/foot angle}}
    \csname pgf@lib@foot@of@\pgfkeysvalueof{/pgf/decoration/foot of}\endcsname
  }
  \state{right}[width=\pgfkeysvalueof{/pgf/decoration/stride length}/2,next state=left]
  {
    \pgftransformyscale{-1}
    \pgftransformyshift{\pgfkeysvalueof{/pgf/decoration/foot sep}/2}
    \pgfmathparse{\pgfkeysvalueof{/pgf/decoration/foot length}}
    \pgftransformscale{\pgfmathresult}
    \pgftransformrotate{\pgfkeysvalueof{/pgf/decoration/foot angle}}
    \csname pgf@lib@foot@of@\pgfkeysvalueof{/pgf/decoration/foot of}\endcsname
  }
}



% Actual footprints. 
%
% A footprint must be name \pgf@lib@foot@of@XXX, be a left foot and
% should fill a rectangle of (0,0) rectangle (1pt,1pt) (more or less)
% and point right. 
%


\def\pgf@lib@foot@of@gnome{
  % Coordinates from a Gnome logo on wikimedia commons. LGPL
  % license... Unknown author.
  % 
  % Flip and rotate
  \pgftransformcm{0}{-1}{-1}{0}{\pgfqpoint{1pt}{0.8pt}}
  \pgftransformscale{0.83333}
  \pgfpathmoveto{\pgfqpoint{.86068pt}{0pt}}
  \pgfpathcurveto{\pgfqpoint{.61466pt}{0pt}}{\pgfqpoint{.56851pt}{.35041pt}}{\pgfqpoint{.70691pt}{.35041pt}}
  \pgfpathcurveto{\pgfqpoint{.84529pt}{.35041pt}}{\pgfqpoint{1.10671pt}{0pt}}{\pgfqpoint{.86068pt}{0pt}}
  \pgfpathclose
  % 
  \pgfpathmoveto{\pgfqpoint{.45217pt}{.30699pt}}
  \pgfpathcurveto{\pgfqpoint{.52586pt}{.31149pt}}{\pgfqpoint{.60671pt}{.02577pt}}{\pgfqpoint{.46821pt}{.04374pt}}
  \pgfpathcurveto{\pgfqpoint{.32976pt}{.06171pt}}{\pgfqpoint{.37845pt}{.30249pt}}{\pgfqpoint{.45217pt}{.30699pt}}
  \pgfpathclose
  % 
  \pgfpathmoveto{\pgfqpoint{.11445pt}{.48453pt}}
  \pgfpathcurveto{\pgfqpoint{.16686pt}{.46146pt}}{\pgfqpoint{.1212pt}{.23581pt}}{\pgfqpoint{.03208pt}{.29735pt}}
  \pgfpathcurveto{\pgfqpoint{-.057pt}{.3589pt}}{\pgfqpoint{.06204pt}{.50759pt}}{\pgfqpoint{.11445pt}{.48453pt}}
  \pgfpathclose
  % 
  \pgfpathmoveto{\pgfqpoint{.26212pt}{.36642pt}}
  \pgfpathcurveto{\pgfqpoint{.32451pt}{.3537pt}}{\pgfqpoint{.32793pt}{.09778pt}}{\pgfqpoint{.21667pt}{.14369pt}}
  \pgfpathcurveto{\pgfqpoint{.10539pt}{.18961pt}}{\pgfqpoint{.19978pt}{.37916pt}}{\pgfqpoint{.26212pt}{.36642pt}}
  \pgfpathlineto{\pgfqpoint{.26212pt}{.36642pt}}
  \pgfpathclose
  % 
  \pgfpathmoveto{\pgfqpoint{.58791pt}{.93913pt}}
  \pgfpathcurveto{\pgfqpoint{.59898pt}{1.02367pt}}{\pgfqpoint{.52589pt}{1.06542pt}}{\pgfqpoint{.45431pt}{1.01092pt}}
  \pgfpathcurveto{\pgfqpoint{.22644pt}{.83743pt}}{\pgfqpoint{.8316pt}{.75088pt}}{\pgfqpoint{.79171pt}{.51386pt}}
  \pgfpathcurveto{\pgfqpoint{.7586pt}{.31712pt}}{\pgfqpoint{.15495pt}{.37769pt}}{\pgfqpoint{.08621pt}{.68553pt}}
  \pgfpathcurveto{\pgfqpoint{.03968pt}{.89374pt}}{\pgfqpoint{.27774pt}{1.1826pt}}{\pgfqpoint{.52614pt}{1.1826pt}}
  \pgfpathcurveto{\pgfqpoint{.64834pt}{1.1826pt}}{\pgfqpoint{.78929pt}{1.07226pt}}{\pgfqpoint{.81566pt}{.93248pt}}
  \pgfpathcurveto{\pgfqpoint{.8358pt}{.82589pt}}{\pgfqpoint{.57867pt}{.8686pt}}{\pgfqpoint{.58791pt}{.93913pt}}
  \pgfpathlineto{\pgfqpoint{.58791pt}{.93913pt}}
  \pgfpathclose
}  



\def\pgf@lib@foot@of@bird{
  % Coordinates derived from vector image created by Mark Wibrow.
  %
  \pgftransformcm{0}{.11}{.11}{0}{\pgfqpoint{.37pt}{.52pt}}
  \pgfpathmoveto{\pgfqpoint{-.886pt}{1.652pt}}
  \pgfpathcurveto{\pgfqpoint{-.4632pt}{2.669pt}}{\pgfqpoint{-.5092pt}{4.3712pt}}{\pgfqpoint{-.4512pt}{5.6734pt}}
  \pgfpathcurveto{\pgfqpoint{-.4374pt}{5.9842pt}}{\pgfqpoint{-.3182pt}{6.0686pt}}{\pgfqpoint{-.2484pt}{5.644pt}}
  \pgfpathcurveto{\pgfqpoint{-.0534pt}{4.459pt}}{\pgfqpoint{.087pt}{3.0132pt}}{\pgfqpoint{.5206pt}{1.8464pt}}
  \pgfpathcurveto{\pgfqpoint{.714pt}{1.326pt}}{\pgfqpoint{.692pt}{1.416pt}}{\pgfqpoint{1.0864pt}{1.759pt}}
  \pgfpathcurveto{\pgfqpoint{1.7662pt}{2.3504pt}}{\pgfqpoint{2.665pt}{3.1756pt}}{\pgfqpoint{3.2028pt}{4.02pt}}
  \pgfpathcurveto{\pgfqpoint{3.4708pt}{4.4408pt}}{\pgfqpoint{3.4258pt}{4.0814pt}}{\pgfqpoint{3.3366pt}{3.8708pt}}
  \pgfpathcurveto{\pgfqpoint{2.9068pt}{2.8562pt}}{\pgfqpoint{.8502pt}{.645pt}}{\pgfqpoint{.4808pt}{-.0864pt}}
  \pgfpathcurveto{\pgfqpoint{.0808pt}{-.8788pt}}{\pgfqpoint{.1664pt}{-2.1246pt}}{\pgfqpoint{.0024pt}{-2.7868pt}}
  \pgfpathcurveto{\pgfqpoint{-.172pt}{-3.4908pt}}{\pgfqpoint{-.2726pt}{-3.704pt}}{\pgfqpoint{-.3812pt}{-2.9558pt}}
  \pgfpathcurveto{\pgfqpoint{-.5316pt}{-1.9202pt}}{\pgfqpoint{-.88pt}{-.256pt}}{\pgfqpoint{-1.332pt}{.128pt}}
  \pgfpathcurveto{\pgfqpoint{-1.716pt}{.4542pt}}{\pgfqpoint{-3.7928pt}{2.3136pt}}{\pgfqpoint{-4.5044pt}{3.3524pt}}
  \pgfpathcurveto{\pgfqpoint{-4.7618pt}{3.728pt}}{\pgfqpoint{-4.709pt}{3.7864pt}}{\pgfqpoint{-4.4212pt}{3.5818pt}}
  \pgfpathcurveto{\pgfqpoint{-3.4844pt}{2.9162pt}}{\pgfqpoint{-2.6164pt}{1.654pt}}{\pgfqpoint{-1.454pt}{1.3886pt}}
  \pgfpathcurveto{\pgfqpoint{-1.0876pt}{1.305pt}}{\pgfqpoint{-1.0296pt}{1.3066pt}}{\pgfqpoint{-.886pt}{1.652pt}}
  \pgfpathclose
}


\expandafter\def\csname pgf@lib@foot@of@felis silvestris\endcsname{
  % Coordinates derived from vector image created by Mark Wibrow, based
  % on the forefoot of `felis silvestris' shown in
  % Pearson, B. and Burton, J. A. (1980), `Wild Animals', Collins, 155.
  % 
  \pgftransformcm{0}{.1}{.1}{0}{\pgfqpoint{.48pt}{.5pt}}
  \pgfpathmoveto{\pgfqpoint{2.7312pt}{-1.992pt}}
  \pgfpathcurveto{\pgfqpoint{1.8716pt}{-1.4226pt}}{\pgfqpoint{2.1404pt}{.0436pt}}{\pgfqpoint{.9202pt}{.0436pt}}
  \pgfpathcurveto{\pgfqpoint{-.1146pt}{.0436pt}}{\pgfqpoint{-.7386pt}{.0178pt}}{\pgfqpoint{-1.319pt}{-1.0288pt}}
  \pgfpathcurveto{\pgfqpoint{-1.7922pt}{-1.8822pt}}{\pgfqpoint{-2.072pt}{-1.5488pt}}{\pgfqpoint{-2.9638pt}{-1.968pt}}
  \pgfpathcurveto{\pgfqpoint{-3.9244pt}{-2.4198pt}}{\pgfqpoint{-4.4394pt}{-3.348pt}}{\pgfqpoint{-4.1136pt}{-4.041pt}}
  \pgfpathcurveto{\pgfqpoint{-3.3862pt}{-5.5882pt}}{\pgfqpoint{-1.6156pt}{-3.83pt}}{\pgfqpoint{-1.1684pt}{-4.312pt}}
  \pgfpathcurveto{\pgfqpoint{-.5806pt}{-4.9454pt}}{\pgfqpoint{.5032pt}{-4.8822pt}}{\pgfqpoint{1.1748pt}{-4.2878pt}}
  \pgfpathcurveto{\pgfqpoint{1.5822pt}{-3.9272pt}}{\pgfqpoint{2.6524pt}{-5.0652pt}}{\pgfqpoint{3.3506pt}{-4.1066pt}}
  \pgfpathcurveto{\pgfqpoint{3.839pt}{-3.4356pt}}{\pgfqpoint{3.1192pt}{-2.249pt}}{\pgfqpoint{2.7312pt}{-1.992pt}}
  \pgfpathclose
  %
  \pgfpathmoveto{\pgfqpoint{5.0576pt}{.4996pt}}
  \pgfpathcurveto{\pgfqpoint{4.6056pt}{.6536pt}}{\pgfqpoint{4.0596pt}{.2516pt}}{\pgfqpoint{3.8382pt}{-.398pt}}
  \pgfpathcurveto{\pgfqpoint{3.6168pt}{-1.0478pt}}{\pgfqpoint{3.8038pt}{-1.6996pt}}{\pgfqpoint{4.2558pt}{-1.8536pt}}
  \pgfpathcurveto{\pgfqpoint{4.7078pt}{-2.0076pt}}{\pgfqpoint{5.2538pt}{-1.6056pt}}{\pgfqpoint{5.4752pt}{-.9558pt}}
  \pgfpathcurveto{\pgfqpoint{5.6966pt}{-.3062pt}}{\pgfqpoint{5.5096pt}{.3456pt}}{\pgfqpoint{5.0576pt}{.4996pt}}
  \pgfpathclose
  %
  \pgfpathmoveto{\pgfqpoint{3.1212pt}{3.5542pt}}
  \pgfpathcurveto{\pgfqpoint{2.5874pt}{3.6726pt}}{\pgfqpoint{1.975pt}{3.1756pt}}{\pgfqpoint{1.7538pt}{2.4442pt}}
  \pgfpathcurveto{\pgfqpoint{1.5324pt}{1.7128pt}}{\pgfqpoint{1.7858pt}{1.0238pt}}{\pgfqpoint{2.3196pt}{.9052pt}}
  \pgfpathcurveto{\pgfqpoint{2.8534pt}{.7868pt}}{\pgfqpoint{3.4658pt}{1.2838pt}}{\pgfqpoint{3.6872pt}{2.0152pt}}
  \pgfpathcurveto{\pgfqpoint{3.9084pt}{2.7466pt}}{\pgfqpoint{3.655pt}{3.4358pt}}{\pgfqpoint{3.1212pt}{3.5542pt}}
  \pgfpathclose
  % 
  \pgfpathmoveto{\pgfqpoint{-.6182pt}{5.0456pt}}
  \pgfpathcurveto{\pgfqpoint{-1.2132pt}{5.0456pt}}{\pgfqpoint{-1.6956pt}{4.3104pt}}{\pgfqpoint{-1.6956pt}{3.4038pt}}
  \pgfpathcurveto{\pgfqpoint{-1.6956pt}{2.4972pt}}{\pgfqpoint{-1.2132pt}{1.7618pt}}{\pgfqpoint{-.6182pt}{1.7618pt}}
  \pgfpathcurveto{\pgfqpoint{-.0232pt}{1.7618pt}}{\pgfqpoint{.4592pt}{2.4972pt}}{\pgfqpoint{.4592pt}{3.4038pt}}
  \pgfpathcurveto{\pgfqpoint{.4592pt}{4.3104pt}}{\pgfqpoint{-.0232pt}{5.0456pt}}{\pgfqpoint{-.6182pt}{5.0456pt}}
  \pgfpathclose
  % 
  \pgfpathmoveto{\pgfqpoint{-4.1176pt}{1.8248pt}}
  \pgfpathcurveto{\pgfqpoint{-4.6334pt}{1.7534pt}}{\pgfqpoint{-4.9806pt}{1.0312pt}}{\pgfqpoint{-4.8928pt}{.212pt}}
  \pgfpathcurveto{\pgfqpoint{-4.8052pt}{-.6072pt}}{\pgfqpoint{-4.3158pt}{-1.2136pt}}{\pgfqpoint{-3.8pt}{-1.1422pt}}
  \pgfpathcurveto{\pgfqpoint{-3.2842pt}{-1.0708pt}}{\pgfqpoint{-2.9372pt}{-.3486pt}}{\pgfqpoint{-3.0248pt}{.4706pt}}
  \pgfpathcurveto{\pgfqpoint{-3.1126pt}{1.2898pt}}{\pgfqpoint{-3.6018pt}{1.8962pt}}{\pgfqpoint{-4.1176pt}{1.8248pt}}
  \pgfpathclose
}



\def\pgf@lib@foot@of@human{%
  % Coordinates derived from vector image created by Mark Wibrow.
  \pgftransformcm{0}{.5}{.5}{0}{\pgfqpoint{.48pt}{.2pt}}
  % 
  % Draw main part of foot.
  % 
  \pgfpathmoveto{\pgfqpoint{.20175pt}{-.72633pt}}
  \pgfpathcurveto{\pgfqpoint{.16314pt}{-.88194pt}}{\pgfqpoint{.07386pt}{-1.0167pt}}{\pgfqpoint{-.08385pt}{-1.0167pt}}
  \pgfpathcurveto{\pgfqpoint{-.24153pt}{-1.0167pt}}{\pgfqpoint{-.36942pt}{-.84897pt}}{\pgfqpoint{-.36942pt}{-.72633pt}}
  \pgfpathcurveto{\pgfqpoint{-.36942pt}{-.60372pt}}{\pgfqpoint{-.32505pt}{-.54825pt}}{\pgfqpoint{-.27633pt}{-.51192pt}}
  \pgfpathcurveto{\pgfqpoint{-.23937pt}{-.48435pt}}{\pgfqpoint{-.17031pt}{-.46539pt}}{\pgfqpoint{-.10611pt}{-.40323pt}}
  \pgfpathcurveto{\pgfqpoint{-.04191pt}{-.3411pt}}{\pgfqpoint{.00495pt}{-.27783pt}}{\pgfqpoint{.00495pt}{-.14787pt}}
  \pgfpathcurveto{\pgfqpoint{.00495pt}{-.01794pt}}{\pgfqpoint{-.08526pt}{.12648pt}}{\pgfqpoint{-.22194pt}{.22467pt}}
  \pgfpathcurveto{\pgfqpoint{-.35862pt}{.32286pt}}{\pgfqpoint{-.40863pt}{.50226pt}}{\pgfqpoint{-.32703pt}{.5979pt}}
  \pgfpathcurveto{\pgfqpoint{-.24543pt}{.69354pt}}{\pgfqpoint{-.00564pt}{.66543pt}}{\pgfqpoint{.17172pt}{.53484pt}}
  \pgfpathcurveto{\pgfqpoint{.34908pt}{.40422pt}}{\pgfqpoint{.39363pt}{.27192pt}}{\pgfqpoint{.37416pt}{.10971pt}}
  \pgfpathcurveto{\pgfqpoint{.35472pt}{-.0525pt}}{\pgfqpoint{.26736pt}{-.46203pt}}{\pgfqpoint{.20175pt}{-.72633pt}}
  \pgfpathclose
  %
  % Draw toe.s
  % 
  \pgfpathmoveto{\pgfqpoint{-.27138pt}{1.01451pt}}
  \pgfpathcurveto{\pgfqpoint{-.21198pt}{1.01451pt}}{\pgfqpoint{-.1638pt}{.94509pt}}{\pgfqpoint{-.1638pt}{.8595pt}}
  \pgfpathcurveto{\pgfqpoint{-.1638pt}{.77388pt}}{\pgfqpoint{-.21198pt}{.70446pt}}{\pgfqpoint{-.27138pt}{.70446pt}}
  \pgfpathcurveto{\pgfqpoint{-.33078pt}{.70446pt}}{\pgfqpoint{-.37896pt}{.77388pt}}{\pgfqpoint{-.37896pt}{.8595pt}}
  \pgfpathcurveto{\pgfqpoint{-.37896pt}{.94509pt}}{\pgfqpoint{-.33078pt}{1.01451pt}}{\pgfqpoint{-.27138pt}{1.01451pt}}
  \pgfpathclose
  %
  \pgfpathmoveto{\pgfqpoint{-.05769pt}{.90573pt}}
  \pgfpathcurveto{\pgfqpoint{-.01659pt}{.90573pt}}{\pgfqpoint{.01674pt}{.86445pt}}{\pgfqpoint{.01674pt}{.81354pt}}
  \pgfpathcurveto{\pgfqpoint{.01674pt}{.7626pt}}{\pgfqpoint{-.01659pt}{.72132pt}}{\pgfqpoint{-.05769pt}{.72132pt}}
  \pgfpathcurveto{\pgfqpoint{-.09879pt}{.72132pt}}{\pgfqpoint{-.13209pt}{.7626pt}}{\pgfqpoint{-.13209pt}{.81354pt}}
  \pgfpathcurveto{\pgfqpoint{-.13209pt}{.86445pt}}{\pgfqpoint{-.09879pt}{.90573pt}}{\pgfqpoint{-.05769pt}{.90573pt}}
  \pgfpathclose
  %
  \pgfpathmoveto{\pgfqpoint{.10497pt}{.81636pt}}
  \pgfpathcurveto{\pgfqpoint{.14214pt}{.81096pt}}{\pgfqpoint{.16722pt}{.77193pt}}{\pgfqpoint{.16104pt}{.72918pt}}
  \pgfpathcurveto{\pgfqpoint{.15483pt}{.68646pt}}{\pgfqpoint{.11964pt}{.65619pt}}{\pgfqpoint{.08247pt}{.66159pt}}
  \pgfpathcurveto{\pgfqpoint{.0453pt}{.66699pt}}{\pgfqpoint{.02019pt}{.70602pt}}{\pgfqpoint{.0264pt}{.74874pt}}
  \pgfpathcurveto{\pgfqpoint{.03261pt}{.79149pt}}{\pgfqpoint{.0678pt}{.82176pt}}{\pgfqpoint{.10497pt}{.81636pt}}
  \pgfpathclose
  % 
  \pgfpathmoveto{\pgfqpoint{.24054pt}{.70842pt}}
  \pgfpathcurveto{\pgfqpoint{.27513pt}{.70842pt}}{\pgfqpoint{.30318pt}{.67686pt}}{\pgfqpoint{.30318pt}{.63795pt}}
  \pgfpathcurveto{\pgfqpoint{.30318pt}{.59904pt}}{\pgfqpoint{.27513pt}{.56751pt}}{\pgfqpoint{.24054pt}{.56751pt}}
  \pgfpathcurveto{\pgfqpoint{.20598pt}{.56751pt}}{\pgfqpoint{.17793pt}{.59904pt}}{\pgfqpoint{.17793pt}{.63795pt}}
  \pgfpathcurveto{\pgfqpoint{.17793pt}{.67686pt}}{\pgfqpoint{.20598pt}{.70842pt}}{\pgfqpoint{.24054pt}{.70842pt}}
  \pgfpathclose
  % 
  \pgfpathmoveto{\pgfqpoint{.35973pt}{.57501pt}}
  \pgfpathcurveto{\pgfqpoint{.3918pt}{.57501pt}}{\pgfqpoint{.41781pt}{.54852pt}}{\pgfqpoint{.41781pt}{.51585pt}}
  \pgfpathcurveto{\pgfqpoint{.41781pt}{.48318pt}}{\pgfqpoint{.3918pt}{.45669pt}}{\pgfqpoint{.35973pt}{.45669pt}}
  \pgfpathcurveto{\pgfqpoint{.32769pt}{.45669pt}}{\pgfqpoint{.30168pt}{.48318pt}}{\pgfqpoint{.30168pt}{.51585pt}}
  \pgfpathcurveto{\pgfqpoint{.30168pt}{.54852pt}}{\pgfqpoint{.32769pt}{.57501pt}}{\pgfqpoint{.35973pt}{.57501pt}}
  \pgfpathclose
}


\endinput
pgflibrarydecorations.fractals.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}



\pgfdeclaredecoration{Koch curve type 1}{init}
{
  \state{init}[width=\pgfdecoratedinputsegmentremainingdistance]
  {
    \pgfpathlineto{\pgfpoint{.33333\pgfdecoratedinputsegmentremainingdistance}{0pt}}
    \pgfpathlineto{\pgfpoint{.33333\pgfdecoratedinputsegmentremainingdistance}{.33333\pgfdecoratedinputsegmentremainingdistance}}
    \pgfpathlineto{\pgfpoint{.66666\pgfdecoratedinputsegmentremainingdistance}{.33333\pgfdecoratedinputsegmentremainingdistance}}
    \pgfpathlineto{\pgfpoint{.66666\pgfdecoratedinputsegmentremainingdistance}{0pt}}
    \pgfpathlineto{\pgfpoint{\pgfdecoratedinputsegmentremainingdistance}{0pt}}
  }
}

\pgfdeclaredecoration{Koch curve type 2}{init}
{
  \state{init}[width=\pgfdecoratedinputsegmentremainingdistance]
  {
    \pgfpathlineto{\pgfpoint{.25\pgfdecoratedinputsegmentremainingdistance}{0pt}}
    \pgfpathlineto{\pgfpoint{.25\pgfdecoratedinputsegmentremainingdistance}{.25\pgfdecoratedinputsegmentremainingdistance}}
    \pgfpathlineto{\pgfpoint{.5\pgfdecoratedinputsegmentremainingdistance}{.25\pgfdecoratedinputsegmentremainingdistance}}
    \pgfpathlineto{\pgfpoint{.5\pgfdecoratedinputsegmentremainingdistance}{0pt}}
    \pgfpathlineto{\pgfpoint{.5\pgfdecoratedinputsegmentremainingdistance}{-.25\pgfdecoratedinputsegmentremainingdistance}}
    \pgfpathlineto{\pgfpoint{.75\pgfdecoratedinputsegmentremainingdistance}{-.25\pgfdecoratedinputsegmentremainingdistance}}
    \pgfpathlineto{\pgfpoint{.75\pgfdecoratedinputsegmentremainingdistance}{0pt}}
    \pgfpathlineto{\pgfpoint{\pgfdecoratedinputsegmentremainingdistance}{0pt}}
  }
}

\pgfdeclaredecoration{Koch snowflake}{init}
{
  \state{init}[width=\pgfdecoratedinputsegmentremainingdistance]
  {
    \pgfpathlineto{\pgfpoint{.3333\pgfdecoratedinputsegmentremainingdistance}{0pt}}
    \pgfpathlineto{\pgfpoint{.5\pgfdecoratedinputsegmentremainingdistance}{0.2886751347\pgfdecoratedinputsegmentremainingdistance}}
    \pgfpathlineto{\pgfpoint{.6666\pgfdecoratedinputsegmentremainingdistance}{0pt}}
    \pgfpathlineto{\pgfpoint{\pgfdecoratedinputsegmentremainingdistance}{0pt}}
  }
}


\pgfdeclaredecoration{Cantor set}{init}
{
  \state{init}[width=\pgfdecoratedinputsegmentremainingdistance]
  {
    \pgfpathlineto{\pgfpoint{.3333\pgfdecoratedinputsegmentremainingdistance}{0pt}}
    \pgfpathmoveto{\pgfpoint{.6666\pgfdecoratedinputsegmentremainingdistance}{0pt}}
    \pgfpathlineto{\pgfpoint{\pgfdecoratedinputsegmentremainingdistance}{0pt}}
  }
}



\endinput
pgflibrarydecorations.markings.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}


% A marking decoration is used to add markings (which are just pgf
% scopes, essentially) at certain positions of a path.

\pgfkeys{
  /pgf/decoration/reset marks/.code=\let\pgf@lib@dec@mark@marks\pgfutil@empty,
  /pgf/decoration/mark/.code=\pgf@lib@dec@parsemark#1\pgf@lib@dec@stop,
}

\let\pgf@lib@dec@mark@marks=\pgfutil@empty

\def\pgf@lib@dec@parsemark{\pgfutil@ifnextchar b{\pgf@lib@dec@parsebetween}{\pgf@lib@dec@parseat}}
\def\pgf@lib@dec@parseat at position#1with#2\pgf@lib@dec@stop{%
  \expandafter\def\expandafter\pgf@lib@dec@mark@marks\expandafter{\pgf@lib@dec@mark@marks%
    \pgf@lib@dec@domark{#1}{#2}%
  }%
}
\def\pgf@lib@dec@parsebetween between positions#1and#2step#3with#4\pgf@lib@dec@stop{%
  \expandafter\def\expandafter\pgf@lib@dec@mark@marks\expandafter{\pgf@lib@dec@mark@marks%
    \pgf@lib@dec@dobetweenmark{#1}{#2}{#3}{#4}%
  }%
}

\def\pgf@lib@dec@arrowhead#1#2{%
  \pgftransformxscale{#1}
  \pgfarrowdraw{#2}%
}

\def\pgf@lib@dec@doarrowhead#1{%
  \pgf@lib@dec@arrowhead{1}{#1}%
}
\def\pgf@lib@dec@doarrowheadrev#1{%
  \pgf@lib@dec@arrowhead{-1}{#1}%
}


\pgfdeclaredecoration{markings}{init}
{
  \state{init}
  [
    width=0pt,
    persistent precomputation={%
      \pgfkeys{/pgf/decoration/mark info/sequence number/.initial=0}%
      \pgfkeys{/pgf/decoration/mark info/distance from start/.initial=}%
    },
    next state=pre
  ]
  {}
  
  \state{pre}
  [
    width=0pt,
    persistent precomputation={%
      \def\pgf@lib@dec@computed@width{0pt}%
      \pgf@lib@dec@mark@marks\pgf@lib@dec@mark@last%
      \let\arrow=\pgf@lib@dec@doarrowhead%
      \let\arrowreversed=\pgf@lib@dec@doarrowheadrev%
    },
    next state=skipper
  ]
  {}

  \state{skipper}[width=\pgf@lib@dec@computed@width-\pgfdecoratedcompleteddistance-1sp,
                  next state=\pgf@lib@dec@next@state]{}
  
  \state{main}
  [
    width=1sp,
    next state=pre,
    persistent precomputation={%
      \pgfutil@tempcnta=\pgfkeysvalueof{/pgf/decoration/mark info/sequence number}\relax%
      \advance\pgfutil@tempcnta by1\relax%
      \pgfkeys{/pgf/decoration/mark info/sequence number/.expanded=\the\pgfutil@tempcnta}%
      \pgfkeys{/pgf/decoration/mark info/distance from start/.expanded=\pgf@lib@dec@computed@width}%
    }%
  ]
  {%
    \pgfinterruptpath%
      \pgfscope%
        \let\pgf@lib@dec@mark@marks=\pgfutil@empty%
        \pgf@lib@dec@computed@action%
      \endpgfscope%
    \endpgfinterruptpath%
    \ifx\pgf@lib@mark@node\pgfutil@empty%
    \else%
      \pgf@lib@mark@connect@node%
    \fi%
  }%

  \state{final}[width=\pgfdecoratedremainingdistance]{
    \ifx\pgf@lib@mark@node\pgfutil@empty%
      \pgfpathmoveto{\pgfpointdecoratedpathlast}
    \else%
      \pgfpathlineto{\pgfpointdecoratedpathlast}
    \fi%
  }
}

\def\pgf@lib@dec@domark#1#2#3\pgf@lib@dec@mark@last{%
  \def\pgf@lib@dec@mark@marks{#3}%
  \pgf@lib@dec@parsenum{#1}%
  \def\pgf@lib@dec@computed@action{#2}%
  \def\pgf@lib@dec@next@state{main}%
}


\def\pgf@lib@dec@dobetweenmark#1#2#3#4#5\pgf@lib@dec@mark@last{%
  \pgf@lib@dec@parsenum{#1}%
  \let\pgf@lib@dec@mark@start=\pgf@lib@dec@computed@width%
  \pgf@lib@dec@parsenum{#2}%
  \let\pgf@lib@dec@mark@end=\pgf@lib@dec@computed@width%
  \ifdim\pgf@lib@dec@mark@end<\pgf@lib@dec@mark@start\relax%
    % Skip!
    #5\pgf@lib@dec@mark@last%
  \else%
    % 
    \pgf@lib@dec@parsenum{#3}%
    \pgfmathparse{\pgf@lib@dec@mark@start+\pgf@lib@dec@computed@width}%
    % Update entry in mark list
    \edef\pgf@temp{\noexpand\pgf@lib@dec@dobetweenmark{\pgfmathresult pt}{\pgf@lib@dec@mark@end}{\pgf@lib@dec@computed@width}}%
    \expandafter\def\expandafter\pgf@lib@dec@mark@marks\expandafter{\pgf@temp{#4}#5}%
    \let\pgf@lib@dec@computed@width\pgf@lib@dec@mark@start%
    \def\pgf@lib@dec@computed@action{#4}%
    \def\pgf@lib@dec@next@state{main}%
  \fi%
}


\def\pgf@lib@dec@parsenum#1{%
  \pgfmathparse{#1}%
  \ifpgfmathunitsdeclared%
    \ifdim\pgfmathresult pt<0pt\relax%
      \pgfmathparse{\pgfdecoratedpathlength\pgfmathresult pt}%
    \else%
      \pgfmathparse{\pgfmathresult pt}%
    \fi%
  \else%  
    \ifdim\pgfmathresult pt<0pt\relax%
      \pgfmathparse{\pgfdecoratedpathlength\pgfmathresult*\pgfdecoratedpathlength}%
    \else%
      \pgfmathparse{\pgfmathresult*\pgfdecoratedpathlength}%
    \fi%
  \fi%
  \edef\pgf@lib@dec@computed@width{\pgfmathresult pt}%  
}

\def\pgf@lib@dec@mark@last{%
  \def\pgf@lib@dec@next@state{final}%
}


%
% If you set the mark connection node inside a mark picture, the
% output path will contain a line to this node  
%

\pgfkeys{/pgf/decoration/mark connection node/.store in=\pgf@lib@mark@node,
  /pgf/decoration/mark connection node=}
\def\pgf@lib@mark@connect@node{%
  % Line to "left" end of the node
  \pgfpathlineto{\pgfpointshapeborder{\pgf@lib@mark@node}{\pgfqpoint{-1pt}{0pt}}}
  % Move to "right" end of the node
  \pgfpathmoveto{\pgfpointshapeborder{\pgf@lib@mark@node}{\pgfqpoint{1pt}{0pt}}}
}%


\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
pgflibrarydecorations.shapes.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}


% Options for shape decorations

\pgfkeys{
  /pgf/decoration/.cd,
  shape/.initial=circle,
  anchor/.initial=center,
  shape start width/.initial=2.5pt,
  shape start height/.initial=2.5pt,
  shape end width/.initial=2.5pt,
  shape end height/.initial=2.5pt,
  shape sep/.store in=\pgf@lib@shapedecoration@sep,
  shape sloped/.is if=pgfshapedecorationsloped,
  shape scaled/.is if=pgfshapedecorationscaled,
  shape evenly spread/.store in=\pgf@lib@shapedecoration@spread,
  shape start size/.style={%
    shape start width=#1,
    shape start height=#1%
  },%
  shape end size/.style={%
    shape end width=#1,
    shape end height=#1%
  },%
  shape size/.style={%
    shape start size=#1,
    shape end size=#1%
  },%
  shape width/.style={%
    shape start width=#1,
    shape end width=#1
  },
  shape height/.style={%
    shape start height=#1,
    shape end height=#1
  }
}

\def\pgf@lib@shapedecoration@sep{.25cm, between centers}
\newif\ifpgfshapedecorationsloped
\pgfshapedecorationslopedtrue
\newif\ifpgfshapedecorationscaled
\let\pgf@lib@shapedecoration@spread\pgfutil@empty%



% triangle decoration

\pgfdeclaredecoration{triangles}{init}
{
  \state{init}[width=+0pt,next state=triangle,persistent precomputation={
    \pgfmathparse{\pgfkeysvalueof{/pgf/decoration/shape start width}}
    \edef\pgf@lib@dec@ssw{\pgfmathresult pt}
    \pgfmathparse{\pgfkeysvalueof{/pgf/decoration/shape start height}/2}
    \edef\pgf@lib@dec@ssh{\pgfmathresult pt}
  }]{}  
  \state{triangle}[switch if less than=+\pgfdecorationsegmentlength to last,
                   width=+\pgfdecorationsegmentlength]
  {
    \pgfpathmoveto{\pgfqpoint{0pt}{\pgf@lib@dec@ssh}}
    \pgfpathlineto{\pgfqpoint{\pgf@lib@dec@ssw}{0pt}}
    \pgfpathlineto{\pgfqpoint{0pt}{-\pgf@lib@dec@ssh}}
    \pgfpathclose
  }
  \state{last}[switch if less than=\pgf@lib@dec@ssw to skip,
               width=\pgfdecoratedremainingdistance,next state=final]
  {
    \pgfpathmoveto{\pgfqpoint{0pt}{\pgf@lib@dec@ssh}}
    \pgfpathlineto{\pgfqpoint{\pgf@lib@dec@ssw}{0pt}}
    \pgfpathlineto{\pgfqpoint{0pt}{-\pgf@lib@dec@ssh}}
    \pgfpathclose
  }
  \state{skip}[width=\pgfdecoratedremainingdistance]
  {}
  \state{final}
  {
    \pgfpathmoveto{\pgfpointdecoratedpathlast}
  }
}




% crosses decoration

\pgfdeclaredecoration{crosses}{init}
{
  \state{init}[width=+0pt,next state=crosses,persistent precomputation={
    \pgfmathparse{\pgfkeysvalueof{/pgf/decoration/shape start width}/2}
    \edef\pgf@lib@dec@ssw{\pgfmathresult pt}
    \pgfmathparse{\pgfkeysvalueof{/pgf/decoration/shape start height}/2}
    \edef\pgf@lib@dec@ssh{\pgfmathresult pt}
  }]{}  
  \state{crosses}[switch if less than=+\pgfdecorationsegmentlength to last,
                  width=+\pgfdecorationsegmentlength]
  {
    \pgfpathmoveto{\pgfqpoint{-\pgf@lib@dec@ssw}{\pgf@lib@dec@ssh}}
    \pgfpathlineto{\pgfqpoint{\pgf@lib@dec@ssw}{-\pgf@lib@dec@ssh}}
    \pgfpathmoveto{\pgfqpoint{-\pgf@lib@dec@ssw}{-\pgf@lib@dec@ssh}}
    \pgfpathlineto{\pgfqpoint{\pgf@lib@dec@ssw}{\pgf@lib@dec@ssh}}
  }
  \state{last}[width=+\pgfdecoratedremainingdistance]
  {
    \pgfpathmoveto{\pgfqpoint{-\pgf@lib@dec@ssw}{\pgf@lib@dec@ssh}}
    \pgfpathlineto{\pgfqpoint{\pgf@lib@dec@ssw}{-\pgf@lib@dec@ssh}}
    \pgfpathmoveto{\pgfqpoint{-\pgf@lib@dec@ssw}{-\pgf@lib@dec@ssh}}
    \pgfpathlineto{\pgfqpoint{\pgf@lib@dec@ssw}{\pgf@lib@dec@ssh}}
  }
  \state{final}{
    \pgfpathmoveto{\pgfpointdecoratedpathlast}
  }
}






% The shape background decoration
%	
% The shape background decoration adds repeated instances of 
% the background path of a specified shape along the path. The shape
% must have been declared  by \pgfdeclareshape. If a shape has
% specialized keys (e.g. the number of points on a star, or the apex
% angle the isosceles triangle), these can be specified in the usual manner. 
%	
% The sepatation between shapes in the path can be specified and can 
% be between the center of the shape or the border of the shape. 
%	
% The height and width of the shape can be independently or
% simultaneously scaled (linearly) along the path. It is also
% possible to prevent the shapes being sloped parallel to the
% path.

% internal if
\newif\ifpgf@lib@shapedecoration@betweenborders

\edef\pgf@lib@shapedecoration@initialise{0pt}%

\pgfdeclaredecoration{shape backgrounds}{initialise}
{
  \state{initialise}
  [
    width=+\pgf@lib@shapedecoration@initialise,
    next state=shape,
    persistent precomputation=
    {
      % 
      % \egroup ends the group started by the automaton before executing
      % a decoration state. This prevents the need for (most) \global variables. 
      % 
      % 
      % Check the shape exists.
      % 
      \pgfutil@ifundefined{pgf@sh@bg@\pgfkeysvalueof{/pgf/decoration/shape}}{%
        \pgferror{I do not know the shape `\pgfkeysvalueof{/pgf/decoration/shape}',
          so I cannot use it in a decoration. Check if its library been loaded or if you 
          simply mistyped the name}}{}%
      % 
      % Calculate a `default' path size.
      % 
      \pgfinterruptpath%
        \pgfinterruptboundingbox%
          \pgftransformreset%
          \pgf@relevantforpicturesizetrue%
          % 
          % This size of this shape is unimportant, but it should
          % be just large/small enough to avoid huge errors when
          % calculting the scaling factors later on.
          % 
          \pgfkeys{/pgf/inner sep=50pt, /pgf/minimum size=1pt}% Arbitrary lengths.
          \setbox\pgfnodeparttextbox\hbox{}% Assume shape does nothing special if box is empty.
          \let\pgf@sh@savedmacros\pgfutil@empty% 
          \let\pgf@sh@savedpoints\pgfutil@empty%
          \csname pgf@sh@s@\pgfkeysvalueof{/pgf/decoration/shape}\endcsname%
          \pgf@sh@savedpoints%
          \pgf@sh@savedmacros%
          % 
          % Save the macros and pionts.
          % 
          \expandafter\gdef\expandafter\pgf@lib@shapedecoration@points\expandafter{\pgf@sh@savedpoints}%
          \expandafter\gdef\expandafter\pgf@lib@shapedecoration@macros\expandafter{\pgf@sh@savedmacros}%
          \csname pgf@sh@bg@\pgfkeysvalueof{/pgf/decoration/shape}\endcsname% 
          % 
          % Save the dimensions of the shape path.
          % 
          \pgf@x\pgf@picmaxx%
          \pgf@y\pgf@picmaxy%
          \advance\pgf@x-\pgf@picminx%
          \advance\pgf@y-\pgf@picminy%
          \xdef\pgf@lib@shapedecoration@shapepathsize{%
            \noexpand\pgf@x\the\pgf@x%
            \noexpand\pgf@y\the\pgf@y%
          }%
        \endpgfinterruptboundingbox%
      \endpgfinterruptpath%
      % 
      \edef\pgf@lib@shapedecoration@beforeshape{0pt}%
      \edef\pgf@lib@shapedecoration@aftershape{0pt}%
      % 
      \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/decoration/shape start width}}%
      \edef\pgf@lib@shapedecoration@startwidth{\the\pgf@x}%
      \edef\pgf@lib@shapedecoration@width{\the\pgf@x}%
      \pgf@x-\pgf@x%
      \pgfmathaddtolength\pgf@x{\pgfkeysvalueof{/pgf/decoration/shape end width}}%
      \edef\pgf@lib@shapedecoration@widthchange{\the\pgf@x}%
      % 
      \pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/decoration/shape start height}}%
      \edef\pgf@lib@shapedecoration@initialheight{\the\pgf@y}%
      \edef\pgf@lib@shapedecoration@height{\the\pgf@y}%
      \pgf@y-\pgf@y%
      \pgfmathaddtolength\pgf@y{\pgfkeysvalueof{/pgf/decoration/shape end height}}%
      \edef\pgf@lib@shapedecoration@heightchange{\the\pgf@y}%		
      % 
      % Calculate the sep.
      % 
      \ifx\pgf@lib@shapedecoration@spread\pgfutil@empty%
        % 
        % Not spreading, so easy:
        % 
        \def\pgf@lib@shapedecoration@borderstext{between borders}%
        \afterassignment\pgf@lib@shapedecoration@setkeyword%
        \expandafter\pgf@x\pgf@lib@shapedecoration@sep,\pgf@stop%
        \edef\pgf@lib@shapedecoration@sep{\the\pgf@x}%
      \else%
        % 
        % Spreading (a bit of a nuiscence actually).
        % 
        \def\pgf@lib@shapedecoration@borderstext{by borders}%
        \afterassignment\pgf@lib@shapedecoration@setkeyword%
        \expandafter\c@pgf@counta\pgf@lib@shapedecoration@spread,\pgf@stop%
        \ifpgf@lib@shapedecoration@betweenborders%
          %  
          % Ok. The required sep between borders is:
          % 
          % (r -(n-1)((a+b)/2))/(n-1)
          % 
          % r = decoration length (here, the remaining distance)
          % a = initial width
          % b = end width
          % n = the number of shapes
          % 
          \ifnum\c@pgf@counta>1\relax%
            \advance\c@pgf@counta-1\relax%
            \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/decoration/shape start width}}%
            \ifpgfshapedecorationscaled%
              \pgfmathaddtolength\pgf@x{\pgfkeysvalueof{/pgf/decoration/shape end width}}%
            \else%
              \advance\pgf@x\pgf@x%
            \fi%
            \pgf@x.5\pgf@x% (a+b)/2
            \multiply\pgf@x-\c@pgf@counta% -(n-1)((a+b)/2)
            \advance\pgf@x\pgfdecoratedremainingdistance%
            \divide\pgf@x\c@pgf@counta%
            \pgf@x.9999\pgf@x% Hackery to control some native TeX inaccuracies.
            % 
            % Unfortunately if the shape is scaled, and evenly spread by borders,
            % it is necessary to do something a bit different to control for 
            % (most) inaccuracies.
            % 
            \ifpgfshapedecorationscaled%
              \pgf@xa\pgf@lib@shapedecoration@widthchange\relax%
              \divide\pgf@xa\c@pgf@counta%
              \edef\pgf@lib@shapedecoration@specialwidth{\the\pgf@xa}%		
            \fi%
          \else%
            \pgf@lib@shapedecoration@betweenbordersfalse%
            \pgf@x\pgfdecoratedremainingdistance%
            \ifnum\c@pgf@counta=1\relax%
              \pgf@y.5\pgf@x%
              \edef\pgf@lib@shapedecoration@initialise{\the\pgf@y}%
            \else%
              \advance\pgf@x5pt\relax% An arbitrary value >0pt.
              \edef\pgf@lib@shapedecoration@initialise{\the\pgf@x}%
            \fi%
          \fi%	
        \else%
          %  
          % Between centers.
          % 
          \pgf@x\pgfdecoratedremainingdistance%
          \ifnum\c@pgf@counta>1\relax%
            \advance\c@pgf@counta-1\relax%
            \divide\pgf@x\c@pgf@counta\relax%
          \else%
            \ifnum\c@pgf@counta=1\relax%
              \pgf@y.5\pgf@x%
              \edef\pgf@lib@shapedecoration@initialise{\the\pgf@y}%
            \else%
              \advance\pgf@x5pt\relax% An arbitrary value >0pt.
              \edef\pgf@lib@shapedecoration@initialise{\the\pgf@x}%
            \fi%
          \fi%
        \fi%
        \edef\pgf@lib@shapedecoration@sep{\the\pgf@x}%
      \fi%
    }]
  {}
  \state{before shape}
  [
    width=\pgf@lib@shapedecoration@beforeshape-1sp,
    next state=shape,
    persistent precomputation=
    {
      \ifpgfshapedecorationscaled%
        \ifpgf@lib@shapedecoration@betweenborders%
          \ifx\pgf@lib@shapedecoration@spread\pgfutil@empty%
            % 
            % Not so straightforward. The required ratio is given by
            % 
            % R = (c+W/2)/(c+r-.5*w)
            % 
            % c = completed distance
            % r = remaining distance
            % W = initial width
            % w = the change in width (i.e., end - start)
            % 
            \pgf@x\pgfdecoratedcompleteddistance%
            \advance\pgf@x\pgfdecoratedremainingdistance%
            \pgf@xa\pgf@lib@shapedecoration@startwidth\relax%
            \pgf@xa.5\pgf@xa%
            \advance\pgf@xa\pgfdecoratedcompleteddistance% c+W/2
            % 
            \pgf@xb\pgf@lib@shapedecoration@widthchange\relax%
            \pgf@xb-.5\pgf@xb%
            \advance\pgf@xb\pgf@x% c+r-.5*w
            % 
            \pgfmathdivide@{\pgfmath@tonumber{\pgf@xa}}{\pgfmath@tonumber{\pgf@xb}}%
          \fi%
        \else%
          % 
          % Easy peasy. The required ratio is 
          % 
          % R = c / (c+r)
          % 
          \pgf@y\pgfdecoratedcompleteddistance%
          \advance\pgf@y\pgfdecoratedremainingdistance%
          \pgfmathdivide@{\pgfmath@tonumber{\pgfdecoratedcompleteddistance}}{\pgfmath@tonumber{\pgf@y}}%			
        \fi%
        % 
        % Get the new width.
        % 
        \ifx\pgf@lib@shapedecoration@spread\pgfutil@empty%
          \pgf@x\pgf@lib@shapedecoration@widthchange\relax%
          \pgf@x\pgfmathresult\pgf@x%
          \advance\pgf@x\pgf@lib@shapedecoration@startwidth\relax%
        \else%
          \ifpgf@lib@shapedecoration@betweenborders%
            % 
            % Specical case when decoration is scaled, and evenly spread by borders.
            % 
            \pgf@x\pgf@lib@shapedecoration@width\relax%
            \advance\pgf@x\pgf@lib@shapedecoration@specialwidth\relax%
            \pgf@xa\pgf@x%
            \advance\pgf@xa-\pgf@lib@shapedecoration@startwidth\relax%
            \pgf@xb\pgf@lib@shapedecoration@widthchange\relax%
            \pgfmathdivide@{\pgfmath@tonumber{\pgf@xa}}{\pgfmath@tonumber{\pgf@xb}}%
          \else%
            \pgf@x\pgf@lib@shapedecoration@widthchange\relax%
            \pgf@x\pgfmathresult\pgf@x%
            \advance\pgf@x\pgf@lib@shapedecoration@startwidth\relax%
          \fi%
        \fi%		
        \edef\pgf@lib@shapedecoration@width{\the\pgf@x}%		
        % 
        % New height = R*h + H
        % 
        \pgf@y\pgf@lib@shapedecoration@heightchange\relax%
        \pgf@y\pgfmathresult\pgf@y%
        \advance\pgf@y\pgf@lib@shapedecoration@initialheight\relax%
        \edef\pgf@lib@shapedecoration@height{\the\pgf@y}%
      \fi%
      % 
      \ifpgf@lib@shapedecoration@betweenborders%
        \pgf@x\pgf@lib@shapedecoration@width\relax%
        \pgf@x.5\pgf@x%
        \edef\pgf@lib@shapedecoration@beforeshape{\the\pgf@x}%
      \else%
        \def\pgf@lib@shapedecoration@beforeshape{0pt}%
      \fi%	
    }]
  {}
  \state{shape}[width=+0sp,next state=after shape]
  {
    \ifpgfshapedecorationsloped%
    \else%
      \pgftransformrotate{-\pgfdecoratedangle}%
    \fi%
    % 
    % Scale the path when it is actually drawn.
    % 
    \pgf@lib@shapedecoration@shapepathsize%
    \pgfutil@tempdima\pgf@x%
    \pgfutil@tempdimb\pgf@y%
    \pgf@xa\pgf@lib@shapedecoration@width\relax%
    \pgf@xb\pgfutil@tempdima%
    \pgfmathdivide@{\pgfmath@tonumber{\pgf@xa}}{\pgfmath@tonumber{\pgf@xb}}%
    \expandafter\pgftransformxscale\expandafter{\pgfmathresult}%
    % 
    \pgf@ya\pgf@lib@shapedecoration@height\relax%
    \pgf@yb\pgfutil@tempdimb%
    \pgfmathdivide@{\pgfmath@tonumber{\pgf@ya}}{\pgfmath@tonumber{\pgf@yb}}%
    \expandafter\pgftransformyscale\expandafter{\pgfmathresult}%
    % 
    % Move to the center anchor.
    % 
    \pgf@lib@shapedecoration@points%
    \pgf@lib@shapedecoration@macros%
    \pgftransformshift{%
      \pgf@sh@reanchor{\pgfkeysvalueof{/pgf/decoration/shape}}{\pgfkeysvalueof{/pgf/decoration/anchor}}%
      \pgf@x-\pgf@x%
      \pgf@y-\pgf@y%
    }%
    % 
    % And draw the shape path.
    % 
    \csname pgf@sh@bg@\pgfkeysvalueof{/pgf/decoration/shape}\endcsname%	
  }
  \state{after shape}
  [
    width=\pgf@lib@shapedecoration@aftershape-1sp,
    next state=sep,
    persistent precomputation=
    {
      \ifpgf@lib@shapedecoration@betweenborders%
        \pgf@x\pgf@lib@shapedecoration@width\relax%
        \pgf@x.5\pgf@x%
        \edef\pgf@lib@shapedecoration@aftershape{\the\pgf@x}%
      \else%
        \edef\pgf@lib@shapedecoration@aftershape{0pt}%
      \fi%
    }
  ]
  {}
  \state{sep}[width=\pgf@lib@shapedecoration@sep,next state=before shape,
              persistent precomputation=\def\pgf@lib@shapedecoration@beforeshape{0pt}]
  {}
  \state{final}
  {
    \pgfpathmoveto{\pgfpointdecoratedpathlast}%
  }
}

\def\pgf@lib@shapedecoration@setkeyword,{%
  \pgfutil@ifnextchar\pgf@stop{\def\pgf@temp{}\pgf@lib@@@shapedecoration@setkeyword}{\pgf@lib@@shapedecoration@setkeyword}%
}
\def\pgf@lib@@shapedecoration@setkeyword#1,{\def\pgf@temp{#1}\pgf@lib@@@shapedecoration@setkeyword}
\def\pgf@lib@@@shapedecoration@setkeyword\pgf@stop{%
  \ifx\pgf@temp\pgf@lib@shapedecoration@borderstext%
    \pgf@lib@shapedecoration@betweenborderstrue%
  \else%
    \pgf@lib@shapedecoration@betweenbordersfalse%
  \fi%
}



\endinput
pgflibrarydecorations.text.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}


% Options for text decorations

\pgfkeys{
  /pgf/decoration/.cd,
  text/.store in=\pgfdecorationtext,%                                                 
  text color/.store in=\pgf@lib@decorationtextcolor,%
  text format delimiters/.code={\expandafter\pgfsetdecoratetextformatdelimiters#1},
  text align/.code={\pgfkeys{/pgf/decoration/text align/.cd,#1}},
	text align/.cd,
	align/.initial=left,
	left/.style={/pgf/decoration/text align/align=left},
	right/.style={/pgf/decoration/text align/align=right},
	center/.style={/pgf/decoration/text align/align=center},
	left indent/.initial=0pt,
	right indent/.initial=0pt,
	fit to path/.is if=pgf@lib@dec@text@fit,
	fit to path stretching spaces/.default=true,
	fit to path stretching spaces/.code={%
		\csname pgf@lib@dec@text@fit#1\endcsname%
		\csname pgf@lib@dec@text@stretch@spaces#1\endcsname%
	}%
}

\newif\ifpgf@lib@dec@text@scan@space
\newif\ifpgf@lib@dec@text@stretch@spaces
\newif\ifpgf@lib@dec@text@fit

\def\pgf@lib@decorationtextcolor{black}

\def\pgf@lib@dec@text@left@text{left}
\def\pgf@lib@dec@text@right@text{right}
\def\pgf@lib@dec@text@right@center{center}

% Decorates a path with a text. The path is removed during this
% process

\pgfdeclaredecoration{text along path}{initial}{
\state{initial}[width=+0pt, next state=left indent, 
	persistent precomputation={%
		\edef\pgf@lib@dec@text@indent@left{\pgfkeysvalueof{/pgf/decoration/text align/left indent}}%
		\edef\pgf@lib@dec@text@indent@right{\pgfkeysvalueof{/pgf/decoration/text align/right indent}}%
		\edef\pgf@lib@dec@text@align{\pgfkeysvalueof{/pgf/decoration/text align/align}}%
		\pgfdecoratedremainingdistance=\pgfdecoratedpathlength%
	  \advance\pgfdecoratedremainingdistance by-\pgf@lib@dec@text@indent@right\relax%
	  \edef\pgfdecoratedpathlength{\the\pgfdecoratedremainingdistance}%
	  \pgf@lib@dec@text@getwidth%
	  \pgf@x=\pgf@lib@dec@text@width\relax%
	  \pgf@y=\pgfdecoratedremainingdistance%
	  \ifpgf@lib@dec@text@fit%
	  	\advance\pgf@y by-\pgf@lib@dec@text@indent@left\relax%
	  	\advance\pgf@y by-\pgf@x%
	  	\ifpgf@lib@dec@text@stretch@spaces%
	  		\def\pgf@lib@dec@text@character@shift{0pt}%
	  		\divide\pgf@y by\pgf@lib@dec@space@count\relax%
	  		\edef\pgf@lib@dec@text@space@shift{\the\pgf@y}%
	  	\else%
		  	\c@pgf@counta=\pgf@lib@dec@character@count\relax%
		  	\advance\c@pgf@counta by-1\relax%
		  	\divide\pgf@y by\c@pgf@counta\relax%
		  	\edef\pgf@lib@dec@text@character@shift{\the\pgf@y}%
		  	\def\pgf@lib@dec@text@space@shift{0pt}%
		  \fi%
		  \ifdim\pgf@y<0pt\relax%
		  	\pgf@lib@dec@text@fitfalse%
		  	\pgf@lib@dec@text@stretch@spacesfalse%
		  	\def\pgf@lib@dec@text@character@shift{0pt}%
		  	\def\pgf@lib@dec@text@space@shift{0pt}%
		  \fi%
	  \else%
	  	\def\pgf@lib@dec@text@character@shift{0pt}%
	  	\def\pgf@lib@dec@text@space@shift{0pt}%
		  \ifx\pgf@lib@dec@text@align\pgf@lib@dec@text@left@text%
		  \else%
		  	\ifx\pgf@lib@dec@text@align\pgf@lib@dec@text@right@text%
		  		\advance\pgf@y by-\pgf@x%
		  		\edef\pgf@lib@dec@text@indent@left{\the\pgf@y}%
		  	\else%
		  		\advance\pgf@y by-\pgf@x%
		  		\advance\pgf@y by-\pgf@lib@dec@text@indent@left\relax%
		  		\pgf@y=0.5\pgf@y%
		  		\advance\pgf@y by\pgf@lib@dec@text@indent@left\relax%
		  		\edef\pgf@lib@dec@text@indent@left{\the\pgf@y}%
		  	\fi%
		  \fi%
	  \fi%
	  \let\pgfdecorationrestoftext=\pgfdecorationtext%
	}]{}
\state{left indent}[width=+\pgf@lib@dec@text@indent@left, next state=scan]{}
%
\state{scan}[width=+0pt, next state=before typeset,
 persistent precomputation={
   \pgf@lib@dec@text@scanchar%
   \ifvoid\pgf@lib@dec@text@box%
     \setbox\pgf@lib@dec@text@box\hbox{}%
     \wd\pgf@lib@dec@text@box16383pt\relax%
   \fi%
 }]{}
%
\state{before typeset}[width=+.5\wd\pgf@lib@dec@text@box, next state=typeset]{}
%
\state{typeset}[width=+0pt, next state=after typeset]
{%
  \pgftransformxshift{+-.5\wd\pgf@lib@dec@text@box}%
  \setbox\pgf@hbox\hbox{\copy\pgf@lib@dec@text@box}%
  \pgfqboxsynced\pgf@hbox%
}
\state{after typeset}[width=+.5\wd\pgf@lib@dec@text@box, next state=shift,
	persistent precomputation={%
  	\ifpgf@lib@dec@text@fit%
	  	\ifpgf@lib@dec@text@stretch@spaces%
	  		\ifpgf@lib@dec@text@scan@space%
	  			\let\pgf@lib@dec@text@shift=\pgf@lib@dec@text@space@shift%
	  		\else%
	  			\def\pgf@lib@dec@text@shift{0pt}%
	  		\fi%
	  	\else%
		  	\let\pgf@lib@dec@text@shift=\pgf@lib@dec@text@character@shift%
		  \fi%
		\else%
			\def\pgf@lib@dec@text@shift{0pt}%
	  \fi%  
  }]{}
\state{shift}[width=+\pgf@lib@dec@text@shift, next state=scan]{}
\state{final}{}
}


% \pgfsetdecoratetextformatdelimiters
% 
% Set the delimiters for formatting in the text decoration.
% NB: Catcodes for delimiters should be 11 or 12.
%
% Examples:
%
% \pgfsetdecoratetextformatdelimiters{|}{}% 2nd argument can be empty.
%
% \def\pgfdecoratetext{A big |\color{red}|red|| apple.}
%
% \pgfsetdecoratetextformatdelimiters{[}{]}
%
% \def\pgfdecoratetext{The [\it]very[+\color{green}]green[] sprouts.}
%
\def\pgfsetdecoratetextformatdelimiters#1#2{%
	\def\pgf@lib@dec@text@formatchar{#1}%
	\def\pgf@test{#2}%
	\ifx\pgf@test\pgfutil@empty%
		\def\pgf@lib@dec@text@collectformat##1#1{%
		\pgf@lib@dec@text@@collectformat##1\pgf@stop}%
	\else%
		\def\pgf@lib@dec@text@collectformat##1#2{%
			\pgf@lib@dec@text@@collectformat##1\pgf@stop}%
	\fi%
}

\pgfsetdecoratetextformatdelimiters{|}{}

\newbox\pgf@lib@dec@text@box
\newif\ifpgf@lib@decorate@textmathmode

\let\pgfdecorationtext=\pgfutil@empty
\let\pgfdecorationrestoftext=\pgfutil@empty%
\let\pgf@lib@dec@text@format=\pgfutil@empty

\def\pgf@lib@dec@text@scanchar{%
	\pgf@lib@dec@text@scan@spacefalse%
	\ifx\pgfdecorationrestoftext\pgfutil@empty%
		\let\pgf@lib@dec@text@char\pgfutil@empty%
		\setbox\pgf@lib@dec@text@box\box\pgfutil@voidb@x%
		\let\pgf@next\relax%
	\else%
		\let\pgf@next\pgf@lib@dec@text@@scanchar%
	\fi%
	\pgf@next}
	
\def\pgf@lib@dec@text@@scanchar{%
	\expandafter\pgf@lib@dec@text@@@scanchar\pgfdecorationrestoftext\pgf@stop}

\def\pgf@lib@dec@text@@@scanchar{%
	\futurelet\pgf@lib@dec@lettoken%
	\pgf@lib@dec@text@@@@scanchar}
	
\def\pgf@lib@dec@text@@@@scanchar{%
	\ifx\pgf@lib@dec@lettoken\pgfutil@sptoken%
		\let\pgf@next\pgf@lib@dec@text@insertspace%
	\else%
		\let\pgf@next\pgf@lib@dec@text@@@@@scanchar%
	\fi%
	\pgf@next}

\def\pgf@lib@dec@text@@@@@scanchar{%
	\pgfutil@ifnextchar\bgroup{\pgf@lib@dec@text@collectgroup}%
		{\pgf@lib@dec@text@@@@@@scanchar}}
		
\def\pgf@lib@dec@text@collectgroup#1{%
	\def\pgf@lib@dec@text@char{#1}%
	\pgf@lib@dec@text@collectrestoftext}
	
\def\pgf@lib@dec@text@@@@@@scanchar#1{%
	\ifx#1\pgf@stop%
		\pgf@lib@dec@text@box\box\pgfutil@voidb@x%
		\let\pgf@next\pgf@lib@dec@text@endoftext%
	\else%
		\def\pgf@lib@dec@text@char{#1}%
		\ifx#1\space%
			\let\pgf@next\pgf@lib@dec@text@collectrestoftext%
		\else%
			\ifx#1\ %
				\let\pgf@next\pgf@lib@dec@text@collectrestoftext%
			\else%
				\ifx\pgf@lib@dec@text@char\pgf@lib@dec@text@formatchar%
					\let\pgf@next\pgf@lib@dec@text@collectformat%
				\else%
					\expandafter\ifcat\noexpand#1\relax%
						\let\pgf@next\pgf@lib@dec@text@expandcs%
					\else%
						\ifnum\catcode`#1=3\relax%
							\ifpgf@lib@decorate@textmathmode%
								\pgf@lib@decorate@textmathmodefalse%
							\else%
								\pgf@lib@decorate@textmathmodetrue%
							\fi%
							\let\pgf@next\pgf@lib@dec@text@@@scanchar%
						\else%
							\let\pgf@next\pgf@lib@dec@text@collectrestoftext%
						\fi%
					\fi%
				\fi%
			\fi%
		\fi%
	\fi%
	\pgf@next%
}

\def\pgf@lib@dec@text@@collectformat{%
	\pgfutil@ifnextchar+{\pgf@lib@dec@text@addtoformat}{\pgf@lib@dec@text@setformat}}
	
\def\pgf@lib@dec@text@setformat#1\pgf@stop{%
	\def\pgf@lib@dec@text@format{#1}%
	\pgf@lib@dec@text@@@scanchar%
}

\def\pgf@lib@dec@text@addtoformat+#1\pgf@stop{%
	\expandafter\def\expandafter\pgf@lib@dec@text@format\expandafter{\pgf@lib@dec@text@format#1}%
	\pgf@lib@dec@text@@@scanchar%
}

\def\pgf@lib@dec@text@insertspace{%
	\pgf@lib@dec@text@scan@spacetrue%
	\pgfutil@ifnextchar\bgroup{\pgf@lib@dec@text@@insertspacegrp}%
		{\pgf@lib@dec@text@@insertspace}}
				
\def\pgf@lib@dec@text@@insertspacegrp#1{%
	\pgf@lib@dec@text@@@@@@scanchar\space{#1}}
	
\def\pgf@lib@dec@text@@insertspace#1{%
	\pgf@lib@dec@text@@@@@@scanchar\space#1}
	
\def\pgf@lib@dec@text@expandcs{%
	\expandafter\expandafter\expandafter\pgf@lib@dec@text@@@@@scanchar%
		\pgf@lib@dec@text@char}

\def\pgf@lib@dec@text@endoftext{%
	\let\pgfdecoraterestoftext\pgfutil@empty%
	\let\pgf@lib@dec@text@char\pgfutil@empty%
}
\def\pgf@lib@dec@text@collectrestoftext{%
	\pgf@lib@dec@text@dobox%
	\futurelet\pgf@lib@dec@text@lettoken%
	\pgf@lib@dec@text@@collectrestoftext}

\def\pgf@lib@dec@text@@collectrestoftext{%
	\ifx\bgroup\pgf@lib@dec@text@lettoken%
		\let\pgf@next\pgf@lib@dec@text@@@collectrestoftextgrp%
	\else%
		\let\pgf@next\pgf@lib@dec@text@@@collectrestoftext%
	\fi%
	\pgf@next}
	
\def\pgf@lib@dec@text@@@collectrestoftextgrp#1#2\pgf@stop{\def\pgfdecorationrestoftext{{#1}#2}%
}

\def\pgf@lib@dec@text@@@collectrestoftext#1\pgf@stop{\def\pgfdecorationrestoftext{#1}}

{%
	\catcode`\$3 %
	\gdef\pgf@lib@dec@mathshift{$}%
	\catcode`\$9 $% For editors with annoying syntax highlighting.
}%

\def\pgf@lib@dec@text@dobox{%
	\setbox\pgf@lib@dec@text@box\hbox{%
		\pgfinterruptpicture%
		\begingroup%
			\pgfsetcolor{\pgf@lib@decorationtextcolor}%
			\ifpgf@lib@decorate@textmathmode\pgf@lib@dec@mathshift\fi%
				\pgf@lib@dec@text@format\relax%
				\pgf@lib@dec@text@char%
			\ifpgf@lib@decorate@textmathmode\pgf@lib@dec@mathshift\fi%
		\endgroup%
		\endpgfinterruptpicture%
	}%
}

\def\pgf@lib@dec@text@getwidth{%
	\begingroup%
		\let\c@pgf@lib@dec@characters=\c@pgf@counta%
		\let\c@pgf@lib@dec@spaces=\c@pgf@countb%
		\let\pgfdecorationrestoftext=\pgfdecorationtext%
		\c@pgf@lib@dec@spaces=0\relax%
		\c@pgf@lib@dec@characters=0\relax%
		\pgfmathloop%
			\pgf@lib@dec@text@scanchar%
			\ifvoid\pgf@lib@dec@text@box%
			\else%
				\setbox\pgf@hbox=\hbox{{%
					\unhbox\pgf@hbox%
					\unhbox\pgf@lib@dec@text@box%
				}}%
				\advance\c@pgf@lib@dec@characters by1\relax%
				\ifpgf@lib@dec@text@scan@space%
					\advance\c@pgf@lib@dec@spaces by1\relax%
				\fi%
		\repeatpgfmathloop%
		\global\pgf@x=\the\wd\pgf@hbox%
		\xdef\pgf@lib@dec@temp{\the\c@pgf@lib@dec@characters}%
		\xdef\pgf@lib@dec@@temp{\the\c@pgf@lib@dec@spaces}%
	\endgroup%
	\edef\pgf@lib@dec@text@width{\the\pgf@x}%
	\let\pgf@lib@dec@character@count=\pgf@lib@dec@temp%
	\let\pgf@lib@dec@space@count=\pgf@lib@dec@@temp%
}



\endinput
pgflibraryfadings.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/pgflibraryfadings.code.tex,v 1.3 2008/02/07 19:25:41 tantau Exp $


% Axial fadings

\pgfdeclarehorizontalshading{pgf@lib@fade@east}{100bp}
{color(0bp)=(pgftransparent!0); color(25bp)=(pgftransparent!0);
 color(75bp)=(pgftransparent!100); color(100bp)=(pgftransparent!100)}

\pgfdeclarehorizontalshading{pgf@lib@fade@west}{100bp}
{color(0bp)=(pgftransparent!100); color(25bp)=(pgftransparent!100);
 color(75bp)=(pgftransparent!0); color(100bp)=(pgftransparent!0)}

\pgfdeclareverticalshading{pgf@lib@fade@north}{100bp}
{color(0bp)=(pgftransparent!0); color(25bp)=(pgftransparent!0);
 color(75bp)=(pgftransparent!100); color(100bp)=(pgftransparent!100)}

\pgfdeclareverticalshading{pgf@lib@fade@south}{100bp}
{color(0bp)=(pgftransparent!100); color(25bp)=(pgftransparent!100);
 color(75bp)=(pgftransparent!0); color(100bp)=(pgftransparent!0)}

\pgfdeclarefading{east}{\pgfuseshading{pgf@lib@fade@east}}
\pgfdeclarefading{west}{\pgfuseshading{pgf@lib@fade@west}}
\pgfdeclarefading{north}{\pgfuseshading{pgf@lib@fade@north}}
\pgfdeclarefading{south}{\pgfuseshading{pgf@lib@fade@south}}


% Circular fadings

\pgfdeclareradialshading{tikz@lib@fade@circle@10}{\pgfpointorigin}{
  color(0pt)=(pgftransparent!0); color(22.5bp)=(pgftransparent!0);
  color(25bp)=(pgftransparent!100); color(50bp)=(pgftransparent!100)}
\pgfdeclarefading{circle with fuzzy edge 10 percent}{\pgfuseshading{tikz@lib@fade@circle@10}}

\pgfdeclareradialshading{tikz@lib@fade@circle@15}{\pgfpointorigin}{
  color(0pt)=(pgftransparent!0); color(21.25bp)=(pgftransparent!0);
  color(25bp)=(pgftransparent!100); color(50bp)=(pgftransparent!100)}
\pgfdeclarefading{circle with fuzzy edge 15 percent}{\pgfuseshading{tikz@lib@fade@circle@15}}

\pgfdeclareradialshading{tikz@lib@fade@circle@20}{\pgfpointorigin}{
  color(0pt)=(pgftransparent!0); color(20bp)=(pgftransparent!0);
  color(25bp)=(pgftransparent!100); color(50bp)=(pgftransparent!100)}
\pgfdeclarefading{circle with fuzzy edge 20 percent}{\pgfuseshading{tikz@lib@fade@circle@20}}

\pgfdeclareradialshading{tikz@lib@fade@fuzzy@15}{\pgfpointorigin}{
  color(0pt)=(pgftransparent!100); color(21.25bp)=(pgftransparent!100); color(23.125bp)=(pgftransparent!0);
  color(25bp)=(pgftransparent!100); color(50bp)=(pgftransparent!100)}
\pgfdeclarefading{fuzzy ring 15 percent}{\pgfuseshading{tikz@lib@fade@fuzzy@15}}

pgflibraryfixedpointarithmetic.code.tex
% Copyright 2006 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.


\pgfkeys{/pgf/.cd,
	fixed point arithmetic/.code={%
		\pgfmathfp@plots@install%
		\pgfmathfp@parser@install%
		\let\pgfmathparse=\pgfmathfpparse%
		\pgfkeys{/pgf/fixed point/.cd, #1}%
	},%
	fixed point/.cd,
	scale results/.code={%
		\pgfmathfpparse{#1}%
		\let\pgfmathfpscale=\pgfmathresult%
	}%		
}

\def\pgfmathfpscale{1}

\def\pgfmathfpparse{%
	\begingroup%
		\let\pgfmathpostparse=\relax%
		\pgfmath@catcodes%
		\pgfmath@quickparsefalse%
		\pgfmathfpparse@}

\def\pgfmathfpparse@#1{%
	\edef\pgfmathfp@expression{#1}%
	\expandafter\pgfmathfpparse@@\pgfmathfp@expression\pgfmathfp@}

\def\pgfmathfp@char@asterisk{*}
\def\pgfmathfpparse@@#1#2\pgfmathfp@{%
	\def\pgfmathfp@test{#1}%
	\ifx\pgfmathfp@test\pgfmathfp@char@asterisk%
		\edef\pgfmathfp@expression{\pgfmathfpscale#1#2}%
	\else%
		\edef\pgfmathfp@expression{#1#2}%
	\fi%
	\expandafter\pgfmathparse@\expandafter{\pgfmathfp@expression}%
	% \endgroup provided by \pgfpathmarse@end
}

% Crude handling of file plots
%
\pgfkeys{/pgf/fixed point/.cd,
  scale file plot x/.code=\pgfmathfpparse{#1}\edef\pgfmathfpplotscalex{\pgfmathresult*},
  scale file plot y/.code=\pgfmathfpparse{#1}\edef\pgfmathfpplotscaley{\pgfmathresult*},
  scale file plot z/.code=\pgfmathfpparse{#1}\edef\pgfmathfpplotscalez{\pgfmathresult*}
}

\def\pgfmathfp@plots@install{%
	\let\pgfmathfpplotscalex=\pgfutil@empty
	\let\pgfmathfpplotscaley=\pgfutil@empty
	\let\pgfmathfpplotscalez=\pgfutil@empty
	\let\pgf@parsexyline=\pgfmathfp@parsexyline%
	\let\pgf@parsexyzline=\pgfmathfp@parsexyzline%
}

\def\pgfmathfp@parsexyline#1 #2 #3\pgf@stop{%
	\edef\pgfmathfp@marshal{%
		\noexpand\pgfplotstreampoint{\noexpand\pgfpointxy{\pgfmathfpplotscalex#1}{\pgfmathfpplotscaley#2}}%
	}%
	\pgfmathfp@marshal%
}

\def\pgfmathfp@parsexyzline#1 #2 #3 #4\pgf@stop{%
  \edef\pgfmathfp@marshal{%
		\noexpand\pgfplotstreampoint{%
			\noexpand\pgfpointxyz{\pgfmathfpplotscalex#1}{\pgfmathfpplotscaley#2}{\pgfmathfpplotscalez#3}%
		}%
	}%
	\pgfmathfp@marshal%
}

% 
\def\pgfmathfp@parser@install{%
	%
	\expandafter\ifx\csname FP@version\endcsname\relax%
		\pgferror{You need to say `\string\usepackage{fp}' to use %
		  fixed point arithmetic}%
	\else%
	  %
		% Don't want messages.
		%
		\FPmessagesfalse%
		\FPdebugfalse%
		%
		% Install float commands...
		%
		\let\pgfmathadd@=\pgfmathfpadd@%
		\let\pgfmathsubtract@=\pgfmathfpsubtract@%
		\let\pgfmathmultiply@=\pgfmathfpmultiply@%
		\let\pgfmathdivide@=\pgfmathfpdivide@%
		\let\pgfmathabs@=\pgfmathfpabs@%
		\let\pgfmathround@=\pgfmathfpround@%
		\let\pgfmathfloor@=\pgfmathfpfloor@%
		\let\pgfmathceil@=\pgfmathfpceil@%
		\let\pgfmathmod@=\pgfmathfpmod@%
		\let\pgfmathmax@=\pgfmathfpmax@%
		\let\pgfmathmin@=\pgfmathfpmin@%
		\let\pgfmathsin@=\pgfmathfpsin@%
		\let\pgfmathcos@=\pgfmathfpcos@%
		\let\pgfmathtan@=\pgfmathfptan@%
		\let\pgfmathdeg@=\pgfmathfpdeg@%
		\let\pgfmathrad@=\pgfmathfprad@%
		\let\pgfmathatan@=\pgfmathfpatan@%
		\let\pgfmathasin@=\pgfmathfpasin@%
		\let\pgfmathacos@=\pgfmathfpacos@%
		\let\pgfmathcot@=\pgfmathfpcot@%
		\let\pgfmathsec@=\pgfmathfpsec@%
		\let\pgfmathcosec@=\pgfmathfpcosec@%
		\let\pgfmathpow@=\pgfmathfppow@%
		\let\pgfmathexp@=\pgfmathfpexp@%
		\let\pgfmathln@=\pgfmathfpln@%
		\let\pgfmathsqrt@=\pgfmathfpsqrt@%
		\let\pgfmath@pi=\pgfmathfppi@%
		\let\pgfmathveclen@=\pgfmathfpveclen@%
		\let\pgfmathe@=\pgfmathfpe@%
		%
		\let\pgfmathlessthan@=\pgfmathfplessthan@%
		\let\pgfmathgreaterthan@=\pgfmathfpgreaterthan@%
		\let\pgfmathequalto@=\pgfmathfpequalto@%
		%
		\let\pgfmathrnd=\pgfmathfprnd%
		\let\pgfmathrand=\pgfmathfprand%
		\let\pgfmathsetseed=\pgfmathfpsetseed%
		%
		\let\pgfmathscientific=\pgfmathfpscientific%
	\fi%
}%

\def\pgfmathfpe@{let\pgfmathresult=\FPe}%
\def\pgfmathfppi@{let\pgfmathresult=\FPpi}%


% Scientific notation.

\def\pgfmathfpscientific#1#2{%
	\begingroup%
		\FPpow\pgfmathresult{10}{#2}\unskip% Needed.
		\FPmul\pgfmathresult{#1}{\pgfmathresult}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% Comparison stuff...

% lessthan
%
\def\pgfmathfplessthan#1#2{%
	\pgfmathfpparse{#2}\let\pgfmath@result=\pgfmathresult%
	\pgfmathfpparse{#1}%
	\pgfmathfplessthan@{\pgfmathresult}{\pgfmath@result}%
}
\def\pgfmathfplessthan@#1#2{%
	\begingroup%
		\FPiflt{#1}{#2}%
			\def\pgfmathresult{1.0}%
		\else%
			\def\pgfmathresult{0.0}%
		\fi%
  	\pgfmath@smuggleone\pgfmathresult%
  \endgroup%
}

% greaterthan
%
\def\pgfmathfpgreaterthan#1#2{%
	\pgfmathfpparse{#2}\let\pgfmath@result=\pgfmathresult%
	\pgfmathfpparse{#1}%
	\pgfmathfpgreaterthan@{\pgfmathresult}{\pgfmath@result}%
}
\def\pgfmathfpgreaterthan@#1#2{%
	\begingroup%
		\FPifgt{#1}{#2}%
			\def\pgfmathresult{1.0}%
		\else%
			\def\pgfmathresult{0.0}%
		\fi%
  	\pgfmath@smuggleone\pgfmathresult%
  \endgroup%
}

% equalto
%
\def\pgfmathfpequalto#1#2{%
	\pgfmathfpparse{#2}\let\pgfmath@result=\pgfmathresult%
	\pgfmathfpparse{#1}%
	\pgfmathfpequalto@{\pgfmathresult}{\pgfmath@result}%
}
\def\pgfmathfpequalto@#1#2{%
	\begingroup%
		\FPifeq{#1}{#2}%
			\def\pgfmathresult{1.0}%
		\else%
			\def\pgfmathresult{0.0}%
		\fi%
  	\pgfmath@smuggleone\pgfmathresult%
  \endgroup%
}

		
% Basic arithmetic stuff...

% add
%
\def\pgfmathfpadd#1#2{%
	\pgfmathfpparse{#2}\let\pgfmath@result=\pgfmathresult%
	\pgfmathfpparse{#1}%
	\pgfmathfpadd@{\pgfmathresult}{\pgfmath@result}%
}
\def\pgfmathfpadd@#1#2{%
	\begingroup%
		\FPadd\pgfmathresult{#1}{#2}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% subtract
%
\def\pgfmathfpsubtract#1#2{%
	\pgfmathfpparse{#2}\let\pgfmath@result=\pgfmathresult%
	\pgfmathfpparse{#1}%
	\pgfmathfpsubtract@{\pgfmathresult}{\pgfmath@result}%
}
\def\pgfmathfpsubtract@#1#2{%
	\begingroup%
		\FPsub\pgfmathresult{#1}{#2}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% multiply
%
\def\pgfmathfpmultiply#1#2{%
	\pgfmathfpparse{#2}\let\pgfmath@result=\pgfmathresult%
	\pgfmathfpparse{#1}%
	\pgfmathfpmultiply@{\pgfmathresult}{\pgfmath@result}%
}
\def\pgfmathfpmultiply@#1#2{%
	\begingroup%
		\FPmul\pgfmathresult{#1}{#2}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% divide
%
\def\pgfmathfpdivide#1#2{%
	\pgfmathfpparse{#2}\let\pgfmath@result=\pgfmathresult%
	\pgfmathfpparse{#1}%
	\pgfmathfpdivide@{\pgfmathresult}{\pgfmath@result}%
}
\def\pgfmathfpdivide@#1#2{%
	\begingroup%
		\FPdiv\pgfmathresult{#1}{#2}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% abs
%
\def\pgfmathfpabs#1{%
	\pgfmathfpparse{#1}%
	\pgfmathfpabs@{\pgfmathresult}%
}
\def\pgfmathfpabs@#1{%
	\begingroup%
		\FPabs\pgfmathresult{#1}
	\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% round
%
\def\pgfmathfpround#1{%
	\pgfmathfpparse{#1}%
	\pgfmathfpround@{\pgfmathresult}%
}
\def\pgfmathfpround@#1{%
	\begingroup%
		\FPround\pgfmathresult{#1}{0}%
		\edef\pgfmathresult{\pgfmathresult.0}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% floor
%
\def\pgfmathfpfloor#1{%
	\pgfmathfpparse{#1}%
	\pgfmathfpfloor@{\pgfmathresult}%
}
\def\pgfmathfpfloor@#1{%
	\begingroup%
		\FPtrunc\pgfmathresult{#1}{0}%
		\FPifneg{#1}%
			\FPsub\pgfmathresult{\pgfmathresult}{1}%
		\fi%
		\edef\pgfmathresult{\pgfmathresult.0}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% ceil
%
\def\pgfmathfpceil#1{%
	\pgfmathfpparse{#1}%
	\pgfmathfpceil@{\pgfmathresult}%
}
\def\pgfmathfpceil@#1{%
	\begingroup%
		\FPtrunc\pgfmathresult{#1}{0}%
		\FPifpos{#1}%
			\FPadd\pgfmathresult{\pgfmathresult}{1}%
		\fi%
		\edef\pgfmathresult{\pgfmathresult.0}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% mod
%
\def\pgfmathfpmod#1#2{%
	\pgfmathfpparse{#2}\let\pgfmath@result=\pgfmathresult%
	\pgfmathfpparse{#1}%
	\pgfmathfpmod@{\pgfmathresult}{\pgfmath@result}%
}
\def\pgfmathfpmod@#1#2{%
	\begingroup%
		\FPdiv\pgfmathresult{#1}{#2}%
		\FPtrunc\pgfmathresult{\pgfmathresult}{0}%
		\FPmul\pgfmathresult{\pgfmathresult}{#2}%
		\FPsub\pgfmathresult{#1}{\pgfmathresult}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% max
%
\def\pgfmathfpmax#1#2{%
	\pgfmathfpparse{#2}\let\pgfmath@result=\pgfmathresult%
	\pgfmathfpparse{#1}%
	\pgfmathfpmax@{\pgfmathresult}{\pgfmath@result}%
}
\def\pgfmathfpmax@#1#2{%
	\begingroup%
		\FPifgt{#1}{#2}%
			\def\pgfmathresult{#1}%
		\else%
			\def\pgfmathresult{#2}%
		\fi%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% min
%
\def\pgfmathfpmin#1#2{%
	\pgfmathfpparse{#2}\let\pgfmath@result=\pgfmathresult%
	\pgfmathfpparse{#1}%
	\pgfmathfpmin@{\pgfmathresult}{\pgfmath@result}%
}
\def\pgfmathfpmin@#1#2{%
	\begingroup%
		\FPiflt{#1}{#2}%
			\def\pgfmathresult{#1}%
		\else%
			\def\pgfmathresult{#2}%
		\fi%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% Functions...

% pow
%
\def\pgfmathfppow#1#2{%
	\pgfmathfpparse{#2}\let\pgfmath@result=\pgfmathresult%
	\pgfmathfpparse{#1}%
	\pgfmathfppow@{\pgfmathresult}{\pgfmath@result}%
}
\def\pgfmathfppow@#1#2{%
	\begingroup%
		\FPpow\pgfmathresult{#1}{#2}\unskip%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% exp
%
\def\pgfmathfpexp#1{%
	\pgfmathfpparse{#1}%
	\pgfmathfpexp@{\pgfmathresult}%
}
\def\pgfmathfpexp@#1{%
	\begingroup%
		\FPexp\pgfmathresult{#1}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% ln
%
\def\pgfmathfpln#1{%
	\pgfmathfpparse{#1}%
	\pgfmathfpln@{\pgfmathresult}%
}
\def\pgfmathfpln@#1{%
	\begingroup%
		\FPln\pgfmathresult{#1}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% sqrt
%
\def\pgfmathfpsqrt#1{%
	\pgfmathfpparse{#1}%
	\pgfmathfpsqrt@{\pgfmathresult}%
}
\def\pgfmathfpsqrt@#1{%
	\begingroup%
		\FProot\pgfmathresult{#1}{2}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% veclen
%
\def\pgfmathfpveclen#1#2{%
	\pgfmathfpparse{#2}\let\pgfmath@result=\pgfmathresult%
	\pgfmathfpparse{#1}%
	\pgfmathfpveclen@{\pgfmathresult}{\pgfmath@result}%
}
\def\pgfmathfpveclen@#1#2{%
	\begingroup%
	  \FPmul\pgfmath@result{#1}{#1}%
	  \FPmul\pgfmath@@result{#2}{#2}%
	  \FPadd\pgfmathresult{\pgfmath@result}{\pgfmath@@result}%
	  \FProot\pgfmathresult{\pgfmathresult}{2}%
	  \pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% Trigonometric stuff...

% sin
%
\def\pgfmathfpsin#1{%
	\pgfmathfpparse{#1}%
	\pgfmathfpsin@{\pgfmathresult}%
}
\def\pgfmathfpsin@#1{%
	\begingroup%
		\FPmul\pgfmathresult{#1}{0.017453292519943295}%
		\FPsin\pgfmathresult{\pgfmathresult}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% cos
%
\def\pgfmathfpcos#1{%
	\pgfmathfpparse{#1}%
	\pgfmathfpcos@{\pgfmathresult}%
}
\def\pgfmathfpcos@#1{%
	\begingroup%
		\FPmul\pgfmathresult{#1}{0.017453292519943295}%
		\FPcos\pgfmathresult{\pgfmathresult}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% tan
%
\def\pgfmathfptan#1{%
	\pgfmathfpparse{#1}%
	\pgfmathfptan@{\pgfmathresult}%
}
\def\pgfmathfptan@#1{%
	\begingroup%
		\FPmul\pgfmathresult{#1}{0.017453292519943295}%
		\FPtan\pgfmathresult{\pgfmathresult}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% acos
%
\def\pgfmathfpacos#1{%
	\pgfmathfpparse{#1}%
	\pgfmathfpacos@{\pgfmathresult}%
}
\def\pgfmathfpacos@#1{%
	\begingroup%
		\FParccos\pgfmathresult{#1}%
		\FPmul\pgfmathresult{\pgfmathresult}{57.295779513082320885}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% asin
%
\def\pgfmathfpasin#1{%
	\pgfmathfpparse{#1}%
	\pgfmathfpasin@{\pgfmathresult}%
}
\def\pgfmathfpasin@#1{%
	\begingroup%
		\FParcsin\pgfmathresult{#1}%
		\FPmul\pgfmathresult{\pgfmathresult}{57.295779513082320885}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% atan
%
\def\pgfmathfpatan#1{%
	\pgfmathfpparse{#1}%
	\pgfmathfpatan@{\pgfmathresult}%
}
\def\pgfmathfpatan@#1{%
	\begingroup%
		\FParctan\pgfmathresult{#1}%
		\FPmul\pgfmathresult{\pgfmathresult}{57.295779513082320885}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% cot
%
\def\pgfmathfpcot#1{%
	\pgfmathfpparse{#1}%
	\pgfmathfpcot@{\pgfmathresult}%
}
\def\pgfmathfpcot@#1{%
	\begingroup%
		\FPmul\pgfmathresult{#1}{0.017453292519943295}%
		\FPcot\pgfmathresult{\pgfmathresult}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% sec
%
\def\pgfmathfpsec#1{%
	\pgfmathfpparse{#1}%
	\pgfmathfpsec@{\pgfmathresult}%
}
\def\pgfmathfpsec@#1{%
	\begingroup%
		\FPmul\pgfmathresult{#1}{0.017453292519943295}%
		\FPcos\pgfmathresult{\pgfmathresult}%
		\FPdiv\pgfmathresult{1}{\pgfmathresult}		
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% cosec
%
\def\pgfmathfpcosec#1{%
	\pgfmathfpparse{#1}%
	\pgfmathfpcosec@{\pgfmathresult}%
}
\def\pgfmathfpcosec@#1{%
	\begingroup%
		\FPmul\pgfmathresult{#1}{0.017453292519943295}%
		\FPsin\pgfmathresult{\pgfmathresult}%
		\FPdiv\pgfmathresult{1}{\pgfmathresult}		
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% deg
%
\def\pgfmathfpdeg#1{%
	\pgfmathfpparse{#1}%
	\pgfmathfpdeg@{\pgfmathresult}%
}
\def\pgfmathfpdeg@#1{%
	\begingroup%
		\FPmul\pgfmathresult{#1}{57.295779513082320885}%
	\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% rad
%
\def\pgfmathfprad#1{%
	\pgfmathfpparse{#1}%
	\pgfmathfprad@{\pgfmathresult}%
}
\def\pgfmathfprad@#1{%
	\begingroup%
		\FPmul\pgfmathresult{#1}{0.01745329251994325}%
	\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% Random stuff...

\def\pgfmathfpsetseed#1{%
	\pgfmathfpparse{#1}%
	\afterassignment\pgfmath@gobbletilpgfmath@%
	\FPseed\pgfmathresult\relax\pgfmath@%
}

% rnd
%
\def\pgfmathfprnd{%
	\begingroup%
		\FPrandom\pgfmathresult%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}

% rand
%
\def\pgfmathfprand{%
	\begingroup%
		\FPrandom\pgfmathresult%
		\FPmul\pgfmathresult{2}{\pgfmathresult}%
		\FPsub\pgfmathresult{\pgfmathresult}{1}%
		\pgfmath@smuggleone\pgfmathresult%
	\endgroup%
}


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

pgflibrarygraphdrawing.circular.code.tex
% Copyright 2010 by Renée Ahrens, Olof Frahm, Jens Kluttig, Matthias Schulz, Stephan Schuster
% Copyright 2011 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/graphdrawing/tex/pgflibrarygraphdrawing.circular.code.tex,v 1.4 2012/11/20 23:34:18 tantau Exp $


\usegdlibrary{circular}

\endinput
pgflibrarygraphdrawing.code.tex
% Copyright 2010 by Renée Ahrens, Olof Frahm, Jens Kluttig, Matthias Schulz, Stephan Schuster
% Copyright 2011 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/graphdrawing/tex/pgflibrarygraphdrawing.code.tex,v 1.38 2013/08/28 11:47:35 tantau Exp $



% check if luatex is running

\ifx\directlua\relax%
  \pgferror{You need to run LuaTeX to use the graph drawing library}
  \expandafter\endinput
\fi
\ifx\directlua\undefined%
  \pgferror{You need to run LuaTeX to use the graph drawing library}
  \expandafter\endinput
\fi




% 
% All graph drawing keys normally live in the following namespace:
% /graph drawing. 
%

\def\pgfgdset{\pgfqkeys{/graph drawing}}


% Setup a key
% 
% #1 = key
% 
% Description:
% 
% An internal macro that sets up #1 as a graph drawing key.

\def\pgfgd@callbackkey#1{
  \pgf@gd@setup@forwards{#1}
  \pgfutil@g@addto@macro\pgf@gd@forwards@list{\pgf@gd@setup@forwards{#1}}
}
\def\pgf@gd@setup@forwards#1{
  \let\pgf@temp\pgfutil@empty
  \foreach \pgf@gd@path in \pgf@gd@forwarding@list {
    \ifx\pgf@gd@path\pgfutil@empty\else%
      \expandafter\pgfutil@g@addto@macro%
      \expandafter\pgf@temp\expandafter{%
        \expandafter\pgfkeys\expandafter{\pgf@gd@path#1/.forward to=/graph drawing/#1}}
    \fi%
  }%
  \pgf@temp
}

\let\pgf@gd@forwards@list\pgfutil@empty


% Append to the forwarding list:
% 
% #1 = paths to append to the forwarding list
% 
% Description:
% 
% Append the paths in #1 (with trailing slashes) to the forwarding
% list.
% 
% If algorithms have already been declared, forwarding will also be
% setup for them (using a bit of magic...).

\def\pgfgdappendtoforwardinglist#1{%
  \let\pgf@gd@forwarding@list@orig\pgf@gd@forwarding@list
  \def\pgf@gd@forwarding@list{#1}%
  \pgf@gd@forwards@list%
  \expandafter\def\expandafter\pgf@gd@forwarding@list\expandafter{\pgf@gd@forwarding@list@orig,#1}
}
\let\pgf@gd@forwarding@list\pgfutil@empty



% 
% 
% Callbacks
% 
% The following macros are called *from* the binding layer. You do not
% call them from the pgf layer.
%  
%


% Callback for declaring a graph parameter key
%
% #1 = Parameter key
% #2 = Parameter type
%
% Description:
%
% When a graph drawing algorithm starts working, a set of options,
% called "graph drawing parameters" in the following, can influence the
% way the algorithm works. For instance, an graph drawing parameter
% might be the average distance between vertices which the algorithm
% should take into account. Another example might be the fact the
% certain nodes are special nodes and that a certain edge should have
% a large label.
%
% These graph drawing parameters are different from "usual" pgf
% options: An alogrithmic parameter influenced the way the algorithm
% works, while usual options normally only influence how the result
% looks like. For instance, the fact that a node is red is not an
% graph drawing parameter (usually, at least), while the shape of a node
% might be an graph drawing parameter.
%
% Graph drawing parameters are declared by the algorithmic layer
% (since only this layer "knows" which parameters there are). The
% binding to TeX will call the \pgfgddeclareparameter function
% internally.
% 
% Specifying the set of graph drawing parameters for a given graph or
% node or edge works as follows: When the graph drawing engine is
% started for a graph (using \pgfgdbeginscope), a snapshot is taken of
% all graph drawing parameters currently setup at this
% point. Similarly, when a node is created inside such a scope, a
% snapshot is taken of the set of all graph drawing parameters in
% force at this point is taken and stored together with the
% node. Finally, when an edge is created, a snapshot of the setting of
% the graph drawing parameters is taken.

\def\pgfgdcallbackdeclareparameter#1#2{%
  \pgfkeysdef{/graph drawing/#1}{\pgf@gd@handle@parameter{#1}{#2}{##1}}%
  \pgfgd@callbackkey{#1}%  
}
\def\pgf@gd@handle@parameter#1#2#3{%
  \def\pgf@temp{#3}%
  \ifx\pgf@temp\pgfkeysnovalue@text%
    \let\pgfgdresult\pgfgd@niltext%
  \else%
    \pgfkeys{/graph drawing/conversions/#2={#3}}%
  \fi%
  \advance\pgf@gd@parameter@stack@height by1\relax%
  \pgf@gd@parameter@stack@height\directlua{%
    local new, main = pgf.gd.interface.InterfaceToDisplay.pushOption('\pgfutil@luaescapestring{#1}',\pgfgdresult,\the\pgf@gd@parameter@stack@height)
    tex.print(new..'\pgfutil@luaescapestring{\relax}')
    if main then
      tex.print('\pgfutil@luaescapestring{\noexpand\pgfgdtriggerrequest}') 
    end}%   
}%
\newcount\pgf@gd@parameter@stack@height

\def\pgfgdtriggerrequest{\pgfgdset{@request scope and layout}}


% Conversions are used to adapt the syntactic description of a
% parameter on the TikZ layer to the one expected by Lua. The set of
% permissible conversions is described in
% InterfaceToAlgorithms.declareParameter. 

\pgfgdset{
  conversions/string/.code=\def\pgfgdresult{'\pgfutil@luaescapestring{\detokenize{#1}}'},
  conversions/raw/.code=\def\pgfgdresult{#1},
  conversions/nil/.code=\let\pgfgdresult\pgfgd@niltext,
  conversions/boolean/.code=\def\pgf@test{#1}\ifx\pgf@test\pgf@truetext\def\pgfgdresult{true}\else\ifx\pgf@test\pgfkeysnovalue@text\def\pgfgdresult{true}\else\def\pgfgdresult{false}\fi\fi,
  conversions/number/.code=\pgfmathparse{#1}\let\pgfgdresult\pgfmathresult,
  conversions/length/.code=\pgfmathparse{#1}\let\pgfgdresult\pgfmathresult,
  conversions/direction/.code=\pgf@lib@gd@grow@dir{#1}\let\pgfgdresult\pgfmathresult,
  conversions/canvas coordinate/.code args={(#1pt,#2pt)}{\edef\pgfgdresult{pgf.gd.model.Coordinate.new(#1,#2)}},
  % deprecated, will be removed:
  conversions/coordinate/.code args={(#1pt,#2pt)}{\edef\pgfgdresult{{#1,#2}}}
}
\def\pgf@truetext{true}
\def\pgfgd@niltext{nil}

\def\pgf@lib@gd@grow@dir#1{%
  \def\pgf@temp{#1}%
  \ifx\pgf@temp\pgf@gd@lib@active@bar%
    \def\pgfmathresult{-90}
  \else%
    \ifcsname pgf@orient@direction@#1\endcsname%
      \expandafter\let\expandafter\pgfmathresult\csname pgf@orient@direction@#1\endcsname%
    \else
      \pgfmathparse{#1}%
    \fi
  \fi
}

\def\pgf@orient@direction@down{-90}
\def\pgf@orient@direction@up{90}
\def\pgf@orient@direction@left{180}
\def\pgf@orient@direction@right{0}

\def\pgf@orient@direction@south{-90}
\def\pgf@orient@direction@north{90}
\def\pgf@orient@direction@west{180}
\def\pgf@orient@direction@east{0}

\expandafter\def\csname pgf@orient@direction@north east\endcsname{45}
\expandafter\def\csname pgf@orient@direction@north west\endcsname{135}
\expandafter\def\csname pgf@orient@direction@south east\endcsname{-45}
\expandafter\def\csname pgf@orient@direction@south west\endcsname{-135}

\expandafter\def\csname pgf@orient@direction@-\endcsname{0}
\expandafter\def\csname pgf@orient@direction@|\endcsname{-90}

{
  \catcode`\|=13
  \gdef\pgf@gd@lib@active@bar{|}
}





% Callback for starting the rendering of a collection kind
%
% #1 = Kind
% #2 = Layer
%
% Description:
% 
% Executes /graph drawing/#1/begin rendering/.try
%

\def\pgfgdcallbackrendercollectionkindstart#1#2{%
  \ifnum#2<0\relax
    \setbox\pgf@gd@prekind@box=\hbox\bgroup%
    \unhbox\pgf@gd@prekind@box%
  \else%
    \setbox\pgf@gd@postkind@box=\hbox\bgroup%
    \unhbox\pgf@gd@postkind@box%
  \fi%
  \pgfgdset{/graph drawing/#1/begin rendering/.try}%
}

% Callback for ending the rendering of a collection kind
%
% #1 = Kind
% #2 = Layer
%
% Description:
% 
% Executes /graph drawing/#1/end rendering/.try
%

\def\pgfgdcallbackrendercollectionkindstop#1#2{%
  \pgfgdset{/graph drawing/#1/end rendering/.try}%
  \egroup % close box
}



% Callback for rendering a collection 
% 
% #1 = Kind
% #2 = Options
%
% Description:
% 
% Executes /graph drawing/#1/render/.try={#2}
%

\def\pgfgdcallbackrendercollection#1#2{
  \pgfgdset{/graph drawing/#1/render/.try={#2}}
}





% Graph events  
% 
% Although a graph consists of nodes and edges, during the
% construction of the graph a lot of information concerning the
% structure of the graph is often available. For instance, as we
% specify a graph using the child-syntax, we do not only which edges
% are present, but we can implicitly specify an ordering on the
% nodes. Even more, there is even information availble concerning
% nodes that are not present at all: A child[missing] is not present
% as a node or an edge, but a tree drawing algorithm will want to know
% about this child nevertheless.
% 
% In order to communicate such information to the graph drawing
% engine, "events" are used. As a graph is created, in addition to
% nodes and edges, "events" may happen. The events come in a
% sequential order and they are stored together with the graph. For
% each node and each edge, its index in the event sequence is
% stored, that is, it is stored how many events happened before the
% node or edge was created.
% 
% Internally, an event consists of a name and, possibly, some
% parameters. When the parameter is created on the tikz level, it will
% be a string that is passed down to Lua. Internally created events
% will also have parameters that are objects.
% 
% Two events are a bit special since they get special internal
% support: The begin and end events. The first signals that some kind
% of group has started; which is closed by the corresponding end
% event. The "kind" of group is indicated by the parameter of the
% begin event.
% 
% 
% 
% Standard events are:
% 
% For each node entered into a graph, a "node" event is automatically
% created internally with the parameter being the node. However, you
% can also create this event yourself. In this case, the parameter
% will be a string and will mean that the node is "virtual" or
% "missing", but space should be reserved for it, if possible (this is
% use, for instance, by certain tree layouts).
% 
% For each edge entered into a graph, an "edge" event is automatically
% created, with the edge as the parameter. Again, an event with a
% string parameter corresponds to a "non-existing" node.
% 
%
% Standard event groups are:
% 
%
% The "descendants" event group include a set of nodes that, at least
% inside the specification, are descendants of the last node
%
% begin descendants
% ...
% end
% 
% 
% The "array" event group collects together some nodes in an array of
% nodes. This can be used, for instance, to specify matrices.
% 
% begin array
% ...
% end 



% Create a new event
% 
% #1 = event name (should be a valid lua identifier name)
% #2 = parameter (some text)
% 
% Description:
% 
% Adds a new event to the event sequence of the graph

\def\pgfgdevent#1#2{%
  \directlua{pgf.gd.interface.InterfaceToDisplay.createEvent('\pgfutil@luaescapestring{#1}', '\pgfutil@luaescapestring{#2}')}%
}


% Start an event group
% 
% #1 = kind of event group
% 
% Description:
% 
% Creates a begin event with #1 as the parameter of the begin
% event.

\def\pgfgdbegineventgroup#1{%
  \pgfgdevent{begin}{#1}%
}

% End an event group
% 
% Description:
% 
% Creates an end event.

\def\pgfgdendeventgroup{%
  \pgfgdevent{end}{}%
}


% Creates an event group for the current TeX group
%
% #1 = event group name 
%
% Description:
% 
% Issues a begin event for #1 and, using \aftergroup, adds an end
% event at the end of the current tex group.

\def\pgfgdeventgroup#1{%
  \pgfgdbegineventgroup{#1}%
  \aftergroup\pgfgdendeventgroup%
}





%
% Nodes
%



%
% Callback method for \pgfpositionnodelater
% 
% This function is called by \pgfnode whenever a node has been newly
% created inside a graph drawing scope. It will create a new vertex on
% the Lua layer.
%
\def\pgf@gd@positionnode@callback{%
  {%
    % evaluate coordinates
    \pgfmathsetmacro{\pgf@gd@node@minx}{\pgfpositionnodelaterminx}%
    \pgfmathsetmacro{\pgf@gd@node@miny}{\pgfpositionnodelaterminy}%
    \pgfmathsetmacro{\pgf@gd@node@maxx}{\pgfpositionnodelatermaxx}%
    \pgfmathsetmacro{\pgf@gd@node@maxy}{\pgfpositionnodelatermaxy}%
    % Assemble the Path object:
    \directlua{pgf.temp = require 'pgf.gd.model.Path'.new ()}%
    \let\pgfsyssoftpath@movetotoken\pgf@gd@movetotoken%
    \let\pgfsyssoftpath@linetotoken\pgf@gd@linetotoken%
    \let\pgfsyssoftpath@rectcornertoken\pgf@gd@rectcornertoken%
    \let\pgfsyssoftpath@curvetosupportatoken\pgf@gd@curvetosupportatoken%
    \let\pgfsyssoftpath@closepathtoken\pgf@gd@closepathtoken%
    \pgfpositionnodelaterpath%
    % 
    \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/outer xsep}}%
    \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/outer ysep}}%
    % 
    {%
      \pgf@process{\pgfpointanchor{\pgfpositionnodelatername}{center}}
      \pgfsettransform{\csname pgf@sh@nt@\pgfpositionnodelatername\endcsname}%
      \pgf@pos@transform{\pgf@x}{\pgf@y}%
      \global\pgf@x=\pgf@x%
      \global\pgf@y=\pgf@y%
    }%
    % call lua system library to create a lua node object
    \directlua{
      pgf.gd.interface.InterfaceToDisplay.createVertex(
        string.sub('\pgfutil@luaescapestring{\pgfpositionnodelatername}',30), % strip "not yet positionedPGFINTERNAL"
        '\pgfutil@luaescapestring{\csname pgf@sh@ns@\pgfpositionnodelatername\endcsname}',
        pgf.temp:pad((\pgf@sys@tonumber\pgf@xa+\pgf@sys@tonumber\pgf@ya)/2), % Padded path
        \the\pgf@gd@parameter@stack@height, % Stack height
        {% Binding info
          x_min = \pgf@gd@node@minx,
          y_min = \pgf@gd@node@miny,
          x_max = \pgf@gd@node@maxx,
          y_max = \pgf@gd@node@maxy,
          tex_box_number = \pgfpositionnodelaterbox
        },
        {% Anchors
          center = require 'pgf.gd.model.Coordinate'.new(\pgf@sys@tonumber\pgf@x,\pgf@sys@tonumber\pgf@y)
        }
      )
      pgf.temp = nil  
    }
  }%
}


\def\pgf@gd@movetotoken#1#2{\directlua{pgf.temp:appendMoveto(\Pgf@geT#1,\Pgf@geT#2)}}
\def\pgf@gd@linetotoken#1#2{\directlua{pgf.temp:appendLineto(\Pgf@geT#1,\Pgf@geT#2)}}
\def\pgf@gd@rectcornertoken#1#2#3#4#5{%
  \directlua{%
    local x,y,dx,dy=\Pgf@geT#1,\Pgf@geT#2,\Pgf@geT#4,\Pgf@geT#5
    pgf.temp:appendMoveto(x,y)
    pgf.temp:appendLineto(x,y+dy)
    pgf.temp:appendLineto(x+dx,y+dy)
    pgf.temp:appendLineto(x+dx,y)
    pgf.temp:appendClosepath()%    
  }%
}
\def\pgf@gd@curvetosupportatoken#1#2#3#4#5#6#7#8{\directlua{pgf.temp:appendCurveto(\Pgf@geT#1,\Pgf@geT#2,\Pgf@geT#4,\Pgf@geT#5,\Pgf@geT#7,\Pgf@geT#8)}}
\def\pgf@gd@closepathtoken#1#2{\directlua{pgf.temp:appendClosepath()}}


% Set options for an already existing node
% 
% #1 = node name
% 
% These node parameters of #1 will be updated with the current values
% of the node parameters. The node #1 must previously have been passed
% to the gd engine. If some of the options have already been set for
% the node, these settings will be overruled.

\def\pgfgdsetlatenodeoption#1{%
  \directlua{
    pgf.gd.interface.InterfaceToDisplay.addToVertexOptions('\pgfutil@luaescapestring{#1}',\the\pgf@gd@parameter@stack@height)
  }
}



%
% A callback for rendering (finally positioning) a node
% 
% #1 = name of the node
% #2 = x min of the bounding box
% #3 = x max of the bounding box
% #4 = y min of the bounding box
% #5 = y max of the bounding box
% #6 = desired x pos of the node
% #7 = desired y pos of the node
% #8 = box register number of the TeX node
%
% This callback will be called by the engine for every original node
% when it finally needs to placed at a final position.

\def\pgfgdcallbackrendernode#1#2#3#4#5#6#7#8{%
  {%
    \def\pgfpositionnodelatername{#1}
    \def\pgfpositionnodelaterminx{#2}
    \def\pgfpositionnodelatermaxx{#3}
    \def\pgfpositionnodelaterminy{#4}
    \def\pgfpositionnodelatermaxy{#5}
    \directlua{pgf.gd.interface.InterfaceCore.binding:retrieveBox(#8,\pgfpositionnodelaterbox)}
    \pgfpositionnodenow{\pgfqpoint{#6}{#7}}
  }%
}



% Adds an edge to the graph
%
% #1 = first node
% #2 = second node
% #3 = edge direction
% #4 = edge options (will be executed in a protected environment)
% #5 = aux stuff (curtesy for TikZ -- edge nodes)
%
% Description:
%
% Creating an edge means that you tell the graph drawing algorithm
% that #1 and #2 are connected. The "kind" of connection is indicated
% by #3, which may be one of the following:
% 
% ->  = a directed edge (also known as an arc) from #1 to #2
% --  = an undirected edge between #1 and #2
% <-  = a directed edge from #2 to #1, but with the "additional hint"
%       that this is a "backward" edge. A graph drawing algorithm may
%       or may not take this hint into account
% <-> = a bi-directed edge between #1 and #2.
% 
%
% The parameters #4 and #5 are a bit more tricky. When an edge between
% two vertices of a graph is created via \pgfgdedge, nothing is
% actually done immediately. After all, without knowing the final
% positions of the nodes #1 and #2, there is no way of
% creating the actual drawing commands for the edge. Thus, the actual
% drawing of the edge is done only when the graph drawing algorithm is
% done (namely in the macro \pgfgdcallbackedge, see later).
% 
% Because of this "delayed" drawing of edges, options that influence
% the edge must be retained until the moment when the edge is actually
% drawn. Parameters #4 and #5 store such options.
% 
% Let us start with #4. This parameter should be set to a list of
% key-value pairs like
% 
%   /tikz/.cd, color=red, very thick, this edge must be vertical
% 
% Some of these options may be of interest to the graph drawing
% algorithm (like the last option) while others will 
% only be important during the drawing of edge (like the first
% option). The options that are important for the graph drawing
% algorithm must be passed to the algorithm via setting keys that have
% been declared using the handler .edge parameter (see 
% above).
% 
% The tricky part is that options that are of interest to the graph
% drawing algorithm must be executed *before* the algorithm starts,
% but the options as a whole are usually only executed during the
% drawing of the edges, which is *after* the algorithm has finished.
% 
% To overcome this problem, the following happens:
% 
% The options in #4 are executed "tentatively" inside
% \pgfgdedge. However, this execution is done in a "heavily guarded
% sandbox" where all effects of the options (like changing the
% color or the line width) do not propagate beyond the sandbox. Only
% the changes of the graph drawing edge parameters leave the
% sandbox. These parameters are then passed down to the graph drawing
% engine.
% 
% Later, when the edge is drawn using \pgfgdcallbackedge, the options #4
% are available once more and then they are executed normally.
%
% Note that when the options in #4 are executed, no path is
% preset. Thus, you typically need to start it with, say, /tikz/.cd.
%
%
% The text in #5 is some "auxilliary" text that is simply stored away
% and later directly to \pgfgdcallbackedge. This is a curtesy to TikZ,
% which can use it to store its node labels. 
%
% Example:
%
% \pgfgdedge{A}{B}{->}{red}{}
%
\def\pgfgdedge#1#2#3#4#5{%
  % Ok, setup sandbox
  \begingroup%
    \setbox0=\hbox{{%
        \pgfinterruptpath%
          \pgfgdprepareedge%
          \pgfkeys{#4}%
          % create edge in Lua
          \toks0={#4}%
          \toks1={#5}%
          \directlua{
            pgf.gd.interface.InterfaceToDisplay.createEdge(
            '\pgfutil@luaescapestring{#1}','\pgfutil@luaescapestring{#2}','\pgfutil@luaescapestring{#3}',
            \the\pgf@gd@parameter@stack@height,
            { pgf_options = '\pgfutil@luaescapestring{\the\toks0}',
              pgf_edge_nodes = '\pgfutil@luaescapestring{\the\toks1}',
            })
          }%
        \endpgfinterruptpath%
      }}%
  \endgroup%
}

\let\pgfgdprepareedge=\pgfutil@empty
\def\pgfgdaddprepareedgehook#1{\expandafter\def\expandafter\pgfgdprepareedge\expandafter{\pgfgdprepareedge#1}}


\newif\ifpgf@gd@nodes@behind@edges



% Define a callback for rendering edges
%
% #1 = macro name
% 
% Descriptions:
% 
% This is a callback from the graph drawing engine. At the end of the
% creation of a graph, when the nodes have been positioned, this macro
% is called once for each edge. The macro should take the following
% parameters:
% 
% #1 = from node, optionally followed by "." and the tail anchor
% #2 = to node, optionally followed by "." and the head anchor
% #3 = direction (<-, --, ->, or <->)
% #4 = original options
% #5 = aux text (typically edge nodes)
% #6 = algorithm-generated options
% #7 = bend information
%
% The first five parameters are the original values that were passed
% down to the \pgfgdedge command.
% 
% #6 contains options that have been "computed by the algorithm". For
% instance, an algorithm might have determined, say, flow capacities
% for edges and it might now wish to communicate this information back
% to the upper layers. These options should be executed with the path
% /graph drawing.
% 
% #7 contains algorithmically-computed information concerning how the
% edge should bend. This will be a text like
% "--(10pt,20pt)--(30pt,40pt)" in tikz-syntax, using the path
% operations "--", "..controls" and "--cycle".
% 
% By default, a simple line is drawn between the nodes. Usually, you
% will wish to install a more "fancy" callback, here.

\def\pgfgdsetedgecallback#1{\let\pgfgdcallbackedge=#1}

\def\pgfgddefaultedgecallback#1#2#3#4#5#6#7{%
  {%
    \pgfscope
      \pgfpathmoveto{
        \pgfutil@in@.{#1}%
        \ifpgfutil@in@
          \pgf@gd@unravel#1\relax%
        \else
          \pgfpointshapeborder{#1}{\pgfpointanchor{#2}{center}}
        \fi
      }
      \pgfpathlineto{
        \pgfutil@in@.{#2}%
        \ifpgfutil@in@
          \pgf@gd@unravel#2\relax%
        \else
          \pgfpointshapeborder{#2}{\pgfpointanchor{#1}{center}}
        \fi
      }
      \pgfusepath{stroke}
    \endpgfscope
  }
}

\pgfgdsetedgecallback{\pgfgddefaultedgecallback}

\def\pgf@gd@unravel#1.#2\relax{%
  \pgfpointanchor{#1}{#2}%
}




% Callbacks: Called before the shipout of nodes and edges starts
%
% First, the general begin shipout is called. Then, the node shipout
% starts, the nodes are created, and then the end of the node shipout
% is signaled. Next, the edge shipout starts and ends. Finally, the
% end shipout is called.

\def\pgfgdcallbackbeginshipout{%
  \pgfscope%
    \catcode`\@=11\relax%
    \setbox\pgf@gd@prekind@box=\box\pgfutil@voidb@x%
    \setbox\pgf@gd@postkind@box=\box\pgfutil@voidb@x%
}
\def\pgfgdcallbackendshipout{%
    \box\pgf@gd@prekind@box%
    \ifpgf@gd@nodes@behind@edges%
      \box\pgf@gd@node@box%
      \box\pgf@gd@edge@box%
    \else%
      \box\pgf@gd@edge@box%
      \box\pgf@gd@node@box%
    \fi%
    \box\pgf@gd@postkind@box%
  \endpgfscope
}

\newbox\pgf@gd@node@box
\newbox\pgf@gd@edge@box
\newbox\pgf@gd@prekind@box
\newbox\pgf@gd@postkind@box

\def\pgfgdcallbackbeginnodeshipout{%
  \setbox\pgf@gd@node@box=\hbox\bgroup%
}
\def\pgfgdcallbackendnodeshipout{%
  \egroup%
}

\def\pgfgdcallbackbeginedgeshipout{%
  \setbox\pgf@gd@edge@box=\hbox\bgroup%
}

\def\pgfgdcallbackendedgeshipout{%
  \egroup
}




% Generate a node 
%
% This callback is called from the engine whenever an algorithm
% generates a new node internally.
%
% #1 = name of the node
% #2 = shape of the node
% #3 = options generated by the algorithm in key-value syntax. The set
% of generated options is algorithm-dependent.
% #4 = text
%
% This is an internal function and will be called by the binding layer

\def\pgfgdcallbackcreatevertex#1#2#3#4{%
  {
    \pgfkeys{#3}
    \pgfnode{#2}{\pgfkeysvalueof{/graph drawing/generated
        node/anchor}}{#4}{#1}{\pgfkeysvalueof{/graph drawing/generated
        node/use path}} 
  }
}

\pgfkeys{
  /graph drawing/generated node/anchor/.initial=center,
  /graph drawing/generated node/use path/.initial=\pgfusepath{}
}



%
% Sublayouts
%
% Description: For a general introduction to (sub)layouts, see
% Section~\ref{section-gd-sublayouts} in the manual. 
% 

\def\pgfgdbeginlayout{
  \begingroup
    \pgfgdlayoutscopeactivetrue
    \advance\pgf@gd@parameter@stack@height by1\relax%
    \directlua{pgf.gd.interface.InterfaceToDisplay.pushLayout(\the\pgf@gd@parameter@stack@height)}
}

\def\pgfgdendlayout{
  \endgroup%
}




% Creates a subgraph node
% 
% #1 = name
% #2 = node options
% #3 = node text
% 
% Description:
% 
% A subgraph node is a node that "surrounds" the nodes of a
% subgraph. The special property of a subgraph node opposed to a
% normal node is that it is created only after the subgraph has been
% laid out. However, the difference to a collection like "hyper" is
% that the node is availble immediately as a normal node in the sense
% that you can connect edges to it.
% 
% What happens internally is that subgraph nodes get "registered"
% immediately both on the pgf level and on the lua level, but the
% actual node is only created inside the layout pipeline using a
% callback. The actual node creation happens when the innermost layout
% in which the subgraph node is declared has finished.
% 
% When you create a subgraph node using this macro, you also start a
% collection (of an internal kind) that stores the subgraph. All
% following nodes in the current TeX scope will become part of this
% collection. 
% 
% See |InterfaceToDisplay.pushSubgraphVertex| for details.

\def\pgfgdsubgraphnode#1#2#3{%
  \advance\pgf@gd@parameter@stack@height by1\relax%
  {%
    % create edge in Lua
    \toks0={#2}%
    \toks1={#3}%
    \directlua{pgf.gd.interface.InterfaceToDisplay.pushSubgraphVertex%
      ('\pgfutil@luaescapestring{#1}',\the\pgf@gd@parameter@stack@height,
      {
        shape = 'rectangle', % typically overwritten by the pgf_options:
        pgf_options = '\pgfutil@luaescapestring{\the\toks0}',
        text = '\pgfutil@luaescapestring{\the\toks1}',
      })
    }%
  }
}

\def\pgfgdsubgraphnodecontents#1{% helper function
  \hbox to \pgfkeysvalueof{/graph drawing/subgraph bounding box width}{%
    \vrule width0pt height\pgfkeysvalueof{/graph drawing/subgraph bounding box height}\hfil}%
}

\pgfgdset{
  subgraph point cloud/.initial=,
  subgraph bounding box width/.initial=,
  subgraph bounding box height/.initial=,
}


% 
% Requests
% 
% Description:
% 
% This key is used to ``request'' a graph drawing scope and a
% layout. The objective of this key is to make it easier for users and
% algorithm designers to control the slightly involved
% back-and-forth-calling between the different layers.
% 
% This key does the following: When called inside a pgfpicture
% (otherwise, the call is "illegal"), it will call a call-back with
% two parameters. This callback will get passed some code that should
% be executed at the beginning of ``the next scope'' and some code
% that should be executed at the end of that scope.
% 
% The code passed to the callbacks will have a different effect,
% depending on whether we are currently inside a layout scope or not
% (if no graph drawing scope is open, we are 
% not inside a layout). If we are not inside a layout scope (or if the
% layout scope has been interrupted), the code will issue a
% \pgfgdbeginscope command in the opening code and a corresponding
% scope ending command in the closing code. Next, the two code pieces
% always contain \pgfgdbeginlayout and \pgfgdendlayout.
% 
% Note that the "@request scope and layout" key will not immediately
% trigger a layout scope to be created; rather, the TikZ callback will
% call it only at the beginning of the scope, which will be after
% other options in the current list of options have been parsed. So,
% when you write \graph [binary tree layout, significant sep=2em] ...,
% the "significant sep" option has an effect despite being given
% *after* the "@request scope and layout" key since the actual opening
% of the scope happens only before the "..." part is parsed.

\pgfgdset{@request scope and layout/.code=\pgfgd@requestcallback{\pgfgdbeginrequest}{\pgfgdendrequest}}

\def\pgfgd@requestcallback#1#2{%
  #1\def\pgf@gd@after@request{#2\egroup}\bgroup\aftergroup\pgf@gd@after@request%
} % Default for basic layer

\def\pgfgdbeginrequest{%
  \ifpgfgdlayoutscopeactive%
  \else%
    \expandafter\pgfgdbeginscope%
  \fi%
      \pgfgdbeginlayout%  
}
\def\pgfgdendrequest{%
      \pgfgdendlayout%
  \ifpgfgdlayoutscopeactive%
  \else%
    \expandafter\pgfgdendscope%
  \fi%  
}
\newif\ifpgfgdlayoutscopeactive


% Set the request callback
% 
% #1 = A macro
% 
% Description:
% 
% Sets the request callback as described in the "@request scope and
% layout" key.

\def\pgfgdsetrequestcallback#1{\let\pgfgd@requestcallback#1}




%
% An if that is true exactly if we are inside a graph drawing scope
%

\newif\ifpgfgdgraphdrawingscopeactive


% Begins a new graph drawing scope
% 
% Description:
%
% Inside a graph drawing scope, all pgf nodes that are newly created
% are automatically passed to the graph drawing engine. In contrast,
% edges have to be indicated explicitly using the macro \pgfgdedge
% (this is because it is somewhat unclear what, exactly, should count
% as an edge). Naturally, users typically will not call \pgfgdedge
% explicitly, but have styles and keys invoke it internally.
%
% Usage:
% 
% \pgfgdset{algorithm=somealgorithm}
% \pgfgdbeginscope
%   \pgfnode{rectangle}{center}{A}{A}{}
%   \pgfnode{rectangle}{center}{B}{B}{}
%   \pgfnode{rectangle}{center}{C}{C}{}
%   \pgfgdedge{A}{B}{->}{}{}
%   \pgfgdedge{B}{C}{->}{}{}
%   \pgfgdedge{C}{A}{->}{}{}
% \pgfgdendscope
% 
% Naturally, users will typically use TikZ's somewhat simpler syntax: '
% 
% \tikz \graph [some algorithm] { A -> B -> C -> A };

\def\pgfgdbeginscope{%
  \begingroup % Protecting scope
    % get options
    \directlua{
      pgf.gd.interface.InterfaceToDisplay.beginGraphDrawingScope(\the\pgf@gd@parameter@stack@height)
    }%
    \begingroup % Inner scope, the actual nodes will be inserted after
                % this scope has been closed
      % Indicate that we are now inside a graph drawing scope
      \pgfgdgraphdrawingscopeactivetrue
      % Switch on late positioning
      \pgfpositionnodelater{\pgf@gd@positionnode@callback}
      % Switch on late edges
      \pgfgd@latecallback%
      % Kill transformations (will be added by the position now
      % macros)
      \pgftransformreset
}


% Ends a graph drawing scope
% 
% Description:
%
% This macro invokes the selected graph drawing algorithm and
% ships out all nodes within this scope
%
% See \pgfgdbeginscope

\def\pgfgdendscope{%
      \directlua{
        pgf.gd.interface.InterfaceToDisplay.runGraphDrawingAlgorithm()
      }
    \endgroup
    % Late positioning has ended
    \directlua{pgf.gd.interface.InterfaceToDisplay.renderGraph()}
    \directlua{pgf.gd.interface.InterfaceToDisplay.endGraphDrawingScope()}
  \endgroup
}






% Hook into graph specification
% 
% #1 = code
% 
% Description:
% 
% Allows you to specify code that should be active while the graph
% drawing engine collects the information concerning the graph, but
% which should no longer be active when the graph is rendered.

\def\pgfgdaddspecificationhook#1{
  \expandafter\def\expandafter\pgfgd@latecallback\expandafter{\pgfgd@latecallback#1}
}
\let\pgfgd@latecallback\pgfutil@empty








% Loading further libraries

% Include a graph drawing library file.
%
% #1 = List of names of library file.
%  
% Description:
%
% This command includes a list of graph drawing library files. For
% each file X in the list, the file pgf.gd.X.lua is included using
% |require|. 
%
% For the convenience of Context users, both round and square brackets
% are possible for the argument.
% 
%
% Example:
%
% \usegdlibrary{trees}
% \usegdlibrary[force,circular]

\def\usegdlibrary{\pgfutil@ifnextchar[{\use@gdlibrary}{\use@@gdlibrary}}%}
\def\use@gdlibrary[#1]{\use@@gdlibrary{#1}}
\def\use@@gdlibrary#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
      \directlua{if not pgf_lookup_and_require('\pgf@temp') then
        tex.print('\pgfutil@luaescapestring{\noexpand\pgferror{Graph drawing library '\pgf@temp' not found}}')
      end}
    \fi
  }
}

% In the following code: Does anyone know how to determine the
% file-system separator in Lua? Or in TeX? 
{
  \catcode`\%=11
\directlua{
  function pgf_lookup_and_require(name)
    local sep = '/'
    if string.find(os.getenv('PATH'),';') then
      sep = '\string\\'
    end
    local function lookup(name)
      local sub = name:gsub('%.',sep)  
      local find_func = function (name, suffix)
        if resolvers then 
          local n = resolvers.findfile (name, suffix)
          return (not (n == '')) and n or nil
        else
          return kpse.find_file(name,suffix)
        end
      end
      if find_func(sub, 'lua') then
        require(name)
      elseif find_func(sub, 'clua') then
        collectgarbage('stop') 
        require(name)
        collectgarbage('restart')
      else
        return false
      end
      return true
    end
    return
      lookup('pgf.gd.' .. name .. '.library') or
      lookup('pgf.gd.' .. name) or
      lookup(name .. '.library') or
      lookup(name) 
  end
}
}


%
% Ok, fire up the system by creating the binding!
%
\directlua{
  require 'pgf.gd.interface.InterfaceToDisplay' 
  pgf.gd.interface.InterfaceToDisplay.bind(require 'pgf.gd.bindings.BindingToPGF')
} 



%
% Special setup for keys that are declared by the above libraries, but
% that have a special meaning on the display layer.
%

\pgfkeys{/graph drawing/nodes behind edges/.append code=\csname pgf@gd@nodes@behind@edges#1\endcsname}
\pgfkeys{/graph drawing/nodes behind edges/.default=true}




\endinput
pgflibrarygraphdrawing.examples.code.tex
% Copyright 2012 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/graphdrawing/tex/pgflibrarygraphdrawing.examples.code.tex,v 1.2 2012/11/20 23:34:18 tantau Exp $

\usepgflibrary{graphdrawing}

\usegdlibrary{examples}


\endinput
pgflibrarygraphdrawing.force.code.tex
% Copyright 2011 by Jannis Pohlmann
%
% 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/graphdrawing/tex/pgflibrarygraphdrawing.force.code.tex,v 1.7 2012/11/20 23:34:18 tantau Exp $



\usepgflibrary{graphdrawing}

\usegdlibrary{force}

\endinput



%
% Definition of spring algorithms as well as options to configure them.
%

\pgfgdset{
  force based/.cd,
  %
  iterations/.graph parameter=number,
  iterations/.parameter initial=500,
  %
  cooling factor/.graph parameter=number,
  cooling factor/.parameter initial=0.95,
  %
  initial step dimension/.graph parameter=number,
  initial step dimension/.parameter initial=0,
  % 
  convergence tolerance/.graph parameter=number,
  convergence tolerance/.parameter initial=0.01,
  %
  spring constant/.graph parameter=number,
  spring constant/.parameter initial=0.01,
  % 
  approximate electric forces/.graph parameter=boolean,
  approximate electric forces/.parameter initial=false,
  approximate electric forces/.default=true,
  % 
  electric force order/.graph parameter=number,
  electric force order/.parameter initial=1,
  %
  % Parameters related to the multilevel approach where the input graph
  % is iteratively coarsened into graphs with fewer nodes, until either
  % the number of nodes is small enough or the number of nodes in the 
  % could not be reduced by at least a user-defined ratio.
  %
  coarsen/.graph parameter=boolean,
  coarsen/.parameter initial=true,
  coarsen/.default=true,
  %
  coarsening/.code=\pgfkeys{
    /graph drawing/force based/coarsening/.cd,
    #1
  },
  %
  coarsening/downsize ratio/.graph parameter=number,
  coarsening/downsize ratio/.parameter initial=0.25,
  %
  coarsening/minimum graph size/.graph parameter=number,
  coarsening/minimum graph size/.parameter initial=2,
  %
  coarsening/collapse independent edges/.graph parameter=boolean,
  coarsening/collapse independent edges/.parameter initial=true,
  coarsening/collapse independent edges/.default=true,
  %
  coarsening/connect independent nodes/.graph parameter=boolean,
  coarsening/connect independent nodes/.parameter initial=false,
  coarsening/connect independent nodes/.default=true,
  %
  % Node parameters for spring algorithms.
  %
  %
  % Edge parameters for spring algorithms.
  %
}

\pgfgddeclareforwardedkeys{/graph drawing}{
  %
  electric charge/.node parameter=number,
  electric charge/.parameter initial=1,
}


%
% Spring algorithm based on the paper
%
%   "Efficient, High-Quality Force-Directed Graph Drawing"
%   Yifan Hu, 2006
%
\pgfgddeclarealgorithmkey
  {spring layout}
  {force based}
  {
    algorithm=pgf.gd.force.SpringHu2006
  }

 
%
% Spring-electrical algorithm based on the paper
% 
%   "Efficient, High-Quality Force-Directed Graph Drawing"
%   Yifan Hu, 2006
%
\pgfgddeclarealgorithmkey
  {spring electrical layout}
  {force based}
  {
    algorithm=pgf.gd.force.SpringElectricalHu2006,
    force based/spring constant=0.2,
  }



%
% Spring-electrical algorithm based on the paper
%
%   "A Multilevel Algorithm for Force-Directed Graph Drawing"
%   C. Walshaw, 2000
%
\pgfgddeclarealgorithmkey
  {spring electrical layout'}
  {force based}
  {
    algorithm=pgf.gd.force.SpringElectricalWalshaw2000,
    force based/spring constant=0.01,
    force based/convergence tolerance=0.001,
  }

pgflibrarygraphdrawing.layered.code.tex
% Copyright 2011 by Jannis Pohlmann
%
% 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/graphdrawing/tex/pgflibrarygraphdrawing.layered.code.tex,v 1.5 2012/11/20 23:34:18 tantau Exp $

\usepgflibrary{graphdrawing}

\usegdlibrary{layered}


\endinput

pgflibrarygraphdrawing.trees.code.tex
% Copyright 2010 by Renée Ahrens, Olof Frahm, Jens Kluttig, Matthias Schulz, Stephan Schuster
% Copyright 2011 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/graphdrawing/tex/pgflibrarygraphdrawing.trees.code.tex,v 1.8 2012/11/20 23:34:18 tantau Exp $


\usepgflibrary{graphdrawing}
\usepgflibrary{graphdrawing.layered}

\usegdlibrary{trees}

\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

pgflibrarylindenmayersystems.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.

\newdimen\pgflsystemstep
\newcount\c@pgf@lsystem@iteration

\newif\ifpgf@lsystem@randomize@step
\newif\ifpgf@lsystem@randomize@angle

\pgfkeys{/pgf/lindenmayer system/.cd,%
	step/.code={\pgfmathsetlength\pgflsystemstep{#1}},%
	randomize step percent/.code={%
		\pgfmathparse{#1}%
		\let\pgflsystemrandomizesteppercent=\pgfmathresult%
		\ifdim\pgfmathresult pt=0pt\relax%
			\pgf@lsystem@randomize@stepfalse%
		\else%
			\pgf@lsystem@randomize@steptrue%
		\fi%
	},%
	left angle/.code={\pgfmathparse{#1}\let\pgflsystemleftangle=\pgfmathresult},%
	right angle/.code={\pgfmathparse{#1}\let\pgflsystemrightangle=\pgfmathresult},%
	angle/.style={/pgf/lindenmayer system/left angle=#1, /pgf/lindenmayer system/right angle=#1},%
	randomize angle percent/.code={%
		\pgfmathparse{#1}%
		\let\pgflsystemrandomizeanglepercent=\pgfmathresult%
		\ifdim\pgfmathresult pt=0pt\relax%
			\pgf@lsystem@randomize@anglefalse%
		\else%
			\pgf@lsystem@randomize@angletrue%
		\fi%
	}%
}

\pgfkeys{/pgf/lindenmayer system/.cd,
	step=5pt,%
	randomize step percent=0,%
	angle=90,%
	randomize angle percent=0%
}

\long\def\pgfdeclarelindenmayersystem#1#2{%
	\pgfutil@ifundefined{pgf@lsystem@#1}%
		{%
			\begingroup%
				\edef\pgf@lsystem@name{#1}%
				\expandafter\global\expandafter\let\csname pgf@lsystem@#1\endcsname=\pgf@lsystem@name%
				\let\symbol=\pgf@lsystem@symbol%
				\let\rule=\pgf@lsystem@rule%
				#2%
			\endgroup%
		}%
		{\pgferror{Lindenmayer system `#1' is already defined}}%
}

\def\pgf@lsystem@symbol#1#2{%
	\expandafter\gdef\csname pgf@lsystem@\pgf@lsystem@name @symbol@#1\endcsname{#2}%
}

\def\pgf@lsystem@rule#1{\expandafter\pgf@lsystem@rule@#1\pgf@stop}
\def\pgf@lsystem@rule@#1{\def\pgf@lsystem@rule@head{#1}\pgf@lsystem@rule@@}
\def\pgf@lsystem@rule@@#1->{% Now some `fooling around' to deal with unwanted spaces.
	\let\pgf@lsystem@rule@body=\pgfutil@empty%
	\pgfutil@ifnextchar x{\pgf@lsystem@rule@@@}{\pgf@lsystem@rule@@@}}
\def\pgf@lsystem@rule@@@#1{%
	\ifx#1\pgf@stop%
		\expandafter\global\expandafter\let%
			\csname pgf@lsystem@\pgf@lsystem@name @rule@\pgf@lsystem@rule@head\endcsname=\pgf@lsystem@rule@body%
	\else%
		\edef\pgf@lsystem@rule@body{\pgf@lsystem@rule@body#1}%
		\expandafter\pgf@lsystem@rule@@@%
	\fi%
}

\def\pgflindenmayersystem#1#2#3{%
	\begingroup%
		\edef\pgf@lsystem@name{#1}%
		\edef\pgf@lsystem@axiom{#2}%
		\pgfmathtruncatemacro\pgf@lsystem@order{#3}%
		%
		\let\pgf@lsystem@current@symbol=\relax%
		%
		\c@pgf@lsystem@iteration=0\relax%
		%
		\ifnum\pgf@lsystem@order=0\relax%
			\expandafter\pgf@lsystem@draw\pgf@lsystem@axiom\pgf@stop
			\let\pgf@lsystem@next=\pgf@lsystem@end%
		\else%
			\let\pgf@lsystem@next=\pgf@lsystem@run%		
		\fi%
		\expandafter\pgf@lsystem@next\pgf@lsystem@axiom\pgf@lsystem@stop%
}

\def\pgf@lsystem@run#1{%
	\ifx#1\pgf@lsystem@stop%
		\def\pgf@lsystem@token{\pgf@lsystem@stop}%
		\let\pgf@lsystem@next=\pgf@lsystem@end%
	\else%
		\ifx#1\pgf@stop%
			\advance\c@pgf@lsystem@iteration by-1\relax%
			\let\pgf@system@token=\pgfutil@empty%
			\let\pgf@lsystem@next=\pgf@lsystem@run%
		\else%
			% Does #1 appear on the RHS of a rule...?
			\expandafter\let\expandafter\pgf@lsystem@token\expandafter=%
				\csname pgf@lsystem@\pgf@lsystem@name @rule@#1\endcsname%				
			\ifx\pgf@lsystem@token\relax%
				% ...nope. So draw it straight away.
				\pgf@lsystem@draw#1\pgf@stop%
				\let\pgf@lsystem@token=\pgfutil@empty%				
			\else%
				% ...yep. So, if the order has been reached draw the LHS 
				% immediately. Otherwise add the LHS to the token stream
				% and continue.
				\advance\c@pgf@lsystem@iteration by1\relax%
				\ifnum\c@pgf@lsystem@iteration=\pgf@lsystem@order%
					\expandafter\pgf@lsystem@draw\pgf@lsystem@token \pgf@stop%
					\advance\c@pgf@lsystem@iteration by-1\relax%
					\let\pgf@lsystem@token=\pgfutil@empty%
				\else%
					\expandafter\def\expandafter\pgf@lsystem@token\expandafter{\pgf@lsystem@token \pgf@stop}%
				\fi%
			\fi%
			\let\pgf@lsystem@next=\pgf@lsystem@run%
		\fi%
	\fi%
	\expandafter\pgf@lsystem@next\pgf@lsystem@token}

\def\pgf@lsystem@end#1\pgf@lsystem@stop{\endgroup}

\def\pgf@lsystem@draw#1{%
	\ifx#1\pgf@stop%
		\let\pgf@lsystem@next=\relax%
	\else%
		\expandafter\let\expandafter\pgf@lsystem@current@symbol\expandafter=%
			\csname pgf@lsystem@\pgf@lsystem@name @symbol@#1\endcsname%
		\ifx\pgf@lsystem@current@symbol\relax% Try a default symbol.
			\expandafter\let\expandafter\pgf@lsystem@current@symbol\expandafter=%
				\csname pgf@lsystem@symbol@default@#1\endcsname%
		\fi%
		\let\pgf@lsystem@next=\pgf@lsystem@@draw%
	\fi%
	\pgf@lsystem@next}

\def\pgf@lsystem@@draw{%
	\edef\pgflsystemcurrentstep{\the\pgflsystemstep}%
	\let\pgflsystemcurrentrightangle=\pgflsystemrightangle%
	\let\pgflsystemcurrentrightangle=\pgflsystemleftangle%
	\pgf@lsystem@current@symbol%
	\pgf@lsystem@draw}

\expandafter\def\csname	pgf@lsystem@symbol@default@F\endcsname{\pgflsystemdrawforward}
\expandafter\def\csname	pgf@lsystem@symbol@default@f\endcsname{\pgflsystemmoveforward}
\expandafter\def\csname	pgf@lsystem@symbol@default@+\endcsname{\pgflsystemturnleft}
\expandafter\def\csname	pgf@lsystem@symbol@default@-\endcsname{\pgflsystemturnright}
\expandafter\def\csname	pgf@lsystem@symbol@default@[\endcsname{\pgflsystemsavestate}
\expandafter\def\csname	pgf@lsystem@symbol@default@]\endcsname{\pgflsystemrestorestate}

\def\pgflsystemradonmizestep{%
	\ifpgf@lsystem@randomize@step%
		\pgfmathrand%
		\pgf@x=\pgflsystemrandomizesteppercent pt\relax%
		\pgf@x=\pgfmathresult\pgf@x%
		\divide\pgf@x by20\relax%
		\advance\pgf@x by\pgflsystemstep\relax%
		\edef\pgflsystemcurrentstep{\the\pgf@x}%
	\else%
		\edef\pgflsystemcurrentstep{\the\pgflsystemstep}%
	\fi%
}

\def\pgflsystemdrawforward{%
	\pgflsystemradonmizestep
	\pgftransformxshift{+\pgflsystemcurrentstep}%
	\pgfpathlineto{\pgfpointorigin}}

\def\pgflsystemmoveforward{%
	\pgflsystemradonmizestep
	\pgftransformxshift{+\pgflsystemcurrentstep}%
	\pgfpathmoveto{\pgfpointorigin}}

\def\pgflsystemranomizerightangle{%
	\ifpgf@lsystem@randomize@angle%
		\pgf@x=\pgflsystemrandomizeanglepercent pt\relax%
		\divide\pgf@x by20\relax%
		\pgfmathrand%
		\pgf@x=\pgfmathresult\pgf@x%
		\advance\pgf@x by\pgflsystemrightangle pt\relax%
		\edef\pgflsystemcurrentrightangle{\pgfmath@tonumber{\pgf@x}}%
	\else%
		\let\pgflsystemcurrentrightangle=\pgflsystemrightangle%
	\fi%
}

\def\pgflsystemranomizeleftangle{%
	\ifpgf@lsystem@randomize@angle%
		\pgf@x=\pgflsystemrandomizeanglepercent pt\relax%
		\divide\pgf@x by20\relax%
		\pgfmathrand%
		\pgf@x=\pgfmathresult\pgf@x%
		\advance\pgf@x by\pgflsystemleftangle pt\relax%
		\edef\pgflsystemcurrentleftangle{\pgfmath@tonumber{\pgf@x}}%
	\else%
		\let\pgflsystemcurrentleftangle=\pgflsystemleftangle%
	\fi%
}

\def\pgflsystemturnright{%
	\pgflsystemranomizerightangle
	\pgftransformrotate{-\pgflsystemcurrentrightangle}}

\def\pgflsystemturnleft{%
	\pgflsystemranomizeleftangle
	\pgftransformrotate{\pgflsystemcurrentleftangle}}

\def\pgflsystemsavestate{\begingroup}
\def\pgflsystemrestorestate{\endgroup\pgfpathmoveto{\pgfpointorigin}}

pgflibraryluamath.code.tex
% Copyright 2011 by Christophe Jorssen 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.
%
% $Id: pgflibraryluamath.code.tex,v 1.11 2012/03/06 16:06:09 cjorssen Exp $
%
% !!! Warning: this library does not work with fpu!!!

% *******************************************************************
% Some luatex stuff. Should be put elsewhere (e.g. in
% pgfutil-luatex-engine).

% 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
% *******************************************************************

% Loading part: based on fpu library

\newif\ifpgfluamathcomputationactive
\newif\ifpgfluamathparseractive

\def\pgfluamath@makecomputationactive{%
  \ifpgfluamathcomputationactive
  \else
    \pgfluamath@checkuninstallcmd%
    \pgfluamath@install%
    \pgfluamathcomputationactivetrue
  \fi}

\def\pgfluamath@makecomputationinactive{%
  \ifpgfluamathcomputationactive
    \pgfluamath@uninstall%
    \pgfluamathcomputationactivefalse
  \fi}

\def\pgfluamath@makeparseractive{%
  \ifpgfluamathparseractive
  \else
    \let\pgfluamath@pgfmathparse\pgfmathparse
    \let\pgfmathparse\pgfluamathparse
    \pgfluamathparseractivetrue
  \fi}

\def\pgfluamath@makeparserinactive{%
  \ifpgfluamathparseractive
    \let\pgfmathparse\pgfluamath@pgfmathparse
    \pgfluamathparseractivefalse
  \fi}    

\pgfqkeys{/pgf}{%
  % Enable lua-side computation of \pgfmathresult
  % (will be deactivated after the current TeX group)
  luamath/.is choice,
  luamath/only computation/.code={%
    \pgfutil@ifluatex
      \pgfluamath@makecomputationactive
      \pgfluamath@makeparserinactive
    \else
      \pgfmath@error{Sorry, you need the luaTeX engine to use the
        luamath library}%
    \fi},
  luamath/parser and computation/.code={%
    \pgfutil@ifluatex
      \pgfluamath@makecomputationactive
      \pgfluamath@makeparseractive
    \else
      \pgfmath@error{Sorry, you need the luaTeX engine to use the
        luamath library}%
    \fi},
  luamath/off/.code={%
    \pgfluamath@makecomputationinactive
    \pgfluamath@makeparserinactive},
  luamath/.default=only computation}

\def\pgfluamath@uninstall@appendcmd#1{%
  \expandafter\gdef\expandafter\pgfluamath@uninstall\expandafter{%
    \pgfluamath@uninstall #1}}

% If the uninstall command is already assembled, it will skip the
% uninstall assemblation.
\def\pgfluamath@checkuninstallcmd{%
  \pgfutil@ifundefined{pgfluamath@uninstall}{%
    \pgfutil@directlua{%
      pgfluamathfunctions = require("pgfluamath.functions")
      pgfluamathparser = require("pgfluamath.parser")}
    \global\let\pgfluamath@uninstall=\pgfutil@empty
  }{%
    % We already HAVE an uninstall command (prepared globally).
    % So: don't waste time assembling one!
    \def\pgfluamath@uninstall@appendcmd##1{}%
    \def\pgfluamath@prepareuninstallcmd##1{}%
  }%
}

% This assembles an uninstall command globally ON FIRST USAGE.
% See \pgfmathfloat@plots@checkuninstallcmd
\def\pgfluamath@prepareuninstallcmd#1{%
  \expandafter\global\expandafter\let
    \csname pgfluamath@backup@\string#1\endcsname=#1%
  \expandafter\gdef\expandafter\pgfluamath@uninstall\expandafter{%
    \pgfluamath@uninstall
    \expandafter\let\expandafter#1\csname pgfluamath@backup@\string#1\endcsname}%
}

\def\pgfluamath@install@function#1=#2{%
  \pgfluamath@prepareuninstallcmd{#1}%
  \let#1=#2%
}

\def\pgfluamath@install{%
  \pgfluamath@install@function\pgfmathadd@=\pgfluamathadd@%
  \pgfluamath@install@function\pgfmathsubtract@=\pgfluamathsubtract@%
  \pgfluamath@install@function\pgfmathneg@=\pgfluamathneg@%
  \pgfluamath@install@function\pgfmathmultiply@=\pgfluamathmultiply@%
  \pgfluamath@install@function\pgfmathdivide@=\pgfluamathdivide@%
  % \pgfluamath@install@function\pgfmathdiv@=\pgfluamathdiv@%
  \pgfluamath@install@function\pgfmathfactorial@=\pgfluamathfactorial@%
  \pgfluamath@install@function\pgfmathsqrt@=\pgfluamathsqrt@%
  % \pgfluamath@install@function\pgfmathpow@=\pgfluamathpow@%
  \pgfluamath@install@function\pgfmathe@=\pgfluamathe@%
  \pgfluamath@install@function\pgfmathexp@=\pgfluamathexp@%
  \pgfluamath@install@function\pgfmathln@=\pgfluamathln@%
  \pgfluamath@install@function\pgfmathlogten@=\pgfluamathlogten@%
  % \pgfluamath@install@function\pgfmathlogtwo@=\pgfluamathlogtwo@%
  \pgfluamath@install@function\pgfmathabs@=\pgfluamathabs@%
  \pgfluamath@install@function\pgfmathmod@=\pgfluamathmod@%
  \pgfluamath@install@function\pgfmathMod@=\pgfluamathMod@%
  \pgfluamath@install@function\pgfmathround@=\pgfluamathround@%
  \pgfluamath@install@function\pgfmathfloor@=\pgfluamathfloor@%
  \pgfluamath@install@function\pgfmathceil@=\pgfluamathceil@%
  % \pgfluamath@install@function\pgfmathint@=\pgfluamathint@%
  % \pgfluamath@install@function\pgfmathfrac@=\pgfluamathfrac@%
  % \pgfluamath@install@function\pgfmathreal@=\pgfluamathreal@%
  \pgfluamath@install@function\pgfmathgcd@=\pgfluamathgcd@%
  \pgfluamath@install@function\pgfmathisprime@=\pgfluamathisprime@%
  \pgfluamath@install@function\pgfmathpi@=\pgfluamathpi@%
  \pgfluamath@install@function\pgfmathrad@=\pgfluamathrad@%
  \pgfluamath@install@function\pgfmathdeg@=\pgfluamathdeg@%
  \pgfluamath@install@function\pgfmathsin@=\pgfluamathsin@%
  \pgfluamath@install@function\pgfmathcos@=\pgfluamathcos@%
  \pgfluamath@install@function\pgfmathtan@=\pgfluamathtan@%
  \pgfluamath@install@function\pgfmathsec@=\pgfluamathsec@%
  \pgfluamath@install@function\pgfmathcosec@=\pgfluamathcosec@%
  \pgfluamath@install@function\pgfmathcot@=\pgfluamathcot@%
  \pgfluamath@install@function\pgfmathasin@=\pgfluamathasin@%
  \pgfluamath@install@function\pgfmathacos@=\pgfluamathacos@%
  \pgfluamath@install@function\pgfmathatan@=\pgfluamathatan@%
  \pgfluamath@install@function\pgfmathatantwo@=\pgfluamathatantwo@%
  \pgfluamath@install@function\pgfmathmax@=\pgfluamathmax@%
  \pgfluamath@install@function\pgfmathmin@=\pgfluamathmin@%
  % \pgfluamath@install@function\pgfmath@pi=\pgfluamathpi@%
  % \pgfluamath@install@function\pgfmathpi=\pgfluamathpi@%
  % \pgfluamath@install@function\pgfmathe@=\pgfluamathe@%
  % \pgfluamath@install@function\pgfmathe=\pgfluamathe@%
  % \pgfluamath@install@function\pgfmathlessthan@=\pgfluamathlessthan@%
  % \pgfluamath@install@function\pgfmathless@=\pgfluamathlessthan@%
  % \pgfluamath@install@function\pgfmathgreaterthan@=\pgfluamathgreaterthan@%
  % \pgfluamath@install@function\pgfmathgreater@=\pgfluamathgreaterthan@%
  % \pgfluamath@install@function\pgfmathpow@=\pgfluamathpow@
  \pgfluamath@install@function\pgfmathrand@=\pgfluamathrand@
  \pgfluamath@install@function\pgfmathrand=\pgfluamathrand@
  \pgfluamath@install@function\pgfmathrnd@=\pgfluamathrnd@
  \pgfluamath@install@function\pgfmathrnd=\pgfluamathrnd@
  % \pgfluamath@install@function\pgfmathtrue@=\pgfluamathtrue@
  % \pgfluamath@install@function\pgfmathfalse@=\pgfluamathfalse@
  % \pgfluamath@install@function\pgfmathnot@=\pgfluamathnot@
  % \pgfluamath@install@function\pgfmathhex@=\pgfluamathhex@
  % \pgfluamath@install@function\pgfmathHex@=\pgfluamathHex@
  % \pgfluamath@install@function\pgfmathoct@=\pgfluamathoct@
  % \pgfluamath@install@function\pgfmathbin@=\pgfluamathbin@
  % \pgfluamath@install@function\pgfmathand@=\pgfluamathand@
  % \pgfluamath@install@function\pgfmathor@=\pgfluamathor@
  % \pgfluamath@install@function\pgfmathfactorial@=\pgfluamathfactorial@
  % \pgfluamath@install@function\pgfmathveclen@=\pgfluamathveclen@
  % \pgfluamath@install@function\pgfmathcosh@=\pgfluamathcosh@
  % \pgfluamath@install@function\pgfmathsinh@=\pgfluamathsinh@
  % \pgfluamath@install@function\pgfmathtanh@=\pgfluamathtanh@
  % \pgfluamath@install@function@unimplemented{ceil}%
  % \pgfluamath@install@function@unimplemented{frac}%
  % \pgfluamath@install@function@unimplemented{log2}%
  % \pgfluamath@install@function@unimplemented{log10}%
  % \pgfluamath@install@function@unimplemented{equalto}%
  % \pgfluamath@install@function@unimplemented{random}%
  % \pgfluamath@install@function@unimplemented{setseed}%
  % \pgfluamath@install@function@unimplemented{Mod}%
  % \pgfluamath@install@function@unimplemented{real}%
  % \pgfluamath@install@function@unimplemented{notequal}%
  \pgfluamath@install@function\pgfmathreciprocal=\pgfluamathreciprocal%
  \pgfluamath@install@function\pgfpointnormalised=\pgfluamathpointnormalised
}

\def\pgfluamathgetresult#1{%
  \edef\pgfmathresult{\pgfutil@directlua{tex.print(-1,#1)}}}

\def\pgfluamathpi@{%
  \pgfluamathgetresult{pgfluamathfunctions.pi()}}
\def\pgfluamathe@{%
  \pgfluamathgetresult{pgfluamathfunctions.e()}}
\def\pgfluamathadd@#1#2{%
  \pgfluamathgetresult{pgfluamathfunctions.add(#1,#2)}}
\def\pgfluamathsubtract@#1#2{%
  \pgfluamathgetresult{pgfluamathfunctions.substract(#1,#2)}}
\def\pgfluamathneg@#1{%
  \pgfluamathgetresult{pgfluamathfunctions.neg(#1)}}
\def\pgfluamathmultiply@#1#2{%
  \pgfluamathgetresult{pgfluamathfunctions.multiply(#1,#2)}}
\def\pgfluamathdivide@#1#2{%
  \pgfluamathgetresult{pgfluamathfunctions.divide(#1,#2)}}
\def\pgfluamathabs@#1{%
  \pgfluamathgetresult{pgfluamathfunctions.abs(#1)}}
\def\pgfluamathround@#1{%
  \pgfluamathgetresult{pgfluamathfunctions.round(#1)}}
\def\pgfluamathfloor@#1{%
  \pgfluamathgetresult{pgfluamathfunctions.floor(#1)}}
\def\pgfluamathceil@#1{%
  \pgfluamathgetresult{pgfluamathfunctions.ceil(#1)}}
\def\pgfluamathgcd@#1#2{%
  \pgfluamathgetresult{pgfluamathfunctions.gcd(#1,#2)}}
\def\pgfluamathisprime@#1{%
  \pgfluamathgetresult{pgfluamathfunctions.isprime(#1)}}
\def\pgfluamathmax@#1{%
  \pgfluamathgetresult{%
    math.max(pgfluamathfunctions.split_braces_to_explist("#1"))}}
\def\pgfluamathmin@#1{%
  \pgfluamathgetresult{%
    math.min(pgfluamathfunctions.split_braces_to_explist("#1"))}}
\def\pgfluamathsin@#1{%
  \pgfluamathgetresult{pgfluamathfunctions.Sin(#1)}}
\def\pgfluamathcos@#1{%
  \pgfluamathgetresult{pgfluamathfunctions.Cos(#1)}}
\def\pgfluamathtan@#1{%
  \pgfluamathgetresult{pgfluamathfunctions.Tan(#1)}}
\def\pgfluamathmod@#1#2{%
  \pgfluamathgetresult{pgfluamathfunctions.mod(#1,#2)}}
\def\pgfluamathMod@#1#2{%
  \pgfluamathgetresult{pgfluamathfunctions.Mod(#1,#2)}}
\def\pgfluamathrad@#1{%
  \pgfluamathgetresult{pgfluamathfunctions.rad(#1)}}
\def\pgfluamathdeg@#1{%
  \pgfluamathgetresult{pgfluamathfunctions.deg(#1)}}
\def\pgfluamathatan@#1{%
  \pgfluamathgetresult{pgfluamathfunctions.aTan(#1)}}
\def\pgfluamathatantwo@#1#2{%
  \pgfluamathgetresult{pgfluamathfunctions.aTan2(#1,#2)}}
\def\pgfluamathasin@#1{%
  \pgfluamathgetresult{pgfluamathfunctions.aSin(#1)}}
\def\pgfluamathacos@#1{%
  \pgfluamathgetresult{pgfluamathfunctions.aCos(#1)}}
\def\pgfluamathcot@#1{%
  \pgfluamathgetresult{1/pgfluamathfunctions.Tan(#1)}}
\def\pgfluamathsec@#1{%
  \pgfluamathgetresult{1/pgfluamathfunctions.Cos(#1)}}
\def\pgfluamathcosec@#1{%
  \pgfluamathgetresult{1/pgfluamathfunctions.Sin(#1)}}
\def\pgfluamathexp@#1{%
  \pgfluamathgetresult{pgfluamathfunctions.exp(#1)}}
\def\pgfluamathln@#1{%
  \pgfluamathgetresult{pgfluamathfunctions.log(#1)}}
\def\pgfluamathlogten@#1{%
  \pgfluamathgetresult{pgfluamathfunctions.log10(#1)}}
\def\pgfluamathsqrt@#1{%
  \pgfluamathgetresult{pgfluamathfunctions.sqrt(#1)}}
\def\pgfluamathrnd@{%
  \pgfluamathgetresult{pgfluamathfunctions.rnd()}}
\def\pgfluamathrand@{%
  \pgfluamathgetresult{pgfluamathfunctions.rand(-1,1)}}
\def\pgfluamathfactorial@#1{%
  \pgfluamathgetresult{pgfluamathfunctions.factorial(#1)}}
\def\pgfluamathreciprocal#1{%
  \pgfluamathgetresult{1/#1}}
% \pgfluamath@install@function\pgfmath@pi=\pgfluamathpi@%
% \pgfluamath@install@function\pgfmathpi=\pgfluamathpi@%
% \pgfluamath@install@function\pgfmathe@=\pgfluamathe@%
% \pgfluamath@install@function\pgfmathe=\pgfluamathe@%
% \pgfluamath@install@function\pgfmathlessthan@=\pgfluamathlessthan@%
% \pgfluamath@install@function\pgfmathless@=\pgfluamathlessthan@%
% \pgfluamath@install@function\pgfmathgreaterthan@=\pgfluamathgreaterthan@%
% \pgfluamath@install@function\pgfmathgreater@=\pgfluamathgreaterthan@%
% \pgfluamath@install@function\pgfmathpow@=\pgfluamathpow@
% \pgfluamath@install@function\pgfmathrand@=\pgfluamathrand@
% \pgfluamath@install@function\pgfmathrand=\pgfluamathrand@
% \pgfluamath@install@function\pgfmathrnd@=\pgfluamathrnd@
% \pgfluamath@install@function\pgfmathrnd=\pgfluamathrnd@
% \pgfluamath@install@function\pgfmathtrue@=\pgfluamathtrue@
% \pgfluamath@install@function\pgfmathfalse@=\pgfluamathfalse@
% \pgfluamath@install@function\pgfmathnot@=\pgfluamathnot@
% \pgfluamath@install@function\pgfmathhex@=\pgfluamathhex@
% \pgfluamath@install@function\pgfmathHex@=\pgfluamathHex@
% \pgfluamath@install@function\pgfmathoct@=\pgfluamathoct@
% \pgfluamath@install@function\pgfmathbin@=\pgfluamathbin@
% \pgfluamath@install@function\pgfmathand@=\pgfluamathand@
% \pgfluamath@install@function\pgfmathor@=\pgfluamathor@
% \pgfluamath@install@function\pgfmathfactorial@=\pgfluamathfactorial@
% \pgfluamath@install@function\pgfmathveclen@=\pgfluamathveclen@
% \pgfluamath@install@function\pgfmathcosh@=\pgfluamathcosh@
% \pgfluamath@install@function\pgfmathsinh@=\pgfluamathsinh@
% \pgfluamath@install@function\pgfmathtanh@=\pgfluamathtanh@

\def\pgfluamathpointnormalised#1{%
  \pgf@process{#1}%
  \pgfutil@directlua{%
    pgfluamathfunctions.pointnormalised(%
      \pgf@sys@tonumber{\pgf@x},\pgf@sys@tonumber{\pgf@y})}%
  \ignorespaces}

% Parser

\newif\ifpgfluamathunitsdeclared

\def\pgfluamathparse#1{%
  \pgfluamathunitsdeclaredfalse
  % The following "two passes" (TeX -> lua -> TeX -> lua -> TeX) is
  % required for chadef'ed named boxes. The parser 
  % adds \number in front of the box name (e.g. \mybox ->
  % \number\mybox). Then this is expanded to the chardef'ed number via
  % \edef expansion.
  \edef\pgfluamath@temp{%
    \pgfutil@directlua{%
    % Double quotes " are needed here. On the lua side, single quotes
    % ' are used. Take care to don't mix them.
      pgfluamathparser.parse("\pgfutil@luaescapestring{#1}")
      tex.sprint(parsed_expression)}}%
  % We can now feed back the evaluator.
  \edef\pgfluamathresult{%
    \pgfutil@directlua{%
      pgfluamathparser.eval('\pgfluamath@temp')
      if pgfluamathparser.result == nil then
        tex.print('nil')
      else
        tex.print(pgfluamathparser.result)
      end}}%
  \csname pgfluamathunitsdeclared\pgfutil@directlua{%
    if pgfluamathparser.units_declared == true then
      tex.print('true')
    else
      tex.print('false')
    end}\endcsname
  \ifpgfluamathparseractive
    \let\pgfmathresult\pgfluamathresult
    \let\ifpgfmathunitsdeclared=\ifpgfluamathunitsdeclared
  \fi}

\endinput
% NEW: CJ (06 March 2012) Work in progress
\documentclass{minimal}

\usepackage{pgfmath}

\makeatletter
\let\pgfutil@directlua\directlua

\directlua{dofile('pgfmathparser.lua')}

\def\pgfluamathdeclarefunction#1#2#3{%
  \pgfutil@directlua{%
    pgfluamath.declare_new_function('#1',#2,#3)}}

\pgfluamathdeclarefunction{add}{2}{%
  function (a,b) return a + b end}

\pgfluamathdeclarefunction{substract}{2}{%
  function (a,b) return a - (b) end}

\pgfluamathdeclarefunction{neg}{1}{%
  function (a) return -(a) end}

\pgfluamathdeclarefunction{multiply}{2}{%
  function (a,b) return a * b end}

\pgfluamathdeclarefunction{divide}{2}{%
  function (a,b) return a / b end}

\pgfluamathdeclarefunction{pow}{2}{%
  function (a,b) return math.pow(a,b) end}

\pgfluamathdeclarefunction{deg}{1}{%
  function (a) return math.deg(a) end}

\pgfluamathdeclarefunction{ifthenelse}{3}{%
  function (a,b,c) if a == 1 then return b else return c end end}

\pgfluamathdeclarefunction{equal}{2}{%
  function (a,b) if a == b then return 1 else return 0 end end}

\pgfluamathdeclarefunction{greater}{2}{%
  function (a,b) if a > b then return 1 else return 0 end end}

\pgfluamathdeclarefunction{less}{2}{%
  function (a,b) if a < b then return 1 else return 0 end end}

\pgfluamathdeclarefunction{notequal}{2}{%
  function (a,b) if a < b or a > b then return 1 else return 0 end end}

\pgfluamathdeclarefunction{notless}{2}{%
  function (a,b) if a >= b then return 1 else return 0 end end}

\pgfluamathdeclarefunction{notgreater}{2}{%
  function (a,b) if a <= b then return 1 else return 0 end end}

\pgfluamathdeclarefunction{andPGF}{2}{%
  function (a,b) if (a < 0 or a > 0) and (b < 0 or b > 0) then return
  1 else return 0 end end}

\pgfluamathdeclarefunction{orPGF}{2}{%
  function (a,b) if (a < 0 or a > 0) or (b < 0 or b > 0) then return 1
  else return 0 end end}

\pgfluamathdeclarefunction{modulo}{2}{%
  % This is the definition of the lua % modulo operator
  % The % operator cannot be used here (catcode issue)
  function (a,b) return a - math.floor(a/b)*b end}

\pgfluamathdeclarefunction{int}{1}{%
  function (a) return a - pgfluamath.defined_functions.modulo.code(a,1) end}

\pgfluamathdeclarefunction{frac}{1}{%
  function (a) return pgfluamath.defined_functions.modulo.code(a,1) end}

\pgfluamathdeclarefunction{factorial}{1}{%
  function (a)
    a = math.abs(pgfluamath.defined_functions.int.code(a))
    if a == 1 then
      return 1
    else
      return a * pgfluamath.defined_functions.factorial.code(a-1)
    end
  end}

\pgfluamathdeclarefunction{sqrt}{1}{%
  function (a) return math.sqrt(a) end}



\def\pgfluamathparseandresult#1{%
  \pgfutil@directlua{%
    local s = pgfluamath.transform_math_expr('#1',pgfluamath.defined_functions_pattern)
    texio.write_nl('pgfluamath: parsed expression "' .. s .. '"')
    loadstring('tex.sprint(-1,' .. s .. ')')()}}

\makeatother
\begin{document}

$\pgfluamathparseandresult{1+2} = 3$

$\pgfluamathparseandresult{2*3} = 6$

$\pgfluamathparseandresult{1--1} = 2$

$\pgfluamathparseandresult{6/2} = 3$

$\pgfluamathparseandresult{2^2} = 4$

$\pgfluamathparseandresult{1>2} = 0$

$\pgfluamathparseandresult{2>1} = 1$

$\pgfluamathparseandresult{1!=1} = 0$

$\pgfluamathparseandresult{1?2:3} = 2$

$\pgfluamathparseandresult{1.0||0} = 1$

$\pgfluamathparseandresult{1&&0} = 0$

$\pgfluamathparseandresult{sqrt(2)} = \pgfmathparse{sqrt(2)}\pgfmathresult$

%\pgfluamathparseandresult{{1,{2,3-7}[1],4}[1]^2}

\end{document}
% Local Variables:
% TeX-engine: luatex
% End:
pgflibrarypatterns.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/pgflibrarypatterns.code.tex,v 1.13 2008/03/03 13:52:35 tantau Exp $


% Lines in different directions

\pgfdeclarepatternformonly{horizontal lines}{\pgfpointorigin}{\pgfqpoint{100pt}{1pt}}{\pgfqpoint{100pt}{3pt}}%
{
  \pgfsetlinewidth{0.4pt}
  \pgfpathmoveto{\pgfqpoint{0pt}{0.5pt}}
  \pgfpathlineto{\pgfqpoint{100pt}{0.5pt}}
  \pgfusepath{stroke}
}

\pgfdeclarepatternformonly{vertical lines}{\pgfpointorigin}{\pgfqpoint{1pt}{100pt}}{\pgfqpoint{3pt}{100pt}}%
{
  \pgfsetlinewidth{0.4pt}
  \pgfpathmoveto{\pgfqpoint{0.5pt}{0pt}}
  \pgfpathlineto{\pgfqpoint{0.5pt}{100pt}}
  \pgfusepath{stroke}
}

\pgfdeclarepatternformonly{north east lines}{\pgfqpoint{-1pt}{-1pt}}{\pgfqpoint{4pt}{4pt}}{\pgfqpoint{3pt}{3pt}}%
{
  \pgfsetlinewidth{0.4pt}
  \pgfpathmoveto{\pgfqpoint{0pt}{0pt}}
  \pgfpathlineto{\pgfqpoint{3.1pt}{3.1pt}}
  \pgfusepath{stroke}
}

\pgfdeclarepatternformonly{north west lines}{\pgfqpoint{-1pt}{-1pt}}{\pgfqpoint{4pt}{4pt}}{\pgfqpoint{3pt}{3pt}}%
{
  \pgfsetlinewidth{0.4pt}
  \pgfpathmoveto{\pgfqpoint{0pt}{3pt}}
  \pgfpathlineto{\pgfqpoint{3.1pt}{-0.1pt}}
  \pgfusepath{stroke}
}

% Crossed lines in different directions

\pgfdeclarepatternformonly{grid}{\pgfqpoint{-1pt}{-1pt}}{\pgfqpoint{4pt}{4pt}}{\pgfqpoint{3pt}{3pt}}%
{
  \pgfsetlinewidth{0.4pt}
  \pgfpathmoveto{\pgfqpoint{0pt}{0pt}}
  \pgfpathlineto{\pgfqpoint{0pt}{3.1pt}}
  \pgfpathmoveto{\pgfqpoint{0pt}{0pt}}
  \pgfpathlineto{\pgfqpoint{3.1pt}{0pt}}
  \pgfusepath{stroke}
}

\pgfdeclarepatternformonly{crosshatch}{\pgfqpoint{-1pt}{-1pt}}{\pgfqpoint{4pt}{4pt}}{\pgfqpoint{3pt}{3pt}}%
{
  \pgfsetlinewidth{0.4pt}
  \pgfpathmoveto{\pgfqpoint{3.1pt}{0pt}}
  \pgfpathlineto{\pgfqpoint{0pt}{3.1pt}}
  \pgfpathmoveto{\pgfqpoint{0pt}{0pt}}
  \pgfpathlineto{\pgfqpoint{3.1pt}{3.1pt}}
  \pgfusepath{stroke}
}


% Dotted regions

\pgfdeclarepatternformonly{dots}{\pgfqpoint{-1pt}{-1pt}}{\pgfqpoint{1pt}{1pt}}{\pgfqpoint{3pt}{3pt}}%
{
  \pgfpathcircle{\pgfqpoint{0pt}{0pt}}{.5pt}
  \pgfusepath{fill}
}

\pgfdeclarepatternformonly{crosshatch dots}{\pgfqpoint{-1pt}{-1pt}}{\pgfqpoint{2.5pt}{2.5pt}}{\pgfqpoint{3pt}{3pt}}%
{
  \pgfpathcircle{\pgfqpoint{0pt}{0pt}}{.5pt}
  \pgfpathcircle{\pgfqpoint{1.5pt}{1.5pt}}{.5pt}
  \pgfusepath{fill}
}




% Star shaped patterns

\pgfdeclarepatternformonly{fivepointed stars}{\pgfpointorigin}{\pgfqpoint{3mm}{3mm}}{\pgfqpoint{3mm}{3mm}}%
{
  \pgftransformshift{\pgfqpoint{1mm}{1mm}}
  \pgfpathmoveto{\pgfqpointpolar{18}{1mm}}
  \pgfpathlineto{\pgfqpointpolar{162}{1mm}}
  \pgfpathlineto{\pgfqpointpolar{306}{1mm}}
  \pgfpathlineto{\pgfqpointpolar{90}{1mm}}
  \pgfpathlineto{\pgfqpointpolar{234}{1mm}}
  \pgfpathclose%
  \pgfusepath{fill}
}

\pgfdeclarepatternformonly{sixpointed stars}{\pgfpointorigin}{\pgfqpoint{3mm}{3mm}}{\pgfqpoint{3mm}{3mm}}%
{
  \pgftransformshift{\pgfqpoint{1mm}{1mm}}
  \pgfpathmoveto{\pgfqpointpolar{30}{1mm}}
  \pgfpathlineto{\pgfqpointpolar{150}{1mm}}
  \pgfpathlineto{\pgfqpointpolar{270}{1mm}}
  \pgfpathclose%
  \pgfpathmoveto{\pgfqpointpolar{-30}{1mm}}
  \pgfpathlineto{\pgfqpointpolar{-270}{1mm}}
  \pgfpathlineto{\pgfqpointpolar{-150}{1mm}}
  \pgfpathclose%
  \pgfsetnonzerorule
  \pgfusepath{fill}
}



% Bricks

\pgfdeclarepatternformonly{bricks}{\pgfqpoint{-1pt}{-1pt}}{\pgfqpoint{5mm}{5mm}}{\pgfqpoint{4mm}{4mm}}%
{
  \pgfsetlinewidth{0.8pt}
  \pgfpathmoveto{\pgfqpoint{0mm}{1mm}}
  \pgfpathlineto{\pgfqpoint{4mm}{1mm}}
  \pgfpathmoveto{\pgfqpoint{0mm}{3mm}}
  \pgfpathlineto{\pgfqpoint{4mm}{3mm}}
  \pgfpathmoveto{\pgfqpoint{1mm}{0mm}}
  \pgfpathlineto{\pgfqpoint{1mm}{1mm}}
  \pgfpathmoveto{\pgfqpoint{3mm}{1mm}}
  \pgfpathlineto{\pgfqpoint{3mm}{3mm}}
  \pgfpathmoveto{\pgfqpoint{1mm}{3mm}}
  \pgfpathlineto{\pgfqpoint{1mm}{4mm}}
  \pgfusepath{stroke}
}


% Checkerboards

\pgfdeclarepatternformonly{checkerboard}{\pgfpointorigin}{\pgfqpoint{4mm}{4mm}}{\pgfqpoint{4mm}{4mm}}%
{
  \pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{2mm}{2mm}}
  \pgfpathrectangle{\pgfqpoint{2mm}{2mm}}{\pgfqpoint{2mm}{2mm}}
  \pgfusepath{fill}
}



% Backgrounds

\pgfdeclarepatterninherentlycolored{checkerboard light gray}
{\pgfpointorigin}{\pgfqpoint{4mm}{4mm}}{\pgfqpoint{4mm}{4mm}}%
{
  \pgfsetfillcolor{black!10}
  \pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{4.1mm}{4.1mm}}% make
                                % slightly larger to ensure that tiles
                                % are really solid
  \pgfusepath{fill}
  \pgfsetfillcolor{black!20}
  \pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{2mm}{2mm}}
  \pgfpathrectangle{\pgfqpoint{2mm}{2mm}}{\pgfqpoint{2mm}{2mm}}
  \pgfusepath{fill}
}

\pgfdeclarepatterninherentlycolored{horizontal lines light gray}
{\pgfpointorigin}{\pgfpoint{100pt}{4pt}}
{\pgfpoint{100pt}{4pt}}
{
  \pgfsetfillcolor{black!10}
  \pgfpathrectangle{\pgfpointorigin}{\pgfpoint{100pt}{2.5pt}}
  \pgfusepath{fill}
  \pgfsetfillcolor{black!15}
  \pgfpathrectangle{\pgfpoint{0pt}{2pt}}{\pgfpoint{100pt}{2.5pt}}
  \pgfusepath{fill}
}

\pgfdeclarepatterninherentlycolored{horizontal lines gray}
{\pgfpointorigin}{\pgfpoint{100pt}{4pt}}
{\pgfpoint{100pt}{4pt}}
{
  \pgfsetfillcolor{black!30}
  \pgfpathrectangle{\pgfpointorigin}{\pgfpoint{100pt}{2.5pt}}
  \pgfusepath{fill}
  \pgfsetfillcolor{black!35}
  \pgfpathrectangle{\pgfpoint{0pt}{2pt}}{\pgfpoint{100pt}{2.5pt}}
  \pgfusepath{fill}
}

\pgfdeclarepatterninherentlycolored{horizontal lines dark gray}
{\pgfpointorigin}{\pgfpoint{100pt}{4pt}}
{\pgfpoint{100pt}{4pt}}
{
  \pgfsetfillcolor{black!90}
  \pgfpathrectangle{\pgfpointorigin}{\pgfpoint{100pt}{2.5pt}}
  \pgfusepath{fill}
  \pgfsetfillcolor{black!85}
  \pgfpathrectangle{\pgfpoint{0pt}{2pt}}{\pgfpoint{100pt}{2.5pt}}
  \pgfusepath{fill}
}

\pgfdeclarepatterninherentlycolored{horizontal lines light blue}
{\pgfpointorigin}{\pgfpoint{100pt}{4pt}}
{\pgfpoint{100pt}{4pt}}
{
  \pgfsetfillcolor{blue!10}
  \pgfpathrectangle{\pgfpointorigin}{\pgfpoint{100pt}{2.5pt}}
  \pgfusepath{fill}
  \pgfsetfillcolor{blue!15}
  \pgfpathrectangle{\pgfpoint{0pt}{2pt}}{\pgfpoint{100pt}{2.5pt}}
  \pgfusepath{fill}
}

\pgfdeclarepatterninherentlycolored{horizontal lines dark blue}
{\pgfpointorigin}{\pgfpoint{100pt}{4pt}}
{\pgfpoint{100pt}{4pt}}
{
  \pgfsetfillcolor{blue!90}
  \pgfpathrectangle{\pgfpointorigin}{\pgfpoint{100pt}{2.5pt}}
  \pgfusepath{fill}
  \pgfsetfillcolor{blue!85}
  \pgfpathrectangle{\pgfpoint{0pt}{2pt}}{\pgfpoint{100pt}{2.5pt}}
  \pgfusepath{fill}
}


\pgfdeclarepatterninherentlycolored{crosshatch dots gray}
{\pgfpointorigin}{\pgfpoint{8pt}{8pt}}
{\pgfpoint{8pt}{8pt}}
{
  \pgfsetfillcolor{black!20}
  \pgfpathrectangle{\pgfpointorigin}{\pgfpoint{8pt}{8pt}}
  \pgfusepath{fill}
  \pgfsetfillcolor{black!10}
  \pgfpathcircle{\pgfpoint{2pt}{1.75pt}}{1pt}
  \pgfpathcircle{\pgfpoint{6pt}{5.75pt}}{1pt}
  \pgfusepath{fill}
  \pgfsetfillcolor{black!70}
  \pgfpathcircle{\pgfpoint{2pt}{2.25pt}}{1pt}
  \pgfpathcircle{\pgfpoint{6pt}{6.25pt}}{1pt}
  \pgfusepath{fill}
}

\pgfutil@definecolor{pgf@lightsteelblue}{rgb}{0.6875,0.765625,0.8671875}
\pgfutil@colorlet{pgf@darklightsteelblue}{black!50!pgf@lightsteelblue}

\pgfdeclarepatterninherentlycolored{crosshatch dots light steel blue}
{\pgfpointorigin}{\pgfpoint{8pt}{8pt}}
{\pgfpoint{8pt}{8pt}}
{
  \pgfsetfillcolor{pgf@lightsteelblue}
  \pgfpathrectangle{\pgfpointorigin}{\pgfpoint{8pt}{8pt}}
  \pgfusepath{fill}
  \pgfsetfillcolor{pgf@darklightsteelblue!10}
  \pgfpathcircle{\pgfpoint{2pt}{1.75pt}}{1pt}
  \pgfpathcircle{\pgfpoint{6pt}{5.75pt}}{1pt}
  \pgfusepath{fill}
  \pgfsetfillcolor{pgf@darklightsteelblue!70}
  \pgfpathcircle{\pgfpoint{2pt}{2.25pt}}{1pt}
  \pgfpathcircle{\pgfpoint{6pt}{6.25pt}}{1pt}
  \pgfusepath{fill}
}




\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

pgflibraryprofiler.code.tex
%--------------------------------------------
%
% TeX profiling library
% 
% 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/>.
%
%--------------------------------------------

\pgfutil@ifundefined{pdfelapsedtime}{%
  % Ok, \pdfelapsedtime is not defined.
  % Maybe we run luatex?
  \pgfutil@ifluatex
    % Yes. So we emulate the primitive by a macro.
    % (see http://tex.stackexchange.com/q/32507/8425)
    \def\pgfutil@pdfelapsedtime{%
      \numexpr\pgfutil@directlua{%
        tex.print(math.floor((os.clock())*65536+0.5))}\relax}
  \else
    % Raise an error
    \pgferror{%
      Library 'profiler' can only be used with pdftex Rev. >= 1.671 
      because it needs the \string\pdfelapsedtime\space command or
      with luatex}%
    \global\let\pgfutil@pdfelapsedtime=\c@pgf@counta
  \fi}{%
  % We run pdftex. That's ok.
  \let\pgfutil@pdfelapsedtime\pdfelapsedtime}


% Defines a new profiler entry named `#1'.
%
% This allocates a set of counters.
\def\pgfprofilenew#1{%
	\pgfutil@ifundefined{c@pgfprofile@elapsedtotal@#1}{%
		\expandafter\gdef\csname c@pgfprofile@elapsedtotal@#1\endcsname{0}%
		\expandafter\gdef\csname c@pgfprofile@elapsedself@#1\endcsname{0}%
		\expandafter\gdef\csname c@pgfprofile@numinvocations@#1\endcsname{0}%
		\expandafter\gdef\csname c@pgfprofile@subtractforself@#1\endcsname{0}%
		\expandafter\gdef\csname c@pgfprofile@semaphor@#1\endcsname{0}%
		\expandafter\gdef\csname c@pgfprofile@elapsed@at@start@#1\endcsname{0}%
		\pgfprofile@all@registered@list@add{#1}%
	}{%
		% it is already defined and registered. Shouldn't hurt, might
		% even be a good feature.
	}%
}%

\def\pgfprofile@TeX@DIALECT@toenvironment@begin#1{\csname #1\endcsname}%
\def\pgfprofile@TeX@DIALECT@toenvironment@end#1{\csname end#1\endcsname}%

\def\pgfprofile@@to@pgfretval#1{%
	\expandafter\let\expandafter\pgfretval#1%
}%

% Defines a new profiler entry for the environment `#1'.
%
% This calls \pgfprofilenew and handles the begin/end of the
% environment automatically.
%
% #1 the environment name (a string)
%
% Optionally in square brackets: the profiler entry name
% \pgfprofilenewforenvironment{<environment name>}
% \pgfprofilenewforenvironment[<profiler entry name>]{<environment name>}
\def\pgfprofilenewforenvironment{\pgfutil@ifnextchar[{\pgfprofilenewforenvironment@}{\pgfprofilenewforenvironment@[]}}%
\def\pgfprofilenewforenvironment@[#1]#2{%
	\expandafter\pgfprofile@@to@pgfretval\pgfprofile@TeX@DIALECT@toenvironment@begin{#2}%
	\ifx\pgfretval\relax
		\pgferror{\string\pgfprofilenewforenvironment{#2} doesn't work: the environment `#2' is (not yet?) known or not known in this context}{}%
	\else
		\expandafter\global\expandafter\let\csname pgfprofile@orig@begin@#2\endcsname=\pgfretval
		\expandafter\pgfprofile@@to@pgfretval\pgfprofile@TeX@DIALECT@toenvironment@end{#2}%
		\expandafter\global\expandafter\let\csname pgfprofile@orig@end@#2\endcsname=\pgfretval
		%
		\def\pgfprofile@temp{#1}%
		\ifx\pgfprofile@temp\pgfutil@empty
			\pgfprofilenewforenvironment@@{\pgfprofileenv #2}{#2}%
		\else
			\pgfprofilenewforenvironment@@{#1}{#2}%
		\fi
	\fi
}%
\def\pgfprofilenewforenvironment@@#1#2{%
	\pgfprofilenew{#1}%
	\expandafter\expandafter\expandafter\gdef\pgfprofile@TeX@DIALECT@toenvironment@begin{#2}{%
		\pgfprofilestart{#1}%
		\csname pgfprofile@orig@begin@#2\endcsname
	}%
	\expandafter\expandafter\expandafter\gdef\pgfprofile@TeX@DIALECT@toenvironment@end{#2}{%
		\csname pgfprofile@orig@end@#2\endcsname
		\pgfprofileend{#1}%
	}%
}


\def\pgfprofilecs{<CS>}%
\def\pgfprofileenv{<ENV>}%

% Defines a new profiler entry for the control sequence '#1'.
%
% This calls \pgfprofilenew and enhances the control sequence with
% support for timings.
% 
% #1: the control sequence (with backslash!)
% #2: the number of arguments (see below).
% 
% The following commands are supported:
% - commands which take one (optional) argument in square brackets,
% - commands which take one (optional) argument in square brackets
%   followed by one optional argument which has to be delimited with
%   curly braces (use an empty argument for '#2' in this case),
% - commands which take one (optional) argument in square brackets
%   and *exactly* #2 arguments afterwards.
\def\pgfprofilenewforcommand{\pgfutil@ifnextchar[{\pgfprofilenewforcommand@}{\pgfprofilenewforcommand@[]}}
\def\pgfprofilenewforcommand@[#1]#2#3{%
	\def\pgfprofile@temp{#3}%
	\ifx\pgfprofile@temp\pgfutil@empty
		\pgfprofilenewforcommandpattern[#1]{#2}{<autocheck>}{}%
	\else
		\ifcase#3\relax
			\pgfprofilenewforcommandpattern[#1]{#2}{}{}%
		\or
			\pgfprofilenewforcommandpattern[#1]{#2}{##1}{{##1}}%
		\or
			\pgfprofilenewforcommandpattern[#1]{#2}{##1##2}{{##1}{##2}}%
		\or
			\pgfprofilenewforcommandpattern[#1]{#2}{##1##2##3}{{##1}{##2}{##3}}%
		\or
			\pgfprofilenewforcommandpattern[#1]{#2}{##1##2##3##4}{{##1}{##2}{##3}{##4}}%
		\or
			\pgfprofilenewforcommandpattern[#1]{#2}{##1##2##3##4##5}{{##1}{##2}{##3}{##4}{##5}}%
		\or
			\pgfprofilenewforcommandpattern[#1]{#2}{##1##2##3##4##5##6}{{##1}{##2}{##3}{##4}{##5}{##6}}%
		\or
			\pgfprofilenewforcommandpattern[#1]{#2}{##1##2##3##4##5##6##7}{{##1}{##2}{##3}{##4}{##5}{##6}{##7}}%
		\else
			\pgferror{library 'profiler' can't replace control sequences with '#3' arguments automatically, sorry.}{}%
		\fi
	\fi
}%

% \pgfprofilenewforcommandpattern[<profile entry name>]{<\CS>}{<definition pattern>}{<invocation pattern>}
%
% example:
% \pgfprofilenewforcommandpattern{\pgfqkeys}{##1##2}{{##1}{##2}}
%
% \def\mymacro##1\to##2\in##3{ .... }
% \pgfprofilenewforcommandpattern{\mymacro}{##1\to##2\in##3}{{##1}\to{##2}\in{##3}}
\def\pgfprofilenewforcommandpattern{\pgfutil@ifnextchar[{\pgfprofilenewforcommandpattern@}{\pgfprofilenewforcommandpattern@[]}}
\def\pgfprofilenewforcommandpattern@[#1]#2#3#4{%
	\def\pgfprofile@known{1}%
	\ifx#2\undefined
		\def\pgfprofile@known{0}%
	\else
		\ifx#2\relax
			\def\pgfprofile@known{0}%
		\fi
	\fi
	\if\pgfprofile@known0%
		\pgferror{\string\pgfprofilenewforcommandpattern{\string#2} doesn't work: the command `\string#2' is (not yet?) known or not known in this context}%
	\else
	\begingroup
	\pgfprofile@cs@to@name{#2}%
	\let\pgfprofilenew@cmdname=\pgfretval
	%
	\def\pgfprofile@temp{#1}%
	\ifx\pgfprofile@temp\pgfutil@empty
		\edef\pgfprofilenew@profilerentryname{\pgfprofilecs\pgfprofilenew@cmdname}%
	\else
		\edef\pgfprofilenew@profilerentryname{#1}%
	\fi
	\expandafter\global\expandafter\let\csname pgfprofile@name@for@\pgfprofilenew@cmdname\endcsname=\pgfprofilenew@profilerentryname
	\pgfprofilenew{\pgfprofilenew@profilerentryname}%
	\expandafter\gdef\csname b@pgfprofile@show@\pgfprofilenew@profilerentryname\endcsname{0}%
	%
	\expandafter\global\expandafter\let\csname pgfprofile@orig@\pgfprofilenew@cmdname\endcsname=#2%
	\toks0={#3}%
	\edef\pgfprofile@temp{\the\toks0}%%
	\def\pgfprofile@tempb{<autocheck>}%
	\ifx\pgfprofile@temp\pgfprofile@tempb
		\expandafter\global\expandafter\let\csname pgfprofile@repl@\pgfprofilenew@cmdname\endcsname=\pgfprofileinvokecommand@uptoonearg
	\else
		\expandafter\gdef\csname pgfprofile@repl@\pgfprofilenew@cmdname\endcsname#3{%
			\pgfprofile@invokeorig{#4}%
		}%
	\fi
	\xdef#2{\noexpand\pgfprofileinvokecommand{\pgfprofilenew@cmdname}}%
	\endgroup
	\fi
}%

\def\pgfprofileshowinvocationsfor#1{%
	\pgfutil@ifundefined{b@pgfprofile@show@#1}{%
		\pgferror{\string\pgfprofileshowinvocationsfor{#1} doesn't work: the argument is no profiler entry}%
	}{%
		\expandafter\gdef\csname b@pgfprofile@show@#1\endcsname{1}%
		\expandafter\gdef\csname b@pgfprofile@show@edef@#1\endcsname{0}%
	}%
}%
\def\pgfprofileshowinvocationsexpandedfor#1{%
	\pgfutil@ifundefined{b@pgfprofile@show@#1}{%
		\pgferror{\string\pgfprofileshowinvocationsfor{#1} doesn't work: the argument is no profiler entry}%
	}{%
		\expandafter\gdef\csname b@pgfprofile@show@#1\endcsname{1}%
		\expandafter\gdef\csname b@pgfprofile@show@edef@#1\endcsname{1}%
	}%
}%

\def\pgfprofile@no@optional@arg@text{<noarg>}
\def\pgfprofileinvokecommand#1{%
	\pgfutil@ifnextchar[{\pgfprofileinvokecommand@{#1}}{\pgfprofileinvokecommand@{#1}[<noarg>]}%
}%
\def\pgfprofileinvokecommand@#1[#2]{%
	\def\pgfprofileinvokecommand@cs{#1}%
	\def\pgfprofileinvokecommand@optarg{#2}%
	\edef\pgfprofileinvokecommand@profilerentryname{\csname pgfprofile@name@for@#1\endcsname}%
	\csname pgfprofile@repl@#1\endcsname%
}%

% #1 contains ALL arguments, including any braces.
\def\pgfprofile@invokeorig#1{%
	% re-insert the control sequence name and the optional argument:
	% this wasn't possible directly.
	\begingroup
	\toks1=\expandafter{\pgfprofileinvokecommand@optarg}%
	\toks2={#1}%
	\toks3=\expandafter{\csname pgfprofile@orig@\pgfprofileinvokecommand@cs\endcsname}%
	%
	\ifx\pgfprofileinvokecommand@optarg\pgfprofile@no@optional@arg@text
		% no [] argument after original command:
		\xdef\pgfprofile@invokeorig@doitfinally{\the\toks3 \the\toks2 }%%
	\else
		\xdef\pgfprofile@invokeorig@doitfinally{\the\toks3[\the\toks1]\the\toks2 }%
	\fi
	\if1\csname b@pgfprofile@show@\pgfprofileinvokecommand@profilerentryname\endcsname
		\pgfprofile@orig@show
	\fi
	\endgroup
	\edef\pgfprofile@temp{{\pgfprofileinvokecommand@cs}{\pgfprofileinvokecommand@profilerentryname}}%
	\expandafter\pgfprofile@invokeorig@\pgfprofile@temp%
}%
\def\pgfprofile@orig@show{%
	\toks4=\expandafter{\csname\pgfprofileinvokecommand@cs\endcsname}%
	\ifx\pgfprofileinvokecommand@optarg\pgfprofile@no@optional@arg@text
		\def\pgfprofile@orig@show@args{\the\toks2 }%
	\else
		\def\pgfprofile@orig@show@args{[\the\toks1] \the\toks2 }%
	\fi
	\if1\csname b@pgfprofile@show@edef@\pgfprofileinvokecommand@profilerentryname\endcsname
		\edef\pgfprofile@orig@show@args{\pgfprofile@orig@show@args}%
		\edef\pgfprofile@orig@show@args{\pgfprofile@orig@show@args}%
	\fi
	\immediate\write16{pgflibraryprofiler: calling 
		\#\csname c@pgfprofile@numinvocations@\pgfprofileinvokecommand@profilerentryname\endcsname\space
		(\the\toks4 \pgfprofile@orig@show@args)}%
}%

% #1: control sequence name (without backslash)
% #2: profiler entry name
\def\pgfprofile@invokeorig@#1#2{%
	% this check should avoid save stack impact
	\pgfprofileifisrunning{#2}{%
		\pgfprofile@invokeorig@doitfinally%
	}{%
		\pgfprofilestart{#2}%
		\pgfprofile@invokeorig@doitfinally%
		\pgfprofileend{#2}%
	}%
}%


\def\pgfprofileinvokecommand@uptoonearg{%
	\pgfutil@ifnextchar\bgroup{\pgfprofileinvokecommand@onearg}{\pgfprofileinvokecommand@noarg}%
}%
\def\pgfprofileinvokecommand@onearg#1{%
	\pgfprofile@invokeorig{{#1}}%
}%
\def\pgfprofileinvokecommand@noarg{%
	\pgfprofile@invokeorig{}%
}%



% Starts / Resumes timing of the profiler entry named `#1'.
%
% The timing will continue until \pgfprofileend{#1} is called.
%
% Nested calls of \pgfprofilestart{#1} (with the same argument) will
% result in the same result as if just one \pgfprofilestart command
% has been issued.
\def\pgfprofilestart#1{%
	\pgfprofileifisrunning{#1}{%
		\relax
	}{%
		\expandafter\xdef\csname c@pgfprofile@elapsed@at@start@#1\endcsname{\the\pgfutil@pdfelapsedtime}%
		\expandafter\gdef\csname c@pgfprofile@subtractforself@#1\endcsname{0}%
		\pgfprofile@advance{c@pgfprofile@numinvocations@#1}{1}%
		\pgfprofilestackpush{#1}%
	}%
	\pgfprofile@advance{c@pgfprofile@semaphor@#1}{1}%
}%

% Stops / Interrupts timing of the profiler entry named `#1'.
\def\pgfprofileend#1{%
	\pgfprofile@advance{c@pgfprofile@semaphor@#1}{-1}%
	\pgfprofileifisrunning{#1}{%
		\relax
	}{%
		\begingroup
			\c@pgf@countb=\pgfutil@pdfelapsedtime\relax
			\advance\c@pgf@countb by-\csname c@pgfprofile@elapsed@at@start@#1\endcsname\relax
			%
			\pgfprofilestackpop\pgfretval
			\edef\pgfprofile@temp{#1}%
			\ifx\pgfprofile@temp\pgfretval
			\else
				\immediate\write16{pgflibraryprofiler WARNING: possible error in self time computation...}%
			\fi
			\pgfprofilestackifempty{%
				\relax
			}{%
				\pgfprofilestacktop\pgfretval
				\pgfprofile@advance{c@pgfprofile@subtractforself@\pgfretval}{\c@pgf@countb}%
			}%
			%
			\pgfprofile@advance{c@pgfprofile@elapsedtotal@#1}{\c@pgf@countb}%
			\advance\c@pgf@countb by-\csname c@pgfprofile@subtractforself@#1\endcsname\relax
			\pgfprofile@advance{c@pgfprofile@elapsedself@#1}{\c@pgf@countb}%
		\endgroup
	}%
}%

% invokes '#2' if '#1' is currently running and '#3' if not.
\def\pgfprofileifisrunning#1#2#3{%
	\ifnum\csname c@pgfprofile@semaphor@#1\endcsname=0 \def\pgfprofileifisrunning@next{#3}\else \def\pgfprofileifisrunning@next{#2}\fi
	\pgfprofileifisrunning@next
}%

% Sets the profiler entry whose total time is used to compute all
% other relative times.
\def\pgfprofilesetrel#1{\edef\pgfprofile@rel{#1}}%

% Stops all running timings and postprocesses them.
\def\pgfprofilepostprocess{%
	\begingroup
	%
	% prepare files.
	\c@pgf@countb=\time
	\divide\c@pgf@countb by60
	\c@pgf@countd=\c@pgf@countb
	\multiply\c@pgf@countd by60
	\c@pgf@countc=\time
	\advance\c@pgf@countc by-\c@pgf@countd
	\immediate\openout\w@pgf@writea=\jobname.profiler.\the\year-\pgfprofiletotwodigitstr\month-\pgfprofiletotwodigitstr\day_\pgfprofiletotwodigitstr\c@pgf@countb h_\pgfprofiletotwodigitstr\c@pgf@countc m.dat
	\immediate\write\w@pgf@writea{%
		\pgfprofile@percent relative values are measured against the totaltime of `\pgfprofile@rel'.%
	}%
	\immediate\write16{pgflibraryprofiler: relative values are measured against the totaltime of `\pgfprofile@rel'.}%
	\immediate\write\w@pgf@writea{%
		profilerentry\pgfprofile@TAB 
		totaltime[s]\pgfprofile@TAB 
		totaltime[percent]\pgfprofile@TAB
		selftime[s]\pgfprofile@TAB
		selftime[percent]\pgfprofile@TAB
		numinvocations\pgfprofile@TAB}%
	%
	%
	% compute main time and prepare computation of relative times:
	\pgfprofileifisrunning{\pgfprofile@rel}{%
		\pgfprofileend{\pgfprofile@rel}%
	}{}%
	\pgf@xa=\csname c@pgfprofile@elapsedtotal@\pgfprofile@rel\endcsname sp
	\edef\pgfprofiletotaltime{\pgf@sys@tonumber\pgf@xa}%
	\pgfmathreciprocal@{\pgfprofiletotaltime}%
	\let\pgfprofiletotaltime@inv=\pgfmathresult
	%
	% postprocess each of them:
	\pgfprofile@all@registered@list@foreach{%
		\pgfprofileifisrunning{##1}{%
			\pgfprofileend{##1}%
		}{}%
		\pgfprofilepostprocess@single{##1}%
	}%
	\immediate\write\w@pgf@writea{%
		\pgfprofile@percent\space vim: ts=40 nowrap nostartofline
	}%
	\immediate\closeout\w@pgf@writea
	\endgroup
}%

{%
\catcode`\[=1 %
\catcode`\]=2 %
\catcode`\{=12 %
\catcode`\}=12 %
\catcode`\^^I=12
\gdef\pgfprofile@lbrace[{]%
\gdef\pgfprofile@rbrace[}]%
\gdef\pgfprofile@TAB[^^I]%
]
{
\catcode`\%=12 \gdef\pgfprofile@percent{%}}

\def\pgfprofilepostprocess@single#1{%
	\begingroup
	\pgf@xa=\csname c@pgfprofile@elapsedtotal@#1\endcsname sp
	\pgf@xb=\csname c@pgfprofile@elapsedself@#1\endcsname sp
	\pgf@ya=\pgfprofiletotaltime@inv\pgf@xa
	\pgf@yb=\pgfprofiletotaltime@inv\pgf@xb
	\multiply\pgf@ya by100
	\multiply\pgf@yb by100
	\edef\pgfprofilecur@total{\pgf@sys@tonumber\pgf@xa}%
	\edef\pgfprofilecur@self{\pgf@sys@tonumber\pgf@xb}%
	\edef\pgfprofilecur@total@rel{\pgf@sys@tonumber\pgf@ya}%
	\edef\pgfprofilecur@self@rel{\pgf@sys@tonumber\pgf@yb}%
	\immediate\write16{
		pgflibraryprofiler(#1) 
		\pgfprofile@lbrace 
			total time=\pgfprofilecur@total sec; (\pgfprofilecur@total@rel\pgfprofile@percent)
			self time=\pgfprofilecur@self sec; (\pgfprofilecur@self@rel\pgfprofile@percent)
			invocations=\csname c@pgfprofile@numinvocations@#1\endcsname;
		\pgfprofile@rbrace
	}%
	\immediate\write\w@pgf@writea{%
		#1\pgfprofile@TAB 
		\pgfprofilecur@total\pgfprofile@TAB 
		\pgfprofilecur@total@rel\pgfprofile@TAB
		\pgfprofilecur@self\pgfprofile@TAB
		\pgfprofilecur@self@rel\pgfprofile@TAB
		\csname c@pgfprofile@numinvocations@#1\endcsname\pgfprofile@TAB
	}%
	\endgroup
}%
% Invokes '#2' for each element of the command separated list '#1'.
% the current list element is available as '#1' inside of '#2'.
\long\def\pgfprofileforeachentryinCSV#1#2{%
	\long\def\pgfprofileinvokeforeach@@##1{#2}%
	\pgfprofileforeachentryinCSVisterminated@loop#1,\pgfeov
}%
\long\def\pgfprofileforeachentryinCSVisterminated@loop{%
	\pgfutil@ifnextchar\pgfeov{\pgfutil@gobble}{\pgfprofileforeachentryinCSV@next}%
}%
\long\def\pgfprofileforeachentryinCSV@next#1,{%
	\pgfprofileinvokeforeach@@{#1}%
	\pgfprofileforeachentryinCSVisterminated@loop%
}%

\xdef\pgfprofile@all@registered@list{}
\xdef\pgfprofile@currently@running@list{}

\def\pgfprofile@all@registered@list@add#1{%
	\ifx\pgfprofile@all@registered@list\pgfutil@empty
		\xdef\pgfprofile@all@registered@list{#1}%
	\else
		\xdef\pgfprofile@all@registered@list{\pgfprofile@all@registered@list,#1}%
	\fi
}%

\def\pgfprofile@all@registered@list@foreach#1{%
	\expandafter\pgfprofileforeachentryinCSV\expandafter{\pgfprofile@all@registered@list}{#1}%
}%

\def\pgfprofile@advance#1#2{%
	\begingroup
		\c@pgf@counta=\csname #1\endcsname\relax
		\advance\c@pgf@counta by#2\relax
		\expandafter\xdef\csname #1\endcsname{\the\c@pgf@counta}%
	\endgroup
}%

\def\pgfprofile@cs@to@name@#1#2\relax{\def\pgfretval{#2}}

% defines '\pgfretval' to be the control sequences name of '#1' *without* the backslash.
\def\pgfprofile@cs@to@name#1{%
	\expandafter\pgfprofile@cs@to@name@\string#1\relax
}%

\newcount\c@pgfprofile@stacktop

\c@pgfprofile@stacktop=-1
\def\pgfprofilestackpush#1{%
	\global\advance\c@pgfprofile@stacktop by1
	\expandafter\xdef\csname pgfprofile@stack@\the\c@pgfprofile@stacktop\endcsname{#1}%
}%
% pops the current stack top to macro #1
\def\pgfprofilestackpop#1{%
	\pgfprofilestacktop#1%
	\global\advance\c@pgfprofile@stacktop by-1
}%
% returns the stack's top to macro #1
\def\pgfprofilestacktop#1{%
	\expandafter\let\expandafter#1\csname pgfprofile@stack@\the\c@pgfprofile@stacktop\endcsname
}%
\def\pgfprofilestackifempty#1#2{%
	\ifnum\c@pgfprofile@stacktop<0 #1\else #2\fi
}%


\def\pgfprofiletotwodigitstr#1{\ifnum#1<10 0\the#1\else\the#1\fi}

\pgfprofilenew{main job}
\pgfprofilestart{main job}
\expandafter\xdef\csname c@pgfprofile@elapsed@at@start@main job\endcsname{0}%
\pgfprofilesetrel{main job}

\pgfutil@ifundefined{AtEndDocument}{%
	% no latex. ok.
}{%
	% do latex specific stuff:
	\pgfprofilenew{preamble}
	\pgfprofilestart{preamble}
	\expandafter\xdef\csname c@pgfprofile@elapsed@at@start@preamble\endcsname{0}%
	\AtBeginDocument{\pgfprofileend{preamble}}%
	%
	\AtEndDocument{\pgfprofilepostprocess}%
}%
\endinput

pgflibraryshadings.code.tex
% Copyright 2008 by Till Tantau and others
%
% 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/pgflibraryshadings.code.tex,v 1.2 2008/10/29 23:06:34 tantau Exp $


%
% An hsv color wheel. Initial code graciously donated by Ken Starks.
%

\pgfdeclarefunctionalshading{color wheel white center}
{\pgfpoint{-50bp}{-50bp}}
{\pgfpoint{50bp}{50bp}}
{}
{ % x y
  2 copy % ... x y x y
  2 copy abs exch abs add 0.0001 ge 
  {atan 360.0 div} % ... x y heading;  heading being in
                   %the interval [0, 1.0]
  { pop } % silently deal with error: return
                  % arbitrary heading of zero for origin
  ifelse  % because we will use it for 'Hue'
  3 1 roll % ... heading x y
  dup mul % ... heading x y*y
  exch dup mul % ... heading y*y x*x
  add sqrt % ... heading ra_pt (distance from origin in points)
  25.0 div % scale it means a ra of 25bp
  dup 1.0 ge % BOOLEAN. ready to clamp to interval [0, 1.0]
  { pop 1.0 }{} ifelse % We shall use the scaled ra as 'Saturation'
  %2.5 mul 0.25 sub % now, Ra in [0.1, 0.5] --> Saturation
                   % in [0.0, 1.0]. Saturation varies between the two radii
  1.0 % ... H S V ( with 'Value' set to literal constant of 1.0 )
  % C version to use as model:
  % H' = H * 6
  % i = floor(H')
  % f = H' - i
  % P = V * (1.0 - S)
  % Q = V * (1.0 - (S*f))
  % T = V * (1.0 - (S * (1.0 - f)))
  3 2 roll 6.0 mul dup 4 1 roll % H' S V H'
  floor cvr  % H' S V i
  dup 5 1 roll % i H' S V i
  3 index sub neg % i H' S V f
  1.0 3 index sub % i H' S V f (1.0 - S )
  2 index mul % i H' S V f P
  6 1 roll % P i H' S V f
  dup 3 index mul neg 1.0 add % P i H' S V f ( 1.0 - (f*S))
  2 index mul % P i H' S V f Q
  7 1 roll % Q P i H' S V f
  neg 1.0 add % Q P i H' S V (1.0 - f)
  2 index mul neg 1.0  add % Q P i H' S V (1.0 - S * (1.0 - f))
  1 index mul % Q P i H' S V T
  7 2 roll % V T Q P i H' S
  pop pop % V T Q P i
  %%% 
  % end of BLOCK B. The rest is just stack manipulation
  dup 0.5 le % TEST II [ i == 0 ]
  { % BLOCK C [ take stack to V T P ]
    pop exch pop
  }
  { dup 1.5 le % TEST III [ i == 1 ]
    { % BLOCK D [ take stack to Q V P ]
      pop exch 4 1 roll exch pop
    }
    { dup 2.5 le % TEST IV [ i == 2 ]
      { % BLOCK E [ take stack to P V T ]
        pop 4 1 roll pop
      }
      { dup 3.5 le % TEST V [ i == 3 ]
        { % BLOCK F [ take stack to P Q V ]
          pop exch 4 2 roll pop
        }
        { dup 4.5 le % TEST VI [ i == 4 ]
          { % BLOCK G [ take stack to T P V ]
            pop exch pop 3 -1 roll
          }
          { % BLOCK H [ take stack to V P Q ]
            pop 3 1 roll exch pop
          }
          ifelse
        }
        ifelse % for V
      }
      ifelse % for IV
    }
    ifelse % for III
  }
  ifelse % for II
}

\pgfdeclarefunctionalshading{color wheel black center}
{\pgfpoint{-50bp}{-50bp}}
{\pgfpoint{50bp}{50bp}}
{}
{ % x y
  2 copy % ... x y x y
  2 copy abs exch abs add 0.0001 ge 
  {atan 360.0 div} % ... x y heading;  heading being in
                   %the interval [0, 1.0]
  { pop } % silently deal with error: return
                  % arbitrary heading of zero for origin
  ifelse  % because we will use it for 'Hue'
  3 1 roll % ... heading x y
  dup mul % ... heading x y*y
  exch dup mul % ... heading y*y x*x
  add sqrt % ... heading ra_pt (distance from origin in points)
  25.0 div % scale it means a ra of 25bp
  dup 1.0 ge % BOOLEAN. ready to clamp to interval [0, 1.0]
  { pop 1.0 }{} ifelse % We shall use the scaled ra as 'Saturation'
  %2.5 mul 0.25 sub % now, Ra in [0.1, 0.5] --> Saturation
                   % in [0.0, 1.0]. Saturation varies between the two radii
  1.0 exch % ... H S V ( with 'Value' set to literal constant of 1.0 )
  % C version to use as model:
  % H' = H * 6
  % i = floor(H')
  % f = H' - i
  % P = V * (1.0 - S)
  % Q = V * (1.0 - (S*f))
  % T = V * (1.0 - (S * (1.0 - f)))
  3 2 roll 6.0 mul dup 4 1 roll % H' S V H'
  floor cvr  % H' S V i
  dup 5 1 roll % i H' S V i
  3 index sub neg % i H' S V f
  1.0 3 index sub % i H' S V f (1.0 - S )
  2 index mul % i H' S V f P
  6 1 roll % P i H' S V f
  dup 3 index mul neg 1.0 add % P i H' S V f ( 1.0 - (f*S))
  2 index mul % P i H' S V f Q
  7 1 roll % Q P i H' S V f
  neg 1.0 add % Q P i H' S V (1.0 - f)
  2 index mul neg 1.0  add % Q P i H' S V (1.0 - S * (1.0 - f))
  1 index mul % Q P i H' S V T
  7 2 roll % V T Q P i H' S
  pop pop % V T Q P i
  %%% 
  % end of BLOCK B. The rest is just stack manipulation
  dup 0.5 le % TEST II [ i == 0 ]
  { % BLOCK C [ take stack to V T P ]
    pop exch pop
  }
  { dup 1.5 le % TEST III [ i == 1 ]
    { % BLOCK D [ take stack to Q V P ]
      pop exch 4 1 roll exch pop
    }
    { dup 2.5 le % TEST IV [ i == 2 ]
      { % BLOCK E [ take stack to P V T ]
        pop 4 1 roll pop
      }
      { dup 3.5 le % TEST V [ i == 3 ]
        { % BLOCK F [ take stack to P Q V ]
          pop exch 4 2 roll pop
        }
        { dup 4.5 le % TEST VI [ i == 4 ]
          { % BLOCK G [ take stack to T P V ]
            pop exch pop 3 -1 roll
          }
          { % BLOCK H [ take stack to V P Q ]
            pop 3 1 roll exch pop
          }
          ifelse
        }
        ifelse % for V
      }
      ifelse % for IV
    }
    ifelse % for III
  }
  ifelse % for II
}

\pgfdeclarefunctionalshading{color wheel}
{\pgfpoint{-50bp}{-50bp}}
{\pgfpoint{50bp}{50bp}}
{}
{ % x y
  2 copy abs exch abs add 0.0001 ge 
  {atan 360.0 div} % ... x y heading;  heading being in
                   %the interval [0, 1.0]
  { pop } % silently deal with error: return
                  % arbitrary heading of zero for origin
  ifelse  % because we will use it for 'Hue'
  1.0 1.0 % ... H S V 
  % C version to use as model:
  % H' = H * 6
  % i = floor(H')
  % f = H' - i
  % P = V * (1.0 - S)
  % Q = V * (1.0 - (S*f))
  % T = V * (1.0 - (S * (1.0 - f)))
  3 2 roll 6.0 mul dup 4 1 roll % H' S V H'
  floor cvr  % H' S V i
  dup 5 1 roll % i H' S V i
  3 index sub neg % i H' S V f
  1.0 3 index sub % i H' S V f (1.0 - S )
  2 index mul % i H' S V f P
  6 1 roll % P i H' S V f
  dup 3 index mul neg 1.0 add % P i H' S V f ( 1.0 - (f*S))
  2 index mul % P i H' S V f Q
  7 1 roll % Q P i H' S V f
  neg 1.0 add % Q P i H' S V (1.0 - f)
  2 index mul neg 1.0  add % Q P i H' S V (1.0 - S * (1.0 - f))
  1 index mul % Q P i H' S V T
  7 2 roll % V T Q P i H' S
  pop pop % V T Q P i
  %%% 
  % end of BLOCK B. The rest is just stack manipulation
  dup 0.5 le % TEST II [ i == 0 ]
  { % BLOCK C [ take stack to V T P ]
    pop exch pop
  }
  { dup 1.5 le % TEST III [ i == 1 ]
    { % BLOCK D [ take stack to Q V P ]
      pop exch 4 1 roll exch pop
    }
    { dup 2.5 le % TEST IV [ i == 2 ]
      { % BLOCK E [ take stack to P V T ]
        pop 4 1 roll pop
      }
      { dup 3.5 le % TEST V [ i == 3 ]
        { % BLOCK F [ take stack to P Q V ]
          pop exch 4 2 roll pop
        }
        { dup 4.5 le % TEST VI [ i == 4 ]
          { % BLOCK G [ take stack to T P V ]
            pop exch pop 3 -1 roll
          }
          { % BLOCK H [ take stack to V P Q ]
            pop 3 1 roll exch pop
          }
          ifelse
        }
        ifelse % for V
      }
      ifelse % for IV
    }
    ifelse % for III
  }
  ifelse % for II
}


%
% A bilinear interpolation.
%

\colorlet{lower left}{white}
\colorlet{lower right}{white}
\colorlet{upper left}{white}
\colorlet{upper right}{white}

\pgfdeclarefunctionalshading[lower left,lower right,upper left,upper right]{bilinear interpolation}
{\pgfpointorigin}
{\pgfpoint{100bp}{100bp}}
{
  \pgfshadecolortorgb{lower left}{\pgf@lib@shadings@ll}\pgfshadecolortorgb{lower right}{\pgf@lib@shadings@lr}
  \pgfshadecolortorgb{upper right}{\pgf@lib@shadings@ur}\pgfshadecolortorgb{upper left}{\pgf@lib@shadings@ul}
}{
  25 sub 50 div exch 25 sub 50 div 2 copy                   % Calculate y/100 x/100.
%  100 div exch 100 div 2 copy                   % Calculate y/100 x/100.
  neg 1 add exch neg 1 add                      % Calculate 1-y/100 1-x/100.
  3 1 roll 2 copy exch 5 2 roll 6 copy 6 copy   % Set up stack.  
  \pgf@lib@shadings@llred mul exch \pgf@lib@shadings@lrred mul add mul     % Process red component.
  4 1 roll
  \pgf@lib@shadings@urred mul exch \pgf@lib@shadings@ulred mul add mul
  add
  13 1 roll
  \pgf@lib@shadings@llgreen mul exch \pgf@lib@shadings@lrgreen mul add mul % Process green component.  
  4 1 roll
  \pgf@lib@shadings@urgreen mul exch \pgf@lib@shadings@ulgreen mul add mul
  add
  7 1 roll
  \pgf@lib@shadings@llblue mul exch \pgf@lib@shadings@lrblue mul add mul   % Process blue component.
  4 1 roll
  \pgf@lib@shadings@urblue mul exch \pgf@lib@shadings@ulblue mul add mul
  add
}


%
% A Mandelbrot set shading. Just for fun...
%

\pgfdeclarefunctionalshading{Mandelbrot set}
{\pgfpoint{-50bp}{-50bp}}
{\pgfpoint{50bp}{50bp}}{}
{
  12.5 div exch 12.5 div exch
  1 index 1 index
  % Stack: c_r c_i z_r z_i
  % Formula: z' = z^2 + c = (z_r + i z_i)^2 + c_r + i c_i 
  %             = (z_r^2 - z_i^2 + c_r) + i (2 z_r z_i + c_i)
  %
  % First iteration
  % 1. Compute z_r^2 -z_i^2 + c_r
  1 index dup mul % z_r^2
  1 index dup mul % z_i^2
  sub             % z_r^2 - z_i^2
  4 index add     % z_r^2 -z_i^2 + c_r
  % 2. Compute 2 z_r z_i + c_i
  3 1 roll
  mul 2 mul       % 2 z_r z_i
  2 index add     % 2 z_r z_i + c_i
  % Second iteration
  % 1. Compute z_r^2 -z_i^2 + c_r
  1 index dup mul % z_r^2
  1 index dup mul % z_i^2
  sub             % z_r^2 - z_i^2
  4 index add     % z_r^2 -z_i^2 + c_r
  % 2. Compute 2 z_r z_i + c_i
  3 1 roll
  mul 2 mul       % 2 z_r z_i
  2 index add     % 2 z_r z_i + c_i
  % Third iteration
  % 1. Compute z_r^2 -z_i^2 + c_r
  1 index dup mul % z_r^2
  1 index dup mul % z_i^2
  sub             % z_r^2 - z_i^2
  4 index add     % z_r^2 -z_i^2 + c_r
  % 2. Compute 2 z_r z_i + c_i
  3 1 roll
  mul 2 mul       % 2 z_r z_i
  2 index add     % 2 z_r z_i + c_i
  % Fourth iteration
  % 1. Compute z_r^2 -z_i^2 + c_r
  1 index dup mul % z_r^2
  1 index dup mul % z_i^2
  sub             % z_r^2 - z_i^2
  4 index add     % z_r^2 -z_i^2 + c_r
  % 2. Compute 2 z_r z_i + c_i
  3 1 roll
  mul 2 mul       % 2 z_r z_i
  2 index add     % 2 z_r z_i + c_i
  % Check for break (to avoid too large numbers)
  1 index dup mul 1 index dup mul add
  4 lt {
  % Fifth iteration
  % 1. Compute z_r^2 -z_i^2 + c_r
  1 index dup mul % z_r^2
  1 index dup mul % z_i^2
  sub             % z_r^2 - z_i^2
  4 index add     % z_r^2 -z_i^2 + c_r
  % 2. Compute 2 z_r z_i + c_i
  3 1 roll
  mul 2 mul       % 2 z_r z_i
  2 index add     % 2 z_r z_i + c_i
  % Sixth iteration
  % 1. Compute z_r^2 -z_i^2 + c_r
  1 index dup mul % z_r^2
  1 index dup mul % z_i^2
  sub             % z_r^2 - z_i^2
  4 index add     % z_r^2 -z_i^2 + c_r
  % 2. Compute 2 z_r z_i + c_i
  3 1 roll
  mul 2 mul       % 2 z_r z_i
  2 index add     % 2 z_r z_i + c_i
  % Seventh iteration
  % 1. Compute z_r^2 -z_i^2 + c_r
  1 index dup mul % z_r^2
  1 index dup mul % z_i^2
  sub             % z_r^2 - z_i^2
  4 index add     % z_r^2 -z_i^2 + c_r
  % 2. Compute 2 z_r z_i + c_i
  3 1 roll
  mul 2 mul       % 2 z_r z_i
  2 index add     % 2 z_r z_i + c_i
  % Eighth iteration
  % 1. Compute z_r^2 -z_i^2 + c_r
  1 index dup mul % z_r^2
  1 index dup mul % z_i^2
  sub             % z_r^2 - z_i^2
  4 index add     % z_r^2 -z_i^2 + c_r
  % 2. Compute 2 z_r z_i + c_i
  3 1 roll
  mul 2 mul       % 2 z_r z_i
  2 index add     % 2 z_r z_i + c_i
  % Ninth iteration
  % 1. Compute z_r^2 -z_i^2 + c_r
  1 index dup mul % z_r^2
  1 index dup mul % z_i^2
  sub             % z_r^2 - z_i^2
  4 index add     % z_r^2 -z_i^2 + c_r
  % 2. Compute 2 z_r z_i + c_i
  3 1 roll
  mul 2 mul       % 2 z_r z_i
  2 index add     % 2 z_r z_i + c_i
  % Tenth iteration
  % 1. Compute z_r^2 -z_i^2 + c_r
  1 index dup mul % z_r^2
  1 index dup mul % z_i^2
  sub             % z_r^2 - z_i^2
  4 index add     % z_r^2 -z_i^2 + c_r
  % 2. Compute 2 z_r z_i + c_i
  3 1 roll
  mul 2 mul       % 2 z_r z_i
  2 index add     % 2 z_r z_i + c_i
  } { pop pop 1000.0 1000.0 } ifelse
  % Compute distance
  dup mul exch
  dup mul 
  add sqrt
  dup 4 1 roll
  2 gt { pop pop 2.0 exch div 1.0 exch sub dup dup} {pop pop 0.0 0.0 0.0} ifelse
}

pgflibraryshapes.arrows.code.tex
% Copyright 2007 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.

\ProvidesFileRCS[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/libraries/shapes/pgflibraryshapes.arrows.code.tex,v 1.1 2008/06/26 16:55:55 tantau Exp $


% keys for shape single arrow
%
% /pgf/single arrow tip angle
% /pgf/single arrow head extend
% /pgf/single arrow head indent

\pgfkeys{/pgf/.cd,
	single arrow tip angle/.initial=90, 
	single arrow head extend/.initial=.25cm,
	single arrow head indent/.initial=0cm}

% Shape single arrow
%
%
\pgfdeclareshape{single arrow}{%
	\savedmacro\getsinglearrowpoints{%
		%
		% Get the outer sep.
		% 
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
		\edef\xoutersep{\the\pgf@x}%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/outer ysep}}%
		\edef\youtersep{\the\pgf@y}%
		%
		% Get the node dimensions.
		%
		\pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/inner xsep}}%
		\advance\pgf@xa.5\wd\pgfnodeparttextbox%
		\advance\pgf@xa.5\pgflinewidth%
		\pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/inner ysep}}%
		\advance\pgf@ya.5\ht\pgfnodeparttextbox%
		\advance\pgf@ya.5\dp\pgfnodeparttextbox%
		\advance\pgf@ya.5\pgflinewidth%
		\ifpgfshapeborderusesincircle%
			\ifdim\pgf@xa<\pgf@ya%
				\pgf@xa\pgf@ya%
			\fi%			
			\pgf@xa1.41421\pgf@xa%
			\pgf@ya\pgf@xa%
			\pgfmathsetmacro\rotate{\pgfkeysvalueof{/pgf/shape border rotate}}%
			\ifdim\xoutersep>\youtersep\relax%
				\let\youtersep\xoutersep%
			\else%
				\let\xoutersep\youtersep%
			\fi%
		\else%
			%
			% Round the rotation.
			%
			\pgfmathsetmacro\rotate{\pgfkeysvalueof{/pgf/shape border rotate}}%
			\pgfmathmod@{\rotate}{360}%
			\afterassignment\pgfmath@gobbletilpgfmath@%
			\expandafter\c@pgf@counta\pgfmathresult\relax\pgfmath@%
			\advance\c@pgf@counta45\relax%
			\divide\c@pgf@counta90\relax%
			\multiply\c@pgf@counta90\relax%
			\ifnum\c@pgf@counta<0\relax%
				\advance\c@pgf@counta360\relax%
			\fi%
			\edef\rotate{\the\c@pgf@counta}%
			%
			% Calculate the width and height of the node
			% contents, according to any border rotation.
			%
			\ifnum\c@pgf@counta=90\relax%
				\pgf@x\pgf@xa%
				\pgf@xa\pgf@ya%
				\pgf@ya\pgf@x%
				\let\pgfmathresult\xoutersep%
				\let\xoutersep\youtersep%
				\let\youtersep\pgfmathresult%
			\else%
				\ifnum\c@pgf@counta=270\relax%
					\pgf@x\pgf@xa%
					\pgf@xa\pgf@ya%
					\pgf@ya\pgf@x%
					\let\pgfmathresult\xoutersep%
					\let\xoutersep\youtersep%
					\let\youtersep\pgfmathresult%
				\fi%
			\fi%
		\fi%
		\addtosavedmacro\rotate%
		%
		% Get some useful trig stuff.
		%
		\pgfmathdivide{\pgfkeysvalueof{/pgf/single arrow tip angle}}{2}%
		\let\halftipangle\pgfmathresult%
		\pgfmathcosec@{\halftipangle}%
		\let\cosechalftipangle\pgfmathresult%
		\pgfmathcos@{\halftipangle}%
		\pgfutil@tempdima\pgfmathresult pt\relax%
		\pgfutil@tempdima\cosechalftipangle\pgfutil@tempdima%
		\edef\cothalftipangle{\pgfmath@tonumber{\pgfutil@tempdima}}%
		\pgfmathreciprocal@{\pgfmathresult}%
		\let\sechalftipangle\pgfmathresult%
		\pgfmathsin@{\halftipangle}%
		\pgfutil@tempdima\pgfmathresult pt\relax%
		\pgfutil@tempdima\sechalftipangle\pgfutil@tempdima%
		\edef\tanhalftipangle{\pgfmath@tonumber{\pgfutil@tempdima}}%
		%
		% Get the single arrow head extend, and adjust for minimum width.
		%
		\pgf@xb\pgf@ya%
		\pgf@xb\cothalftipangle\pgf@xb%
		\pgfmathsetlength\pgf@xc{\pgfkeysvalueof{/pgf/single arrow head extend}}%
		\pgf@yc\pgf@xc%
		\advance\pgf@xc\pgf@ya%
		\pgfmathsetlength\pgfutil@tempdimb{\pgfkeysvalueof{/pgf/minimum width}}%
		\ifdim\pgf@xc<.5\pgfutil@tempdimb%
			\pgfutil@tempdimb.5\pgfutil@tempdimb%
			\pgfmathdivide@{\pgfmath@tonumber{\pgfutil@tempdimb}}{\pgfmath@tonumber{\pgf@xc}}%
			\pgf@ya\pgfmathresult\pgf@ya%
			\pgf@xc\pgfmathresult\pgf@xc%
			\pgf@yc\pgfmathresult\pgf@yc%
			\pgf@xb\pgfmathresult\pgf@xb%
		\fi%
		%
		% Now calculate the height of the arrow and adjust for minimum height.
		%
		\advance\pgf@xc-\pgf@ya%
		\pgf@xc\cothalftipangle\pgf@xc%
		\pgf@xa2.0\pgf@xa%
		\advance\pgf@xa\pgf@xb%
		\pgfmathsetlength\pgfutil@tempdimb{\pgfkeysvalueof{/pgf/minimum height}}%
		\ifdim\pgf@xa<\pgfutil@tempdimb%
			\pgf@xa\pgfutil@tempdimb%
		\fi%
		\advance\pgf@xa-\pgf@xb%
		\pgf@xa.5\pgf@xa%		
		\pgfmathsetlength\pgfutil@tempdima{\pgfkeysvalueof{/pgf/single arrow head indent}}%
		%
		% Now:
		%
		% xa - .5 * width of the node minus xb.
		% ya - .5 * height of the node contents.
		% xb - distance from the end of the node contents to the arrow tip.
		% xc - distance from the end of the node contents to the back end of the arrow head.
		% yc - distance from the top of the node contents to the top end of the arrow head.
		%
		\pgfsavepgf@process\centerpoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgf@y.5\ht\pgfnodeparttextbox%
			\advance\pgf@y-.5\dp\pgfnodeparttextbox%
		}%
		\pgfsavepgf@process\basepoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgf@y0pt%
		}%
		\pgfsavepgf@process\midpoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgfmathsetlength\pgf@y{+.5ex}%
		}%
		%
		% As the arrow is symmetrical it can be described by only four points:
		%
		\pgfsavepgf@process\arrowtip{%
			\pgf@x\pgf@xa%
			\advance\pgf@x\pgf@xb%
			\pgf@y0pt\relax%
		}%
		\pgfsavepgf@process\beforearrowtip{%
			\pgf@x\pgf@xa%
			\advance\pgf@x-\pgf@xc%
			\pgf@y\pgf@ya%
			\advance\pgf@y\pgf@yc%
		}%
		\pgfsavepgf@process\beforearrowhead{%
			\pgf@x\pgf@xa%
			\advance\pgf@x-\pgf@xc%
			\advance\pgf@x\pgfutil@tempdima%
			\pgf@y\pgf@ya%
		}%
		\pgfsavepgf@process\afterarrowtail{%
			\pgf@x-\pgf@xa%
			\pgf@y\pgf@ya%
		}%
		%
		% Calculate the anchor point at the arrow tip...
		%
		\pgfsavepgf@process\arrowtipanchor{%
			\pgfpointadd{\centerpoint}{\arrowtip}%
			\pgf@xa\xoutersep\relax%
			\advance\pgf@x\cosechalftipangle\pgf@xa%
		}%
		\advance\pgf@x.5\wd\pgfnodeparttextbox%
		\edef\externalradius{\the\pgf@x}%
		\addtosavedmacro\externalradius%
		%
		% ...and the rest of the points.
		%
		\pgfmathanglebetweenlines{\beforearrowtip}{\beforearrowhead}{\beforearrowtip}{\arrowtip}%
		\pgf@xa\xoutersep\relax%
		\pgfutil@tempdima\pgfmathresult pt\relax%
		\pgfutil@tempdima.5\pgfutil@tempdima%
		\pgfmathcosec@{\pgfmath@tonumber{\pgfutil@tempdima}}%
		\pgf@xa\pgfmathresult\pgf@xa%
		\pgfutil@tempdima-\pgfutil@tempdima%
		\advance\pgfutil@tempdima180pt\relax%
		\advance\pgfutil@tempdima-\halftipangle pt\relax%
		%
		\pgfsavepgf@process\beforearrowtipanchor{%
			\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgf@xa}%
			\pgf@xb\pgf@x%
			\pgf@yb\pgf@y%
			\pgf@process{\pgfpointadd{\centerpoint}{\beforearrowtip}}%
			\advance\pgf@x\pgf@xb%
			\advance\pgf@y\pgf@yb%
		}%
		\pgfmathanglebetweenpoints{\beforearrowhead}{\beforearrowtip}%
		\pgfutil@tempdima-\pgfmathresult pt\relax%
		\advance\pgfutil@tempdima180pt\relax%
		\pgfutil@tempdima.5\pgfutil@tempdima%
		\pgfmathcosec@{\pgfmath@tonumber{\pgfutil@tempdima}}%
		\pgf@xa\xoutersep\relax%
		\pgf@xa\pgfmathresult\pgf@xa%
		\pgfutil@tempdima-\pgfutil@tempdima%
		\advance\pgfutil@tempdima180pt\relax%
		\pgfsavepgf@process\beforearrowheadanchor{%
			\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgf@xa}%
			\pgf@xb\pgf@x%
			\pgf@yb\pgf@y%
			\pgf@process{\pgfpointadd{\centerpoint}{\beforearrowhead}}%
			\advance\pgf@x\pgf@xb%
			\advance\pgf@y\pgf@yb%
		}%
		\pgfsavepgf@process\afterarrowtailanchor{%
			\pgfpointadd{\centerpoint}{\afterarrowtail}%
			\advance\pgf@x-\xoutersep\relax%
			\advance\pgf@y\youtersep\relax%
		}%
		%
		\pgfmathanglebetweenpoints{\centerpoint}{\beforearrowtipanchor}%
		\let\center@angle@beforearrowtip\pgfmathresult%
		\pgfmathanglebetweenpoints{\centerpoint}{\beforearrowheadanchor}%
		\let\center@angle@beforearrowhead\pgfmathresult%
		\pgfmathanglebetweenpoints{\centerpoint}{\afterarrowtailanchor}%
		\let\center@angle@afterarrowtail\pgfmathresult%
		\addtosavedmacro\center@angle@beforearrowtip%
		\addtosavedmacro\center@angle@beforearrowhead%
		\addtosavedmacro\center@angle@afterarrowtail%
		%
		\pgfmathanglebetweenpoints{\midpoint}{\beforearrowtipanchor}%
		\let\mid@angle@beforearrowtip\pgfmathresult%
		\pgfmathanglebetweenpoints{\midpoint}{\beforearrowheadanchor}%
		\let\mid@angle@beforearrowhead\pgfmathresult%
		\pgfmathanglebetweenpoints{\midpoint}{\afterarrowtailanchor}%
		\let\mid@angle@afterarrowtail\pgfmathresult%
		\addtosavedmacro\mid@angle@beforearrowtip%
		\addtosavedmacro\mid@angle@beforearrowhead%
		\addtosavedmacro\mid@angle@afterarrowtail%
		%
		\pgfmathanglebetweenpoints{\basepoint}{\beforearrowtipanchor}%
		\let\base@angle@beforearrowtip\pgfmathresult%
		\pgfmathanglebetweenpoints{\basepoint}{\beforearrowheadanchor}%
		\let\base@angle@beforearrowhead\pgfmathresult%
		\pgfmathanglebetweenpoints{\basepoint}{\afterarrowtailanchor}%
		\let\base@angle@afterarrowtail\pgfmathresult%
		\addtosavedmacro\base@angle@beforearrowtip%
		\addtosavedmacro\base@angle@beforearrowhead%
		\addtosavedmacro\base@angle@afterarrowtail%
		%
		\addtosavedmacro\arrowtipanchor%
		\addtosavedmacro\beforearrowtipanchor%
		\addtosavedmacro\beforearrowheadanchor%
		\addtosavedmacro\afterarrowtailanchor%
	}
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}%
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+0.5ex}%
	}%
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt%
	}%
	\anchor{center}{\centerpoint}%
	\anchor{mid}{\midpoint}%
	\anchor{mid east}{%
		\getsinglearrowpoints%
		\let\pgf@singlearrow@referencepoint\midpoint%
		\csname pgf@anchor@single arrow@border\endcsname{\pgfqpoint{\externalradius}{0pt}}%
	}	
	\anchor{mid west}{%
		\getsinglearrowpoints%
		\let\pgf@singlearrow@referencepoint\midpoint%
		\csname pgf@anchor@single arrow@border\endcsname{\pgfqpoint{-\externalradius}{0pt}}%
	}	
	\anchor{base}{\basepoint}%
	\anchor{base east}{%
		\getsinglearrowpoints%
		\let\pgf@singlearrow@referencepoint\basepoint%
		\csname pgf@anchor@single arrow@border\endcsname{\pgfqpoint{\externalradius}{0pt}}%
	}	
	\anchor{base west}{%
		\getsinglearrowpoints%
		\let\pgf@singlearrow@referencepoint\basepoint%
		\csname pgf@anchor@single arrow@border\endcsname{\pgfqpoint{-\externalradius}{0pt}}%
	}	
	\anchor{north}{%
		\getsinglearrowpoints%
		\csname pgf@anchor@single arrow@border\endcsname{\pgfqpoint{0pt}{\externalradius}}%
	}
	\anchor{south}{%
		\getsinglearrowpoints%
		\csname pgf@anchor@single arrow@border\endcsname{\pgfqpoint{0pt}{-\externalradius}}%
	}
	\anchor{east}{%
		\getsinglearrowpoints%
		\csname pgf@anchor@single arrow@border\endcsname{\pgfqpoint{\externalradius}{0pt}}%
	}
	\anchor{west}{%
		\getsinglearrowpoints%
		\csname pgf@anchor@single arrow@border\endcsname{\pgfqpoint{-\externalradius}{0pt}}%
	}
	\anchor{north east}{%
		\getsinglearrowpoints%
		\csname pgf@anchor@single arrow@border\endcsname{\pgfqpoint{\externalradius}{\externalradius}}%
	}
	\anchor{south east}{%
		\getsinglearrowpoints%
		\csname pgf@anchor@single arrow@border\endcsname{\pgfqpoint{\externalradius}{-\externalradius}}%
	}
	\anchor{south west}{%
		\getsinglearrowpoints%
		\csname pgf@anchor@single arrow@border\endcsname{\pgfqpoint{-\externalradius}{-\externalradius}}%
	}
	\anchor{north west}{%
		\getsinglearrowpoints%
		\csname pgf@anchor@single arrow@border\endcsname{\pgfqpoint{-\externalradius}{\externalradius}}%
	}
	\anchor{before head}{%
		\getsinglearrowpoints%
		\pgfmathrotatepointaround{\beforearrowheadanchor}{\centerpoint}{\rotate}%
	}%
	\anchor{before tip}{%
		\getsinglearrowpoints%
		\pgfmathrotatepointaround{\beforearrowtipanchor}{\centerpoint}{\rotate}%
	}%
	\anchor{tip}{%
		\getsinglearrowpoints%
		\pgfmathrotatepointaround{\arrowtipanchor}{\centerpoint}{\rotate}%
	}%
	\anchor{after tip}{%
		\getsinglearrowpoints%
		\pgfmathrotatepointaround{%
			\pgfpointadd{%
				\pgfpointdiff{\centerpoint}{\beforearrowtipanchor}%
				\pgf@y-\pgf@y%
			}{\centerpoint}}%
		{\centerpoint}{\rotate}%
	}
	\anchor{after head}{%
		\getsinglearrowpoints%
		\pgfmathrotatepointaround{%
			\pgfpointadd{%
				\pgfpointdiff{\centerpoint}{\beforearrowheadanchor}%
				\pgf@y-\pgf@y%
			}{\centerpoint}}%
		{\centerpoint}{\rotate}%
	}
	\anchor{before tail}{%
		\getsinglearrowpoints%
		\pgfmathrotatepointaround{%
			\pgfpointadd{%
				\pgfpointdiff{\centerpoint}{\afterarrowtailanchor}%
				\pgf@y-\pgf@y%
			}{\centerpoint}}%
		{\centerpoint}{\rotate}%
	}
	\anchor{after tail}{%
		\getsinglearrowpoints%
		\pgfmathrotatepointaround{\afterarrowtailanchor}{\centerpoint}{\rotate}%
	}
	\anchor{tail}{%
		\getsinglearrowpoints%
		\pgfpointlineattime{0.5}{%
			\pgfmathrotatepointaround{\afterarrowtailanchor}{\centerpoint}{\rotate}%
		}%
		{%
			\pgfmathrotatepointaround{%
			\pgfpointadd{%
				\pgfpointdiff{\centerpoint}{\afterarrowtailanchor}%
				\pgf@y-\pgf@y%
			}{\centerpoint}}%
			{\centerpoint}{\rotate}%
		}%	
	}%
	\backgroundpath{%
		{%
			\pgftransformshift{\centerpoint}%
			\pgftransformrotate{\rotate}%
			\pgfpathmoveto{\arrowtip}%
			\pgfpathlineto{\beforearrowtip}%
			\pgfpathlineto{\beforearrowhead}%
			\pgfpathlineto{\afterarrowtail}%
			\pgfpathlineto{\afterarrowtail\pgf@y-\pgf@y}%
			\pgfpathlineto{\beforearrowhead\pgf@y-\pgf@y}%
			\pgfpathlineto{\beforearrowtip\pgf@y-\pgf@y}%			
		}%
		\pgfpathclose%
	}%
	\anchorborder{%
		\pgfsavepgf@process\externalpoint{}%			
		\getsinglearrowpoints%
		\pgfutil@ifundefined{pgf@singlearrow@referencepoint}{\let\referencepoint\centerpoint}%
			{\let\referencepoint\pgf@singlearrow@referencepoint}%
		\pgfsavepgf@process\externalpoint{%
			\externalpoint%
			\pgf@xa\pgf@x%
			\pgf@ya\pgf@y%
			\referencepoint%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y\pgf@ya}% 
		\pgfmathanglebetweenpoints{\centerpoint}{\externalpoint}%
		\pgfmathsubtract@{\pgfmathresult}{\rotate}%
		\ifdim\pgfmathresult pt<0pt\relax%
			\pgfmathadd@{\pgfmathresult}{360}%
		\fi%
		\let\externalangle\pgfmathresult%
		\pgf@x\externalangle pt\relax%
		\ifx\referencepoint\midpoint%
			\pgf@xa\mid@angle@beforearrowtip pt\relax%
			\pgf@xb\mid@angle@beforearrowhead pt\relax%
			\pgf@xc\mid@angle@afterarrowtail pt\relax%
		\else%
			\ifx\referencepoint\basepoint%
				\pgf@xa\base@angle@beforearrowtip pt\relax%
				\pgf@xb\base@angle@beforearrowhead pt\relax%
				\pgf@xc\base@angle@afterarrowtail pt\relax%
			\else%
				\pgf@xa\center@angle@beforearrowtip pt\relax%
				\pgf@xb\center@angle@beforearrowhead pt\relax%
				\pgf@xc\center@angle@afterarrowtail pt\relax%
			\fi%
		\fi%
		\ifdim\pgf@x<\pgf@xa%
			\let\firstpoint\arrowtipanchor%
			\let\secondpoint\beforearrowtipanchor%
		\else%
			\ifdim\pgf@x<\pgf@xb%
				\ifdim\pgf@xb<\pgf@xa%
					\let\firstpoint\arrowtipanchor%
					\let\secondpoint\beforearrowtipanchor%
				\else%
					\let\firstpoint\beforearrowheadanchor%
					\let\secondpoint\beforearrowtipanchor%
				\fi%
			\else%
				\ifdim\pgf@x<\pgf@xc%
					\let\firstpoint\beforearrowheadanchor%
					\let\secondpoint\afterarrowtailanchor%
				\else%
					\pgf@xc-\pgf@xc%
					\advance\pgf@xc360pt\relax%
					\ifdim\pgf@x<\pgf@xc%
						\let\firstpoint\afterarrowtailanchor%
						\pgfsavepgf@process\secondpoint{%
							\pgfpointadd{%
								\pgfpointdiff{\centerpoint}{\afterarrowtailanchor}%
								\pgf@y-\pgf@y%
							}{\centerpoint}%
						}%
					\else%
						\pgf@xa-\pgf@xa%
						\advance\pgf@xa360pt\relax%
						\pgf@xb-\pgf@xb%
						\advance\pgf@xb360pt\relax%
						\ifdim\pgf@x<\pgf@xa%
							\ifdim\pgf@x<\pgf@xb%
								\pgfsavepgf@process\firstpoint{%
									\pgfpointadd{%
											\pgfpointdiff{\centerpoint}{\afterarrowtailanchor}%
											\pgf@y-\pgf@y%
									}{\centerpoint}%
								}%
								\pgfsavepgf@process\secondpoint{%
									\pgfpointadd{%
										\pgfpointdiff{\centerpoint}{\beforearrowheadanchor}%
										\pgf@y-\pgf@y%
									}{\centerpoint}%
								}%
							\else%
								\ifdim\pgf@xb<\pgf@xa%
									\pgfsavepgf@process\firstpoint{%
										\pgfpointadd{%
												\pgfpointdiff{\centerpoint}{\beforearrowheadanchor}%
												\pgf@y-\pgf@y%
										}{\centerpoint}%
									}%									
								\else%
									\pgfsavepgf@process\firstpoint{%
										\pgfpointadd{%
												\pgfpointdiff{\centerpoint}{\arrowtipanchor}%
												\pgf@y-\pgf@y%
										}{\centerpoint}%
									}%	
								\fi%
								\pgfsavepgf@process\secondpoint{%
										\pgfpointadd{%
											\pgfpointdiff{\centerpoint}{\beforearrowtipanchor}%
											\pgf@y-\pgf@y%
										}{\centerpoint}%
									}%
							\fi%
						\else%
							\pgfsavepgf@process\firstpoint{%
								\pgfpointadd{%
									\pgfpointdiff{\centerpoint}{\beforearrowtipanchor}%
									\pgf@y-\pgf@y%
								}{\centerpoint}%
							}%
							\let\secondpoint\arrowtipanchor%
						\fi%
					\fi%
				\fi%
			\fi%
		\fi%
		\pgfsavepgf@process\firstpoint{%
			\pgfmathrotatepointaround{\firstpoint}{\centerpoint}{\rotate}%
		}%
		\pgfsavepgf@process\secondpoint{%
			\pgfmathrotatepointaround{\secondpoint}{\centerpoint}{\rotate}%
		}%
		\pgfpointintersectionoflines{\referencepoint}{\externalpoint}%
			{\firstpoint}{\secondpoint}%			
	}%
}







% keys for shape double arrow
%
% /pgf/double arrow tip angle
% /pgf/double arrow head sep

\pgfkeys{/pgf/.cd,
	double arrow tip angle/.initial=90,
	double arrow head extend/.initial=.25cm,
	double arrow head indent/.initial=0cm}

% Shape double arrow
%
%
\pgfdeclareshape{double arrow}{%
	\savedmacro\getdoublearrowpoints{%
		%
		% Get the outer sep.
		% 
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
		\edef\xoutersep{\the\pgf@x}%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/outer ysep}}%
		\edef\youtersep{\the\pgf@y}%
		%
		% Get the node dimensions.
		%
		\pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/inner xsep}}%
		\advance\pgf@xa.5\wd\pgfnodeparttextbox%
		\advance\pgf@xa.5\pgflinewidth%
		\pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/inner ysep}}%
		\advance\pgf@ya.5\ht\pgfnodeparttextbox%
		\advance\pgf@ya.5\dp\pgfnodeparttextbox%
		\advance\pgf@ya.5\pgflinewidth%
		\ifpgfshapeborderusesincircle%
			\ifdim\pgf@xa<\pgf@ya%
				\pgf@xa\pgf@ya%
			\fi%			
			\pgf@xa1.41421\pgf@xa%
			\pgf@ya\pgf@xa%
			\pgfmathsetmacro\rotate{\pgfkeysvalueof{/pgf/shape border rotate}}%
			\ifdim\xoutersep>\youtersep\relax%
				\let\youtersep\xoutersep%
			\else%
				\let\xoutersep\youtersep%
			\fi%
		\else%
			%
			% Round the rotation.
			%
			\pgfmathsetmacro\rotate{\pgfkeysvalueof{/pgf/shape border rotate}}
			\pgfmathmod@{\rotate}{360}%
			\afterassignment\pgfmath@gobbletilpgfmath@%
			\expandafter\c@pgf@counta\pgfmathresult\relax\pgfmath@%
			\advance\c@pgf@counta45\relax%
			\divide\c@pgf@counta90\relax%
			\multiply\c@pgf@counta90\relax%
			\ifnum\c@pgf@counta<0\relax%
				\advance\c@pgf@counta360\relax%
			\fi%
			\edef\rotate{\the\c@pgf@counta}%
			%
			% Calculate the width and height of the node
			% contents, according to any border rotation.
			%
			\ifnum\c@pgf@counta=90\relax%
				\pgf@x\pgf@xa%
				\pgf@xa\pgf@ya%
				\pgf@ya\pgf@x%
				\let\pgfmathresult\xoutersep%
				\let\xoutersep\youtersep%
				\let\youtersep\pgfmathresult%
			\else%
				\ifnum\c@pgf@counta=270\relax%
					\pgf@x\pgf@xa%
					\pgf@xa\pgf@ya%
					\pgf@ya\pgf@x%
					\let\pgfmathresult\xoutersep%
					\let\xoutersep\youtersep%
					\let\youtersep\pgfmathresult%
				\fi%
			\fi%
		\fi%
		\addtosavedmacro\rotate%
		%
		% Get some useful trig stuff.
		%
		\pgfmathdivide{\pgfkeysvalueof{/pgf/double arrow tip angle}}{2}%
		\let\halftipangle\pgfmathresult%
		\pgfmathcosec@{\halftipangle}%
		\let\cosechalftipangle\pgfmathresult%
		\pgfmathcos@{\halftipangle}%
		\pgfutil@tempdima\pgfmathresult pt\relax%
		\pgfutil@tempdima\cosechalftipangle\pgfutil@tempdima%
		\edef\cothalftipangle{\pgfmath@tonumber{\pgfutil@tempdima}}%
		\pgfmathreciprocal@{\pgfmathresult}%
		\let\sechalftipangle\pgfmathresult%
		\pgfmathsin@{\halftipangle}%
		\pgfutil@tempdima\pgfmathresult pt\relax%
		\pgfutil@tempdima\sechalftipangle\pgfutil@tempdima%
		\edef\tanhalftipangle{\pgfmath@tonumber{\pgfutil@tempdima}}%
		%
		% Get the double arrow head extend, and adjust for minimum width.
		%
		\pgf@xb\pgf@ya%
		\pgf@xb\cothalftipangle\pgf@xb%
		\pgfmathsetlength\pgf@xc{\pgfkeysvalueof{/pgf/double arrow head extend}}%
		\pgf@yc\pgf@xc%
		\advance\pgf@xc\pgf@ya%
		\pgfmathsetlength\pgfutil@tempdimb{\pgfkeysvalueof{/pgf/minimum width}}%
		\ifdim\pgf@xc<.5\pgfutil@tempdimb%
			\pgfutil@tempdimb.5\pgfutil@tempdimb%
			\pgfmathdivide@{\pgfmath@tonumber{\pgfutil@tempdimb}}{\pgfmath@tonumber{\pgf@xc}}%
			\pgf@ya\pgfmathresult\pgf@ya%
			\pgf@xc\pgfmathresult\pgf@xc%
			\pgf@yc\pgfmathresult\pgf@yc%
			\pgf@xb\pgfmathresult\pgf@xb%
		\fi%
		%
		% Now calculate the height of the arrow and adjust for minimum height.
		%
		\advance\pgf@xc-\pgf@ya%
		\pgf@xc\cothalftipangle\pgf@xc%
		\advance\pgf@xa\pgf@xb%
		\pgf@xa2.0\pgf@xa%
		\pgfmathsetlength\pgfutil@tempdimb{\pgfkeysvalueof{/pgf/minimum height}}%
		\ifdim\pgf@xa<\pgfutil@tempdimb%
			\pgf@xa\pgfutil@tempdimb%
		\fi%
		\pgf@xa.5\pgf@xa%	
		\advance\pgf@xa-\pgf@xb%
		\pgfmathsetlength\pgfutil@tempdima{\pgfkeysvalueof{/pgf/double arrow head indent}}%
		%
		% Now:
		%
		% xa - .5 * width of the node minus xb.
		% ya - .5 * height of the node contents.
		% xb - distance from the end of the node contents to the arrow tip.
		% xc - distance from the end of the node contents to the back end of the arrow head.
		% yc - distance from the top of the node contents to the top end of the arrow head.
		%
		\pgfsavepgf@process\centerpoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgf@y.5\ht\pgfnodeparttextbox%
			\advance\pgf@y-.5\dp\pgfnodeparttextbox%
		}%
		\pgfsavepgf@process\basepoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgf@y0pt%
		}%
		\pgfsavepgf@process\midpoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgfmathsetlength\pgf@y{+.5ex}%
		}%
		%
		% As the arrow is symmetrical it can be described by only 3 points:
		%
		\pgfsavepgf@process\arrowtip{%
			\pgf@x\pgf@xa%
			\advance\pgf@x\pgf@xb%
			\pgf@y0pt\relax%
		}%
		\pgfsavepgf@process\beforearrowtip{%
			\pgf@x\pgf@xa%
			\advance\pgf@x-\pgf@xc%
			\pgf@y\pgf@ya%
			\advance\pgf@y\pgf@yc%
		}%
		\pgfsavepgf@process\beforearrowhead{%
			\pgf@x\pgf@xa%
			\advance\pgf@x-\pgf@xc%
			\advance\pgf@x\pgfutil@tempdima%
			\pgf@y\pgf@ya%
		}%
		%
		% Calculate the anchor point at the arrow tip.
		%
		\pgfsavepgf@process\arrowtipanchor{%
			\pgfpointadd{\centerpoint}{\arrowtip}%
			\pgf@xa\xoutersep\relax%
			\advance\pgf@x\cosechalftipangle\pgf@xa%
		}%
		\advance\pgf@x.5\wd\pgfnodeparttextbox%
		\edef\externalradius{\the\pgf@x}%
		\addtosavedmacro\externalradius%
		%
		%
		\pgfmathanglebetweenlines{\beforearrowtip}{\beforearrowhead}{\beforearrowtip}{\arrowtip}%
		\pgf@xa\xoutersep\relax%
		\pgfutil@tempdima\pgfmathresult pt\relax%
		\pgfutil@tempdima.5\pgfutil@tempdima%
		\pgfmathcosec@{\pgfmath@tonumber{\pgfutil@tempdima}}%
		\pgf@xa\pgfmathresult\pgf@xa%
		\pgfutil@tempdima-\pgfutil@tempdima%
		\advance\pgfutil@tempdima180pt\relax%
		\advance\pgfutil@tempdima-\halftipangle pt\relax%
		\pgfsavepgf@process\beforearrowtipanchor{%
			\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgf@xa}%
			\pgf@xb\pgf@x%
			\pgf@yb\pgf@y%
			\pgf@process{\pgfpointadd{\centerpoint}{\beforearrowtip}}%
			\advance\pgf@x\pgf@xb%
			\advance\pgf@y\pgf@yb%
		}%
		\pgfmathanglebetweenpoints{\beforearrowhead}{\beforearrowtip}%
		\pgfutil@tempdima-\pgfmathresult pt\relax%
		\advance\pgfutil@tempdima180pt\relax%
		\pgfutil@tempdima.5\pgfutil@tempdima%
		\pgfmathcosec@{\pgfmath@tonumber{\pgfutil@tempdima}}%
		\pgf@xa\xoutersep\relax%
		\pgf@xa\pgfmathresult\pgf@xa%
		\pgfutil@tempdima-\pgfutil@tempdima%
		\advance\pgfutil@tempdima180pt\relax%
		\pgfsavepgf@process\beforearrowheadanchor{%
			\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgf@xa}%
			\pgf@xb\pgf@x%
			\pgf@yb\pgf@y%
			\pgf@process{\pgfpointadd{\centerpoint}{\beforearrowhead}}%
			\advance\pgf@x\pgf@xb%
			\advance\pgf@y\pgf@yb%
		}%
		%
		\pgfmathanglebetweenpoints{\centerpoint}{\beforearrowtipanchor}%
		\let\center@angle@beforearrowtip\pgfmathresult%
		\addtosavedmacro\center@angle@beforearrowtip%
		%
		\pgfmathanglebetweenpoints{\midpoint}{\beforearrowtipanchor}%
		\let\mid@angle@beforearrowtip\pgfmathresult%
		\addtosavedmacro\mid@angle@beforearrowtip%
		%
		\pgfmathanglebetweenpoints{\basepoint}{\beforearrowtipanchor}%
		\let\base@angle@beforearrowtip\pgfmathresult%
		\addtosavedmacro\base@angle@beforearrowtip%
		%
		\addtosavedmacro\arrowtipanchor%
		\addtosavedmacro\beforearrowtipanchor%
		\addtosavedmacro\beforearrowheadanchor%
	}
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}%
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+0.5ex}%
	}%
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt%
	}%
	\anchor{center}{\centerpoint}%
	\anchor{mid}{\midpoint}%
	\anchor{mid east}{%
		\getdoublearrowpoints%
		\let\pgf@singlearrow@referencepoint\midpoint%
		\csname pgf@anchor@double arrow@border\endcsname{\pgfqpoint{\externalradius}{0pt}}%
	}	
	\anchor{mid west}{%
		\getdoublearrowpoints%
		\let\pgf@singlearrow@referencepoint\midpoint%
		\csname pgf@anchor@double arrow@border\endcsname{\pgfqpoint{-\externalradius}{0pt}}%
	}	
	\anchor{base}{\basepoint}%
	\anchor{base east}{%
		\getdoublearrowpoints%
		\let\pgf@singlearrow@referencepoint\basepoint%
		\csname pgf@anchor@double arrow@border\endcsname{\pgfqpoint{\externalradius}{0pt}}%
	}	
	\anchor{base west}{%
		\getdoublearrowpoints%
		\let\pgf@singlearrow@referencepoint\basepoint%
		\csname pgf@anchor@double arrow@border\endcsname{\pgfqpoint{-\externalradius}{0pt}}%
	}	
	\anchor{north}{%
		\getdoublearrowpoints%
		\csname pgf@anchor@double arrow@border\endcsname{\pgfqpoint{0pt}{\externalradius}}%
	}
	\anchor{south}{%
		\getdoublearrowpoints%
		\csname pgf@anchor@double arrow@border\endcsname{\pgfqpoint{0pt}{-\externalradius}}%
	}
	\anchor{east}{%
		\getdoublearrowpoints%
		\csname pgf@anchor@double arrow@border\endcsname{\pgfqpoint{\externalradius}{0pt}}%
	}
	\anchor{west}{%
		\getdoublearrowpoints%
		\csname pgf@anchor@double arrow@border\endcsname{\pgfqpoint{-\externalradius}{0pt}}%
	}
	\anchor{north east}{%
		\getdoublearrowpoints%
		\csname pgf@anchor@double arrow@border\endcsname{\pgfqpoint{\externalradius}{\externalradius}}%
	}
	\anchor{south east}{%
		\getdoublearrowpoints%
		\csname pgf@anchor@double arrow@border\endcsname{\pgfqpoint{\externalradius}{-\externalradius}}%
	}
	\anchor{south west}{%
		\getdoublearrowpoints%
		\csname pgf@anchor@double arrow@border\endcsname{\pgfqpoint{-\externalradius}{-\externalradius}}%
	}
	\anchor{north west}{%
		\getdoublearrowpoints%
		\csname pgf@anchor@double arrow@border\endcsname{\pgfqpoint{-\externalradius}{\externalradius}}%
	}
	\anchor{before head 1}{%
		\getdoublearrowpoints%
		\pgfmathrotatepointaround{\beforearrowheadanchor}{\centerpoint}{\rotate}%
	}%
	\anchor{before tip 1}{%
		\getdoublearrowpoints%
		\pgfmathrotatepointaround{\beforearrowtipanchor}{\centerpoint}{\rotate}%
	}%
	\anchor{tip 1}{%
		\getdoublearrowpoints%
		\pgfmathrotatepointaround{\arrowtipanchor}{\centerpoint}{\rotate}%
	}%
	\anchor{after tip 1}{%
		\getdoublearrowpoints%
		\pgfmathrotatepointaround{%
			\pgfpointadd{%
				\pgfpointdiff{\centerpoint}{\beforearrowtipanchor}%
				\pgf@y-\pgf@y%
			}{\centerpoint}}%
		{\centerpoint}{\rotate}%
	}
	\anchor{after head 1}{%
		\getdoublearrowpoints%
		\pgfmathrotatepointaround{%
			\pgfpointadd{%
				\pgfpointdiff{\centerpoint}{\beforearrowheadanchor}%
				\pgf@y-\pgf@y%
			}{\centerpoint}}%
		{\centerpoint}{\rotate}%
	}
	\anchor{before head 2}{%
		\getdoublearrowpoints%
		\pgfmathrotatepointaround{%
			\pgfpointadd{%
				\pgfpointdiff{\centerpoint}{\beforearrowheadanchor}%
				\pgf@x-\pgf@x%
				\pgf@y-\pgf@y%
			}{\centerpoint}}%
		{\centerpoint}{\rotate}%
	}%
	\anchor{before tip 2}{%
		\getdoublearrowpoints%
		\pgfmathrotatepointaround{%
			\pgfpointadd{%
				\pgfpointdiff{\centerpoint}{\beforearrowtipanchor}%
				\pgf@x-\pgf@x%
				\pgf@y-\pgf@y%
			}{\centerpoint}}%
		{\centerpoint}{\rotate}%
	}%
	\anchor{tip 2}{%
		\getdoublearrowpoints%
		\pgfmathrotatepointaround{%
			\pgfpointadd{%
				\pgfpointdiff{\centerpoint}{\arrowtipanchor}%
				\pgf@x-\pgf@x%
			}{\centerpoint}}%
		{\centerpoint}{\rotate}%
	}%
	\anchor{after tip 2}{%
		\getdoublearrowpoints%
		\pgfmathrotatepointaround{%
			\pgfpointadd{%
				\pgfpointdiff{\centerpoint}{\beforearrowtipanchor}%
				\pgf@x-\pgf@x%
			}{\centerpoint}}%
		{\centerpoint}{\rotate}%
	}
	\anchor{after head 2}{%
		\getdoublearrowpoints%
		\pgfmathrotatepointaround{%
			\pgfpointadd{%
				\pgfpointdiff{\centerpoint}{\beforearrowheadanchor}%
				\pgf@x-\pgf@x%
			}{\centerpoint}}%
		{\centerpoint}{\rotate}%
	}
	\backgroundpath{%
		{%
			\pgftransformshift{\centerpoint}%
			\pgftransformrotate{\rotate}%
			\pgfpathmoveto{\arrowtip}%
			\pgfpathlineto{\beforearrowtip}%
			\pgfpathlineto{\beforearrowhead}%
			\pgfpathlineto{\beforearrowhead\pgf@x-\pgf@x}%
			\pgfpathlineto{\beforearrowtip\pgf@x-\pgf@x}%
			\pgfpathlineto{\arrowtip\pgf@x-\pgf@x}%
			\pgfpathlineto{\beforearrowtip\pgf@x-\pgf@x\pgf@y-\pgf@y}%
			\pgfpathlineto{\beforearrowhead\pgf@x-\pgf@x\pgf@y-\pgf@y}%
			\pgfpathlineto{\beforearrowhead\pgf@y-\pgf@y}%
			\pgfpathlineto{\beforearrowtip\pgf@y-\pgf@y}%			
		}%
		\pgfpathclose%
	}%
	\anchorborder{%
		\pgfsavepgf@process\externalpoint{}%			
		\getdoublearrowpoints%
		\pgfutil@ifundefined{pgf@singlearrow@referencepoint}{\let\referencepoint\centerpoint}%
			{\let\referencepoint\pgf@singlearrow@referencepoint}%
		\pgfsavepgf@process\externalpoint{%
			\externalpoint%
			\pgf@xa\pgf@x%
			\pgf@ya\pgf@y%
			\referencepoint%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y\pgf@ya}% 
		\pgfmathanglebetweenpoints{\centerpoint}{\externalpoint}%
		\pgfmathsubtract@{\pgfmathresult}{\rotate}%
		\ifdim\pgfmathresult pt<0pt\relax%
			\pgfmathadd@{\pgfmathresult}{360}%
		\fi%
		\let\externalangle\pgfmathresult%
		\pgf@x\externalangle pt\relax%
		\ifx\referencepoint\midpoint%
			\pgf@xa\mid@angle@beforearrowtip pt\relax%
		\else%
			\ifx\referencepoint\basepoint%
				\pgf@xa\base@angle@beforearrowtip pt\relax%
			\else%
				\pgf@xa\center@angle@beforearrowtip pt\relax%
			\fi%
		\fi%
		\ifdim\pgf@x<180pt\relax%
			\ifdim\pgf@x<\pgf@xa%
				\let\firstpoint\arrowtipanchor%
				\let\secondpoint\beforearrowtipanchor%
			\else%
				\pgf@xa-\pgf@xa%
				\advance\pgf@xa180pt\relax%
				\ifdim\pgf@x<\pgf@xa%
					\let\firstpoint\beforearrowheadanchor%
					\pgfsavepgf@process\secondpoint{%
						\pgfpointadd{%
							\pgfpointdiff{\centerpoint}{\beforearrowheadanchor}%
							\pgf@x-\pgf@x
							}{\centerpoint}}%
				\else%
					\pgfsavepgf@process\firstpoint{%
						\pgfpointadd{%
							\pgfpointdiff{\centerpoint}{\beforearrowtipanchor}%
							\pgf@x-\pgf@x
							}{\centerpoint}}%
					\pgfsavepgf@process\secondpoint{%
						\pgfpointadd{%
							\pgfpointdiff{\centerpoint}{\arrowtipanchor}%
							\pgf@x-\pgf@x%
							\pgf@y-\pgf@y%
						}{\centerpoint}}%
				\fi%
			\fi%
		\else%
			\pgf@xa-\pgf@xa%
			\advance\pgf@xa360pt\relax%
			\ifdim\pgf@x<\pgf@xa%
				\pgf@xa-\pgf@xa%
				\advance\pgf@xa540pt\relax%
				\ifdim\pgf@x<\pgf@xa%
					\pgfsavepgf@process\firstpoint{%
						\pgfpointadd{%
							\pgfpointdiff{\centerpoint}{\arrowtipanchor}%
							\pgf@x-\pgf@x%
						}{\centerpoint}}%
					\pgfsavepgf@process\secondpoint{%
						\pgfpointadd{%
							\pgfpointdiff{\centerpoint}{\beforearrowtipanchor}%
							\pgf@x-\pgf@x%
							\pgf@y-\pgf@y%
						}{\centerpoint}}%
				\else%
					\pgfsavepgf@process\firstpoint{%
						\pgfpointadd{%
							\pgfpointdiff{\centerpoint}{\beforearrowheadanchor}%
							\pgf@x-\pgf@x%
							\pgf@y-\pgf@y%
						}{\centerpoint}}%
					\pgfsavepgf@process\secondpoint{%
						\pgfpointadd{%
							\pgfpointdiff{\centerpoint}{\beforearrowheadanchor}%
							\pgf@y-\pgf@y%
						}{\centerpoint}}%
				\fi%
			\else%
				\pgfsavepgf@process\firstpoint{%
						\pgfpointadd{%
							\pgfpointdiff{\beforearrowtipanchor}{\centerpoint}%
							\pgf@x-\pgf@x%
						}{\centerpoint}}%
				\let\secondpoint\arrowtipanchor%
			\fi%
		\fi%
		\pgfsavepgf@process\firstpoint{%
			\pgfmathrotatepointaround{\firstpoint}{\centerpoint}{\rotate}%
		}%
		\pgfsavepgf@process\secondpoint{%
			\pgfmathrotatepointaround{\secondpoint}{\centerpoint}{\rotate}%
		}%
		\pgfpointintersectionoflines{\referencepoint}{\externalpoint}%
			{\firstpoint}{\secondpoint}%			
	}%
}




%
% Internal macros for the arrow box/shape.
%
\def\pgf@lib@arrowbox@parsearrowlength#1#2#3{%
	\edef\pgf@lib@temp{#3}%
	\edef\pgf@lib@marshal{%
		\noexpand\pgfutil@in@{none}{\pgf@lib@temp}%
	}%
	\pgf@lib@marshal%
	\ifpgfutil@in@%
		#10pt\relax%
	\else%
		\afterassignment\pgfmath@gobbletilpgfmath@%
		\expandafter#1\pgf@lib@temp\relax\pgfmath@%
		%
		\edef\pgf@lib@marshal{%
			\noexpand\pgfutil@in@{from center}{\pgf@lib@temp}%
		}%
		\pgf@lib@marshal%
		\ifpgfutil@in@%
		\else%
			\ifdim#1>0pt\relax%
				\advance#1#2\relax%
			\fi%
		\fi%
	\fi}

\def\pgf@lib@arrowbox@parsearrows#1{%
	\pgfkeys{/pgf/.cd,%
		arrow box west arrow=0pt,
		arrow box east arrow=0pt,
		arrow box south arrow=0pt,
		arrow box north arrow=0pt
	}%
	\def\pgf@lib@arrowbox@extend{0pt}%
	\edef\pgf@lib@temp{#1}%
	\expandafter\pgf@lib@arrowbox@@parsearrows\pgf@lib@temp,\pgf@lib@arrowbox@parsearrows,}


\def\pgf@lib@arrowbox@@parsearrows#1,{%
	\ifx\pgf@lib@arrowbox@parsearrows#1%
		\let\pgflib@next\relax%
	\else%
		\pgfutil@in@:{#1}%
		\ifpgfutil@in@%
			\pgf@lib@arrowbox@getextend#1\pgf@lib%
		\else%
			\def\pgf@lib@arrowbox@direction{#1}%
		\fi%
		\edef\pgf@marshal{%
			\noexpand\pgfkeys{/pgf/arrow box  \pgf@lib@arrowbox@direction\space arrow=\pgf@lib@arrowbox@extend}%
		}%
		\pgf@marshal%
		\let\pgflib@next\pgf@lib@arrowbox@@@parsearrows%
	\fi%
	\pgflib@next%
}
\def\pgf@lib@arrowbox@@@parsearrows{%
	\pgfutil@ifnextchar x{\relax\pgf@lib@arrowbox@@parsearrows}{\relax\pgf@lib@arrowbox@@parsearrows}%
}

\def\pgf@lib@arrowbox@getextend#1:#2\pgf@lib{%
	\def\pgf@lib@arrowbox@direction{#1}%
	\def\pgf@lib@arrowbox@extend{#2}%
}%

%
% /pgf/arrow box north arrow  
% /pgf/arrow box south arrow  
% /pgf/arrow box west arrow   
% /pgf/arrow box east arrow   
% /pgf/arrow box arrows       
% /pgf/arrow box shaft width  
% /pgf/arrow box head extend   
% /pgf/arrow box head indent 
% /pgf/arrow box tip angle   
%
\pgfkeys{/pgf/.cd,
	arrow box west arrow/.initial=.5cm,
	arrow box east arrow/.initial=.5cm,
	arrow box south arrow/.initial=.5cm,
	arrow box north arrow/.initial=.5cm,
	arrow box shaft width/.initial=.125cm,
	arrow box head extend/.initial=.125cm,
	arrow box head indent/.initial=0cm,
	arrow box tip angle/.initial=90,
}	

%
% arrow box/Shape.
%
\pgfdeclareshape{arrow box}{%
	\saveddimen\shaftwidth{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/arrow box shaft width}}%
	}%
	%
	% Calculate far the arrows extend from the center of the node.
	%
	\savedmacro\arrowboxpoints{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
		\advance\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/minimum width}}%
		\ifdim\pgf@x<.5\pgf@xa%
			\pgf@x.5\pgf@xa%
		\fi%
		\pgfmathaddtolength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
		%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
		\advance\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y.5\dp\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/minimum height}}%
		\ifdim\pgf@y<.5\pgf@ya%
			\pgf@y.5\pgf@ya%
		\fi%	
		\pgfmathaddtolength\pgf@y{\pgfkeysvalueof{/pgf/outer ysep}}%	
		%
		\edef\halfboxwidth{\the\pgf@x}%
		\edef\halfboxheight{\the\pgf@y}%
		\pgfextract@process\arrowboxcorner{}%
		\addtosavedmacro\arrowboxcorner%
		%
		\pgf@lib@arrowbox@parsearrowlength\pgf@x{\halfboxwidth}%
			{\pgfkeysvalueof{/pgf/arrow box west arrow}}%
		\edef\westextend{\the\pgf@x}%
		\addtosavedmacro\westextend%
		%
		\pgf@lib@arrowbox@parsearrowlength\pgf@x{\halfboxwidth}%
			{\pgfkeysvalueof{/pgf/arrow box east arrow}}%
		\edef\eastextend{\the\pgf@x}%
		\addtosavedmacro\eastextend%
		%
		\pgf@lib@arrowbox@parsearrowlength\pgf@x{\halfboxheight}%
			{\pgfkeysvalueof{/pgf/arrow box north arrow}}%
		\edef\northextend{\the\pgf@x}%
		\addtosavedmacro\northextend%
		%
		\pgf@lib@arrowbox@parsearrowlength\pgf@x{\halfboxheight}%
			{\pgfkeysvalueof{/pgf/arrow box south arrow}}%
		\edef\southextend{\the\pgf@x}%
		\addtosavedmacro\southextend%
	}%
	\saveddimen\arrowheadextend{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/arrow box head extend}}%
	}%
	\saveddimen\arrowheadindent{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/arrow box head indent}}%
	}%
	%
	% Calculate the `miter' angle for the outer sep at the arrow tip.
	%
	\savedmacro\arrowtipmiterangle{%
		\pgfmathparse{\pgfkeysvalueof{/pgf/arrow box tip angle}}%
		\pgfmathdivide@{\pgfmathresult}{2}%
		\let\arrowtipmiterangle\pgfmathresult%
	}%
	%
	% Calculate the `miter' angle for the outer sep at the point just 
	% before the arrow tip. 
	% 
	\savedmacro\arrowheadangles{%
		%
		% Calculate the `miter' angle and its cosecant at the arrow tip...
		%
		\pgfmathparse{\pgfkeysvalueof{/pgf/arrow box tip angle}}%
		\pgfmathdivide@{\pgfmathresult}{2}%
		\let\arrowtipmiterangle\pgfmathresult%
		\addtosavedmacro\arrowtipmiterangle%
		\pgfmathcosec@{\arrowtipmiterangle}%
		\let\cosecarrowtipmiterangle\pgfmathresult%
		\addtosavedmacro\cosecarrowtipmiterangle%
		%
		% ...before the arrow head...
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/arrow box head extend}}%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/arrow box head indent}}%
		\ifdim\pgf@y=0pt\relax%
			\def\pgfmathresult{90}%
		\else%
			\ifdim\pgf@y<0pt\relax%
				\pgfmathdivide@{\pgfmath@tonumber{\pgf@x}}{\pgfmath@tonumber{\pgf@y}}%
				\pgfmathatan@{\pgfmathresult}%
				\pgfmathadd@{\pgfmathresult}{180}%
			\else%
				\pgfmathdivide@{\pgfmath@tonumber{\pgf@x}}{\pgfmath@tonumber{\pgf@y}}%
				\pgfmathatan@{\pgfmathresult}%
			\fi%			
		\fi%
		\pgfmathdivide@{\pgfmathresult}{2}%
		\let\beforearrowheadmiterangle\pgfmathresult%
		\addtosavedmacro\beforearrowheadmiterangle%
		\pgfmathcosec@{\beforearrowheadmiterangle}%
		\let\cosecbeforearrowheadmiterangle\pgfmathresult%
		\addtosavedmacro\cosecbeforearrowheadmiterangle%
		%
		% ...and before the arrow tip.
		%
		\pgfutil@tempdima-\arrowtipmiterangle pt\relax%
		\advance\pgfutil@tempdima90pt\relax%
		\pgfutil@tempdimb\beforearrowheadmiterangle pt\relax%
		\pgfutil@tempdimb2.0\pgfutil@tempdimb%
		\advance\pgfutil@tempdimb-90pt\relax%
		\advance\pgfutil@tempdima\pgfutil@tempdimb%
		\divide\pgfutil@tempdima2\relax%	
		\edef\beforearrowtipmiterangle{\pgfmath@tonumber{\pgfutil@tempdima}}%
		\addtosavedmacro\beforearrowtipmiterangle%
		\pgfmathcosec@{\beforearrowtipmiterangle}%
		\let\cosecbeforearrowtipmiterangle\pgfmathresult%
		\addtosavedmacro\cosecbeforearrowtipmiterangle%
	}
	\saveddimen\outerxsep{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
	}%
	\saveddimen\outerysep{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/outer ysep}}%
	}%
	%
	% Calculate the (path) point immediately prior to an arrow tip. 
	%
	\savedanchor\beforearrowtip{%
		\pgfmathparse{\pgfkeysvalueof{/pgf/arrow box tip angle}}%
		\pgfmathdivide@{\pgfmathresult}{2}%
		\pgfmathcot@{\pgfmathresult}%
		\let\cothalfangle\pgfmathresult%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/arrow box shaft width}}%
		\pgf@y.5\pgf@y%
		\pgfmathaddtolength\pgf@y{\pgfkeysvalueof{/pgf/arrow box head extend}}%
		\pgf@y\pgf@y%	
		\pgf@x\cothalfangle\pgf@y%	
	}%
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}%
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt\relax%
	}%
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+.5ex}%
	}%
	\anchor{center}{\centerpoint}
	\anchor{mid}{\midpoint}
	\anchor{mid east}{%
		\arrowboxpoints%
		\ifdim\eastextend>0pt\relax%
			\let\pgf@lib@shapes@arrowbox@referencepoint\midpoint%
			\csname pgf@anchor@arrow box@border\endcsname{\pgfqpoint{\eastextend}{0pt}};
		\else%
			\arrowboxcorner%
			\pgf@xa\pgf@x%
			\midpoint%
			\advance\pgf@x\pgf@xa%
		\fi%
	}
	\anchor{mid west}{%
		\arrowboxpoints%
		\ifdim\westextend>0pt\relax%
			\let\pgf@lib@shapes@arrowbox@referencepoint\midpoint%
			\csname pgf@anchor@arrow box@border\endcsname{\pgfqpoint{-\westextend}{0pt}};
		\else%
			\arrowboxcorner%
			\pgf@xa\pgf@x%
			\midpoint%
			\advance\pgf@x-\pgf@xa%
		\fi%
	}
	\anchor{base}{\basepoint}
	\anchor{base east}{%
		\arrowboxpoints%
		\ifdim\eastextend>0pt\relax%
			\let\pgf@lib@shapes@arrowbox@referencepoint\basepoint%
			\csname pgf@anchor@arrow box@border\endcsname{\pgfqpoint{\eastextend}{0pt}};
		\else%
			\arrowboxcorner%
			\pgf@xa\pgf@x%
			\basepoint%
			\advance\pgf@x\pgf@xa%
		\fi%
	}
	\anchor{base west}{%
		\arrowboxpoints%
		\ifdim\westextend>0pt\relax%
			\let\pgf@lib@shapes@arrowbox@referencepoint\basepoint%
			\csname pgf@anchor@arrow box@border\endcsname{\pgfqpoint{-\westextend}{0pt}};
		\else%
			\arrowboxcorner%
			\pgf@xa\pgf@x%
			\basepoint%
			\advance\pgf@x-\pgf@xa%
		\fi%
	}
	\anchor{north}{%
		\arrowboxpoints%
		\ifdim\northextend>0pt\relax%
			\csname pgf@anchor@arrow box@north arrow tip\endcsname%
		\else%
			\pgfpointadd{\centerpoint}{\arrowboxcorner}%
			\pgf@ya\pgf@y%
			\centerpoint%
			\pgf@y\pgf@ya%
		\fi%
	}%
	\anchor{south}{%
		\arrowboxpoints%
		\ifdim\southextend>0pt\relax%
			\csname pgf@anchor@arrow box@south arrow tip\endcsname%
		\else%
			\pgfpointadd{\centerpoint}{\arrowboxcorner\pgf@y-\pgf@y}%
			\pgf@ya\pgf@y%
			\centerpoint%
			\pgf@y\pgf@ya%
		\fi%
	}%
	\anchor{east}{%
		\arrowboxpoints%
		\ifdim\eastextend>0pt\relax%
			\csname pgf@anchor@arrow box@east arrow tip\endcsname%
		\else%
			\pgfpointadd{\centerpoint}{\arrowboxcorner}%
			\pgf@xa\pgf@x%
			\centerpoint%
			\pgf@x\pgf@xa%
		\fi%
	}%
	\anchor{west}{%
		\arrowboxpoints%
		\ifdim\westextend>0pt\relax%
			\csname pgf@anchor@arrow box@west arrow tip\endcsname%
		\else%
			\pgfpointadd{\centerpoint}{\arrowboxcorner\pgf@x-\pgf@x}%
			\pgf@xa\pgf@x%
			\centerpoint%
			\pgf@x\pgf@xa%
		\fi%
	}%
	\anchor{north east}{%
		\arrowboxpoints%
		\pgfpointadd{\centerpoint}{\arrowboxcorner}%
	}%
	\anchor{north west}{%
		\arrowboxpoints%
		\pgfpointadd{\centerpoint}{\arrowboxcorner\pgf@x-\pgf@x}%
	}%
	\anchor{south west}{%
		\arrowboxpoints%
		\pgfpointadd{\centerpoint}{\arrowboxcorner\pgf@x-\pgf@x\pgf@y-\pgf@y}%
	}%
	\anchor{south east}{%
		\arrowboxpoints%
		\pgfpointadd{\centerpoint}{\arrowboxcorner\pgf@y-\pgf@y}%
	}%
	\anchor{before east arrow}{%
		\arrowboxpoints%
		\ifdim\eastextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\arrowboxcorner%
				\pgf@y\shaftwidth\relax%
				\pgf@y.5\pgf@y%
				\advance\pgf@y\outerysep\relax%
			}%
		\else%
			\csname pgf@anchor@arrow box@east\endcsname%
		\fi%
	}%
	\anchor{before east arrow head}{%
		\arrowboxpoints%	
		\ifdim\eastextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\pgfpointadd{%
					\arrowheadangles%
					\pgfutil@tempdima-\beforearrowheadmiterangle pt\relax%
					\advance\pgfutil@tempdima180pt\relax%
					\pgfutil@tempdimb\outerxsep\relax%
					\pgfutil@tempdimb\cosecbeforearrowheadmiterangle\pgfutil@tempdimb%
					\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
				}%
				{%
					\beforearrowtip%
					\pgf@x-\pgf@x%
					\advance\pgf@x\eastextend\relax%
					\advance\pgf@x\arrowheadindent\relax%
					\pgf@y\shaftwidth\relax%
					\pgf@y.5\pgf@y%
				}%
			}%
		\else%
			\csname pgf@anchor@arrow box@east\endcsname%
		\fi%			
	}
	\anchor{before east arrow tip}{%
		\arrowboxpoints%
		\ifdim\eastextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\pgfpointadd{%
					\arrowheadangles%
					\pgfutil@tempdima-\arrowtipmiterangle pt\relax%
					\advance\pgfutil@tempdima-\beforearrowtipmiterangle pt\relax%
					\advance\pgfutil@tempdima180pt\relax%
					\pgfutil@tempdimb\outerysep\relax%
					\pgfutil@tempdimb\cosecbeforearrowtipmiterangle\pgfutil@tempdimb%
					\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
				}%
				{%
					\beforearrowtip%
					\pgf@x-\pgf@x%
					\advance\pgf@x\eastextend\relax%
				}%
			}%
		\else%
			\csname pgf@anchor@arrow box@east\endcsname%
		\fi%
	}
	\anchor{east arrow tip}{%
		\arrowboxpoints%
		\ifdim\eastextend>0pt\relax%
			\centerpoint%
			\advance\pgf@x\eastextend\relax%
			\pgf@xa\outerxsep\relax%
			\pgfmathcosec@{\arrowtipmiterangle}%
			\advance\pgf@x\pgfmathresult\pgf@xa%
		\else%
			\csname pgf@anchor@arrow box@east\endcsname%
		\fi%	
	}
	\anchor{after east arrow tip}{%
		\arrowboxpoints%
		\ifdim\eastextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\pgfpointadd{%
					\arrowheadangles%
					\pgfutil@tempdima-\arrowtipmiterangle pt\relax%
					\advance\pgfutil@tempdima-\beforearrowtipmiterangle pt\relax%
					\advance\pgfutil@tempdima180pt\relax%
					\pgfutil@tempdimb\outerysep\relax%
					\pgfutil@tempdimb\cosecbeforearrowtipmiterangle\pgfutil@tempdimb%
					\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
				}%
				{%
					\beforearrowtip%
					\pgf@x-\pgf@x%
					\advance\pgf@x\eastextend\relax%
				}%
				\pgf@y-\pgf@y%
			}%
		\else%
			\csname pgf@anchor@arrow box@east\endcsname%
		\fi%
	}
	\anchor{after east arrow head}{%
		\arrowboxpoints%
		\ifdim\eastextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\pgfpointadd{%
					\arrowheadangles%
					\pgfutil@tempdima-\beforearrowheadmiterangle pt\relax%
					\advance\pgfutil@tempdima180pt\relax%
					\pgfutil@tempdimb\outerxsep\relax%
					\pgfutil@tempdimb\cosecbeforearrowheadmiterangle\pgfutil@tempdimb%
					\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
				}%
				{%
					\beforearrowtip%
					\pgf@x-\pgf@x%
					\advance\pgf@x\eastextend\relax%
					\advance\pgf@x\arrowheadindent\relax%
					\pgf@y\shaftwidth\relax%
					\pgf@y.5\pgf@y%
				}%
				\pgf@y-\pgf@y%
			}%
		\else%
			\csname pgf@anchor@arrow box@east\endcsname%
		\fi%
	}
	\anchor{after east arrow}{%
		\arrowboxpoints%
		\ifdim\eastextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\arrowboxcorner%
				\pgf@y\shaftwidth\relax%
				\pgf@y.5\pgf@y%
				\advance\pgf@y\outerysep\relax%
				\pgf@y-\pgf@y%
			}%
		\else%
			\csname pgf@anchor@arrow box@east\endcsname%
		\fi%
	}%
	%
	\anchor{before west arrow}{%
		\arrowboxpoints%
		\ifdim\westextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\arrowboxcorner%
				\pgf@x-\pgf@x%
				\pgf@y\shaftwidth\relax%
				\pgf@y.5\pgf@y%
				\advance\pgf@y\outerysep\relax%
				\pgf@y-\pgf@y%
			}%
		\else%
			\csname pgf@anchor@arrow box@west\endcsname%
		\fi%
	}%
	\anchor{before west arrow head}{%
		\arrowboxpoints%
		\ifdim\westextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\pgfpointadd{%
					\arrowheadangles%
					\pgfutil@tempdima-\beforearrowheadmiterangle pt\relax%
					\advance\pgfutil@tempdima180pt\relax%
					\pgfutil@tempdimb\outerxsep\relax%
					\pgfutil@tempdimb\cosecbeforearrowheadmiterangle\pgfutil@tempdimb%
					\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
				}%
				{%
					\beforearrowtip%
					\pgf@x-\pgf@x%
					\advance\pgf@x\westextend\relax%
					\advance\pgf@x\arrowheadindent\relax%
					\pgf@y\shaftwidth\relax%
					\pgf@y.5\pgf@y%
				}%
				\pgf@x-\pgf@x%
				\pgf@y-\pgf@y%
			}%
		\else%
			\csname pgf@anchor@arrow box@west\endcsname%
		\fi%			
	}
	\anchor{before west arrow tip}{%
		\arrowboxpoints%
		\ifdim\westextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\pgfpointadd{%
					\arrowheadangles%
					\pgfutil@tempdima-\arrowtipmiterangle pt\relax%
					\advance\pgfutil@tempdima-\beforearrowtipmiterangle pt\relax%
					\advance\pgfutil@tempdima180pt\relax%
					\pgfutil@tempdimb\outerysep\relax%
					\pgfutil@tempdimb\cosecbeforearrowtipmiterangle\pgfutil@tempdimb%
					\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
				}%
				{%
					\beforearrowtip%
					\pgf@x-\pgf@x%
					\advance\pgf@x\westextend\relax%
				}%
				\pgf@x-\pgf@x%
				\pgf@y-\pgf@y%
			}%
		\else%
			\csname pgf@anchor@arrow box@west\endcsname%
		\fi%
	}
	\anchor{west arrow tip}{%
		\arrowboxpoints%
		\ifdim\westextend>0pt\relax%
			\centerpoint%
			\advance\pgf@x-\westextend\relax%
			\pgf@xa\outerxsep\relax%
			\pgfmathcosec@{\arrowtipmiterangle}%
			\advance\pgf@x-\pgfmathresult\pgf@xa%
		\else%
			\csname pgf@anchor@arrow box@west\endcsname%
		\fi%	
	}
	\anchor{after west arrow tip}{%
		\arrowboxpoints%
		\ifdim\westextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\pgfpointadd{%
					\arrowheadangles%
					\pgfutil@tempdima-\arrowtipmiterangle pt\relax%
					\advance\pgfutil@tempdima-\beforearrowtipmiterangle pt\relax%
					\advance\pgfutil@tempdima180pt\relax%
					\pgfutil@tempdimb\outerysep\relax%
					\pgfutil@tempdimb\cosecbeforearrowtipmiterangle\pgfutil@tempdimb%
					\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
				}%
				{%
					\beforearrowtip%
					\pgf@x-\pgf@x%
					\advance\pgf@x\westextend\relax%
				}%
				\pgf@x-\pgf@x%
			}%
		\else%
			\csname pgf@anchor@arrow box@west\endcsname%
		\fi%
	}
	\anchor{after west arrow head}{%
		\arrowboxpoints%
		\ifdim\westextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\pgfpointadd{%
					\arrowheadangles%
					\pgfutil@tempdima-\beforearrowheadmiterangle pt\relax%
					\advance\pgfutil@tempdima180pt\relax%
					\pgfutil@tempdimb\outerxsep\relax%
					\pgfutil@tempdimb\cosecbeforearrowheadmiterangle\pgfutil@tempdimb%
					\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
				}%
				{%
					\beforearrowtip%
					\pgf@x-\pgf@x%
					\advance\pgf@x\westextend\relax%
					\advance\pgf@x\arrowheadindent\relax%
					\pgf@y\shaftwidth\relax%
					\pgf@y.5\pgf@y%
				}%
				\pgf@x-\pgf@x%
			}%
		\else%
			\csname pgf@anchor@arrow box@west\endcsname%
		\fi%
	}
	\anchor{after west arrow}{%
		\arrowboxpoints%
		\ifdim\westextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\arrowboxcorner%
				\pgf@y\shaftwidth\relax%
				\pgf@y.5\pgf@y%
				\advance\pgf@y\outerysep\relax%
				\pgf@x-\pgf@x%
			}%
		\else%
			\csname pgf@anchor@arrow box@west\endcsname%
		\fi%
	}%
	%
	\anchor{before north arrow}{%
		\arrowboxpoints%
		\ifdim\northextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\arrowboxcorner%
				\pgf@x-\shaftwidth\relax%
				\pgf@x.5\pgf@x%
				\advance\pgf@x-\outerxsep\relax%
			}%
		\else%
			\csname pgf@anchor@arrow box@north\endcsname%
		\fi%
	}
	\anchor{before north arrow head}{%
		\arrowboxpoints%
		\ifdim\northextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\pgfpointadd{%
					\arrowheadangles%
					\pgfutil@tempdima-\beforearrowheadmiterangle pt\relax%
					\advance\pgfutil@tempdima270pt\relax%
					\pgfutil@tempdimb\outerysep\relax%
					\pgfutil@tempdimb\cosecbeforearrowheadmiterangle\pgfutil@tempdimb%
					\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
				}%
				{%
					\beforearrowtip%
					\pgf@y-\pgf@x%
					\advance\pgf@y\northextend\relax%
					\advance\pgf@y\arrowheadindent\relax%
					\pgf@x-\shaftwidth\relax%
					\pgf@x.5\pgf@x%
				}%
			}%
		\else%
			\csname pgf@anchor@arrow box@north\endcsname%
		\fi%			
	}
	\anchor{before north arrow tip}{%
		\arrowboxpoints%
		\ifdim\northextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\pgfpointadd{%
					\arrowheadangles%
					\pgfutil@tempdima\arrowtipmiterangle pt\relax%
					\advance\pgfutil@tempdima\beforearrowtipmiterangle pt\relax%
					\advance\pgfutil@tempdima-90pt\relax%
					\pgfutil@tempdimb\outerxsep\relax%
					\pgfutil@tempdimb\cosecbeforearrowtipmiterangle\pgfutil@tempdimb%
					\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
				}%
				{%
					\beforearrowtip%
					\pgf@xa\pgf@x%
					\pgf@x\pgf@y%
					\pgf@y-\pgf@xa%
					\advance\pgf@y\northextend\relax%
				}%
				\pgf@x-\pgf@x%
			}%
		\else%
			\csname pgf@anchor@arrow box@north\endcsname%
		\fi%
	}
	\anchor{north arrow tip}{%
		\arrowboxpoints%
		\ifdim\northextend>0pt\relax%
			\centerpoint%
			\advance\pgf@y\northextend\relax%
			\pgf@ya\outerysep\relax%
			\pgfmathcosec@{\arrowtipmiterangle}%
			\advance\pgf@y\pgfmathresult\pgf@ya%
		\else%
			\csname pgf@anchor@arrow box@north\endcsname%
		\fi%	
	}
	\anchor{after north arrow tip}{%
		\arrowboxpoints%
		\ifdim\northextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\pgfpointadd{%
					\arrowheadangles%
					\pgfutil@tempdima\arrowtipmiterangle pt\relax%
					\advance\pgfutil@tempdima\beforearrowtipmiterangle pt\relax%
					\advance\pgfutil@tempdima-90pt\relax%
					\pgfutil@tempdimb\outerxsep\relax%
					\pgfutil@tempdimb\cosecbeforearrowtipmiterangle\pgfutil@tempdimb%
					\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
				}%
				{%
					\beforearrowtip%
					\pgf@xa\pgf@x%
					\pgf@x\pgf@y%
					\pgf@y-\pgf@xa%
					\advance\pgf@y\northextend\relax%
				}%
			}%
		\else%
			\csname pgf@anchor@arrow box@north\endcsname%
		\fi%
		}
	\anchor{after north arrow head}{%
		\arrowboxpoints%
		\ifdim\northextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\pgfpointadd{%
					\arrowheadangles%
					\pgfutil@tempdima-\beforearrowheadmiterangle pt\relax%
					\advance\pgfutil@tempdima270pt\relax%
					\pgfutil@tempdimb\outerysep\relax%
					\pgfutil@tempdimb\cosecbeforearrowheadmiterangle\pgfutil@tempdimb%
					\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
				}%
				{%
					\beforearrowtip%
					\pgf@y-\pgf@x%
					\advance\pgf@y\northextend\relax%
					\advance\pgf@y\arrowheadindent\relax%
					\pgf@x-\shaftwidth\relax%
					\pgf@x.5\pgf@x%
				}%
				\pgf@x-\pgf@x%
			}%
		\else%
			\csname pgf@anchor@arrow box@north\endcsname%
		\fi%	
		}
	\anchor{after north arrow}{%
		\arrowboxpoints%
		\ifdim\northextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\arrowboxcorner%
				\pgf@x\shaftwidth\relax%
				\pgf@x.5\pgf@x%
				\advance\pgf@x\outerxsep\relax%
			}%
		\else%
			\csname pgf@anchor@arrow box@north\endcsname%
		\fi%
	}
	%
	\anchor{before south arrow}{%
		\arrowboxpoints%
		\ifdim\southextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\arrowboxcorner%
				\pgf@x\shaftwidth\relax%
				\pgf@x.5\pgf@x%
				\advance\pgf@x\outerxsep\relax%
				\pgf@y-\pgf@y%
			}%
		\else%
			\csname pgf@anchor@arrow box@south\endcsname%
		\fi%
	}%
	\anchor{before south arrow head}{%
		\arrowboxpoints%
		\ifdim\northextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\pgfpointadd{%
					\arrowheadangles%
					\pgfutil@tempdima-\beforearrowheadmiterangle pt\relax%
					\advance\pgfutil@tempdima270pt\relax%
					\pgfutil@tempdimb\outerysep\relax%
					\pgfutil@tempdimb\cosecbeforearrowheadmiterangle\pgfutil@tempdimb%
					\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
				}%
				{%
					\beforearrowtip%
					\pgf@y-\pgf@x%
					\advance\pgf@y\northextend\relax%
					\advance\pgf@y\arrowheadindent\relax%
					\pgf@x-\shaftwidth\relax%
					\pgf@x.5\pgf@x%
				}%
				\pgf@x-\pgf@x%
				\pgf@y-\pgf@y%
			}%
		\else%
			\csname pgf@anchor@arrow box@south\endcsname%
		\fi%	
		}
	\anchor{before south arrow tip}{%
		\arrowboxpoints%
		\ifdim\northextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\pgfpointadd{%
					\arrowheadangles%
					\pgfutil@tempdima\arrowtipmiterangle pt\relax%
					\advance\pgfutil@tempdima\beforearrowtipmiterangle pt\relax%
					\advance\pgfutil@tempdima-90pt\relax%
					\pgfutil@tempdimb\outerxsep\relax%
					\pgfutil@tempdimb\cosecbeforearrowtipmiterangle\pgfutil@tempdimb%
					\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
				}%
				{%
					\beforearrowtip%
					\pgf@xa\pgf@x%
					\pgf@x\pgf@y%
					\pgf@y-\pgf@xa%
					\advance\pgf@y\northextend\relax%
				}%
				\pgf@y-\pgf@y%
			}%
		\else%
			\csname pgf@anchor@arrow box@south\endcsname%
		\fi%
		}
	\anchor{south arrow tip}{%
		\arrowboxpoints%
		\ifdim\southextend>0pt\relax%
			\centerpoint%
			\advance\pgf@y-\southextend\relax%
			\pgf@ya\outerysep\relax%
			\pgfmathcosec@{\arrowtipmiterangle}%
			\advance\pgf@y-\pgfmathresult\pgf@ya%
		\else%
			\csname pgf@anchor@arrow box@east\endcsname%
		\fi%	
	}
	\anchor{after south arrow tip}{%
		\arrowboxpoints%
		\ifdim\northextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\pgfpointadd{%
					\arrowheadangles%
					\pgfutil@tempdima\arrowtipmiterangle pt\relax%
					\advance\pgfutil@tempdima\beforearrowtipmiterangle pt\relax%
					\advance\pgfutil@tempdima-90pt\relax%
					\pgfutil@tempdimb\outerxsep\relax%
					\pgfutil@tempdimb\cosecbeforearrowtipmiterangle\pgfutil@tempdimb%
					\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
				}%
				{%
					\beforearrowtip%
					\pgf@xa\pgf@x%
					\pgf@x\pgf@y%
					\pgf@y-\pgf@xa%
					\advance\pgf@y\northextend\relax%
				}%
				\pgf@x-\pgf@x%
				\pgf@y-\pgf@y%
			}%
		\else%
			\csname pgf@anchor@arrow box@south\endcsname%
		\fi%
		}
	\anchor{after south arrow head}{%
		\arrowboxpoints%
		\ifdim\northextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\pgfpointadd{%
					\arrowheadangles%
					\pgfutil@tempdima-\beforearrowheadmiterangle pt\relax%
					\advance\pgfutil@tempdima270pt\relax%
					\pgfutil@tempdimb\outerysep\relax%
					\pgfutil@tempdimb\cosecbeforearrowheadmiterangle\pgfutil@tempdimb%
					\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
				}%
				{%
					\beforearrowtip%
					\pgf@y-\pgf@x%
					\advance\pgf@y\northextend\relax%
					\advance\pgf@y\arrowheadindent\relax%
					\pgf@x-\shaftwidth\relax%
					\pgf@x.5\pgf@x%
				}%
				\pgf@y-\pgf@y%
			}%
		\else%
			\csname pgf@anchor@arrow box@south\endcsname%
		\fi%	
		}
	\anchor{after south arrow}{%
		\arrowboxpoints%
		\ifdim\southextend>0pt\relax%
			\pgfpointadd{\centerpoint}{%
				\arrowboxcorner%
				\pgf@x-\shaftwidth\relax%
				\pgf@x.5\pgf@x%
				\advance\pgf@x-\outerxsep\relax%
				\pgf@y-\pgf@y%
			}%
		\else%
			\csname pgf@anchor@arrow box@south\endcsname%
		\fi%
	}%
	%
	\backgroundpath{%
		\arrowboxpoints%
		\pgfextract@process\arrowboxcorner{%
			\arrowboxcorner%
			\pgfmathaddtolength\pgf@x{-\pgfkeysvalueof{/pgf/outer xsep}}%
			\pgfmathaddtolength\pgf@y{-\pgfkeysvalueof{/pgf/outer ysep}}%
		}%
		{%
			\pgftransformshift{\centerpoint}%
			\pgfpathmoveto{\arrowboxcorner}%
			\ifdim\eastextend>0pt\relax%
				\pgfpathlineto{%
					\arrowboxcorner%
					\pgf@y\shaftwidth\relax%
					\pgf@y.5\pgf@y%
				}%
				\pgfpathlineto{%
					\beforearrowtip%
					\pgf@x-\pgf@x%
					\advance\pgf@x\eastextend\relax%
					\advance\pgf@x\arrowheadindent\relax%
					\pgf@y\shaftwidth\relax%
					\pgf@y.5\pgf@y%
				}%
				\pgfpathlineto{%
					\beforearrowtip%
					\pgf@x-\pgf@x%
					\advance\pgf@x\eastextend\relax%
				}%
				\pgfpathlineto{%
					\pgf@x\eastextend\relax%
					\pgf@y0pt\relax%
				}%
				\pgfpathlineto{%
					\beforearrowtip%
					\pgf@x-\pgf@x%
					\advance\pgf@x\eastextend\relax%
					\pgf@y-\pgf@y%
				}%
				\pgfpathlineto{%
					\beforearrowtip%
					\pgf@x-\pgf@x%
					\advance\pgf@x\eastextend\relax%
					\advance\pgf@x\arrowheadindent\relax%
					\pgf@y\shaftwidth\relax%
					\pgf@y-.5\pgf@y%
				}%
				\pgfpathlineto{%
					\arrowboxcorner%
					\pgf@y\shaftwidth\relax%
					\pgf@y-.5\pgf@y%
				}%
			\fi%
			\pgfpathlineto{\arrowboxcorner\pgf@y-\pgf@y}%
			\ifdim\southextend>0pt\relax%
				\pgfpathlineto{%
					\arrowboxcorner%
					\pgf@x\shaftwidth\relax%
					\pgf@x.5\pgf@x%
					\pgf@y-\pgf@y%
				}%
				\pgfpathlineto{%
					\beforearrowtip%
					\pgf@y\pgf@x%
					\advance\pgf@y-\southextend\relax%
					\advance\pgf@y-\arrowheadindent\relax%
					\pgf@x\shaftwidth\relax%
					\pgf@x.5\pgf@x%
				}%
				\pgfpathlineto{%
					\beforearrowtip%
					\pgf@xa\pgf@y%
					\pgf@y\pgf@x%
					\advance\pgf@y-\southextend\relax%
					\pgf@x\pgf@xa%
				}%
				\pgfpathlineto{%
					\pgf@x0pt\relax%
					\pgf@y-\southextend\relax%
				}%
				\pgfpathlineto{%
					\beforearrowtip%
					\pgf@xa\pgf@y%
					\pgf@y\pgf@x%
					\advance\pgf@y-\southextend\relax%
					\pgf@x-\pgf@xa%
				}%
				\pgfpathlineto{%
					\beforearrowtip%
					\pgf@y\pgf@x%
					\advance\pgf@y-\southextend\relax%
					\advance\pgf@y-\arrowheadindent\relax%
					\pgf@x\shaftwidth\relax%
					\pgf@x-.5\pgf@x%
				}%
				\pgfpathlineto{%
					\arrowboxcorner%
					\pgf@x\shaftwidth\relax%
					\pgf@x-.5\pgf@x%
					\pgf@y-\pgf@y%
				}%
			\fi%
			\pgfpathlineto{\arrowboxcorner\pgf@x-\pgf@x\pgf@y-\pgf@y}%
			\ifdim\westextend>0pt\relax%
				\pgfpathlineto{%
					\arrowboxcorner%
					\pgf@x-\pgf@x
					\pgf@y\shaftwidth\relax%
					\pgf@y-.5\pgf@y%
				}%
				\pgfpathlineto{%
					\beforearrowtip%
					\advance\pgf@x-\westextend\relax%
					\advance\pgf@x-\arrowheadindent\relax%
					\pgf@y\shaftwidth\relax%
					\pgf@y-.5\pgf@y%
				}%
				\pgfpathlineto{%
					\beforearrowtip%
					\advance\pgf@x-\westextend\relax%
					\pgf@y-\pgf@y%
				}%
				\pgfpathlineto{%
					\pgf@x-\westextend\relax%
					\pgf@y0pt\relax%
				}%
				\pgfpathlineto{%
					\beforearrowtip%
					\advance\pgf@x-\westextend\relax%
				}%
				\pgfpathlineto{%
					\beforearrowtip%
					\advance\pgf@x-\westextend\relax%
					\advance\pgf@x-\arrowheadindent\relax%
					\pgf@y\shaftwidth\relax%
					\pgf@y.5\pgf@y%
				}%
				\pgfpathlineto{%
					\arrowboxcorner%
					\pgf@x-\pgf@x%
					\pgf@y\shaftwidth\relax%
					\pgf@y.5\pgf@y%
				}%
			\fi%
			\pgfpathlineto{\arrowboxcorner\pgf@x-\pgf@x}%
			\ifdim\northextend>0pt\relax%
				\pgfpathlineto{%
					\arrowboxcorner%
					\pgf@x\shaftwidth\relax%
					\pgf@x-.5\pgf@x%
				}%
				\pgfpathlineto{%
					\beforearrowtip%
					\pgf@y-\pgf@x%
					\advance\pgf@y\northextend\relax%
					\advance\pgf@y\arrowheadindent\relax%
					\pgf@x\shaftwidth\relax%
					\pgf@x-.5\pgf@x%
				}%
				\pgfpathlineto{%
					\beforearrowtip%
					\pgf@xa\pgf@y%
					\pgf@y-\pgf@x%
					\advance\pgf@y\northextend\relax%
					\pgf@x-\pgf@xa%
				}%
				\pgfpathlineto{%
					\pgf@x0pt\relax%
					\pgf@y\northextend\relax%
				}%
				\pgfpathlineto{%
					\beforearrowtip%
					\pgf@xa\pgf@y%
					\pgf@y-\pgf@x%
					\advance\pgf@y\northextend\relax%
					\pgf@x\pgf@xa%
				}%
				\pgfpathlineto{%
					\beforearrowtip%
					\pgf@y-\pgf@x%
					\advance\pgf@y\northextend\relax%
					\advance\pgf@y\arrowheadindent\relax%
					\pgf@x\shaftwidth\relax%
					\pgf@x.5\pgf@x%
				}%				
				\pgfpathlineto{%
					\arrowboxcorner%
					\pgf@x\shaftwidth\relax%
					\pgf@x.5\pgf@x%
				}%
			\fi%
			\pgfpathclose%	
		}%
	}
	\anchorborder{%
		\pgfextract@process\externalpoint{}%
		\pgfutil@ifundefined{pgf@lib@shapes@arrowbox@referencepoint}%
			{\let\referencepoint\centerpoint}{\let\referencepoint\pgf@lib@shapes@arrowbox@referencepoint}%
		\pgfextract@process\externalpoint{%
			\pgfpointadd{\referencepoint}{\externalpoint}%
		}%
		\pgfmathanglebetweenpoints{\centerpoint}{\externalpoint}%
		\let\externalangle\pgfmathresult%
		\pgfmathanglebetweenpoints{\referencepoint}%
			{\csname pgf@anchor@arrow box@west\endcsname}%
		\ifdim\externalangle pt<\pgfmathresult pt\relax%
			\pgfmathanglebetweenpoints{\referencepoint}%
				{\csname pgf@anchor@arrow box@north\endcsname}%
			\ifdim\externalangle pt<\pgfmathresult pt\relax%
				\pgfmathanglebetweenpoints{\referencepoint}%
					{\csname pgf@anchor@arrow box@north east\endcsname}%
				\ifdim\externalangle pt<\pgfmathresult pt\relax%
					\pgfmathanglebetweenpoints{\referencepoint}%
						{\csname pgf@anchor@arrow box@before east arrow tip\endcsname}%
					\ifdim\externalangle pt<\pgfmathresult pt\relax%
						\def\firstpoint{east arrow tip}%
						\def\secondpoint{before east arrow tip}%
					\else%
						\pgfmathanglebetweenpoints{\referencepoint}%
							{\csname pgf@anchor@arrow box@before east arrow\endcsname}%
						\ifdim\externalangle pt<\pgfmathresult pt\relax%
							\def\firstpoint{before east arrow head}%
							\def\secondpoint{before east arrow}%
						\else%
							\def\firstpoint{before east arrow}%
							\def\secondpoint{north east}%
						\fi%
					\fi%
				\else%
					\pgfmathanglebetweenpoints{\referencepoint}%
						{\csname pgf@anchor@arrow box@after north arrow tip\endcsname}%
					\ifdim\externalangle pt<\pgfmathresult pt\relax%
						\pgfmathanglebetweenpoints{\referencepoint}%
							{\csname pgf@anchor@arrow box@after north arrow\endcsname}%
						\ifdim\externalangle pt<\pgfmathresult pt\relax%
							\def\firstpoint{north east}%
							\def\secondpoint{after north arrow}%
						\else%
							\def\firstpoint{after north arrow}%
							\def\secondpoint{after north arrow head}%
						\fi%
					\else%
						\def\firstpoint{after north arrow tip}%
						\def\secondpoint{north arrow tip}%
					\fi%
				\fi%
			\else%	
				\pgfmathanglebetweenpoints{\referencepoint}%
					{\csname pgf@anchor@arrow box@north west\endcsname}%
				\ifdim\externalangle pt<\pgfmathresult pt\relax%
					\pgfmathanglebetweenpoints{\referencepoint}%
						{\csname pgf@anchor@arrow box@before north arrow tip\endcsname}%
					\ifdim\externalangle pt<\pgfmathresult pt\relax%
						\def\firstpoint{north arrow tip}%
						\def\secondpoint{before north arrow tip}%
					\else%
						\pgfmathanglebetweenpoints{\referencepoint}%
							{\csname pgf@anchor@arrow box@before north arrow\endcsname}%
						\ifdim\externalangle pt<\pgfmathresult pt\relax%
							\def\firstpoint{before north head}%
							\def\secondpoint{before north arrow}%
						\else%
							\def\firstpoint{before north arrow}%
							\def\secondpoint{north west}%
						\fi%
					\fi%
				\else%
					\pgfmathanglebetweenpoints{\referencepoint}%
						{\csname pgf@anchor@arrow box@after west arrow tip\endcsname}%
					\ifdim\externalangle pt<\pgfmathresult pt\relax%
						\pgfmathanglebetweenpoints{\referencepoint}%
							{\csname pgf@anchor@arrow box@after west arrow\endcsname}%
						\ifdim\externalangle pt<\pgfmathresult pt\relax%
							\def\firstpoint{north west}%
							\def\secondpoint{after west arrow}%
						\else%
							\def\firstpoint{after west arrow}%
							\def\secondpoint{after west arrow head}%
						\fi%
					\else%
						\def\firstpoint{after west arrow tip}%
						\def\secondpoint{west arrow tip}%
					\fi%
				\fi%
			\fi%
		\else%
			\pgfmathanglebetweenpoints{\referencepoint}%
				{\csname pgf@anchor@arrow box@south arrow tip\endcsname}%
			\ifdim\externalangle pt<\pgfmathresult pt\relax%
				\pgfmathanglebetweenpoints{\referencepoint}%
					{\csname pgf@anchor@arrow box@south west\endcsname}%
				\ifdim\externalangle pt<\pgfmathresult pt\relax%
					\pgfmathanglebetweenpoints{\referencepoint}%
						{\csname pgf@anchor@arrow box@before west arrow tip\endcsname}%
					\ifdim\externalangle pt<\pgfmathresult pt\relax%
						\def\firstpoint{west arrow tip}%
						\def\secondpoint{before west arrow tip}%
					\else%
						\pgfmathanglebetweenpoints{\referencepoint}%
							{\csname pgf@anchor@arrow box@before west arrow\endcsname}%
						\ifdim\externalangle pt<\pgfmathresult pt\relax%
							\def\firstpoint{before west arrow head}%
							\def\secondpoint{before west arrow}%
						\else%
							\def\firstpoint{before west arrow}%
							\def\secondpoint{south west}%
						\fi%
					\fi%
				\else%
					\pgfmathanglebetweenpoints{\referencepoint}%
						{\csname pgf@anchor@arrow box@after south arrow tip\endcsname}%
					\ifdim\externalangle pt<\pgfmathresult pt\relax%
						\pgfmathanglebetweenpoints{\referencepoint}%
							{\csname pgf@anchor@arrow box@after south arrow\endcsname}%
						\ifdim\externalangle pt<\pgfmathresult pt\relax%
							\def\firstpoint{south west}%
							\def\secondpoint{after south arrow}%
						\else%
							\def\firstpoint{after south arrow}%
							\def\secondpoint{after south arrow head}%
						\fi%
					\else%
						\def\firstpoint{after south arrow tip}%
						\def\secondpoint{south arrow tip}%
					\fi%
				\fi%
			\else%
				\pgfmathanglebetweenpoints{\referencepoint}%
					{\csname pgf@anchor@arrow box@south east\endcsname}%
				\ifdim\externalangle pt<\pgfmathresult pt\relax%
					\pgfmathanglebetweenpoints{\referencepoint}%
						{\csname pgf@anchor@arrow box@before south arrow tip\endcsname}%
					\ifdim\externalangle pt<\pgfmathresult pt\relax%
						\def\firstpoint{south arrow tip}%
						\def\secondpoint{before south arrow tip}%
					\else%
						\pgfmathanglebetweenpoints{\referencepoint}%
							{\csname pgf@anchor@arrow box@before south arrow\endcsname}%
						\ifdim\externalangle pt<\pgfmathresult pt\relax%
							\def\firstpoint{before south arrow head}%
							\def\secondpoint{before south arrow}%
						\else%
							\def\firstpoint{before south arrow}%
							\def\secondpoint{south east}%
						\fi%
					\fi%
				\else%
					\pgfmathanglebetweenpoints{\referencepoint}%
						{\csname pgf@anchor@arrow box@after east arrow tip\endcsname}%
					\ifdim\externalangle pt<\pgfmathresult pt\relax%
						\pgfmathanglebetweenpoints{\referencepoint}%
							{\csname pgf@anchor@arrow box@after east arrow\endcsname}%
						\ifdim\externalangle pt<\pgfmathresult pt\relax%
							\def\firstpoint{south east}%
							\def\secondpoint{after east arrow}%
						\else%
							\def\firstpoint{after east arrow}%
							\def\secondpoint{after east arrow head}%
						\fi%
					\else%
						\def\firstpoint{after east arrow tip}%
						\def\secondpoint{east arrow tip}%
					\fi%
				\fi%
			\fi%
		\fi%
		\pgfpointintersectionoflines{\referencepoint}{\externalpoint}%
			{\csname pgf@anchor@arrow box@\firstpoint\endcsname}%
			{\csname pgf@anchor@arrow box@\secondpoint\endcsname}%					
	}
}


		
 
\endinput

pgflibraryshapes.callouts.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.

\usepgflibrary{shapes.symbols}

% Keys for callouts
%
% Common to all callouts:
%	/pgf/callout absolute pointer
%	/pgf/callout relative pointer
%
% ellipse callout only:
%	/pgf/callout pointer arc    
%
% rectangle callout only:    
%	/pgf/callout pointer width      
%
% cloud callout only:
%	/pgf/callout pointer start size
%	/pgf/callout pointer end size
%	/pgf/callout pointer segments
%
\newif\ifpgf@lib@callout@absolutepointer
\pgfkeys{/pgf/.cd,
	callout pointer arc/.initial=15,
	callout pointer width/.initial=.25cm,
	callout pointer start size/.initial=.2 of callout,
	callout pointer end size/.initial=.1 of callout,
	callout pointer segments/.initial=2,
	callout absolute pointer/.code={\pgf@lib@callout@makeabsolutepointer{#1}},
	callout relative pointer/.code={\pgf@lib@callout@makerelativepointer{#1}},
	callout pointer shorten/.initial=0cm
}



\def\pgf@lib@callout@makeabsolutepointer#1{%
	\pgf@lib@callout@absolutepointertrue%
	{%
		\pgftransformshift{#1}%
		\pgfmultipartnode{coordinate}{center}{pgf@lib@callout@pointer}{}%
	}%
}

\def\pgf@lib@callout@makerelativepointer#1{%
	\pgf@lib@callout@absolutepointerfalse%
	\def\pgf@lib@callout@relativepointer{#1}%
}
\pgfkeys{/pgf/callout relative pointer=\pgfpointpolar{300}{.5cm}}


% Shape ellipse callout
%
%
\pgfdeclareshape{ellipse callout}{%
	\savedmacro\ellipsecalloutpoints{%
		%
		% Get the larger of the outer sep.
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/outer ysep}}%
		\ifdim\pgf@x>\pgf@y%
			\edef\outersep{\the\pgf@x}%
		\else%
			\edef\outersep{\the\pgf@y}%
		\fi%
		\addtosavedmacro\outersep%
		%
		% Calculate the node dimensions...
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
		\advance\pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@x1.4142136\pgf@x%
    \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/minimum width}}%
    \ifdim\pgf@x<.5\pgf@xa%
      \pgf@x.5\pgf@xa%
    \fi%
    %
   	\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%    
		\advance\pgf@y.5\ht\pgfnodeparttextbox%
    \advance\pgf@y.5\dp\pgfnodeparttextbox%
    \pgf@y1.4142136\pgf@y%
    \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/minimum height}}%
    \ifdim\pgf@y<.5\pgf@ya%
      \pgf@y.5\pgf@ya%
    \fi%
    %
    % ...without outer sep...
    %
    \edef\xpathradius{\the\pgf@x}%
    \edef\ypathradius{\the\pgf@y}%
    %
    % ...and width outer sep.
    %
    \pgfmathaddtolength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
    \edef\xradius{\the\pgf@x}%
    \pgfmathaddtolength\pgf@y{\pgfkeysvalueof{/pgf/outer ysep}}%
    \edef\yradius{\the\pgf@y}%
    %
    \addtosavedmacro\xradius%
    \addtosavedmacro\xpathradius%
    \addtosavedmacro\yradius% 
    \addtosavedmacro\ypathradius%
  	%
	  \pgfmathsetmacro\pointerarc{\pgfkeysvalueof{/pgf/callout pointer arc}}%
		\addtosavedmacro\pointerarc%
	  %
	  \pgfextract@process\centerpoint{%
	    \pgf@x.5\wd\pgfnodeparttextbox%
	    \pgf@y.5\ht\pgfnodeparttextbox%
	    \advance\pgf@y-.5\dp\pgfnodeparttextbox%
	  }%
	  %
	  % Get the realtive pointer.
	  %
	  \ifpgf@lib@callout@absolutepointer%
	  \else%
	   	\pgfextract@process\calloutpointer{%
				\pgfextract@process\borderpoint{%
					\expandafter\pgfpointborderellipse\expandafter{\pgf@lib@callout@relativepointer}{\pgfqpoint{\xpathradius}{\ypathradius}}%
				}%
				\pgfmathanglebetweenpoints{\pgfpointorigin}{\borderpoint}%
				\let\pointerangle\pgfmathresult%
				\expandafter\pgf@process\expandafter{\pgf@lib@callout@relativepointer}%
				\pgfmathveclen@{\pgfmath@tonumber{\pgf@x}}{\pgfmath@tonumber{\pgf@y}}%
				\edef\pointerradius{\pgfmathresult pt}%
				\pgfpointadd{\borderpoint}{\pgfqpointpolar{\pointerangle}{\pointerradius}}%
				\pgf@xa\pgf@x%
				\pgf@ya\pgf@y%
				\centerpoint%
				\advance\pgf@x\pgf@xa%
				\advance\pgf@y\pgf@ya%
			}%
			%
			\addtosavedmacro\calloutpointer%
			\pgf@lib@callouts@shortenpointer%
			\pgf@lib@ellipsecallout@getpoints%
	  	\addtosavedmacro\calloutpointeranchor%
	  	\addtosavedmacro\beforecalloutangle%
	  	\addtosavedmacro\aftercalloutangle%
  	\fi%
  }%
  \savedanchor\centerpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y.5\ht\pgfnodeparttextbox%
    \advance\pgf@y-.5\dp\pgfnodeparttextbox%
  }
  \savedanchor\midpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@y{+.5ex}%
  }
  \savedanchor\basepoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y0pt\relax%
  }
  \anchor{center}{\centerpoint}%
  \anchor{mid}{\midpoint}%
  \anchor{mid east}{%
  	\ellipsecalloutpoints%
  	\pgfmathpointintersectionoflineandarc{\midpoint\advance\pgf@x\xradius}{\midpoint}%
  		{\centerpoint}{270}{450}{\xradius and \yradius}%
  }%
  \anchor{mid west}{%
  	\ellipsecalloutpoints%
  	\pgfmathpointintersectionoflineandarc{\midpoint\advance\pgf@x-\xradius}{\midpoint}%
  		{\centerpoint}{90}{270}{\xradius and \yradius}%
  }%
  \anchor{base}{\basepoint}%
  \anchor{base east}{%
  	\ellipsecalloutpoints%
  	\pgfmathpointintersectionoflineandarc{\basepoint\advance\pgf@x\xradius}{\basepoint}%
  		{\centerpoint}{270}{450}{\xradius and \yradius}%
  }%
  \anchor{base west}{%
  	\ellipsecalloutpoints%
  	\pgfmathpointintersectionoflineandarc{\basepoint\advance\pgf@x-\xradius}{\basepoint}%
  		{\centerpoint}{90}{270}{\xradius and \yradius}%
  }%
  \anchor{north}{%
  	\ellipsecalloutpoints%
  	\centerpoint%
  	\advance\pgf@y\yradius\relax%
  }
  \anchor{south}{%
  	\ellipsecalloutpoints%
  	\centerpoint%
  	\advance\pgf@y-\yradius\relax%
  }
  \anchor{east}{%
  	\ellipsecalloutpoints%
  	\centerpoint%
  	\advance\pgf@x\xradius\relax%
  }
  \anchor{west}{%
  	\ellipsecalloutpoints%
  	\centerpoint%
  	\advance\pgf@x-\xradius\relax%
  }
  \anchor{north west}{%
  	\ellipsecalloutpoints%
  	\pgf@xa\xradius\relax%
  	\pgf@ya\yradius\relax%
  	\centerpoint%
  	\advance\pgf@y0.7071067\pgf@ya%
  	\advance\pgf@x-0.7071067\pgf@xa%
  }
  \anchor{north east}{%
  	\ellipsecalloutpoints%
  	\pgf@xa\xradius\relax%
  	\pgf@ya\yradius\relax%
  	\centerpoint%
  	\advance\pgf@y0.7071067\pgf@ya%
  	\advance\pgf@x0.7071067\pgf@xa%
  }
  \anchor{south west}{%
  	\ellipsecalloutpoints%
  	\pgf@xa\xradius\relax%
  	\pgf@ya\yradius\relax%
  	\centerpoint%
  	\advance\pgf@y-0.7071067\pgf@ya%
  	\advance\pgf@x-0.7071067\pgf@xa%
  }
  \anchor{south east}{%
  	\ellipsecalloutpoints%
  	\pgf@xa\xradius\relax%
  	\pgf@ya\yradius\relax%
  	\centerpoint%
  	\advance\pgf@y-0.7071067\pgf@ya%
  	\advance\pgf@x0.7071067\pgf@xa%
  }
  \anchor{pointer}{%
  	\ellipsecalloutpoints%
  	\calloutpointeranchor%
	}%
  \backgroundpath{%
  	\ellipsecalloutpoints%
   	\ifpgf@lib@callout@absolutepointer%
   		\pgfextract@process\calloutpointer{%
				\pgfpointanchor{pgf@lib@callout@pointer}{center}%
			}%
			\pgf@lib@callouts@shortenpointer%
			\pgf@lib@ellipsecallout@getpoints%	
			\calloutpointeranchor%	
			\ifx\pgf@node@name\pgfutil@empty%
			\else%
				\edef\pgf@sh@@temp{\noexpand\expandafter\noexpand\pgfutil@g@addto@macro\noexpand\csname pgf@sh@np@\pgf@node@name\noexpand\endcsname}%
				\edef\pgf@sh@@@temp{%
					\noexpand\def\noexpand\calloutpointeranchor{%
						\noexpand\pgf@x\the\pgf@x%
						\noexpand\pgf@y\the\pgf@y%
					}%
				}%
				\expandafter\pgf@sh@@temp\expandafter{\pgf@sh@@@temp}
			\fi%
		\fi%
		\pgfpathmoveto{\calloutpointer}%
		\pgfpathlineto{\aftercalloutpointer}%
		\ifdim\aftercalloutangle pt<\beforecalloutangle pt\relax%
			\pgfpatharc{\aftercalloutangle}{\beforecalloutangle}{\xpathradius and \ypathradius}%
		\else%
			\pgfpatharc{\aftercalloutangle}{360}{\xpathradius and \ypathradius}%
			\pgfpatharc{0}{\beforecalloutangle}{\xpathradius and \ypathradius}%
		\fi%
		\pgfpathclose%
  }%    
  \anchorborder{%
  	\pgfextract@process\externalpoint{}%
  	\ellipsecalloutpoints%
   	\pgfpointadd{\pgfpointborderellipse{\externalpoint}{\pgfpoint{\xradius}{\yradius}}%
  	}{\centerpoint}%  		
  }%
}

% Internal macro for calculating the points for the
% ellipse callout pointer.
%
% The following must be set up:
%
% \centerpoint    - the center of the ellipse.
% \calloutpointer - the location of the callout point.
% \pointerarc     - the width of the pointer.
% \xpathradius    - the x radius of the ellipse.
% \ypathradius    - the y radius of the ellipse.
%
\def\pgf@lib@ellipsecallout@getpoints{%
	\pgfextract@process\borderpoint{%
		\pgfpointborderellipse{%
			\centerpoint%
			\pgf@xa\pgf@x%
			\pgf@ya\pgf@y%
			\calloutpointer%
			\advance\pgf@x-\pgf@xa%
			\advance\pgf@y-\pgf@ya%
		}{\pgfqpoint{\xpathradius}{\ypathradius}}%
	}%
	\pgfmathangleonellipse{\borderpoint}{\xpathradius and \ypathradius}%
	\pgfutil@tempdima\pointerarc pt\relax%
	\pgfutil@tempdimb\pgfmathresult pt\relax%
	\advance\pgfutil@tempdimb-.5\pgfutil@tempdima%
	\ifdim\pgfutil@tempdimb<0pt\relax%
		\advance\pgfutil@tempdimb360pt\relax%
	\fi%
	\edef\beforecalloutangle{\pgfmath@tonumber{\pgfutil@tempdimb}}%
	\advance\pgfutil@tempdimb\pgfutil@tempdima%
	\ifdim\pgfutil@tempdimb<360pt\relax%
	\else%
		\advance\pgfutil@tempdimb-360pt\relax%
	\fi%
	\edef\aftercalloutangle{\pgfmath@tonumber{\pgfutil@tempdimb}}%	
	%
	\pgfextract@process\beforecalloutpointer{%
		\pgfpointadd{\centerpoint}{%
			\pgfpointpolar{\beforecalloutangle}{\xpathradius and \ypathradius}%
		}%
	}%
	\pgfextract@process\aftercalloutpointer{%
		\pgfpointadd{\centerpoint}{%
			\pgfpointpolar{\aftercalloutangle}{\xpathradius and \ypathradius}%
		}%
	}%
	%
	% Calculate the pointer anchor.
	%
	\pgf@lib@callouts@pointeranchor%
}


% If the callout pointer is very pointed and stroked, the anchor will be 
% miles away from the end of the pointer which will (typically) be
% bevelled. 
% Using outer sep=0pt is one solution, however, another is provided
% using this special key:
%
% /pgf/callout pointer anchor aspect
% 
% which takes a value from 0 (ignore any outer sep) to 1 (use
% the full outer sep).

\pgfkeys{/pgf/callout pointer anchor aspect/.initial=1}

% Internal macro for calculating the anchor for the callout pointer.
%
% Requires the following to be set up (points are anti-clockwise)
%
% \beforecalloutpointer - point on the border before the callout pointer 
% \calloutpointer    
% \aftercalloutpointer  - point on the border after the callout pointer
% \outersep             - the largest of the outer xsep or ysep.
%
\def\pgf@lib@callouts@pointeranchor{%
	\pgfutil@tempdimb\outersep\relax%
	%
	\pgfmathanglebetweenlines{\calloutpointer}{\aftercalloutpointer}{\calloutpointer}{\beforecalloutpointer}%
	\pgfmathdivide@{\pgfmathresult}{2}%
	\pgfutil@tempdima\pgfmathresult pt\relax%
	\pgfmathcosec@{\pgfmathresult}%
	\pgfutil@tempdimb\pgfmathresult\pgfutil@tempdimb%
	\pgfmathanglebetweenpoints{\calloutpointer}{\aftercalloutpointer}%
	\advance\pgfutil@tempdima\pgfmathresult pt\relax%
	\advance\pgfutil@tempdima180pt\relax%
	%	
	\pgfextract@process\calloutpointeranchor{%
		\pgfpointadd{%
			\pgfmathparse{\pgfkeysvalueof{/pgf/callout pointer anchor aspect}}%
			\pgfutil@tempdimb\pgfmathresult\pgfutil@tempdimb%
			\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
		}{%
			\calloutpointer%
		}%
	}%	
}%

\def\pgf@lib@callouts@shortenpointer{%
	\pgfextract@process\calloutpointer{%
		\pgfmathanglebetweenpoints{\calloutpointer}{\centerpoint}%
		\let\angle\pgfmathresult%
		\pgfmathsin@{\angle}%
		\let\sinpointerangle\pgfmathresult%
		\pgfmathcos@{\angle}%
		\let\cospointerangle\pgfmathresult%	
		\pgfpointadd{\calloutpointer}{%
			\pgfmathsetlength\pgfutil@tempdima{\pgfkeysvalueof{/pgf/callout pointer shorten}}%
			\pgf@x\cospointerangle\pgfutil@tempdima%
			\pgf@y\sinpointerangle\pgfutil@tempdima%
		}%
	}%
}%
	

\pgfdeclareshape{rectangle callout}{%
	\savedmacro\rectanglecalloutpoints{%
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
		\advance\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/minimum width}}%
		\ifdim\pgf@x<.5\pgf@xa%
			\pgf@x.5\pgf@xa%
		\fi%
		\edef\xtemp{\the\pgf@x}%
		\pgfmathaddtolength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
		%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
		\advance\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y.5\dp\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/minimum height}}%
		\ifdim\pgf@y<.5\pgf@ya%
			\pgf@y.5\pgf@ya%
		\fi%
		\edef\ytemp{\the\pgf@y}%
		\pgfmathaddtolength\pgf@y{\pgfkeysvalueof{/pgf/outer ysep}}%
		%
		\edef\xlength{\the\pgf@x}%
		\edef\ylength{\the\pgf@y}%
		\addtosavedmacro\xlength%
		\addtosavedmacro\ylength%
		%
		\pgfmathsetlengthmacro\pointerwidth{\pgfkeysvalueof{/pgf/callout pointer width}}%
		\addtosavedmacro\pointerwidth%
		%
		\pgfextract@process\centerpoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgf@y.5\ht\pgfnodeparttextbox%
			\advance\pgf@y-.5\dp\pgfnodeparttextbox%
		}%
		%
		% Process the relative callout pointer.
		%
		\ifpgf@lib@callout@absolutepointer%
		\else%
			\pgfextract@process\calloutpointer{%
				\pgfextract@process\borderpoint{%
					\expandafter\pgfpointborderrectangle\expandafter{\pgf@lib@callout@relativepointer}%
						{\pgfqpoint{\xtemp}{\ytemp}}%
				}%
				\pgfmathanglebetweenpoints{\pgfpointorigin}{\borderpoint}%
				\let\pointerangle\pgfmathresult%
				\expandafter\pgf@process\expandafter{\pgf@lib@callout@relativepointer}%
				\pgfmathveclen@{\pgfmath@tonumber{\pgf@x}}{\pgfmath@tonumber{\pgf@y}}%
				\edef\pointerradius{\pgfmathresult pt}%
				\pgfpointadd{\borderpoint}{\pgfqpointpolar{\pointerangle}{\pointerradius}}%
				\pgf@xa\pgf@x%
				\pgf@ya\pgf@y%
				\centerpoint%
				\advance\pgf@x\pgf@xa%
				\advance\pgf@y\pgf@ya%
			}%
			\pgf@lib@callouts@shortenpointer%
			\addtosavedmacro\calloutpointer%
			\pgf@lib@rectanglecallout@pointer%
			\addtosavedmacro\calloutpointeranchor%
			\addtosavedmacro\beforecalloutpointer%
			\addtosavedmacro\aftercalloutpointer%
			\addtosavedmacro\firstpoint%
			\addtosavedmacro\secondpoint%
			\addtosavedmacro\thirdpoint%
			\addtosavedmacro\fourthpoint%
		\fi%
	}
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt\relax%
	}
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+.5em}%
	}
	\anchor{center}{\centerpoint}
	\anchor{mid}{\midpoint}
	\anchor{mid east}{%
		\rectanglecalloutpoints%
		\midpoint%
		\advance\pgf@x\xlength\relax%		
	}
	\anchor{mid west}{%
		\rectanglecalloutpoints%
		\midpoint%
		\advance\pgf@x-\xlength\relax%		
	}
	\anchor{base}{\basepoint}
	\anchor{base east}{%
		\rectanglecalloutpoints%
		\basepoint%
		\advance\pgf@x\xlength\relax%		
	}
	\anchor{base west}{%
		\rectanglecalloutpoints%
		\basepoint%
		\advance\pgf@x-\xlength\relax%		
	}
	\anchor{north}{%
		\rectanglecalloutpoints%
		\centerpoint%
		\advance\pgf@y\ylength\relax%
	}%
	\anchor{south}{%
		\rectanglecalloutpoints%
		\centerpoint%
		\advance\pgf@y-\ylength\relax%
	}%
	\anchor{east}{%
		\rectanglecalloutpoints%
		\centerpoint%
		\advance\pgf@x\xlength\relax%
	}%
	\anchor{west}{%
		\rectanglecalloutpoints%
		\centerpoint%
		\advance\pgf@x-\xlength\relax%
	}%
	\anchor{north east}{%
		\rectanglecalloutpoints%
		\centerpoint%
		\advance\pgf@x\xlength\relax%
		\advance\pgf@y\ylength\relax%
	}%
	\anchor{south west}{%
		\rectanglecalloutpoints%
		\centerpoint%
		\advance\pgf@x-\xlength\relax%
		\advance\pgf@y-\ylength\relax%
	}%
	\anchor{south east}{%
		\rectanglecalloutpoints%
		\centerpoint%
		\advance\pgf@x\xlength\relax%
		\advance\pgf@y-\ylength\relax%
	}%
	\anchor{north west}{%
		\rectanglecalloutpoints%
		\centerpoint%
		\advance\pgf@x-\xlength\relax%
		\advance\pgf@y\ylength\relax%
	}%
	\anchor{pointer}{%
		\rectanglecalloutpoints%
		\calloutpointeranchor%
	}%
	\backgroundpath{%
		\rectanglecalloutpoints%
		\pgf@x\xlength\relax%
		\pgf@y\ylength\relax%
		\pgfmathaddtolength\pgf@x{-\pgfkeysvalueof{/pgf/outer xsep}}%
		\pgfmathaddtolength\pgf@y{-\pgfkeysvalueof{/pgf/outer ysep}}%
		\edef\xtemp{\the\pgf@x}%
		\edef\ytemp{\the\pgf@y}%
		%
		% The absolute pointer must be calculated here because the
		% anchor of the shape (which is calculated after the saved
		% macros and points) affects how the pointer joins the 
		% main rectangle. 
		%
		\ifpgf@lib@callout@absolutepointer%
			\pgfextract@process\calloutpointer{%
				\pgfpointanchor{pgf@lib@callout@pointer}{center}%
			}%
			\pgf@lib@callouts@shortenpointer%
			\pgfmathsetlengthmacro\pointerwidth{\pgfkeysvalueof{/pgf/callout pointer width}}%
			\pgf@lib@rectanglecallout@pointer%
			%
			% \pgf@node@name = the shape name (from \pgfmultipartnode)
			%
			\ifx\pgf@node@name\pgfutil@empty%
			\else%
				%
				% Now hack an extra saved anchor \calloutpointeranchor,
				% with the new anchor for the callout pointer.
				%
				\edef\pgf@sh@@temp{\noexpand\expandafter\noexpand\pgfutil@g@addto@macro\noexpand\csname pgf@sh@np@\pgf@node@name\noexpand\endcsname}%
				\edef\pgf@sh@@@temp{%
					\noexpand\def\noexpand\calloutpointeranchor{%
						\noexpand\pgf@x\the\pgf@x%
						\noexpand\pgf@y\the\pgf@y%
					}%
				}%
				\expandafter\pgf@sh@@temp\expandafter{\pgf@sh@@@temp}%
			\fi%
		\fi%
		{%
			\pgfsetcornersarced{\pgfqpoint{0pt}{0pt}}%
			\pgfpathmoveto{\beforecalloutpointer}%
		}%
		\pgfpathlineto{\calloutpointer}%
		{%
			\pgfsetcornersarced{\pgfqpoint{0pt}{0pt}}%
			\pgfpathlineto{\aftercalloutpointer}%
		}%
		{%
			\pgftransformshift{\centerpoint}%
			\pgfpathlineto{\firstpoint}%
			\pgfpathlineto{\secondpoint}%
			\pgfpathlineto{\thirdpoint}%
			\pgfpathlineto{\fourthpoint}%
			{%
				\pgfsetcornersarced{\pgfqpoint{0pt}{0pt}}%
				\pgfpathclose%
			}%
		}			
	}
	\anchorborder{%
		\pgfextract@process\externalpoint{}%
		\rectanglecalloutpoints%
		\pgfpointadd{\centerpoint}%
		{%
			\pgfpointborderrectangle{\pgfpointadd{\centerpoint}{\externalpoint}}%
			{\pgfqpoint{\xlength}{\ylength}}%
		}%
	}%
}



% \pgf@lib@rectanglecallout@pointer
%
% Internal macro for calculations relating to the rectangle callout.
%
% Requires the following to be set up:
%
% \calloutpointer - the location of the callout point.
% \xtemp          - the half width of the rectangle
% \ytemp          - the half height of the rectangle
% \pointerwidth   - the width of the pointer.
%
\def\pgf@lib@rectanglecallout@pointer{%
	%
	% Ensure that the pointer never connects to the main shape
	% too near to a corner. This is done for two reasons:
	% 1. It can look ugly.
	% 2. If the corners are rounded, a mess can result.
	%
	\pgfextract@process\borderpoint{%
			\pgfpointborderrectangle{%
				\centerpoint%
				\pgf@xa\pgf@x%
				\pgf@ya\pgf@y%
				\calloutpointer%
				\advance\pgf@x-\pgf@xa%
				\advance\pgf@y-\pgf@ya%
			}{\pgfqpoint{\xtemp}{\ytemp}}%
		}%
	\pgfmathanglebetweenpoints{\pgfpointorigin}{\borderpoint}%
	\let\borderangle\pgfmathresult%
	%
	\pgfutil@tempdima\pointerwidth\relax%
	\pgf@xa\xtemp\relax%
	\advance\pgf@xa-\pgfutil@tempdima%
	\pgf@ya\ytemp\relax%
	\advance\pgf@ya-\pgfutil@tempdima%
	%
	\pgf@process{%
		\pgfutil@ifundefined{pgf@corner@arc}{\pgfpointorigin}{%
			\expandafter\pgfqpoint\pgf@corner@arc}%
	}%
	\advance\pgf@xa-\pgf@x%
	\advance\pgf@ya-\pgf@y%
	%
	\borderpoint%
	\pgf@xb\pgf@x%
	\pgf@yb\pgf@y%
	%
	\pgf@xc0pt\relax%
	\pgf@yc0pt\relax%
	%
	\pgfmathanglebetweenpoints{\pgfpointorigin}{\pgfqpoint{\xtemp}{\ytemp}}%
	\ifdim\borderangle pt<\pgfmathresult pt\relax%
		\pgf@yc.5\pgfutil@tempdima%
		\ifdim\pgf@yb>\pgf@ya%
			\pgf@yb\pgf@ya%
		\fi%
		%
		% Establish the order for drawing the rectangle corners.
		%
		\edef\firstpoint{\noexpand\pgfqpoint{\xtemp}{\ytemp}}%
		\edef\secondpoint{\noexpand\pgfqpoint{-\xtemp}{\ytemp}}%
		\edef\thirdpoint{\noexpand\pgfqpoint{-\xtemp}{-\ytemp}}%
		\edef\fourthpoint{\noexpand\pgfqpoint{\xtemp}{-\ytemp}}%
	\else%
		\pgfmathanglebetweenpoints{\pgfpointorigin}{\pgfqpoint{-\xtemp}{\ytemp}}%
		\ifdim\borderangle pt<\pgfmathresult pt\relax%
			\pgf@xc-.5\pgfutil@tempdima%
			\ifdim\pgf@xb>\pgf@xa%
				\pgf@xb\pgf@xa%
			\else%
				\ifdim\pgf@xb<-\pgf@xa%
					\pgf@xb-\pgf@xa%
				\fi%
			\fi%
			\edef\firstpoint{\noexpand\pgfqpoint{-\xtemp}{\ytemp}}%
			\edef\secondpoint{\noexpand\pgfqpoint{-\xtemp}{-\ytemp}}%
			\edef\thirdpoint{\noexpand\pgfqpoint{\xtemp}{-\ytemp}}%
			\edef\fourthpoint{\noexpand\pgfqpoint{\xtemp}{\ytemp}}%
		\else%
			\pgfmathanglebetweenpoints{\pgfpointorigin}{\pgfqpoint{-\xtemp}{-\ytemp}}%
			\ifdim\borderangle pt<\pgfmathresult pt\relax%
				\pgf@yc-.5\pgfutil@tempdima%
				\ifdim\pgf@yb>\pgf@ya%
					\pgf@yb\pgf@ya%
				\else%
					\ifdim\pgf@yb<-\pgf@ya%
						\pgf@yb-\pgf@ya%
					\fi%
				\fi%
				\edef\firstpoint{\noexpand\pgfqpoint{-\xtemp}{-\ytemp}}%
				\edef\secondpoint{\noexpand\pgfqpoint{\xtemp}{-\ytemp}}%
				\edef\thirdpoint{\noexpand\pgfqpoint{\xtemp}{\ytemp}}%
				\edef\fourthpoint{\noexpand\pgfqpoint{-\xtemp}{\ytemp}}%
			\else%
				\pgfmathanglebetweenpoints{\pgfpointorigin}{\pgfqpoint{\xtemp}{-\ytemp}}%
				\ifdim\borderangle pt<\pgfmathresult pt\relax%
					\pgf@xc.5\pgfutil@tempdima%
					\ifdim\pgf@xb>\pgf@xa%
						\pgf@xb\pgf@xa%
					\else%
						\ifdim\pgf@xb<-\pgf@xa%
							\pgf@xb-\pgf@xa%
						\fi%
					\fi%
					\edef\firstpoint{\noexpand\pgfqpoint{\xtemp}{-\ytemp}}%
					\edef\secondpoint{\noexpand\pgfqpoint{\xtemp}{\ytemp}}%
					\edef\thirdpoint{\noexpand\pgfqpoint{-\xtemp}{\ytemp}}%
					\edef\fourthpoint{\noexpand\pgfqpoint{-\xtemp}{-\ytemp}}%
				\else%
					\pgf@yc.5\pgfutil@tempdima%
					\ifdim\pgf@yb<-\pgf@ya%
						\pgf@yb-\pgf@ya%
					\fi%
					\edef\firstpoint{\noexpand\pgfqpoint{\xtemp}{\ytemp}}%
					\edef\secondpoint{\noexpand\pgfqpoint{-\xtemp}{\ytemp}}%
					\edef\thirdpoint{\noexpand\pgfqpoint{-\xtemp}{-\ytemp}}%
					\edef\fourthpoint{\noexpand\pgfqpoint{\xtemp}{-\ytemp}}%
				\fi%
			\fi%
		\fi%
	\fi%
	\pgfextract@process\beforecalloutpointer{%
		\centerpoint%
		\advance\pgf@x\pgf@xb%
		\advance\pgf@y\pgf@yb%
		\advance\pgf@x-\pgf@xc%		
		\advance\pgf@y-\pgf@yc%
	}%	
	\pgfextract@process\aftercalloutpointer{%
		\centerpoint%
		\advance\pgf@x\pgf@xb%
		\advance\pgf@y\pgf@yb%
		\advance\pgf@x\pgf@xc%		
		\advance\pgf@y\pgf@yc%
	}%	
	%
	% Now calculate the pointer anchor.
	%
	\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
	\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/outer ysep}}%
	\ifdim\pgf@x>\pgf@y%
		\edef\outersep{\the\pgf@x}%
	\else%
		\edef\outersep{\the\pgf@y}%
	\fi%
	\pgf@lib@callouts@pointeranchor%
}


% Internal macro for parsing the size of 
% the cloud callout pointer.
%
% \pgf@x and \pgf@y should be set up as the
% width and height of the main shape.
%
% \pgf@xa and \pgf@ya are returned appropriately.
%
\def\pgf@lib@callout@setpointersize#1{%
	\edef\pgf@lib@callout@temp{#1}%
	\edef\pgf@marshall{\noexpand\pgfutil@in@{of callout}{\pgf@lib@callout@temp}}%
	\pgf@marshall%
	\ifpgfutil@in@%
		\expandafter\pgf@xa\expandafter\pgf@lib@callout@setpointerrelativesize%
			\pgf@lib@callout@temp\pgf@lib@stop\pgf@x%
		\expandafter\pgf@ya\expandafter\pgf@lib@callout@setpointerrelativesize%
			\pgf@lib@callout@temp\pgf@lib@stop\pgf@y%
	\else%
		\edef\pgf@marshall{\noexpand\pgfutil@in@{and}{\pgf@lib@callout@temp}}%
		\pgf@marshall%
		\ifpgfutil@in@%
			\expandafter\pgf@lib@callout@setpointerbothsizes\pgf@lib@callout@temp\pgf@lib@stop%
		\else%
			\pgfmathsetlength\pgf@xa{#1}%
			\pgfmathsetlength\pgf@ya{#1}%
		\fi%
	\fi%		 
}
\def\pgf@lib@callout@setpointerrelativesize#1of callout#2\pgf@lib@stop{#1}%
\def\pgf@lib@callout@setpointerbothsizes#1and#2\pgf@lib@stop{%
	\pgfmathsetlength\pgf@xa{#2}%
	\pgfmathsetlength\pgf@ya{#2}%
}

% Shape: cloud callout.
%
\pgfdeclareshape{cloud callout}{%
	\savedanchor\calloutpointer{%
		\pgfutil@ifundefined{pgf@sh@s@cloud}{%
			\pgferror{I cannot find the cloud shape. Please load the `symbol shapes' library}}{}%
		\pgf@sh@s@cloud%
		\pgf@sh@savedmacros%
		%
		\pgfextract@process\centerpoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgf@y.5\ht\pgfnodeparttextbox%
			\advance\pgf@y-.5\dp\pgfnodeparttextbox%
		}%
		\ifpgf@lib@callout@absolutepointer%
	  \else%
	  	\pgfextract@process\calloutpointer{%
				\pgfextract@process\borderpoint{%
					\expandafter\pgfpointborderellipse\expandafter{\pgf@lib@callout@relativepointer}%
						{\pgfqpoint{\xouterradius}{\youterradius}}%
				}%
				\pgfmathanglebetweenpoints{\pgfpointorigin}{\borderpoint}%
				\let\pointerangle\pgfmathresult%
				\expandafter\pgf@process\expandafter{\pgf@lib@callout@relativepointer}%
				\pgfmathveclen@{\pgfmath@tonumber{\pgf@x}}{\pgfmath@tonumber{\pgf@y}}%
				\edef\pointerradius{\pgfmathresult pt}%
				\pgfpointadd{\borderpoint}{\pgfqpointpolar{\pointerangle}{\pointerradius}}%
				\pgf@xa\pgf@x%
				\pgf@ya\pgf@y%
				\centerpoint%
				\advance\pgf@x\pgf@xa%
				\advance\pgf@y\pgf@ya%
			}%
			\pgf@lib@callouts@shortenpointer%
		\fi%
	}
	\anchor{pointer}{%
		\calloutpointer%
	}%
	\inheritsavedanchors[from=cloud]
	\inheritanchor[from=cloud]{center}
	\inheritanchor[from=cloud]{base}
	\inheritanchor[from=cloud]{mid}
	\inheritanchor[from=cloud]{north}
	\inheritanchor[from=cloud]{south}
	\inheritanchor[from=cloud]{east}
	\inheritanchor[from=cloud]{west}
	\inheritanchor[from=cloud]{north east}
	\inheritanchor[from=cloud]{south west}
	\inheritanchor[from=cloud]{south east}
	\inheritanchor[from=cloud]{north west}
	\inheritanchorborder[from=cloud]
	\backgroundpath{%
		\pgf@sh@bg@cloud%
		\ifpgf@lib@callout@absolutepointer%
   		\pgfextract@process\calloutpointer{%
				\pgfpointanchor{pgf@lib@callout@pointer}{center}%
			}%
			\ifx\pgf@node@name\pgfutil@empty%
			\else%
				\edef\pgf@sh@@temp{\noexpand\expandafter\noexpand\pgfutil@g@addto@macro\noexpand\csname pgf@sh@np@\pgf@node@name\noexpand\endcsname}%
				\edef\pgf@sh@@@temp{%
					\noexpand\def\noexpand\calloutpointeranchor{%
						\noexpand\pgf@x\the\pgf@x%
						\noexpand\pgf@y\the\pgf@y%
					}%
				}%
				\expandafter\pgf@sh@@temp\expandafter{\pgf@sh@@@temp}
			\fi%
		\fi%
		%
		\pgfextract@process\borderpoint{%
			\pgfpointadd{%
				\pgfpointborderellipse{\pgfpointdiff{\centerpoint}{\calloutpointer}}%
						{\pgfqpoint{\xouterradius}{\youterradius}}%
			}{\centerpoint}%
		}%
		\pgf@lib@callouts@shortenpointer%
		\pgfmathanglebetweenpoints{\calloutpointer}{\centerpoint}%
		\let\angle\pgfmathresult%
		\pgfmathsin@{\angle}%
		\let\sinpointerangle\pgfmathresult%
		\pgfmathcos@{\angle}%
		\let\cospointerangle\pgfmathresult%	
		%
		\pgf@x\xouterradius\relax%
		\pgf@x2.0\pgf@x%
		\pgf@y\yinnerradius\relax%
		\pgf@y2.0\pgf@y%
		\pgf@lib@callout@setpointersize{\pgfkeysvalueof{/pgf/callout pointer start size}}%
		\pgf@xb\pgf@xa%
		\pgf@yb\pgf@ya%
		\pgf@lib@callout@setpointersize{\pgfkeysvalueof{/pgf/callout pointer end size}}%
		\advance\pgf@xb-\pgf@xa%
		\advance\pgf@yb-\pgf@ya%
		%
		\pgfmathsetcount\c@pgf@counta{\pgfkeysvalueof{/pgf/callout pointer segments}}%
		\divide\pgf@xb\c@pgf@counta%
		\divide\pgf@yb\c@pgf@counta%
		%
		\pgf@process{\pgfpointdiff{\borderpoint}{\calloutpointer}}%
		\pgfmathveclen@{\pgfmath@tonumber{\pgf@x}}{\pgfmath@tonumber{\pgf@y}}%
		\pgfutil@tempdima\pgfmathresult pt\relax%
		\divide\pgfutil@tempdima\c@pgf@counta%
		%
		\pgfutil@tempdimb0pt\relax%
		\pgfmathloop%
		\ifnum\pgfmathcounter>\c@pgf@counta%
		\else%
			{%
				\pgf@xa.5\pgf@xa%
				\pgf@ya.5\pgf@ya%
				\edef\tempxradius{\the\pgf@xa}%
				\edef\tempyradius{\the\pgf@ya}%
				\pgfpathellipse%
					{%
						\calloutpointer%
						\advance\pgf@x\cospointerangle\pgfutil@tempdimb%
						\advance\pgf@y\sinpointerangle\pgfutil@tempdimb%
					}%
					{\pgfqpoint{\tempxradius}{0pt}}{\pgfqpoint{0pt}{\tempyradius}}%
			}%
			\advance\pgf@xa\pgf@xb%
			\advance\pgf@ya\pgf@yb%
			\advance\pgfutil@tempdimb\pgfutil@tempdima%
		\repeatpgfmathloop%
	}%
	%
	% Hack the puff anchors for the callout.
	%
	\expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@cloud callout\endcsname{%
		\c@pgf@counta\puffs\relax%
		\pgfmathloop%
			\ifnum\c@pgf@counta>0\relax%
				\pgfutil@ifundefined{pgf@anchor@cloud callout@puff\space\the\c@pgf@counta}{%
				\expandafter\xdef\csname pgf@anchor@cloud callout@puff\space\the\c@pgf@counta\endcsname{%
					\noexpand\pgf@sh@@cloudpuffanchor{\the\c@pgf@counta}%
				}%
			}{\c@pgf@counta0\relax}%
			\advance\c@pgf@counta-1\relax%
		\repeatpgfmathloop%	
	}%
}

\endinput

pgflibraryshapes.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/shapes/pgflibraryshapes.code.tex,v 1.1 2008/06/26 16:55:55 tantau Exp $

% Only the following are loaded by default and only for historical
% reasons. 

\usepgflibrary{shapes.geometric}
\usepgflibrary{shapes.misc}
\usepgflibrary{shapes.symbols}

% Further libraries should be included directly

\endinput

pgflibraryshapes.gates.ee.code.tex
% Copyright 2008 by Till Tantau and others 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.



%
% Base shapes
%
% These shapes are identical to the shapes without "ee", only an "input"
% and an "output" anchor have been added at the left and right end.

\pgfdeclareshape{rectangle ee}
{
  \inheritsavedanchors[from=rectangle] 
  \inheritanchorborder[from=rectangle]
  \inheritanchor[from=rectangle]{north}
  \inheritanchor[from=rectangle]{north west}
  \inheritanchor[from=rectangle]{north east}
  \inheritanchor[from=rectangle]{center}
  \inheritanchor[from=rectangle]{west}
  \inheritanchor[from=rectangle]{east}
  \inheritanchor[from=rectangle]{mid}
  \inheritanchor[from=rectangle]{mid west}
  \inheritanchor[from=rectangle]{mid east}
  \inheritanchor[from=rectangle]{base}
  \inheritanchor[from=rectangle]{base west}
  \inheritanchor[from=rectangle]{base east}
  \inheritanchor[from=rectangle]{south}
  \inheritanchor[from=rectangle]{south west}
  \inheritanchor[from=rectangle]{south east}
  \inheritbackgroundpath[from=rectangle]
  % New:
  \anchor{input}{
    \pgf@process{\northeast}%
    \pgf@ya=.5\pgf@y%
    \pgf@process{\southwest}%
    \pgf@y=.5\pgf@y%
    \advance\pgf@y by \pgf@ya%
  }
  \anchor{output}{%
    \pgf@process{\southwest}%
    \pgf@ya=.5\pgf@y%
    \pgf@process{\northeast}%
    \pgf@y=.5\pgf@y%
    \advance\pgf@y by \pgf@ya%
  }
}

\pgfdeclareshape{circle ee}
{
  \inheritsavedanchors[from=circle] 
  \inheritanchorborder[from=circle]
  \inheritanchor[from=circle]{north}
  \inheritanchor[from=circle]{north west}
  \inheritanchor[from=circle]{north east}
  \inheritanchor[from=circle]{center}
  \inheritanchor[from=circle]{west}
  \inheritanchor[from=circle]{east}
  \inheritanchor[from=circle]{mid}
  \inheritanchor[from=circle]{mid west}
  \inheritanchor[from=circle]{mid east}
  \inheritanchor[from=circle]{base}
  \inheritanchor[from=circle]{base west}
  \inheritanchor[from=circle]{base east}
  \inheritanchor[from=circle]{south}
  \inheritanchor[from=circle]{south west}
  \inheritanchor[from=circle]{south east}
  \inheritbackgroundpath[from=circle]
  % New:
  \anchor{input}{\centerpoint\advance\pgf@x by-\radius}
  \anchor{output}{\centerpoint\advance\pgf@x by\radius}
}



%
% Current direction indicator. This shape uses the current setting of
% the current direction arrow tip for the arrow. The shape is a
% rectangle around the arrow tip. 
%

\pgfdeclareshape{direction ee}
{
  \savedanchor\northeast{
    \pgf@x=0pt%
    % Height is given by minimum height/2
    \pgfmathsetlength{\pgf@y}{\pgfkeysvalueof{/pgf/minimum height}}%
    \pgf@y=.5\pgf@y
  }
  \savedanchor\southwest{
    % Left border is given by left extend
    \pgfarrowtotallength{\pgfkeysvalueof{/pgf/direction ee arrow}}%
    \pgf@x=-\pgf@x%
    % Height is given by minimum height/2
    \pgfmathsetlength{\pgf@y}{\pgfkeysvalueof{/pgf/minimum height}}%
    \pgf@y=-.5\pgf@y
  }

  \inheritanchor[from=rectangle ee]{center}
  \inheritanchor[from=rectangle ee]{north}
  \inheritanchor[from=rectangle ee]{south}
  \inheritanchor[from=rectangle ee]{east}
  \inheritanchor[from=rectangle ee]{west}
  \inheritanchor[from=rectangle ee]{north east}
  \inheritanchor[from=rectangle ee]{north west}
  \inheritanchor[from=rectangle ee]{south east}
  \inheritanchor[from=rectangle ee]{south west}
  \inheritanchor[from=rectangle ee]{input}
  \inheritanchor[from=rectangle ee]{output}
  \inheritanchorborder[from=rectangle ee]
  \nodeparts{}% no text

  \behindbackgroundpath{
    \pgf@process{\southwest}
    \pgf@xa=\pgf@x
    \pgf@process{\northeast}
    \pgf@xb=\pgf@x
    \pgfpathmoveto{\pgfqpoint{\pgf@xa}{0pt}}
    \pgfpathlineto{\pgfqpoint{\pgf@xb}{0pt}}
    \pgfusepathqstroke
  }

  \beforebackgroundpath{
    {
      \pgfsys@beginscope
      \pgfarrowdraw{\pgfkeysvalueof{/pgf/direction ee arrow}}%
      \pgfsys@endscope
    }
  }
}

\pgfkeys{
  /pgf/direction ee arrow/.initial=direction ee,
}



% Special arrow for ee directions:

\pgfarrowsdeclare{direction ee}{direction ee}
{
  \pgfmathsetlength\pgfutil@tempdima{\pgfgetarrowoptions{direction ee}}%
  \pgfutil@tempdima=.5\pgfutil@tempdima
  \pgfarrowsleftextend{+-\pgfutil@tempdima}
  \pgfarrowsrightextend{+\pgfutil@tempdima}
}
{
  \pgfmathsetlength\pgfutil@tempdima{\pgfgetarrowoptions{direction ee}}%
  \pgfsetdash{}{+0pt}
  \pgfsetroundjoin
  \pgfpathmoveto{\pgfqpoint{-0.5\pgfutil@tempdima}{0.38268343237\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{0.5\pgfutil@tempdima}{0\pgfutil@tempdima}}
  \pgfpathlineto{\pgfqpoint{-0.5\pgfutil@tempdima}{-0.38268343237\pgfutil@tempdima}}
  \pgfpathclose
  \pgfusepathqfillstroke
}

\pgfsetarrowoptions{direction ee}{4pt}





\endinput


pgflibraryshapes.gates.ee.IEC.code.tex
% Copyright 2008 by Till Tantau and others 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.


%
% Resistor shape based on a zig-zag-line
%

\pgfdeclareshape{var resistor IEC}
{
  \inheritsavedanchors[from=rectangle ee]
  \inheritanchor[from=rectangle ee]{center}
  \inheritanchor[from=rectangle ee]{north}
  \inheritanchor[from=rectangle ee]{south}
  \inheritanchor[from=rectangle ee]{east}
  \inheritanchor[from=rectangle ee]{west}
  \inheritanchor[from=rectangle ee]{north east}
  \inheritanchor[from=rectangle ee]{north west}
  \inheritanchor[from=rectangle ee]{south east}
  \inheritanchor[from=rectangle ee]{south west}
  \inheritanchor[from=rectangle ee]{input}
  \inheritanchor[from=rectangle ee]{output}
  \inheritanchorborder[from=rectangle ee]

  \backgroundpath{
    \pgf@process{\pgfpointadd{\southwest}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}
    \pgf@xa=\pgf@x \pgf@ya=\pgf@y
    \pgf@process{\pgfpointadd{\northeast}{\pgfpointscale{-1}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}}
    \pgf@xb=\pgf@x \pgf@yb=\pgf@y
    % Middle line
    \pgf@yc=.5\pgf@ya
    \advance\pgf@yc by.5\pgf@yb
    % Height
    \pgf@xc=-.5\pgf@ya
    \advance\pgf@xc by.5\pgf@yb
    % Start point
    \pgfpathmoveto{\pgfqpoint{\pgf@xa}{\pgf@yc}}
    % Lines
    \advance\pgf@xb by.1pt%
    \pgfutil@loop%
      \advance\pgf@xa by4\pgf@xc\relax%
    \ifdim\pgf@xa<\pgf@xb%
      \advance\pgf@xa by-3\pgf@xc%
      \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@yb}}%
      \advance\pgf@xa by2\pgf@xc%
      \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@ya}}%
      \advance\pgf@xa by\pgf@xc%
      \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@yc}}%
    \pgfutil@repeat%
    \advance\pgf@xb by-.1pt%
    \pgfpathlineto{\pgfqpoint{\pgf@xb}{\pgf@yc}}%  
  }
}



%
% Inductor shape based on a bumpy line
%

\pgfdeclareshape{inductor IEC}
{
  \savedanchor\northeast{%
    \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/outer xsep}}%
    \pgfmathsetlength\pgf@xb{\pgfkeysvalueof{/pgf/minimum width}}%
    \pgf@x=\pgf@xa%
    \advance\pgf@x by .5\pgf@xb%
    \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/outer ysep}}%
    \pgfmathsetlength\pgf@yb{\pgfkeysvalueof{/pgf/minimum height}}%
    \pgf@y=\pgf@ya%
    \advance\pgf@y by\pgf@yb%
  }
  \savedanchor\southwest{%
    \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/outer xsep}}%
    \pgfmathsetlength\pgf@xb{\pgfkeysvalueof{/pgf/minimum width}}%
    \pgf@x=-\pgf@xa%
    \advance\pgf@x by -.5\pgf@xb%
    \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/outer ysep}}%
    \pgf@y=-\pgf@ya%
  }

  \anchor{center}{\pgfpointorigin}
  \inheritanchor[from=rectangle ee]{north}
  \inheritanchor[from=rectangle ee]{south}
  \inheritanchor[from=rectangle ee]{east}
  \inheritanchor[from=rectangle ee]{west}
  \inheritanchor[from=rectangle ee]{north east}
  \inheritanchor[from=rectangle ee]{north west}
  \inheritanchor[from=rectangle ee]{south east}
  \inheritanchor[from=rectangle ee]{south west}
  \inheritanchor[from=rectangle ee]{input}
  \inheritanchor[from=rectangle ee]{output}

  \anchorborder{%
    \ifdim\pgf@y<0pt%
      % tricky... simpilfy to the origin...
      \pgf@xc=\pgf@x%
      \pgf@yc=\pgf@y%
      \pgf@process{\southwest}%
      \advance\pgf@y by-0.5pt%
      \pgf@xa=\pgf@x%
      \pgf@ya=\pgf@y%
      \pgf@process{\pgfpointborderrectangle{\pgfqpoint{\pgf@xc}{\the\pgf@yc}}{\pgfqpoint{-\pgf@xa}{-\pgf@ya}}}%
    \else%
      \pgf@xc=\pgf@x%
      \pgf@yc=\pgf@y%
      \pgf@process{\pgfpointborderrectangle{\pgfqpoint{\pgf@xc}{\the\pgf@yc}}{\northeast}}%
    \fi%
  }
  
  \backgroundpath{
    \pgf@process{\pgfpointadd{\northeast}{\pgfpointscale{-1}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}}
    \pgf@xa=-\pgf@x \pgf@ya=0pt
    \pgf@xb=\pgf@x \pgf@yb=\pgf@y
    % Height
    \pgf@xc=\pgf@yb%
    % Start point
    \pgfpathmoveto{\pgfqpoint{\pgf@xa}{0pt}}
    % Lines
    \advance\pgf@xb by.1pt%
    \pgfutil@loop%
      \advance\pgf@xa by2\pgf@xc\relax%
    \ifdim\pgf@xa<\pgf@xb%
      \pgfpatharc{180}{0}{\pgf@xc}%  
    \pgfutil@repeat%
    \advance\pgf@xb by-.1pt%
    \pgfpathlineto{\pgfqpoint{\pgf@xb}{0pt}}%  
  }
}




%
% Simple capacitor, consisting of two parallel lines
%

\pgfdeclareshape{capacitor IEC}
{
  \inheritsavedanchors[from=rectangle ee]
  \inheritanchor[from=rectangle ee]{center}
  \inheritanchor[from=rectangle ee]{north}
  \inheritanchor[from=rectangle ee]{south}
  \inheritanchor[from=rectangle ee]{east}
  \inheritanchor[from=rectangle ee]{west}
  \inheritanchor[from=rectangle ee]{north east}
  \inheritanchor[from=rectangle ee]{north west}
  \inheritanchor[from=rectangle ee]{south east}
  \inheritanchor[from=rectangle ee]{south west}
  \inheritanchor[from=rectangle ee]{input}
  \inheritanchor[from=rectangle ee]{output}
  \inheritanchorborder[from=rectangle ee]

  \backgroundpath{
    \pgf@process{\pgfpointadd{\southwest}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}
    \pgf@xa=\pgf@x \pgf@ya=\pgf@y
    \pgf@process{\pgfpointadd{\northeast}{\pgfpointscale{-1}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}}
    \pgf@xb=\pgf@x \pgf@yb=\pgf@y
    \pgfpathmoveto{\pgfqpoint{\pgf@xa}{\pgf@ya}}
    \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@yb}}
    \pgfpathmoveto{\pgfqpoint{\pgf@xb}{\pgf@ya}}
    \pgfpathlineto{\pgfqpoint{\pgf@xb}{\pgf@yb}}
  }
}




%
% Simple ground, consisting of three lines, getting smaller
%

\pgfdeclareshape{ground IEC}
{
  \inheritsavedanchors[from=rectangle ee]
  \inheritanchor[from=rectangle ee]{center}
  \inheritanchor[from=rectangle ee]{north}
  \inheritanchor[from=rectangle ee]{south}
  \inheritanchor[from=rectangle ee]{east}
  \inheritanchor[from=rectangle ee]{west}
  \inheritanchor[from=rectangle ee]{north east}
  \inheritanchor[from=rectangle ee]{north west}
  \inheritanchor[from=rectangle ee]{south east}
  \inheritanchor[from=rectangle ee]{south west}
  \inheritanchor[from=rectangle ee]{input}
  \inheritanchor[from=rectangle ee]{output}
  \inheritanchorborder[from=rectangle ee]

  \backgroundpath{
    \pgf@process{\pgfpointadd{\southwest}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}
    \pgf@xa=\pgf@x \pgf@ya=\pgf@y
    \pgf@process{\pgfpointadd{\northeast}{\pgfpointscale{-1}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}}
    \pgf@xb=\pgf@x \pgf@yb=\pgf@y
    % First line, simple
    \pgfpathmoveto{\pgfqpoint{\pgf@xa}{\pgf@ya}}
    \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@yb}}
    % Advance to middle
    \pgfmathsetlength\pgf@xa{.5\pgf@xa+.5\pgf@xb}
    % Make smaller
    \pgfmathsetlength\pgf@yc{.16666\pgf@yb-.16666\pgf@ya}
    \advance\pgf@ya by\pgf@yc
    \advance\pgf@yb by-\pgf@yc
    \pgfpathmoveto{\pgfqpoint{\pgf@xa}{\pgf@ya}}
    \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@yb}}
    % Make even smaller
    \advance\pgf@ya by\pgf@yc
    \advance\pgf@yb by-\pgf@yc
    \pgfpathmoveto{\pgfqpoint{\pgf@xb}{\pgf@ya}}
    \pgfpathlineto{\pgfqpoint{\pgf@xb}{\pgf@yb}}
  }
}



%
% Battery, consisting of two parallel lines, one smaller than
% the other
%

\pgfdeclareshape{battery IEC}
{
  \inheritsavedanchors[from=rectangle ee]
  \inheritanchor[from=rectangle ee]{center}
  \inheritanchor[from=rectangle ee]{north}
  \inheritanchor[from=rectangle ee]{south}
  \inheritanchor[from=rectangle ee]{east}
  \inheritanchor[from=rectangle ee]{west}
  \inheritanchor[from=rectangle ee]{north east}
  \inheritanchor[from=rectangle ee]{north west}
  \inheritanchor[from=rectangle ee]{south east}
  \inheritanchor[from=rectangle ee]{south west}
  \inheritanchor[from=rectangle ee]{input}
  \inheritanchor[from=rectangle ee]{output}
  \inheritanchorborder[from=rectangle ee]

  \backgroundpath{
    \pgf@process{\pgfpointadd{\southwest}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}
    \pgf@xa=\pgf@x \pgf@ya=\pgf@y
    \pgf@process{\pgfpointadd{\northeast}{\pgfpointscale{-1}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}}
    \pgf@xb=\pgf@x \pgf@yb=\pgf@y
    % First line, simple
    \pgfpathmoveto{\pgfqpoint{\pgf@xa}{\pgf@ya}}
    \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@yb}}
    % Make smaller
    \pgfmathsetlength\pgf@yc{.25\pgf@yb-.25\pgf@ya}
    \advance\pgf@ya by\pgf@yc
    \advance\pgf@yb by-\pgf@yc
    \pgfpathmoveto{\pgfqpoint{\pgf@xb}{\pgf@ya}}
    \pgfpathlineto{\pgfqpoint{\pgf@xb}{\pgf@yb}}
  }
}


%
% Special diodes
%


\pgfdeclareshape{breakdown diode IEC}
{
  \inheritsavedanchors[from=rectangle ee]
  \inheritanchor[from=rectangle ee]{center}
  \inheritanchor[from=rectangle ee]{north}
  \inheritanchor[from=rectangle ee]{south}
  \inheritanchor[from=rectangle ee]{east}
  \inheritanchor[from=rectangle ee]{west}
  \inheritanchor[from=rectangle ee]{north east}
  \inheritanchor[from=rectangle ee]{north west}
  \inheritanchor[from=rectangle ee]{south east}
  \inheritanchor[from=rectangle ee]{south west}
  \inheritanchor[from=rectangle ee]{input}
  \inheritanchor[from=rectangle ee]{output}
  \inheritanchorborder[from=rectangle ee]

  \backgroundpath{
    \pgf@process{\pgfpointadd{\southwest}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}
    \pgf@xa=\pgf@x \pgf@ya=\pgf@y
    \pgf@process{\pgfpointadd{\northeast}{\pgfpointscale{-1}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}}
    \pgf@xb=\pgf@x \pgf@yb=\pgf@y
    \pgf@xc=.5\pgf@xa \advance\pgf@xc by.5\pgf@xb
    \pgf@yc=.5\pgf@ya
    \advance\pgf@yc by .5\pgf@yb
    % Triangles:
    \pgfpathmoveto{\pgfqpoint{\pgf@xa}{\pgf@ya}}
    \pgfpathlineto{\pgfqpoint{\pgf@xc}{\pgf@yc}}
    \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@yb}}
    \pgfpathclose
    \pgfpathmoveto{\pgfqpoint{\pgf@xb}{\pgf@ya}}
    \pgfpathlineto{\pgfqpoint{\pgf@xc}{\pgf@yc}}
    \pgfpathlineto{\pgfqpoint{\pgf@xb}{\pgf@yb}}
    \pgfpathclose
  }

  
  \beforebackgroundpath{
    {
      \pgf@process{\pgfpointadd{\southwest}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}
      \pgf@xa=\pgf@x \pgf@ya=\pgf@y
      \pgf@process{\pgfpointadd{\northeast}{\pgfpointscale{-1}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}}
      \pgf@xb=\pgf@x \pgf@yb=\pgf@y
      \pgf@yc=.5\pgf@ya
      \advance\pgf@yc by.5\pgf@yb
      \pgfpathmoveto{\pgfqpoint{\pgf@xa}{\pgf@yc}}
      \pgfpathlineto{\pgfqpoint{\pgf@xb}{\pgf@yc}}
      \pgfusepathqstroke
      \pgf@xc=.5\pgf@xa
      \advance\pgf@xc by.5\pgf@xb
      \pgftransformshift{\pgfqpoint{\pgf@xc}{\pgf@yc}}  
      \pgf@yc=.5\pgf@yb
      \advance\pgf@yc by-.5\pgf@ya
      \pgftransformscale{\pgf@sys@tonumber{\pgf@yc}}
      \pgfpathmoveto{\pgfqpoint{-.5pt}{-1pt}}
      \pgfpathlineto{\pgfqpoint{0pt}{-1pt}}
      \pgfpathlineto{\pgfqpoint{0pt}{1pt}}
      \pgfpathlineto{\pgfqpoint{.5pt}{1pt}}
      \pgfusepathqstroke
    }
  }
}






% Generic shapes
%
% When these shapes are used, you can set a key derived form the
% shapes name to some code that will be executed as the before
% background path. This means that the basic shape is fixed, but
% things like a special line inside the shape or at the border can be
% added without having to define a whole new shape.


\pgfdeclareshape{generic circle IEC}
{
  % This shape is a generic circle, to which you can add something to
  % the before background path using the key
  % /pgf/generic circle IEC/before background
  % When this key is invoked, the transformation matrix will have been
  % setup such that the circle's center is at the origin and that the
  % position \pgfpoint{1pt}{0pt} lies exactly on the top of the circle
  % (and, there, on the middle of the line).
  
  \inheritsavedanchors[from=circle ee]
  \inheritanchorborder[from=circle ee]
  \inheritanchor[from=circle ee]{north}
  \inheritanchor[from=circle ee]{north west}
  \inheritanchor[from=circle ee]{north east}
  \inheritanchor[from=circle ee]{center}
  \inheritanchor[from=circle ee]{west}
  \inheritanchor[from=circle ee]{east}
  \inheritanchor[from=circle ee]{south}
  \inheritanchor[from=circle ee]{south west}
  \inheritanchor[from=circle ee]{south east}
  \inheritanchor[from=circle ee]{input}
  \inheritanchor[from=circle ee]{output}
  \inheritbackgroundpath[from=circle ee]
  
  \beforebackgroundpath{
    {
      \centerpoint%
      \pgf@xc=\pgf@x%
      \pgf@yc=\pgf@y%
      \pgftransformshift{}  
      \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%
      \pgftransformscale{\pgf@sys@tonumber{\pgfutil@tempdima}}
      \pgfkeysvalueof{/pgf/generic circle IEC/before background}
    }
  }
}



%
% Generic diode, based on a rectangle
%

\pgfdeclareshape{generic diode IEC}
{
  % This shape is a generic diode, to which you can add something to
  % the before background path using the key
  % /pgf/generic diode IEC/before background
  % When this key is invoked, the transformation matrix will have been
  % setup such that the center is at the tip of the diode. The 
  % position \pgfpoint{1pt}{0pt} lies exactly on the top of the
  % (suggested) line before the diode. 
  
  \inheritsavedanchors[from=rectangle ee]
  \inheritanchor[from=rectangle ee]{center}
  \inheritanchor[from=rectangle ee]{north}
  \inheritanchor[from=rectangle ee]{south}
  \inheritanchor[from=rectangle ee]{east}
  \inheritanchor[from=rectangle ee]{west}
  \inheritanchor[from=rectangle ee]{north east}
  \inheritanchor[from=rectangle ee]{north west}
  \inheritanchor[from=rectangle ee]{south east}
  \inheritanchor[from=rectangle ee]{south west}
  \inheritanchor[from=rectangle ee]{input}
  \inheritanchor[from=rectangle ee]{output}
  \inheritanchorborder[from=rectangle ee]

  \backgroundpath{
    \pgf@process{\pgfpointadd{\southwest}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}
    \pgf@xa=\pgf@x \pgf@ya=\pgf@y
    \pgf@process{\pgfpointadd{\northeast}{\pgfpointscale{-1}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}}
    \pgf@xb=\pgf@x \pgf@yb=\pgf@y
    % Move tip back a little bit
    \advance\pgf@xb by-.5\pgflinewidth
    % Triangle triangle:
    \pgfpathmoveto{\pgfqpoint{\pgf@xa}{\pgf@ya}}
    \pgfpathlineto{\pgfqpoint{\pgf@xa}{\pgf@yb}}
    \pgf@yc=.5\pgf@ya
    \advance\pgf@yc by .5\pgf@yb
    \pgfpathlineto{\pgfqpoint{\pgf@xb}{\pgf@yc}}
    \pgfpathclose
  }

  
  \beforebackgroundpath{
    {
      \pgf@process{\pgfpointadd{\southwest}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}
      \pgf@xa=\pgf@x \pgf@ya=\pgf@y
      \pgf@process{\pgfpointadd{\northeast}{\pgfpointscale{-1}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}}
      \pgf@xb=\pgf@x \pgf@yb=\pgf@y
      \pgf@yc=.5\pgf@ya
      \advance\pgf@yc by.5\pgf@yb
      \pgfpathmoveto{\pgfqpoint{\pgf@xa}{\pgf@yc}}
      \pgfpathlineto{\pgfqpoint{\pgf@xb}{\pgf@yc}}
      \pgfusepathqstroke
      \pgftransformshift{\pgfqpoint{\pgf@xb}{\pgf@yc}}  
      \pgf@yc=.5\pgf@yb
      \advance\pgf@yc by-.5\pgf@ya
      \pgftransformscale{\pgf@sys@tonumber{\pgf@yc}}
      \pgfkeysvalueof{/pgf/generic diode IEC/before background}
    }
  }
}


\pgfkeys{
  /pgf/generic circle IEC/before background/.initial=,
  /pgf/generic diode IEC/before background/.initial=,
}





%
% Concacts
%

\pgfdeclareshape{make contact IEC}
{
  \savedanchor\northeast{%
    \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/outer xsep}}%
    \pgfmathsetlength\pgf@xb{\pgfkeysvalueof{/pgf/minimum width}}%
    \pgf@x=\pgf@xa%
    \advance\pgf@x by .5\pgf@xb%
    \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/outer ysep}}%
    \pgfmathsetlength\pgf@yb{\pgfkeysvalueof{/pgf/minimum height}}%
    \pgf@y=\pgf@ya%
    \advance\pgf@y by\pgf@yb%
  }
  \savedanchor\southwest{%
    \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/outer xsep}}%
    \pgfmathsetlength\pgf@xb{\pgfkeysvalueof{/pgf/minimum width}}%
    \pgf@x=-.5\pgf@xa%
    \advance\pgf@x by -.5\pgf@xb%
    \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/outer ysep}}%
    \pgf@y=-\pgf@ya%
  }

  \anchor{center}{\pgfpointorigin}
  \inheritanchor[from=rectangle ee]{north}
  \inheritanchor[from=rectangle ee]{south}
  \inheritanchor[from=rectangle ee]{east}
  \inheritanchor[from=rectangle ee]{west}
  \inheritanchor[from=rectangle ee]{north east}
  \inheritanchor[from=rectangle ee]{north west}
  \inheritanchor[from=rectangle ee]{south east}
  \inheritanchor[from=rectangle ee]{south west}
  \inheritanchor[from=rectangle ee]{input}
  \inheritanchor[from=rectangle ee]{output}

  \anchorborder{%
    \ifdim\pgf@y<0pt%
      % tricky... simpilfy to the origin...
      \pgf@xc=\pgf@x%
      \pgf@yc=\pgf@y%
      \pgf@process{\southwest}%
      \advance\pgf@y by-0.5pt%
      \pgf@xa=\pgf@x%
      \pgf@ya=\pgf@y%
      \pgf@process{\pgfpointborderrectangle{\pgfqpoint{\pgf@xc}{\the\pgf@yc}}{\pgfqpoint{-\pgf@xa}{-\pgf@ya}}}%
    \else%
      \pgf@xc=\pgf@x%
      \pgf@yc=\pgf@y%
      \pgf@process{\pgfpointborderrectangle{\pgfqpoint{\pgf@xc}{\the\pgf@yc}}{\northeast}}%
    \fi%
  }
  
  \backgroundpath{
    \pgf@process{\pgfpointadd{\northeast}{\pgfpointscale{-1}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}}
    \pgf@xa=-\pgf@x \pgf@ya=0pt
    \pgf@xb=\pgf@x \pgf@yb=\pgf@y
    % Start point
    \pgfpathmoveto{\pgfqpoint{\pgf@xa}{0pt}}
    \pgfpathlineto{\pgfqpoint{\pgf@xb}{\pgf@yb}}
  }
}



%
% Concacts
%

\pgfdeclareshape{var make contact IEC}
{
  \savedanchor\northeast{%
    \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/outer xsep}}%
    \pgfmathsetlength\pgf@xb{\pgfkeysvalueof{/pgf/minimum width}}%
    \pgf@x=\pgf@xa%
    \advance\pgf@x by .5\pgf@xb%
    \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/outer ysep}}%
    \pgfmathsetlength\pgf@yb{\pgfkeysvalueof{/pgf/minimum height}}%
    \pgf@y=\pgf@ya%
    \advance\pgf@y by\pgf@yb%
  }
  \savedanchor\southwest{%
    \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/outer xsep}}%
    \pgfmathsetlength\pgf@xb{\pgfkeysvalueof{/pgf/minimum width}}%
    \pgf@x=-.5\pgf@xa%
    \advance\pgf@x by -.5\pgf@xb%
    \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/outer ysep}}%
    \pgf@y=-\pgf@ya%
    \pgf@xc=0.083333\pgf@x%
    \advance\pgf@y by\pgf@xc%
  }

  \anchor{center}{\pgfpointorigin}
  \inheritanchor[from=rectangle ee]{north}
  \inheritanchor[from=rectangle ee]{south}
  \inheritanchor[from=rectangle ee]{east}
  \inheritanchor[from=rectangle ee]{west}
  \inheritanchor[from=rectangle ee]{north east}
  \inheritanchor[from=rectangle ee]{north west}
  \inheritanchor[from=rectangle ee]{south east}
  \inheritanchor[from=rectangle ee]{south west}
  \inheritanchor[from=rectangle ee]{input}
  \inheritanchor[from=rectangle ee]{output}

  \anchorborder{%
    \ifdim\pgf@y<0pt%
      % tricky... simpilfy to the origin...
      \pgf@xc=\pgf@x%
      \pgf@yc=\pgf@y%
      \pgf@process{\southwest}%
      \pgf@xa=\pgf@x%
      \pgf@ya=\pgf@y%
      \pgf@process{\pgfpointborderrectangle{\pgfqpoint{\pgf@xc}{\the\pgf@yc}}{\pgfqpoint{-\pgf@xa}{-\pgf@ya}}}%
    \else%
      \pgf@xc=\pgf@x%
      \pgf@yc=\pgf@y%
      \pgf@process{\pgfpointborderrectangle{\pgfqpoint{\pgf@xc}{\the\pgf@yc}}{\northeast}}%
    \fi%
  }
  
  \backgroundpath{
    \pgf@process{\pgfpointadd{\northeast}{
        \pgfpointscale{-1}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}}
    \pgf@xa=-\pgf@x \pgf@ya=0pt
    \pgf@xb=\pgf@x \pgf@yb=\pgf@y
    \pgf@xc=\pgf@xa
    \pgfutil@tempdima=2\pgf@xb%
    \pgfutil@tempdima=0.083333\pgfutil@tempdima%
    \advance\pgf@xa by \pgfutil@tempdima
    % Circle
    {\pgfpathcircle{\pgfqpoint{\pgf@xa}{0pt}}{\pgfutil@tempdima}}
    % Height
    % Start point
    \pgf@process{\pgfpointnormalised{\pgfpointdiff{\pgfqpoint{\pgf@xa}{0pt}}{\pgfqpoint{\pgf@xb}{\pgf@yb}}}}
    \pgf@xc=\pgf@x
    \pgf@yc=\pgf@y
    \pgfpathmoveto{\pgfpointadd{\pgfqpoint{\pgf@xa}{0pt}}{%
        \pgfpointscale{\pgfutil@tempdima}{\pgfqpoint{\pgf@xc}{\pgf@yc}}}}
    \pgfpathlineto{\pgfqpoint{\pgf@xb}{\pgf@yb}}
  }
}



\pgfdeclareshape{break contact IEC}
{
  \savedanchor\northeast{%
    \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/outer xsep}}%
    \pgfmathsetlength\pgf@xb{\pgfkeysvalueof{/pgf/minimum width}}%
    \pgf@x=\pgf@xa%
    \advance\pgf@x by .5\pgf@xb%
    \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/outer ysep}}%
    \pgfmathsetlength\pgf@yb{\pgfkeysvalueof{/pgf/minimum height}}%
    \pgf@y=\pgf@ya%
    \advance\pgf@y by\pgf@yb%
  }
  \savedanchor\southwest{%
    \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/outer xsep}}%
    \pgfmathsetlength\pgf@xb{\pgfkeysvalueof{/pgf/minimum width}}%
    \pgf@x=-.5\pgf@xa%
    \advance\pgf@x by -.5\pgf@xb%
    \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/outer ysep}}%
    \pgf@y=-\pgf@ya%
  }

  \anchor{center}{\pgfpointorigin}
  \inheritanchor[from=rectangle ee]{north}
  \inheritanchor[from=rectangle ee]{south}
  \inheritanchor[from=rectangle ee]{east}
  \inheritanchor[from=rectangle ee]{west}
  \inheritanchor[from=rectangle ee]{north east}
  \inheritanchor[from=rectangle ee]{north west}
  \inheritanchor[from=rectangle ee]{south east}
  \inheritanchor[from=rectangle ee]{south west}
  \inheritanchor[from=rectangle ee]{input}
  \inheritanchor[from=rectangle ee]{output}

  \anchorborder{%
    \ifdim\pgf@y<0pt%
      % tricky... simpilfy to the origin...
      \pgf@xc=\pgf@x%
      \pgf@yc=\pgf@y%
      \pgf@process{\southwest}%
      \advance\pgf@y by-0.5pt%
      \pgf@xa=\pgf@x%
      \pgf@ya=\pgf@y%
      \pgf@process{\pgfpointborderrectangle{\pgfqpoint{\pgf@xc}{\the\pgf@yc}}{\pgfqpoint{-\pgf@xa}{-\pgf@ya}}}%
    \else%
      \pgf@xc=\pgf@x%
      \pgf@yc=\pgf@y%
      \pgf@process{\pgfpointborderrectangle{\pgfqpoint{\pgf@xc}{\the\pgf@yc}}{\northeast}}%
    \fi%
  }
  
  \backgroundpath{
    \pgf@process{\pgfpointadd{\northeast}{\pgfpointscale{-1}{\pgfpoint{\pgfkeysvalueof{/pgf/outer xsep}}{\pgfkeysvalueof{/pgf/outer ysep}}}}}
    \pgf@xa=-\pgf@x \pgf@ya=0pt
    \pgf@xb=\pgf@x \pgf@yb=\pgf@y
    % Start point
    \pgfpathmoveto{\pgfqpoint{\pgf@xa}{0pt}}
    \pgfpathlineto{\pgfqpoint{\pgf@xb}{\pgf@yb}}
    % Break point
    \pgf@xc=.2\pgf@xb
    \advance\pgf@xc by-.2\pgf@xa
    \pgfpathmoveto{\pgfqpoint{\pgf@xb}{0pt}}
    \advance\pgf@xb by-\pgf@xc
    \pgfpathlineto{\pgfqpoint{\pgf@xb}{0pt}}
    \pgfpathlineto{\pgfqpoint{\pgf@xb}{\pgf@yb}}
  }
}





\endinput


pgflibraryshapes.gates.logic.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.


% Common keys for all logic gates.
%
\pgfkeys{/pgf/.cd,%
	logic gate input sep/.initial=0.125cm,
	logic gate inputs/.initial={normal,normal},%
	logic gate inverted radius/.initial=2pt
}


% Internal macro for parsing inputs.
%
\expandafter\ifx\csname pgf@lib@sh@logicgate@parseinputs\endcsname\relax%
\def\pgf@lib@sh@logicgate@parseinputs#1{%
	\edef\pgf@lib@sh@temp{\pgfkeysvalueof{/pgf/logic gate inputs}}%
	\c@pgf@counta#1\relax%
	\c@pgf@countb0\relax%
	\expandafter\pgfutil@in@\expandafter,\expandafter{\pgf@lib@sh@temp}%
	\ifpgfutil@in@%
		\let\pgf@lib@sh@next\pgf@lib@sh@logicgate@parseinputs@long%
	\else%
		\let\pgf@lib@sh@next\pgf@lib@sh@logicgate@parseinputs@short%
	\fi%
	\pgf@lib@sh@next%
}	
\def\pgf@lib@sh@itext{i}
\def\pgf@lib@sh@invertedtext{inverted}
%
%	The `short' version for input specifcation is an extension of
%	ideas due to Juergen Werber and Christoph Bartoschek.
%
\def\pgf@lib@sh@logicgate@parseinputs@short{%
	\expandafter\pgf@lib@sh@logicgate@parseinputs@@short\pgf@lib@sh@temp\pgf@stop%
}
\def\pgf@lib@sh@logicgate@parseinputs@@short#1{%
	\ifx#1\pgf@stop%
		\edef\pgf@lib@sh@logicgate@numinputs{\the\c@pgf@countb}%
		\let\pgf@lib@sh@next\relax%
	\else%
		\ifnum\c@pgf@countb=\c@pgf@counta%
			\edef\pgf@lib@sh@logicgate@numinputs{\the\c@pgf@countb}%
			\let\pgf@lib@sh@next\relax%
		\else%
			\advance\c@pgf@countb1\relax%
			\expandafter\ifx\pgf@lib@sh@itext#1%
				\expandafter\pgf@sh@resavedmacro\expandafter{\csname input-\the\c@pgf@countb\endcsname}{%
					\expandafter\def\csname input-\the\c@pgf@countb\endcsname{i}}%
			\else%
				\expandafter\pgf@sh@resavedmacro\expandafter{\csname input-\the\c@pgf@countb\endcsname}{%
					\expandafter\def\csname input-\the\c@pgf@countb\endcsname{n}}%
			\fi%		
			\let\pgf@lib@sh@next\pgf@lib@sh@logicgate@parseinputs@@short%
		\fi%
	\fi%
	\pgf@lib@sh@next%
}
\def\pgf@lib@sh@logicgate@parseinputs@long{%
	\expandafter\pgf@lib@sh@logicgate@parseinputs@@long\pgf@lib@sh@temp,\pgf@stop,%
}
\def\pgf@lib@sh@logicgate@parseinputs@@long#1,{%
	\ifx#1\pgf@stop%
		\edef\pgf@lib@sh@logicgate@numinputs{\the\c@pgf@countb}%
		\let\pgf@lib@sh@next\relax%
	\else%
		\ifnum\c@pgf@countb=\c@pgf@counta%
			\edef\pgf@lib@sh@logicgate@numinputs{\the\c@pgf@countb}%
			\let\pgf@lib@sh@next\relax%
		\else%
			\advance\c@pgf@countb1\relax%
			\def\pgf@lib@sh@temp{#1}%
			\ifx\pgf@lib@sh@invertedtext\pgf@lib@sh@temp%
				\expandafter\pgf@sh@resavedmacro\expandafter{\csname input-\the\c@pgf@countb\endcsname}{%
					\expandafter\def\csname input-\the\c@pgf@countb\endcsname{i}}%
			\else%
				\expandafter\pgf@sh@resavedmacro\expandafter{\csname input-\the\c@pgf@countb\endcsname}{%
					\expandafter\def\csname input-\the\c@pgf@countb\endcsname{n}}%
			\fi%		
			\let\pgf@lib@sh@next\pgf@lib@sh@logicgate@parseinputs@@@long%
		\fi%
	\fi%
	\pgf@lib@sh@next%
}
\def\pgf@lib@sh@logicgate@parseinputs@@@long{%
	\pgfutil@ifnextchar x{\pgf@lib@sh@logicgate@parseinputs@@long}%
		{\pgf@lib@sh@logicgate@parseinputs@@long}%
}
\fi%



pgflibraryshapes.gates.logic.IEC.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.

\usepgflibrary{shapes.gates.logic}

\pgfkeys{/pgf/.cd,
  and gate IEC symbol/.initial=$\char`\&$,
  nand gate IEC symbol/.initial=$\char`\&$,
  or gate IEC symbol/.initial=$\geq1$,
  nor gate IEC symbol/.initial=$\geq1$,
  xor gate IEC symbol/.initial={$=1$},
  xnor gate IEC symbol/.initial={$=1$},
  not gate IEC symbol/.initial=1,
  buffer gate IEC symbol/.initial=1,
  logic gate IEC symbol align/.initial=top,
  logic gate IEC symbol color/.initial=% no value
}

\pgfkeys{/pgf/logic gate IEC symbol align/.cd,
  top/.code=\pgftransformyshift{\innerhalfheight},
  bottom/.code=\pgftransformyshift{-\innerhalfheight},
  left/.code=\pgftransformxshift{-\innerhalfwidth},
  right/.code=\pgftransformxshift{\innerhalfwidth}
}

\def\pgf@lib@sh@logicgates@IEC@foregroundpath#1{%
  \dimensions%
  {%
    \pgftransformshift{\centerpoint}%
    \edef\pgf@lib@sh@temp{\pgfkeysvalueof{/pgf/logic gate IEC symbol align}}%
    \edef\pgf@lib@sh@@temp{/pgf/logic gate IEC symbol align/.cd, \pgf@lib@sh@temp}%
    \expandafter\pgfkeys\expandafter{\pgf@lib@sh@@temp}%
    \expandafter\pgftext\expandafter[\pgf@lib@sh@temp]{%
      \pgfkeysgetvalue{/pgf/logic gate IEC symbol color}{\pgf@lib@sh@temp}%
      \ifx\pgf@lib@sh@temp\pgfutil@empty%
      \else%
        \expandafter\color\expandafter{\pgf@lib@sh@temp}%
      \fi%
      \pgfkeysvalueof{/pgf/#1 gate IEC symbol}%
    }%
  }%
}  


\def\pgf@lib@sh@logicgates@dimensions@IEC#1{%
  \pgf@x.5\wd\pgfnodeparttextbox%
  \pgf@y.5\ht\pgfnodeparttextbox%
  \advance\pgf@y.5\dp\pgfnodeparttextbox%
  %
  % Adjust for the width of the gate symbol.
  %
  \setbox\pgf@hbox\hbox{{\pgfkeysvalueof{/pgf/#1 gate IEC  symbol}}}% add braces as color-aftergroup-fix TT
  \pgf@xa.5\wd\pgf@hbox%
  \pgf@ya.5\ht\pgf@hbox%
  \advance\pgf@ya.5\dp\pgf@hbox%
  \ifdim\pgf@x<\pgf@xa%
    \pgf@x\pgf@xa%
  \fi%
  \ifdim\pgf@y<\pgf@ya%
    \pgf@y\pgf@ya%
  \fi%
  \pgfmathaddtolength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
  \pgfmathaddtolength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
  %
  % Adjust for minimum height and width.
  %
  \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/minimum width}}%
  \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/minimum height}}%
  \ifdim\pgf@x<.5\pgf@xa%
    \pgf@x.5\pgf@xa%
  \fi%
  \ifdim\pgf@y<.5\pgf@ya%
    \pgf@y.5\pgf@ya%
  \fi%
  %
  % Adjust the height for the number of inputs.
  %
  \c@pgf@counta\pgf@lib@sh@logicgate@numinputs%
  \advance\c@pgf@counta1\relax%
  \pgfmathsetlength\pgf@yb{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
  \pgf@yb2.0\pgf@yb%
  \advance\pgf@yb\pgflinewidth%
  \pgfmathsetlength\pgf@yc{\pgfkeysvalueof{/pgf/logic gate input sep}}%
  \edef\inputsep{\the\pgf@yc}%
  \addtosavedmacro\inputsep%
  \ifdim\pgf@yb<\pgf@yc%
    \pgf@yb\pgf@yc%
  \fi%
  \multiply\pgf@yb\c@pgf@counta%
  \ifdim\pgf@y<.5\pgf@yb%
    \pgf@y.5\pgf@yb%
  \fi%
  %
  \pgf@xa\pgf@x%
  \pgfmathaddtolength\pgf@xa{-\pgfkeysvalueof{/pgf/inner xsep}}%
  \edef\innerhalfwidth{\the\pgf@xa}%
  \addtosavedmacro\innerhalfwidth%
  %
  \pgf@ya\pgf@y%
  \pgfmathaddtolength\pgf@ya{-\pgfkeysvalueof{/pgf/inner ysep}}%
  \edef\innerhalfheight{\the\pgf@ya}%
  \addtosavedmacro\innerhalfheight%
  %
  % Take into account the outer sep.
  %
  \pgfmathaddtolength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
  \pgfmathaddtolength\pgf@y{\pgfkeysvalueof{/pgf/outer ysep}}%
  %
  \edef\halfwidth{\the\pgf@x}%
  \edef\halfheight{\the\pgf@y}%
  \addtosavedmacro\halfwidth%
  \addtosavedmacro\halfheight%
}%

\def\pgf@lib@sh@logicgate@IEC@inputanchor#1{%
  \dimensions%
  \centerpoint%
  \advance\pgf@x-\halfwidth%
  \expandafter\ifx\expandafter\pgf@lib@sh@itext\csname input-#1\endcsname%
    \advance\pgf@x-\invertedradius%
    \advance\pgf@x-\outerinvertedradius%
  \fi%
  %
  \pgfutil@tempdima\halfheight%
  \multiply\pgfutil@tempdima2\relax%
  \c@pgf@counta\numinputs%
  \advance\c@pgf@counta1\relax%
  \divide\pgfutil@tempdima\c@pgf@counta%
  \multiply\pgfutil@tempdima#1\relax%
  \advance\pgf@y\halfheight%
  \advance\pgf@y-\pgfutil@tempdima%
}



% Shape and gate IEC
%
\pgfdeclareshape{and gate IEC}{
  \expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@and gate IEC\endcsname{%
    \pgf@lib@sh@logicgate@parseinputs{1024}% Maximum 1024 (!) inputs.
    %
    \pgfmathloop%
    \ifnum\pgfmathcounter>\pgf@lib@sh@logicgate@numinputs%
    \else%
      \pgfutil@ifundefined{pgf@anchor@and gate IEC@input \pgfmathcounter}{%
        \expandafter\xdef\csname pgf@anchor@and gate IEC@input \pgfmathcounter\endcsname{%
          \noexpand\pgf@lib@sh@logicgate@IEC@inputanchor{\pgfmathcounter}%
        }%
      }{}%
    \repeatpgfmathloop%
    \ifnum\pgf@lib@sh@logicgate@numinputs<2\relax%
      \pgferror{An and gate must have at least two inputs}%
    \fi%
  }%
  \savedmacro\numinputs{\let\numinputs\pgf@lib@sh@logicgate@numinputs}%
  \saveddimen\invertedradius{%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
  }%
  \saveddimen\outerinvertedradius{%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
    \advance\pgf@x.5\pgflinewidth%
  }
  \savedmacro\dimensions{%
    \pgf@lib@sh@logicgates@dimensions@IEC{and}%
  }
  \savedanchor\centerpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y.5\ht\pgfnodeparttextbox%
    \advance\pgf@y-.5\dp\pgfnodeparttextbox%
  }
  \savedanchor\midpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@y{+0.5ex}%
  }
  \savedanchor\basepoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y0pt%
  }
  \anchor{center}{\centerpoint}%
  \anchor{mid}{\midpoint}
  \anchor{mid west}{%
    \dimensions%
    \midpoint%
    \advance\pgf@x-\halfwidth}%
  \anchor{mid east}{%
    \dimensions%
    \midpoint%
    \advance\pgf@x\halfwidth}%
  \anchor{base}{\basepoint}
  \anchor{base west}{%
    \dimensions%
    \basepoint%
    \advance\pgf@x-\halfwidth}%
  \anchor{base east}{%
    \dimensions%
    \basepoint%
    \advance\pgf@x\halfwidth}%
  \anchor{north}{\dimensions\centerpoint\advance\pgf@y\halfheight}%
  \anchor{south}{\dimensions\centerpoint\advance\pgf@y-\halfheight}%
  \anchor{east}{\dimensions\centerpoint\advance\pgf@x\halfwidth}%
  \anchor{west}{\dimensions\centerpoint\advance\pgf@x-\halfwidth}%
  \anchor{north east}{\dimensions\centerpoint\advance\pgf@x\halfwidth\advance\pgf@y\halfheight}%
  \anchor{north west}{\dimensions\centerpoint\advance\pgf@x-\halfwidth\advance\pgf@y\halfheight}%
  \anchor{south east}{\dimensions\centerpoint\advance\pgf@x\halfwidth\advance\pgf@y-\halfheight}%
  \anchor{south west}{\dimensions\centerpoint\advance\pgf@x-\halfwidth\advance\pgf@y-\halfheight}%
  \anchor{output}{\dimensions\centerpoint\advance\pgf@x\halfwidth} 
  \backgroundpath{%
    \dimensions%
    \pgf@xc\halfwidth%
    \pgf@yc\halfheight%
    \pgfmathaddtolength\pgf@xc{-\pgfkeysvalueof{/pgf/outer xsep}}%
    \pgfmathaddtolength\pgf@yc{-\pgfkeysvalueof{/pgf/outer xsep}}%
    {%
      \pgftransformshift{\centerpoint}%
      \pgfpathrectangle{\pgfqpoint{-\pgf@xc}{-\pgf@yc}}%
        {%
          \pgf@xc2.0\pgf@xc%
          \pgf@yc2.0\pgf@yc%
          \pgfqpoint{\pgf@xc}{\pgf@yc}%
        }%
      \pgfpathclose%
      %
      % Draw inputs.
      %
      \pgf@xc-\halfwidth%
      \advance\pgf@xc-\invertedradius%
      \pgf@yc\halfheight%
      \pgfutil@tempdima2.0\pgf@yc%
      \c@pgf@counta\numinputs%
      \advance\c@pgf@counta1\relax%
      \divide\pgfutil@tempdima\c@pgf@counta%
      \pgfmathloop%
      \ifnum\pgfmathcounter>\numinputs%
      \else%
        \advance\pgf@yc-\pgfutil@tempdima%
        \expandafter\ifx\expandafter\pgf@lib@sh@itext\csname input-\pgfmathcounter\endcsname%
          {%
            \pgfpathcircle{\pgfqpoint{\pgf@xc}{\pgf@yc}}{\invertedradius}%      
          }%
        \fi%
      \repeatpgfmathloop%
    }%
  }
  \foregroundpath{\pgf@lib@sh@logicgates@IEC@foregroundpath{and}}
  \anchorborder{%
    \pgfextract@process\externalpoint{}%
    \dimensions%
    \pgfpointadd{\centerpoint}{\pgfpointborderrectangle{\externalpoint}{\pgfqpoint{\halfwidth}{\halfheight}}}%
  }%  
}





% Shape nand gate IEC
%
\pgfdeclareshape{nand gate IEC}{
  \expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@nand gate IEC\endcsname{%
    \pgf@lib@sh@logicgate@parseinputs{1024}% Maximum 1024 (!) inputs.
    %
    \pgfmathloop%
    \ifnum\pgfmathcounter>\pgf@lib@sh@logicgate@numinputs%
    \else%
      \pgfutil@ifundefined{pgf@anchor@nand gate IEC@input \pgfmathcounter}{%
        \expandafter\xdef\csname pgf@anchor@nand gate IEC@input \pgfmathcounter\endcsname{%
          \noexpand\pgf@lib@sh@logicgate@IEC@inputanchor{\pgfmathcounter}%
        }%
      }{}%
    \repeatpgfmathloop%
    \ifnum\pgf@lib@sh@logicgate@numinputs<2\relax%
      \pgferror{A nand gate must have at least two inputs}%
    \fi%
  }%
  \savedmacro\numinputs{\let\numinputs\pgf@lib@sh@logicgate@numinputs}%
  \saveddimen\invertedradius{%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
  }%
  \saveddimen\outerinvertedradius{%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
    \advance\pgf@x.5\pgflinewidth%
  }
  \savedmacro\dimensions{%
    \pgf@lib@sh@logicgates@dimensions@IEC{nand}%
  }
  \savedanchor\centerpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y.5\ht\pgfnodeparttextbox%
    \advance\pgf@y-.5\dp\pgfnodeparttextbox%
  }
  \savedanchor\midpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@y{+0.5ex}%
  }
  \savedanchor\basepoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y0pt%
  }
  \inheritanchor[from=and gate IEC]{center}
  \inheritanchor[from=and gate IEC]{mid}
  \inheritanchor[from=and gate IEC]{mid west}
  \inheritanchor[from=and gate IEC]{mid east}
  \inheritanchor[from=and gate IEC]{base}
  \inheritanchor[from=and gate IEC]{base west}
  \inheritanchor[from=and gate IEC]{base east}
  \inheritanchor[from=and gate IEC]{north}
  \inheritanchor[from=and gate IEC]{south}
  \inheritanchor[from=and gate IEC]{east}
  \inheritanchor[from=and gate IEC]{west}
  \inheritanchor[from=and gate IEC]{north east}
  \inheritanchor[from=and gate IEC]{north west}
  \inheritanchor[from=and gate IEC]{south east}
  \inheritanchor[from=and gate IEC]{south west}
  \anchor{output}{%
    \csname pgf@anchor@and gate IEC@east\endcsname%
    \advance\pgf@x\invertedradius%
    \advance\pgf@x\outerinvertedradius%
  }
  \backgroundpath{%
    \csname pgf@sh@bg@and gate IEC\endcsname%
    \pgfpathcircle{%
      \centerpoint%
      \advance\pgf@x\halfwidth%
      \advance\pgf@x\invertedradius%
    }{+\invertedradius}%
  }
  \foregroundpath{\pgf@lib@sh@logicgates@IEC@foregroundpath{nand}}
  \inheritanchorborder[from=and gate IEC]
}





% Shape or gate IEC
%
\pgfdeclareshape{or gate IEC}{
  \expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@or gate IEC\endcsname{%
    \pgf@lib@sh@logicgate@parseinputs{1024}% Maximum 1024 (!) inputs.
    %
    \pgfmathloop%
    \ifnum\pgfmathcounter>\pgf@lib@sh@logicgate@numinputs%
    \else%
      \pgfutil@ifundefined{pgf@anchor@or gate IEC@input \pgfmathcounter}{%
        \expandafter\xdef\csname pgf@anchor@or gate IEC@input \pgfmathcounter\endcsname{%
          \noexpand\pgf@lib@sh@logicgate@IEC@inputanchor{\pgfmathcounter}%
        }%
      }{}%
    \repeatpgfmathloop%
    \ifnum\pgf@lib@sh@logicgate@numinputs<2\relax%
      \pgferror{An or gate must have at least two inputs}%
    \fi%
  }%
  \savedmacro\numinputs{\let\numinputs\pgf@lib@sh@logicgate@numinputs}%
  \saveddimen\invertedradius{%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
  }%
  \saveddimen\outerinvertedradius{%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
    \advance\pgf@x.5\pgflinewidth%
  }
  \savedmacro\dimensions{%
    \pgf@lib@sh@logicgates@dimensions@IEC{or}%
  }
  \savedanchor\centerpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y.5\ht\pgfnodeparttextbox%
    \advance\pgf@y-.5\dp\pgfnodeparttextbox%
  }
  \savedanchor\midpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@y{+0.5ex}%
  }
  \savedanchor\basepoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y0pt%
  }
  \inheritanchor[from=and gate IEC]{center}
  \inheritanchor[from=and gate IEC]{mid}
  \inheritanchor[from=and gate IEC]{mid west}
  \inheritanchor[from=and gate IEC]{mid east}
  \inheritanchor[from=and gate IEC]{base}
  \inheritanchor[from=and gate IEC]{base west}
  \inheritanchor[from=and gate IEC]{base east}
  \inheritanchor[from=and gate IEC]{north}
  \inheritanchor[from=and gate IEC]{south}
  \inheritanchor[from=and gate IEC]{east}
  \inheritanchor[from=and gate IEC]{west}
  \inheritanchor[from=and gate IEC]{north east}
  \inheritanchor[from=and gate IEC]{north west}
  \inheritanchor[from=and gate IEC]{south east}
  \inheritanchor[from=and gate IEC]{south west}
  \inheritanchor[from=and gate IEC]{output}
  \inheritbackgroundpath[from=and gate IEC]
  \foregroundpath{\pgf@lib@sh@logicgates@IEC@foregroundpath{or}}
  \inheritanchorborder[from=and gate IEC]
}





% Shape nor gate IEC
%
\pgfdeclareshape{nor gate IEC}{
  \expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@nor gate IEC\endcsname{%
    \pgf@lib@sh@logicgate@parseinputs{1024}% Maximum 1024 (!) inputs.
    %
    \pgfmathloop%
    \ifnum\pgfmathcounter>\pgf@lib@sh@logicgate@numinputs%
    \else%
      \pgfutil@ifundefined{pgf@anchor@nor gate IEC@input \pgfmathcounter}{%
        \expandafter\xdef\csname pgf@anchor@nor gate IEC@input \pgfmathcounter\endcsname{%
          \noexpand\pgf@lib@sh@logicgate@IEC@inputanchor{\pgfmathcounter}%
        }%
      }{}%
    \repeatpgfmathloop%
    \ifnum\pgf@lib@sh@logicgate@numinputs<2\relax%
      \pgferror{A nor gate must have at least two inputs}%
    \fi%
  }%
  \savedmacro\numinputs{\let\numinputs\pgf@lib@sh@logicgate@numinputs}%
  \saveddimen\invertedradius{%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
  }%
  \saveddimen\outerinvertedradius{%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
    \advance\pgf@x.5\pgflinewidth%
  }
  \savedmacro\dimensions{%
    \pgf@lib@sh@logicgates@dimensions@IEC{nor}%
  }
  \savedanchor\centerpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y.5\ht\pgfnodeparttextbox%
    \advance\pgf@y-.5\dp\pgfnodeparttextbox%
  }
  \savedanchor\midpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@y{+0.5ex}%
  }
  \savedanchor\basepoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y0pt%
  }
  \inheritanchor[from=and gate IEC]{center}
  \inheritanchor[from=and gate IEC]{mid}
  \inheritanchor[from=and gate IEC]{mid west}
  \inheritanchor[from=and gate IEC]{mid east}
  \inheritanchor[from=and gate IEC]{base}
  \inheritanchor[from=and gate IEC]{base west}
  \inheritanchor[from=and gate IEC]{base east}
  \inheritanchor[from=and gate IEC]{north}
  \inheritanchor[from=and gate IEC]{south}
  \inheritanchor[from=and gate IEC]{east}
  \inheritanchor[from=and gate IEC]{west}
  \inheritanchor[from=and gate IEC]{north east}
  \inheritanchor[from=and gate IEC]{north west}
  \inheritanchor[from=and gate IEC]{south east}
  \inheritanchor[from=and gate IEC]{south west}
  \inheritanchor[from=nand gate IEC]{output}%
  \inheritbackgroundpath[from=nand gate IEC]
  \foregroundpath{\pgf@lib@sh@logicgates@IEC@foregroundpath{nor}}
  \inheritanchorborder[from=and gate IEC]
}





% Shape xor gate IEC
%
\pgfdeclareshape{xor gate IEC}{
  \expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@xor gate IEC\endcsname{%
    \pgf@lib@sh@logicgate@parseinputs{2}% Maximum 1024 (!) inputs.
    %
    \pgfmathloop%
    \ifnum\pgfmathcounter>\pgf@lib@sh@logicgate@numinputs%
    \else%
      \pgfutil@ifundefined{pgf@anchor@xor gate IEC@input \pgfmathcounter}{%
        \expandafter\xdef\csname pgf@anchor@xor gate IEC@input \pgfmathcounter\endcsname{%
          \noexpand\pgf@lib@sh@logicgate@IEC@inputanchor{\pgfmathcounter}%
        }%
      }{}%
    \repeatpgfmathloop%
    \ifnum\pgf@lib@sh@logicgate@numinputs<2\relax%
      \pgferror{An xor gate must have two inputs}%
    \fi%
  }%
  \savedmacro\numinputs{\let\numinputs\pgf@lib@sh@logicgate@numinputs}%
  \saveddimen\invertedradius{%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
  }%
  \saveddimen\outerinvertedradius{%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
    \advance\pgf@x.5\pgflinewidth%
  }
  \savedmacro\dimensions{%
    \pgf@lib@sh@logicgates@dimensions@IEC{xor}%
  }
  \savedanchor\centerpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y.5\ht\pgfnodeparttextbox%
    \advance\pgf@y-.5\dp\pgfnodeparttextbox%
  }
  \savedanchor\midpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@y{+0.5ex}%
  }
  \savedanchor\basepoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y0pt%
  }
  \inheritanchor[from=and gate IEC]{center}
  \inheritanchor[from=and gate IEC]{mid}
  \inheritanchor[from=and gate IEC]{mid west}
  \inheritanchor[from=and gate IEC]{mid east}
  \inheritanchor[from=and gate IEC]{base}
  \inheritanchor[from=and gate IEC]{base west}
  \inheritanchor[from=and gate IEC]{base east}
  \inheritanchor[from=and gate IEC]{north}
  \inheritanchor[from=and gate IEC]{south}
  \inheritanchor[from=and gate IEC]{east}
  \inheritanchor[from=and gate IEC]{west}
  \inheritanchor[from=and gate IEC]{north east}
  \inheritanchor[from=and gate IEC]{north west}
  \inheritanchor[from=and gate IEC]{south east}
  \inheritanchor[from=and gate IEC]{south west}
  \inheritanchor[from=and gate IEC]{output}
  \inheritbackgroundpath[from=and gate IEC]
  \foregroundpath{\pgf@lib@sh@logicgates@IEC@foregroundpath{xor}}
  \inheritanchorborder[from=and gate IEC]
}




% Shape xnor gate IEC
%

\pgfdeclareshape{xnor gate IEC}{
  \expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@xnor gate IEC\endcsname{%
    \pgf@lib@sh@logicgate@parseinputs{1024}% Maximum 1024 (!) inputs.
    %
    \pgfmathloop%
    \ifnum\pgfmathcounter>\pgf@lib@sh@logicgate@numinputs%
    \else%
      \pgfutil@ifundefined{pgf@anchor@xnor gate IEC@input \pgfmathcounter}{%
        \expandafter\xdef\csname pgf@anchor@xnor gate IEC@input \pgfmathcounter\endcsname{%
          \noexpand\pgf@lib@sh@logicgate@IEC@inputanchor{\pgfmathcounter}%
        }%
      }{}%
    \repeatpgfmathloop%
    \ifnum\pgf@lib@sh@logicgate@numinputs<2\relax%
      \pgferror{A xnor gate must have two inputs}%
    \fi%
  }%
  \savedmacro\numinputs{\let\numinputs\pgf@lib@sh@logicgate@numinputs}%
  \saveddimen\invertedradius{%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
  }%
  \saveddimen\outerinvertedradius{%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
    \advance\pgf@x.5\pgflinewidth%
  }
  \savedmacro\dimensions{%
    \pgf@lib@sh@logicgates@dimensions@IEC{xnor}%
  }
  \savedanchor\centerpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y.5\ht\pgfnodeparttextbox%
    \advance\pgf@y-.5\dp\pgfnodeparttextbox%
  }
  \savedanchor\midpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@y{+0.5ex}%
  }
  \savedanchor\basepoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y0pt%
  }
  \inheritanchor[from=and gate IEC]{center}
  \inheritanchor[from=and gate IEC]{mid}
  \inheritanchor[from=and gate IEC]{mid west}
  \inheritanchor[from=and gate IEC]{mid east}
  \inheritanchor[from=and gate IEC]{base}
  \inheritanchor[from=and gate IEC]{base west}
  \inheritanchor[from=and gate IEC]{base east}
  \inheritanchor[from=and gate IEC]{north}
  \inheritanchor[from=and gate IEC]{south}
  \inheritanchor[from=and gate IEC]{east}
  \inheritanchor[from=and gate IEC]{west}
  \inheritanchor[from=and gate IEC]{north east}
  \inheritanchor[from=and gate IEC]{north west}
  \inheritanchor[from=and gate IEC]{south east}
  \inheritanchor[from=and gate IEC]{south west}
  \inheritanchor[from=nand gate IEC]{output}
  \inheritbackgroundpath[from=nand gate IEC]
  \foregroundpath{\pgf@lib@sh@logicgates@IEC@foregroundpath{xnor}}
  \inheritanchorborder[from=and gate IEC]
}




% Shape buffer gate IEC
%
\pgfdeclareshape{buffer gate IEC}{
  \expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@buffer gate IEC\endcsname{%
    \pgf@lib@sh@logicgate@parseinputs{1}% Maximum 1 input.
    %
    \expandafter\gdef\csname pgf@anchor@buffer gate IEC@input\endcsname{%
      \pgf@lib@sh@logicgate@IEC@inputanchor{1}%
    }%
    \ifnum\pgf@lib@sh@logicgate@numinputs=0\relax%
      \pgferror{A buffer gate must have one inputs}%
    \fi%
  }%
  \savedmacro\numinputs{\let\numinputs\pgf@lib@sh@logicgate@numinputs}%
  \saveddimen\invertedradius{%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
  }%
  \saveddimen\outerinvertedradius{%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
    \advance\pgf@x.5\pgflinewidth%
  }
  \savedmacro\dimensions{%
    \pgf@lib@sh@logicgates@dimensions@IEC{xor}%
  }
  \savedanchor\centerpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y.5\ht\pgfnodeparttextbox%
    \advance\pgf@y-.5\dp\pgfnodeparttextbox%
  }
  \savedanchor\midpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@y{+0.5ex}%
  }
  \savedanchor\basepoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y0pt%
  }
  \inheritanchor[from=and gate IEC]{center}
  \inheritanchor[from=and gate IEC]{mid}
  \inheritanchor[from=and gate IEC]{mid west}
  \inheritanchor[from=and gate IEC]{mid east}
  \inheritanchor[from=and gate IEC]{base}
  \inheritanchor[from=and gate IEC]{base west}
  \inheritanchor[from=and gate IEC]{base east}
  \inheritanchor[from=and gate IEC]{north}
  \inheritanchor[from=and gate IEC]{south}
  \inheritanchor[from=and gate IEC]{east}
  \inheritanchor[from=and gate IEC]{west}
  \inheritanchor[from=and gate IEC]{north east}
  \inheritanchor[from=and gate IEC]{north west}
  \inheritanchor[from=and gate IEC]{south east}
  \inheritanchor[from=and gate IEC]{south west}
  \inheritanchor[from=and gate IEC]{output}
  \inheritbackgroundpath[from=and gate IEC]
  \foregroundpath{\pgf@lib@sh@logicgates@IEC@foregroundpath{buffer}}
  \inheritanchorborder[from=and gate IEC]
}





% Shape not gate IEC
%
\pgfdeclareshape{not gate IEC}{
  \expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@not gate IEC\endcsname{%
    \pgf@lib@sh@logicgate@parseinputs{1}%
    %
    \pgfutil@ifundefined{pgf@anchor@not gate IEC@input}{%
      \expandafter\gdef\csname pgf@anchor@not gate IEC@input\endcsname{%
          \pgf@lib@sh@logicgate@IEC@inputanchor{1}%
        }}{}%
    \ifnum\pgf@lib@sh@logicgate@numinputs=0\relax%
      \pgferror{A not gate must have one input}%
    \fi%
  }%
  \savedmacro\numinputs{\let\numinputs\pgf@lib@sh@logicgate@numinputs}%
  \saveddimen\invertedradius{%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
  }%
  \saveddimen\outerinvertedradius{%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
    \advance\pgf@x.5\pgflinewidth%
  }
  \savedmacro\dimensions{%
    \pgf@lib@sh@logicgates@dimensions@IEC{not}%
  }
  \savedanchor\centerpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y.5\ht\pgfnodeparttextbox%
    \advance\pgf@y-.5\dp\pgfnodeparttextbox%
  }
  \savedanchor\midpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@y{+0.5ex}%
  }
  \savedanchor\basepoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y0pt%
  }
  \inheritanchor[from=and gate IEC]{center}
  \inheritanchor[from=and gate IEC]{mid}
  \inheritanchor[from=and gate IEC]{mid west}
  \inheritanchor[from=and gate IEC]{mid east}
  \inheritanchor[from=and gate IEC]{base}
  \inheritanchor[from=and gate IEC]{base west}
  \inheritanchor[from=and gate IEC]{base east}
  \inheritanchor[from=and gate IEC]{north}
  \inheritanchor[from=and gate IEC]{south}
  \inheritanchor[from=and gate IEC]{east}
  \inheritanchor[from=and gate IEC]{west}
  \inheritanchor[from=and gate IEC]{north east}
  \inheritanchor[from=and gate IEC]{north west}
  \inheritanchor[from=and gate IEC]{south east}
  \inheritanchor[from=and gate IEC]{south west}
  \inheritanchor[from=nand gate IEC]{output}
  \inheritbackgroundpath[from=nand gate IEC]
  \foregroundpath{\pgf@lib@sh@logicgates@IEC@foregroundpath{not}}
  \inheritanchorborder[from=and gate IEC]
}

\endinput
pgflibraryshapes.gates.logic.US.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.

\usepgflibrary{shapes.gates.logic}


\newif\ifpgfgateanchorsuseboundingrectangle%


% Keys for US/CDH logic gates.
%
\pgfkeys{
  /pgf/logic gate anchors use bounding box/.is if=pgfgateanchorsuseboundingrectangle,%
}

% An internal macro for calculating internal dimensions of 
% the US + CDH gates (excluding and gate US and nand gate US).
%
\def\pgf@lib@sh@logicgates@dimensions@orUS{%
	\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
	\advance\pgf@x.5\wd\pgfnodeparttextbox%
	\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
	\advance\pgf@y.5\ht\pgfnodeparttextbox%
	\advance\pgf@y.5\dp\pgfnodeparttextbox%
	%
	% Adjust the height for the number of inputs.
	%
	\c@pgf@counta\pgf@lib@sh@logicgate@numinputs%
	\advance\c@pgf@counta1\relax%
	\pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
	\advance\pgf@ya\pgflinewidth%
	\pgfmathsetlength\pgf@yb{\pgfkeysvalueof{/pgf/logic gate input sep}}%
	\pgf@yb.5\pgf@yb%
	\ifdim\pgf@ya<\pgf@yb%
		\pgf@ya\pgf@yb%
	\fi%	
	\multiply\pgf@ya\c@pgf@counta%
	\ifdim\pgf@y<\pgf@ya%
		\pgf@y\pgf@ya%
	\fi%
	%
	\ifdim\pgf@x>\pgf@y%
		\pgf@y\pgf@x%
	\else%
		\pgf@x\pgf@y%
	\fi%
	%
	% Adjust for minimum height and width.
	%
	\pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/minimum width}}%
	\pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/minimum height}}%
	\ifdim\pgf@y<.5\pgf@ya%
		\pgf@y.5\pgf@ya%
	\fi%
	\pgf@xb\pgf@x%
	\advance\pgf@xb1.732051\pgf@y% 2y*cos(30)
	\ifdim\pgf@xb<\pgf@xa%
		\pgf@xb\pgf@xa%
		\pgf@x0.366025\pgf@xb% xb / (1 + 2*cos(30))
	\fi%
	%
	\ifdim\pgf@x>\pgf@y%
		\pgf@y\pgf@x%
	\else%
		\pgf@x\pgf@y%
	\fi%
	\edef\halfside{\the\pgf@x}%
	\addtosavedmacro\halfside%
	%
	% Take into account the outer sep.
	%
	\pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/outer xsep}}%
	\pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/outer ysep}}%
	\edef\outerxsep{\the\pgf@xa}%
	\edef\outerysep{\the\pgf@ya}%
	\addtosavedmacro\outerxsep%
	\addtosavedmacro\outerysep%
	\advance\pgf@x\pgf@xa%
	\advance\pgf@y\pgf@ya%
	%
	\edef\halfwidth{\the\pgf@x}%
	\edef\halfheight{\the\pgf@y}%
	\addtosavedmacro\halfwidth%
	\addtosavedmacro\halfheight%
	%
	\pgfextract@process\tipanchor{%
		\advance\pgf@x-\pgf@xa%
		\advance\pgf@y-\pgf@ya%	
		\pgf@x-.16666\pgf@x%
		\pgf@yb2.0\pgf@y%
		\advance\pgf@x.866025\pgf@yb%	
		\advance\pgf@x1.154701\pgf@xa%
		\pgf@y0pt%
	}%
	\addtosavedmacro\tipanchor%		
}%


% An internal macro for calculating internal dimensions of 
% the and gate US and nand gate US.
%
\def\pgf@lib@sh@logicgates@dimensions@andUS{%
	\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
	\advance\pgf@x.5\wd\pgfnodeparttextbox%
	\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
	\advance\pgf@y.5\ht\pgfnodeparttextbox%
	\advance\pgf@y.5\dp\pgfnodeparttextbox%
	%
	% Adjust the height for the number of inputs.
	%
	\c@pgf@counta\pgf@lib@sh@logicgate@numinputs%
	\advance\c@pgf@counta1\relax%
	\pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
	\advance\pgf@ya\pgflinewidth%
	\pgfmathsetlength\pgf@yb{\pgfkeysvalueof{/pgf/logic gate input sep}}%
	\pgf@yb.5\pgf@yb%
	\ifdim\pgf@ya<\pgf@yb%
		\pgf@ya\pgf@yb%
	\fi%	
	\multiply\pgf@ya\c@pgf@counta%
	\ifdim\pgf@y<\pgf@ya%
		\pgf@y\pgf@ya%
	\fi%
	%
	\ifdim\pgf@x>\pgf@y%
		\pgf@y\pgf@x%
	\else%
		\pgf@x\pgf@y%
	\fi%
	%
	% Adjust for minimum height and width.
	%
	\pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/minimum width}}%
	\pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/minimum height}}%
	\ifdim\pgf@y<.5\pgf@ya%
		\pgf@y.5\pgf@ya%
	\fi%
	\pgf@xb2.5\pgf@x%
	\ifdim\pgf@xb<\pgf@xa%
		\pgf@xb\pgf@xa%
		\pgf@x0.4\pgf@xb% 
	\fi% 
	%
	\ifdim\pgf@x>\pgf@y%
		\pgf@y\pgf@x%
	\else%
		\pgf@x\pgf@y%
	\fi%
	\edef\halfside{\the\pgf@x}%
	\addtosavedmacro\halfside%
	%
	% Take into account the outer sep.
	%
	\pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/outer xsep}}%
	\pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/outer ysep}}%
	\edef\outerxsep{\the\pgf@xa}%
	\edef\outerysep{\the\pgf@ya}%
	\addtosavedmacro\outerxsep%
	\addtosavedmacro\outerysep%
	\advance\pgf@x\pgf@xa%
	\advance\pgf@y\pgf@ya%
	%
	\edef\halfwidth{\the\pgf@x}%
	\edef\halfheight{\the\pgf@y}%
	\addtosavedmacro\halfwidth%
	\addtosavedmacro\halfheight%
	%
}%


% Internal macro for calculation input anchors. Used by
% both and gates and nand gates, and also the not gate and buffer.
%
\def\pgf@lib@sh@logicgate@AND@inputanchor#1{%
	\dimensions%
	\centerpoint%
	\pgf@xa\halfside%
	\advance\pgf@x-.166666\pgf@xa%
	\advance\pgf@x-\halfwidth%
	\expandafter\ifx\expandafter\pgf@lib@sh@itext\csname input-#1\endcsname%
		\advance\pgf@x-\invertedradius%
		\advance\pgf@x-\outerinvertedradius%
	\fi%
	%
	\pgfutil@tempdima\halfside%
	\multiply\pgfutil@tempdima2\relax%
	\c@pgf@counta\numinputs%
	\advance\c@pgf@counta1\relax%
	\divide\pgfutil@tempdima\c@pgf@counta%
	\multiply\pgfutil@tempdima#1\relax%
	\advance\pgf@y\halfside%
	\advance\pgf@y-\pgfutil@tempdima%
}




% Shape and gate US
%
\pgfdeclareshape{and gate US}{%
	\expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@and gate US\endcsname{%
		\pgf@lib@sh@logicgate@parseinputs{1024}% Maximum 1024 (!) inputs.
		%
		\pgfmathloop%
		\ifnum\pgfmathcounter>\pgf@lib@sh@logicgate@numinputs%
		\else%
			\pgfutil@ifundefined{pgf@anchor@and gate US@input \pgfmathcounter}{%
				\expandafter\xdef\csname pgf@anchor@and gate US@input \pgfmathcounter\endcsname{%
					\noexpand\pgf@lib@sh@logicgate@AND@inputanchor{\pgfmathcounter}%
				}%
			}{}%
		\repeatpgfmathloop%
		\ifnum\pgf@lib@sh@logicgate@numinputs<2\relax%
			\pgferror{An and gate must have at least two inputs}%
		\fi%
	}%
	\savedmacro\numinputs{\let\numinputs\pgf@lib@sh@logicgate@numinputs}%
	\saveddimen\invertedradius{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
	}%
	\saveddimen\outerinvertedradius{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
		\advance\pgf@x.5\pgflinewidth%
	}
	\savedmacro\dimensions{\pgf@lib@sh@logicgates@dimensions@andUS}
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+0.5ex}%
	}
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt%
	}
	\anchor{center}{\centerpoint}%
	\anchor{mid}{\midpoint}%
	\anchor{mid east}{%
		\csname pgf@anchor@and gate US@east\endcsname%
		\pgf@xa\pgf@x%
		\midpoint%
		\pgf@x\pgf@xa}
	\anchor{mid west}{%
		\csname pgf@anchor@and gate US@west\endcsname%
		\pgf@xa\pgf@x%
		\midpoint%
		\pgf@x\pgf@xa}
	\anchor{base}{\basepoint}%
	\anchor{base east}{%
		\csname pgf@anchor@and gate US@east\endcsname%
		\pgf@xa\pgf@x%
		\basepoint%
		\pgf@x\pgf@xa}
	\anchor{base west}{%
		\csname pgf@anchor@and gate US@west\endcsname%
		\pgf@xa\pgf@x%
		\basepoint%
		\pgf@x\pgf@xa}
	\anchor{east}{%
		\dimensions%
		\pgf@xa\halfwidth%
		\pgf@xb\pgf@xa%
		\advance\pgf@xb-\outerxsep%
		\centerpoint%
		\advance\pgf@x.333333\pgf@xb%
		\advance\pgf@x\pgf@xa%
	}
	\anchor{output}{\csname pgf@anchor@and gate US@east\endcsname}
	\anchor{north east}{%
		\dimensions%
		\ifpgfgateanchorsuseboundingrectangle%
			\csname pgf@anchor@nand gate US@east\endcsname%
			\advance\pgf@y\halfheight%
		\else
			\pgf@xa\halfwidth%
			\pgf@ya\halfheight%
			\pgf@xb\pgf@xa%
			\advance\pgf@xb-\outerxsep%
			\centerpoint%
			\advance\pgf@x.333333\pgf@xb%
			\advance\pgf@x.707106\pgf@xa%
			\advance\pgf@y.707106\pgf@ya%
		\fi%
	}
	\anchor{south east}{%
		\dimensions%
		\ifpgfgateanchorsuseboundingrectangle%
			\csname pgf@anchor@nand gate US@east\endcsname%
			\advance\pgf@y-\halfheight%
		\else
			\pgf@xa\halfwidth%
			\pgf@ya\halfheight%
			\pgf@xb\pgf@xa%
			\advance\pgf@xb-\outerxsep%
			\centerpoint%
			\advance\pgf@x.333333\pgf@xb%
			\advance\pgf@x.707106\pgf@xa%
			\advance\pgf@y-.707106\pgf@ya%
		\fi%
	}
	\anchor{north}{%
		\dimensions%
		\centerpoint%
		\advance\pgf@y\halfheight%		
	}
	\anchor{south}{%
		\dimensions%
		\centerpoint%
		\advance\pgf@y-\halfheight%
	}
	\anchor{south west}{%
		\dimensions%
		\centerpoint%
		\pgf@xa\halfside%
		\advance\pgf@x-1.16666\pgf@xa%
		\advance\pgf@x-\outerxsep%
		\advance\pgf@y-\halfheight%
	}
	\anchor{north west}{%
		\dimensions%
		\centerpoint%
		\pgf@xa\halfside%
		\advance\pgf@x-1.16666\pgf@xa%
		\advance\pgf@x-\outerxsep%
		\advance\pgf@y\halfheight%
	}
	\anchor{west}{%
		\dimensions%
		\centerpoint%
		\pgf@xa\halfside%
		\advance\pgf@x-1.16666\pgf@xa%
		\advance\pgf@x-\outerxsep%
	}
	\backgroundpath{%
		\dimensions%
		\pgf@xc\halfwidth%
		\pgf@yc\halfheight%
		\advance\pgf@xc-\outerxsep%
		\advance\pgf@yc-\outerysep%
		\pgf@xb.333333\pgf@xc%
		{%
			\pgftransformshift{\centerpoint}%
			\pgfpathmoveto{\pgfqpoint{\pgf@xb}{\pgf@yc}}%
			{%
				\edef\pgf@marshal{%
					\noexpand\pgfpatharc{90}{-90}{\the\pgf@yc}%
				}%
				\pgf@marshal%
			}
			\pgfpathlineto{\pgfqpoint{-1.16666\pgf@xc}{-\pgf@yc}}%
			\pgfpathlineto{\pgfqpoint{-1.16666\pgf@xc}{\pgf@yc}}%
			\pgfpathclose%
			%
			% Draw the inputs.
			%
			\pgfutil@tempdima2.0\pgf@yc%
			\c@pgf@counta\numinputs%
			\advance\c@pgf@counta1\relax%
			\divide\pgfutil@tempdima\c@pgf@counta%
			\pgfmathloop%
			\ifnum\pgfmathcounter>\numinputs%
			\else%
				\advance\pgf@yc-\pgfutil@tempdima%
				\expandafter\ifx\expandafter\pgf@lib@sh@itext\csname input-\pgfmathcounter\endcsname%
					{%
						\pgfpathcircle{%
							\pgf@xa\halfside%
							\pgf@x-1.16666\pgf@xa%
							\advance\pgf@x-.5\pgflinewidth%
							\advance\pgf@x-\invertedradius%
							\pgf@y\pgf@yc%
						}{+\invertedradius}%				
					}%
				\fi%				
			\repeatpgfmathloop%
		}%
	}%
	\anchorborder{%
		\pgfextract@process\externalpoint{}%
		\pgfextract@process\externalpoint{\pgfpointadd{\centerpoint}{\externalpoint}}%
		\pgfmathanglebetweenpoints{\centerpoint}{\externalpoint}%
		\let\externalangle\pgfmathresult%
		\dimensions%
		\pgf@xb\halfside%
		\pgf@xc1.66666\pgf@xb%
		\advance\pgf@xc\outerxsep%
		\pgf@yc\halfheight%
		\pgfmathanglebetweenpoints{\centerpoint}{\csname pgf@anchor@and gate US@north west\endcsname}%
		\ifdim\externalangle pt<\pgfmathresult pt\relax%
			\pgfmathanglebetweenpoints{\centerpoint}{\centerpoint\advance\pgf@x.333333\pgf@xb\advance\pgf@y\pgf@yc}%
			\ifdim\externalangle pt<\pgfmathresult pt\relax%
				\pgfmathpointintersectionoflineandarc{\externalpoint}{\centerpoint}%
					{%
						\centerpoint%
						\advance\pgf@x.333333\pgf@xb%	
					}%
					{0}{90}{+\halfwidth and +\halfheight}%
			\else%
				\pgfpointintersectionoflines{\externalpoint}{\centerpoint}%
					{\centerpoint\advance\pgf@x.333333\pgf@xb\advance\pgf@y\pgf@yc}%
					{\centerpoint\advance\pgf@x-\pgf@xc\advance\pgf@y\pgf@yc}%			
			\fi%
		\else%
			\pgfmathanglebetweenpoints{\centerpoint}{\centerpoint\advance\pgf@x.333333\pgf@xb\advance\pgf@y-\pgf@yc}%
			\ifdim\externalangle pt>\pgfmathresult pt\relax%
					\pgfmathpointintersectionoflineandarc{\externalpoint}{\centerpoint}%
					{%
						\centerpoint%
						\advance\pgf@x.333333\pgf@xb%		
					}%
					{270}{360}{+\halfwidth and +\halfheight}%
			\else%
				\pgfmathanglebetweenpoints{\centerpoint}{\csname pgf@anchor@and gate US@south west\endcsname}%
				\ifdim\externalangle pt>\pgfmathresult pt\relax%
					\pgfpointintersectionoflines{\externalpoint}{\centerpoint}%
						{\centerpoint\advance\pgf@x.333333\pgf@xb\advance\pgf@y-\pgf@yc}%
						{\csname pgf@anchor@and gate US@south west\endcsname}%	
				\else%
					\pgfpointintersectionoflines{\externalpoint}{\centerpoint}%
						{\csname pgf@anchor@and gate US@north west\endcsname}%
						{\csname pgf@anchor@and gate US@south west\endcsname}%
				\fi%
			\fi%
		\fi%
	}
}





% Shape nand gate US
%
\pgfdeclareshape{nand gate US}{%
	\expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@nand gate US\endcsname{%
		\pgf@lib@sh@logicgate@parseinputs{1024}% Maximum 1024 (!) inputs.
		%
		\pgfmathloop%
		\ifnum\pgfmathcounter>\pgf@lib@sh@logicgate@numinputs%
		\else%
			\pgfutil@ifundefined{pgf@anchor@nand gate US@input \pgfmathcounter}{%
				\expandafter\xdef\csname pgf@anchor@nand gate US@input \pgfmathcounter\endcsname{%
					\noexpand\pgf@lib@sh@logicgate@AND@inputanchor{\pgfmathcounter}%
				}%
			}{}%
		\repeatpgfmathloop%
		\ifnum\pgf@lib@sh@logicgate@numinputs<2\relax%
			\pgferror{A nand gate must have at least two inputs}%
		\fi%
	}%
	\savedmacro\numinputs{\let\numinputs\pgf@lib@sh@logicgate@numinputs}%
	\saveddimen\invertedradius{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
	}%
	\saveddimen\outerinvertedradius{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
		\advance\pgf@x.5\pgflinewidth%
	}
	\savedmacro\dimensions{\pgf@lib@sh@logicgates@dimensions@andUS}
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+0.5ex}%
	}
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt%
	}
	\anchor{center}{\centerpoint}%
	\inheritanchor[from=and gate US]{mid}
	\inheritanchor[from=and gate US]{mid east}
	\inheritanchor[from=and gate US]{mid west}
	\inheritanchor[from=and gate US]{base}
	\inheritanchor[from=and gate US]{base east}
	\inheritanchor[from=and gate US]{base west}
	\anchor{output}{%
		\dimensions
		\pgfpointadd{\centerpoint}{%
			\pgf@xa\halfside%
			\pgf@x1.33333\pgf@xa%
			\advance\pgf@x\invertedradius%
			\advance\pgf@x\outerinvertedradius%
			\advance\pgf@x\outerxsep%
			\pgf@y0pt%
		}%
	}
	\inheritanchor[from=and gate US]{east}
	\inheritanchor[from=and gate US]{north east}
	\inheritanchor[from=and gate US]{south east}
	\inheritanchor[from=and gate US]{north}
	\inheritanchor[from=and gate US]{south}
	\inheritanchor[from=and gate US]{south west}
	\inheritanchor[from=and gate US]{north west}
	\inheritanchor[from=and gate US]{west}
	\backgroundpath{%
		\dimensions%
		\pgf@xc\halfwidth%
		\pgf@yc\halfheight%
		\advance\pgf@xc-\outerxsep%
		\advance\pgf@yc-\outerysep%
		\pgf@xb.333333\pgf@xc%
		{%
			\pgftransformshift{\centerpoint}%
			\pgfpathmoveto{\pgfqpoint{\pgf@xb}{\pgf@yc}}%
			{%
				\edef\pgf@marshal{%
					\noexpand\pgfpatharc{90}{-90}{\the\pgf@yc}%
				}%
				\pgf@marshal%
			}
			\pgfpathlineto{\pgfqpoint{-1.16666\pgf@xc}{-\pgf@yc}}%
			\pgfpathlineto{\pgfqpoint{-1.16666\pgf@xc}{\pgf@yc}}%
			\pgfpathclose%
			%
			% Draw the inputs.
			%
			\pgfutil@tempdima2.0\pgf@yc%
			\c@pgf@counta\numinputs%
			\advance\c@pgf@counta1\relax%
			\divide\pgfutil@tempdima\c@pgf@counta%
			\pgfmathloop%
			\ifnum\pgfmathcounter>\numinputs%
			\else%
				\advance\pgf@yc-\pgfutil@tempdima%
				\expandafter\ifx\expandafter\pgf@lib@sh@itext\csname input-\pgfmathcounter\endcsname%
					{%
						\pgfpathcircle{%
							\pgf@xa\halfside%
							\pgf@x-1.166666\pgf@xa%
							\advance\pgf@x-.5\pgflinewidth%
							\advance\pgf@x-\invertedradius%
							\pgf@y\pgf@yc%
						}{+\invertedradius}%				
					}%
				\fi%				
			\repeatpgfmathloop%
			%
			% Draw the output inverter.
			%
			{%
				\pgfpathcircle{%
					\pgf@x1.33333\pgf@xc%
					\advance\pgf@x\outerinvertedradius%
					\pgf@y0pt%
				}{+\invertedradius}%			
			}%
		}%
	}		
	\inheritanchorborder[from=and gate US]
}


% Internal macro for calculation input anchors. Used by
% or, nor xnor gates (US).
%
\def\pgf@lib@sh@logicgate@OR@inputanchor#1{%
	\dimensions%
	\pgf@ya\halfside%
	\pgf@yb2.0\pgf@ya%
	%
	\pgfutil@tempdima\halfside%
	\multiply\pgfutil@tempdima2\relax%
	\c@pgf@counta\numinputs%
	\advance\c@pgf@counta1\relax%
	\divide\pgfutil@tempdima\c@pgf@counta%
	\multiply\pgfutil@tempdima#1\relax%
	\pgf@yc\pgf@ya%
	\advance\pgf@yc-\pgfutil@tempdima%
	%
	\pgf@xb\pgf@yb%
	\advance\pgf@yb-\halflinewidth%
	\pgfmathdivide@{\pgfmath@tonumber{\pgf@yc}}{\pgfmath@tonumber{\pgf@yb}}%
	\pgfmathasin@{\pgfmathresult}%
	\pgfmathcos@{\pgfmathresult}%
	%
	\pgf@xc-1.166666\pgf@ya%
	\advance\pgf@xc-.866025\pgf@xb%
	\advance\pgf@xc\pgfmathresult\pgf@yb%
	\advance\pgf@xc\halflinewidth%
	\advance\pgf@xc-\outerxsep%
	%
	\expandafter\ifx\expandafter\pgf@lib@sh@itext\csname input-#1\endcsname%
		\advance\pgf@xc-\invertedradius%
		\advance\pgf@xc-\outerinvertedradius%
	\fi%
	%
	\centerpoint%
	\advance\pgf@x\pgf@xc%
	\advance\pgf@y\pgf@yc%
}


% Shape or gate US
%
\pgfdeclareshape{or gate US}{%
	\expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@or gate US\endcsname{%
		\pgf@lib@sh@logicgate@parseinputs{1024}% Maximum 1024 (!) inputs.
		%
		\pgfmathloop%
		\ifnum\pgfmathcounter>\pgf@lib@sh@logicgate@numinputs%
		\else%
			\pgfutil@ifundefined{pgf@anchor@or gate US@input \pgfmathcounter}{%
				\expandafter\xdef\csname pgf@anchor@or gate US@input \pgfmathcounter\endcsname{%
					\noexpand\pgf@lib@sh@logicgate@OR@inputanchor{\pgfmathcounter}%
				}%
			}{}%
		\repeatpgfmathloop%
		\ifnum\pgf@lib@sh@logicgate@numinputs<2\relax%
			\pgferror{An or gate must have at least two inputs}%
		\fi%
	}%
	\savedmacro\numinputs{\let\numinputs\pgf@lib@sh@logicgate@numinputs}%
	\saveddimen\invertedradius{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
	}%
	\saveddimen\halflinewidth{%
		\pgf@x.5\pgflinewidth%
	}%
	\saveddimen\outerinvertedradius{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
		\advance\pgf@x.5\pgflinewidth%
	}
	\savedmacro\dimensions{\pgf@lib@sh@logicgates@dimensions@orUS}
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+0.5ex}%
	}
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt%
	}
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+0.5ex}%
	}
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt%
	}
	\anchor{center}{\centerpoint}%
	\anchor{mid}{\midpoint}%
	\anchor{mid east}{%
		\csname pgf@anchor@or gate US@east\endcsname%
		\pgf@xa\pgf@x%
		\midpoint%
		\pgf@x\pgf@xa}
	\anchor{mid west}{%
		\csname pgf@anchor@or gate US@north west\endcsname%
		\pgf@xa\pgf@x%
		\midpoint%
		\pgf@x\pgf@xa}
	\anchor{base}{\basepoint}%
	\anchor{base east}{%
		\csname pgf@anchor@or gate US@east\endcsname%
		\pgf@xa\pgf@x%
		\basepoint%
		\pgf@x\pgf@xa}
	\anchor{base west}{%
		\csname pgf@anchor@or gate US@north west\endcsname%
		\pgf@xa\pgf@x%
		\basepoint%
		\pgf@x\pgf@xa}
	\anchor{east}{%
		\dimensions%
		\pgfpointadd{\centerpoint}{\tipanchor}%
	}
	\anchor{output}{\csname pgf@anchor@or gate US@east\endcsname}
	\anchor{north east}{%
		\dimensions%
		\ifpgfgateanchorsuseboundingrectangle%
			\tipanchor%
			\pgf@xa\pgf@x%
			\centerpoint%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y\halfheight%
		\else%
			\centerpoint%
			\pgf@xa\halfwidth%
			\pgf@ya\halfheight%
			\pgf@xb\halfside%
			\advance\pgf@x-.166666\pgf@xb%
			\advance\pgf@xa\pgf@xb%
			\advance\pgf@x.5\pgf@xa%
			\advance\pgf@y-\pgf@xb%
			\advance\pgf@ya\pgf@xb%
			\advance\pgf@y.866025\pgf@ya%
		\fi%
	}
	\anchor{south east}{%
		\dimensions%
		\ifpgfgateanchorsuseboundingrectangle%
			\tipanchor%
			\pgf@xa\pgf@x%
			\centerpoint%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y-\halfheight%
		\else
			\centerpoint%
			\pgf@xa\halfwidth%
			\pgf@ya\halfheight%
			\pgf@xb\halfside%
			\advance\pgf@x-.166666\pgf@xb%
			\advance\pgf@xa\pgf@xb%
			\advance\pgf@x.5\pgf@xa%
			\advance\pgf@y\pgf@xb%
			\advance\pgf@ya\pgf@xb%
			\advance\pgf@y-.866025\pgf@ya%
		\fi%
	}
	\anchor{north}{%
		\dimensions%
		\centerpoint%
		\ifpgfgateanchorsuseboundingrectangle%
			\advance\pgf@y\halfheight%
		\else%
			\pgf@ya\halfheight%
			\advance\pgf@y.993043\pgf@ya%
		\fi%	
	}
	\anchor{south}{%
		\dimensions%
		\centerpoint%
		\ifpgfgateanchorsuseboundingrectangle%
			\advance\pgf@y-\halfheight%
		\else%
			\pgf@ya\halfheight%
			\advance\pgf@y-.993043\pgf@ya%
		\fi%	
	}
	\anchor{south west}{%
		\dimensions%
		\centerpoint%
		\pgf@xa\halfside%
		\advance\pgf@x-1.16666\pgf@xa%
		\pgf@xa\outerxsep%
		\advance\pgf@x-1.732050\pgf@xa%
		\advance\pgf@y-\halfheight%
	}
	\anchor{north west}{%
		\dimensions%
		\centerpoint%
		\pgf@xa\halfside%
		\advance\pgf@x-1.16666\pgf@xa%
		\pgf@xa\outerxsep%
		\advance\pgf@x-1.732050\pgf@xa%
		\advance\pgf@y\halfheight%
	}
	\anchor{west}{%
		\dimensions%
		\centerpoint%
		\pgf@xa\halfside%
		\ifpgfgateanchorsuseboundingrectangle%			
			\advance\pgf@x-1.16666\pgf@xa%
			\advance\pgf@x-\outerxsep%
		\else%
			\advance\pgf@x-1.16666\pgf@xa%
			\advance\pgf@x-\outerxsep%
			\advance\pgf@x0.267949\pgf@xa%
		\fi%
	}
	\backgroundpath{%
		\dimensions%
		\pgf@xc\halfwidth%
		\pgf@yc\halfheight%
		\advance\pgf@xc-\outerxsep%
		\advance\pgf@yc-\outerysep%
		{%
			\pgftransformshift{\centerpoint}%
			\pgfpathmoveto{\pgfqpoint{-.16666\pgf@xc}{\pgf@yc}}%
			{%
				\pgf@yc2.0\pgf@yc%
				\edef\pgf@marshal{%
					\noexpand\pgfpatharc{90}{30}{\the\pgf@yc}%
				}%
				\pgf@marshal%
			}
			{%
				\pgf@yc2.0\pgf@yc%
				\edef\pgf@marshal{%
					\noexpand\pgfpatharc{-30}{-90}{\the\pgf@yc}%
				}%
				\pgf@marshal%
			}
			\pgfpathlineto{\pgfqpoint{-1.16666\pgf@xc}{-\pgf@yc}}%
			{%
				\pgf@yc2.0\pgf@yc%
				\pgfpatharc{-30}{0}{+\pgf@yc}%			
			}
			{%
				\pgf@yc2.0\pgf@yc%
				\pgfpatharc{0}{30}{+\pgf@yc}%			
			}%
			\pgfpathclose%
			%
			% Draw the inputs.
			%
			\pgfutil@tempdima2.0\pgf@yc%
			\c@pgf@counta\numinputs%
			\advance\c@pgf@counta1\relax%
			\divide\pgfutil@tempdima\c@pgf@counta%
			\pgfmathloop%
			\ifnum\pgfmathcounter>\numinputs%
			\else%
				\advance\pgf@yc-\pgfutil@tempdima%
				\expandafter\ifx\expandafter\pgf@lib@sh@itext\csname input-\pgfmathcounter\endcsname%
					{%
						\pgfpathcircle{%
							\pgf@ya\halfside%
							\pgf@yb2.0\pgf@ya%
							\pgf@xa\pgf@yb%
							\advance\pgf@yb-\halflinewidth%
							\pgfmathdivide@{\pgfmath@tonumber{\pgf@yc}}{\pgfmath@tonumber{\pgf@yb}}%
							\let\sineangle\pgfmathresult%
							\pgfmathasin@{\pgfmathresult}%
							\pgfmathcos@{\pgfmathresult}%
							%
							\pgf@x-1.166666\pgf@ya%
							\advance\pgf@x-.866025\pgf@xa%
							\advance\pgf@x\pgfmathresult\pgf@yb%
							\advance\pgf@x-\invertedradius%
							\pgf@y\pgf@yc%
						}{+\invertedradius}%				
					}%
				\fi%				
			\repeatpgfmathloop%
		}%
	}%
	\anchorborder{%
		\pgfextract@process\externalpoint{}%
		\pgfextract@process\externalpoint{\pgfpointadd{\centerpoint}{\externalpoint}}%
		\pgf@xa\pgf@x%
		\pgf@ya\pgf@y%
		\centerpoint%
		\pgf@xb\pgf@x%
		\pgf@yb\pgf@y%
		\pgfmathanglebetweenpoints{\centerpoint}{\externalpoint}%
		\let\externalangle\pgfmathresult%
		\dimensions%
		\pgf@xc\halfside%
		%
		\pgf@xc-.166666\pgf@xc%
		\ifdim\pgf@xa<\pgf@xc%
			\pgfmathanglebetweenpoints{\centerpoint}{\csname pgf@anchor@or gate US@north west\endcsname}%
			\ifdim\externalangle pt<\pgfmathresult pt\relax%
				\pgfpointintersectionoflines{\externalpoint}{\centerpoint}%
					{%
						\pgfgateanchorsuseboundingrectangletrue%
						\csname pgf@anchor@or gate US@north\endcsname%
					}%
					{\csname pgf@anchor@or gate US@north west\endcsname}%
			\else%
				\pgfmathsubtract@{360}{\pgfmathresult}%
				\ifdim\externalangle pt>\pgfmathresult pt\relax%
					\pgfpointintersectionoflines{\externalpoint}{\centerpoint}%
					{%
						\pgfgateanchorsuseboundingrectangletrue%
						\csname pgf@anchor@or gate US@south\endcsname%
					}%
					{\csname pgf@anchor@or gate US@south west\endcsname}%
				\else%
					\ifdim\pgf@ya>\pgf@yb%
						\pgf@yc\halfheight%
						\advance\pgf@yc\halfside%
						\advance\pgf@yc-\outerxsep%
						\pgfextract@process\point{%
							\pgfmathpointintersectionoflineandarc{\centerpoint}{\externalpoint}%
							{%
								\centerpoint%
								\pgf@xa\halfside%
								\advance\pgf@x-1.166666\pgf@xa%
								\pgf@xa2.0\pgf@xa%
								\advance\pgf@x-.866025\pgf@xa%
								\advance\pgf@x-\outerxsep%
							}%
							{0}{90}{+\pgf@yc}%
						}%
					\else%
						\pgf@yc\halfheight%
						\advance\pgf@yc\halfside%
						\advance\pgf@yc-\outerxsep%
						\pgfextract@process\point{%
							\pgfmathpointintersectionoflineandarc{\centerpoint}{\externalpoint}%
							{%
								\centerpoint%
								\pgf@xa\halfside%
								\advance\pgf@x-1.166666\pgf@xa%
								\pgf@xa2.0\pgf@xa%
								\advance\pgf@x-.866025\pgf@xa%
								\advance\pgf@x-\outerxsep%
							}%
							{270}{360}{+\pgf@yc}%
						}%
					\fi%
				\fi%
			\fi%
		\else%
			\ifdim\pgf@y=0pt\relax%
				\csname pgf@anchor@and gate US@east\endcsname%
			\else%
				\pgf@xc\halfwidth%
				\advance\pgf@xc\halfside%
				\pgf@yc\halfheight%
				\advance\pgf@yc\halfside%
				\pgf@xb\halfside%
				\pgf@xb-.166666\pgf@xb%
				\ifdim\pgf@ya<0pt%
					\pgfmathpointintersectionoflineandarc{\externalpoint}{\centerpoint}%
					{%
						\centerpoint%
						\advance\pgf@y\halfside%	
						\advance\pgf@x\pgf@xb%		
					}%
					{270}{330}{+\pgf@yc}%
				\else%
					\pgfmathpointintersectionoflineandarc{\externalpoint}{\centerpoint}%
					{%
						\centerpoint%
						\advance\pgf@y-\halfside%	
						\advance\pgf@x\pgf@xb%
					}%
					{30}{90}{+\pgf@xc and +\pgf@yc}%
				\fi%
			\fi%
		\fi%
	}%
}




% Shape nor gate US
%
\pgfdeclareshape{nor gate US}{%
	\expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@nor gate US\endcsname{%
		\pgf@lib@sh@logicgate@parseinputs{1024}% Maximum 1024 (!) inputs.
		%
		\pgfmathloop%
		\ifnum\pgfmathcounter>\pgf@lib@sh@logicgate@numinputs%
		\else%
			\pgfutil@ifundefined{pgf@anchor@nor gate US@input \pgfmathcounter}{%
				\expandafter\xdef\csname pgf@anchor@nor gate US@input \pgfmathcounter\endcsname{%
					\noexpand\pgf@lib@sh@logicgate@OR@inputanchor{\pgfmathcounter}%
				}%
			}{}%
		\repeatpgfmathloop%
		\ifnum\pgf@lib@sh@logicgate@numinputs<2\relax%
			\pgferror{A nor gate must have at least two inputs}%
		\fi%
	}%
	\savedmacro\numinputs{\let\numinputs\pgf@lib@sh@logicgate@numinputs}%
	\saveddimen\invertedradius{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
	}%
	\saveddimen\halflinewidth{%
		\pgf@x.5\pgflinewidth%
	}%
	\saveddimen\outerinvertedradius{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
		\advance\pgf@x.5\pgflinewidth%
	}
	\savedmacro\dimensions{\pgf@lib@sh@logicgates@dimensions@orUS}
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+0.5ex}%
	}
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt%
	}
	\inheritanchor[from=or gate US]{center}
	\inheritanchor[from=or gate US]{mid}
	\inheritanchor[from=or gate US]{mid east}
	\inheritanchor[from=or gate US]{mid west}
	\inheritanchor[from=or gate US]{base}
	\inheritanchor[from=or gate US]{base east}
	\inheritanchor[from=or gate US]{base west}
	\inheritanchor[from=or gate US]{east}
	\inheritanchor[from=or gate US]{north east}
	\inheritanchor[from=or gate US]{south east}
	\inheritanchor[from=or gate US]{north}
	\inheritanchor[from=or gate US]{south}
	\inheritanchor[from=or gate US]{south west}
	\inheritanchor[from=or gate US]{north west}
	\inheritanchor[from=or gate US]{west}
	\anchor{output}{%
		\dimensions%
		\centerpoint%
		\pgf@xc\halfside%
		\pgf@yc\pgf@xc%
		\advance\pgf@x-.166666\pgf@xc%
		\pgf@yc2.0\pgf@yc%
		\advance\pgf@x.866025\pgf@yc%
		\advance\pgf@x\outerinvertedradius%
		\advance\pgf@x\invertedradius%
		\advance\pgf@x\outerxsep%
	}%
	\backgroundpath{%
		\dimensions%
		\pgf@xc\halfwidth%
		\pgf@yc\halfheight%
		\advance\pgf@xc-\outerxsep%
		\advance\pgf@yc-\outerysep%
		{%
			\pgftransformshift{\centerpoint}%
			\pgfpathmoveto{\pgfqpoint{-.16666\pgf@xc}{\pgf@yc}}%
			{%
				\pgf@yc2.0\pgf@yc%
				\edef\pgf@marshal{%
					\noexpand\pgfpatharc{90}{30}{\the\pgf@yc}%
				}%
				\pgf@marshal%
			}
			{%
				\pgf@yc2.0\pgf@yc%
				\edef\pgf@marshal{%
					\noexpand\pgfpatharc{-30}{-90}{\the\pgf@yc}%
				}%
				\pgf@marshal%
			}
			\pgfpathlineto{\pgfqpoint{-1.16666\pgf@xc}{-\pgf@yc}}%
			{%
				\pgf@yc2.0\pgf@yc%
				\pgfpatharc{-30}{0}{+\pgf@yc}%			
			}
			{%
				\pgf@yc2.0\pgf@yc%
				\pgfpatharc{0}{30}{+\pgf@yc}%			
			}%
			\pgfpathclose%
			% Draw the output inverter.
			%
			{%
				\pgfpathcircle{%
					\pgf@x-.166666\pgf@xc%
					\pgf@yc2.0\pgf@yc%
					\advance\pgf@x.866025\pgf@yc%
					\advance\pgf@x\outerinvertedradius%
					\pgf@y0pt%
				}{+\invertedradius}%			
			}%
			%
			% Draw the inputs.
			%
			\pgfutil@tempdima2.0\pgf@yc%
			\c@pgf@counta\numinputs%
			\advance\c@pgf@counta1\relax%
			\divide\pgfutil@tempdima\c@pgf@counta%
			\pgfmathloop%
			\ifnum\pgfmathcounter>\numinputs%
			\else%
				\advance\pgf@yc-\pgfutil@tempdima%
				\expandafter\ifx\expandafter\pgf@lib@sh@itext\csname input-\pgfmathcounter\endcsname%
					{%
						\pgfpathcircle{%
							\pgf@ya\halfside%
							\pgf@yb2.0\pgf@ya%
							\pgf@xa\pgf@yb%
							\advance\pgf@yb-\halflinewidth%
							\pgfmathdivide@{\pgfmath@tonumber{\pgf@yc}}{\pgfmath@tonumber{\pgf@yb}}%
							\let\sineangle\pgfmathresult%
							\pgfmathasin@{\pgfmathresult}%
							\pgfmathcos@{\pgfmathresult}%
							%
							\pgf@x-1.166666\pgf@ya%
							\advance\pgf@x-.866025\pgf@xa%
							\advance\pgf@x\pgfmathresult\pgf@yb%
							\advance\pgf@x-\invertedradius%
							\pgf@y\pgf@yc%
						}{+\invertedradius}%				
					}%
				\fi%				
			\repeatpgfmathloop%
		}%
	}%
	\inheritanchorborder[from=or gate US]
}



% Internal macro for calculation input anchors. Used by
% xor and xnor gates (US).
%
\def\pgf@lib@sh@logicgate@XOR@inputanchor#1{%
	\dimensions%
	\pgf@ya\halfside%
	\pgf@yb2.0\pgf@ya%
	%
	\pgfutil@tempdima\halfside%
	\multiply\pgfutil@tempdima2\relax%
	\c@pgf@counta\numinputs%
	\advance\c@pgf@counta1\relax%
	\divide\pgfutil@tempdima\c@pgf@counta%
	\multiply\pgfutil@tempdima#1\relax%
	\pgf@yc\pgf@ya%
	\advance\pgf@yc-\pgfutil@tempdima%
	%
	\pgf@xb\pgf@yb%
	\advance\pgf@yb-\halflinewidth%
	\pgfmathdivide@{\pgfmath@tonumber{\pgf@yc}}{\pgfmath@tonumber{\pgf@yb}}%
	\pgfmathasin@{\pgfmathresult}%
	\pgfmathcos@{\pgfmathresult}%
	%
	\pgf@xc-1.166666\pgf@ya%
	\advance\pgf@xc-.866025\pgf@xb%
	\advance\pgf@xc\pgfmathresult\pgf@yb%
	\advance\pgf@xc\halflinewidth%
	\advance\pgf@xc-\outerxsep%
	%
	\expandafter\ifx\expandafter\pgf@lib@sh@itext\csname input-#1\endcsname%
		\advance\pgf@xc-\invertedradius%
		\advance\pgf@xc-\outerinvertedradius%
	\fi%
	%
	\centerpoint%
	\advance\pgf@x\pgf@xc%
	\advance\pgf@y\pgf@yc%
	\pgf@xa\halfside%
	\advance\pgf@x-.333333\pgf@xa%
}





% Shape xor gate US
%
\pgfdeclareshape{xor gate US}{%
	\expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@xor gate US\endcsname{%
		\pgf@lib@sh@logicgate@parseinputs{2}% 
		%
		\pgfmathloop%
		\ifnum\pgfmathcounter>\pgf@lib@sh@logicgate@numinputs%
		\else%
			\pgfutil@ifundefined{pgf@anchor@xor gate US@input \pgfmathcounter}{%
				\expandafter\xdef\csname pgf@anchor@xor gate US@input \pgfmathcounter\endcsname{%
					\noexpand\pgf@lib@sh@logicgate@XOR@inputanchor{\pgfmathcounter}%
				}%
			}{}%
		\repeatpgfmathloop%
		\ifnum\pgf@lib@sh@logicgate@numinputs<2\relax%
			\pgferror{An xor gate must have at two inputs}%
		\fi%
	}%
	\savedmacro\numinputs{\let\numinputs\pgf@lib@sh@logicgate@numinputs}%
	\saveddimen\invertedradius{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
	}%
	\saveddimen\halflinewidth{%
		\pgf@x.5\pgflinewidth%
	}%
	\saveddimen\outerinvertedradius{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
		\advance\pgf@x.5\pgflinewidth%
	}
	\savedmacro\dimensions{\pgf@lib@sh@logicgates@dimensions@orUS}
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+0.5ex}%
	}
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt%
	}
	\anchor{center}{\centerpoint}%
	\anchor{mid}{\midpoint}%
	\inheritanchor[from=or gate US]{mid east}
	\anchor{mid west}{%
		\csname pgf@anchor@xor gate US@north west\endcsname%
		\pgf@xa\pgf@x%
		\midpoint%
		\pgf@x\pgf@xa}
	\anchor{base}{\basepoint}%
	\inheritanchor[from=or gate US]{base east}
	\anchor{base west}{%
		\csname pgf@anchor@xor gate US@north west\endcsname%
		\pgf@xa\pgf@x%
		\basepoint%
		\pgf@x\pgf@xa}
	\inheritanchor[from=or gate US]{base}
	\inheritanchor[from=or gate US]{output}
	\inheritanchor[from=or gate US]{east}
	\inheritanchor[from=or gate US]{north east}
	\inheritanchor[from=or gate US]{south east}
	\inheritanchor[from=or gate US]{north}
	\inheritanchor[from=or gate US]{south}
	\anchor{south west}{%
		\dimensions%
		\pgf@xa\halfside%
		\pgf@xa-3.232051\pgf@xa% (7/6 + 2*cos(30) + 1/3) * x
		\pgf@xb\halfside%
		\pgf@xb2.0\pgf@xb%
		\advance\pgf@xb-\halflinewidth%
		\advance\pgf@xa.866025\pgf@xb%
		\pgf@ya.5\pgf@xb%
		\centerpoint%
		\advance\pgf@x\pgf@xa%
		\ifpgfgateanchorsuseboundingrectangle%
			\advance\pgf@y-\halfheight%
		\else%
			\advance\pgf@y-\pgf@ya%
		\fi%
	}
	\anchor{north west}{%
		\dimensions%
		\pgf@xa\halfside%
		\pgf@xa-3.232051\pgf@xa% (7/6 + 2*cos(30) + 1/3) * x
		\pgf@xb\halfside%
		\pgf@xb2.0\pgf@xb%
		\advance\pgf@xb-\halflinewidth%
		\advance\pgf@xa.866025\pgf@xb%
		\pgf@ya.5\pgf@xb%
		\centerpoint%
		\advance\pgf@x\pgf@xa%
		\ifpgfgateanchorsuseboundingrectangle%
			\advance\pgf@y\halfheight%
		\else%
			\advance\pgf@y\pgf@ya%
		\fi%
	}
	\anchor{west}{%
		\dimensions%
		\pgf@ya\halfside%
		\pgf@yb2.0\pgf@ya%
		%
		\pgf@xb\pgf@yb%
		\advance\pgf@yb-\halflinewidth%
		\pgfmathdivide@{0}{\pgfmath@tonumber{\pgf@yb}}%
		\pgfmathasin@{\pgfmathresult}%
		\pgfmathcos@{\pgfmathresult}%
		%
		\pgf@xc-1.166666\pgf@ya%
		\advance\pgf@xc-.866025\pgf@xb%
		\advance\pgf@xc\pgfmathresult\pgf@yb%
		\advance\pgf@xc\halflinewidth%
		\advance\pgf@xc-\outerxsep%
		%
		\centerpoint%
		\advance\pgf@x\pgf@xc%
		\pgf@xa\halfside%
		\advance\pgf@x-.333333\pgf@xa%
		\ifpgfgateanchorsuseboundingrectangle%
			\pgf@xa2.0\pgf@xa%
			\advance\pgf@x-0.133974\pgf@xa%
		\fi%
	}
	\backgroundpath{%
		\dimensions%
		\pgf@xc\halfwidth%
		\pgf@yc\halfheight%
		\advance\pgf@xc-\outerxsep%
		\advance\pgf@yc-\outerysep%
		{%
			\pgftransformshift{\centerpoint}%
			\pgfpathmoveto{\pgfqpoint{-.16666\pgf@xc}{\pgf@yc}}%
			{%
				\pgf@yc2.0\pgf@yc%
				\edef\pgf@marshal{%
					\noexpand\pgfpatharc{90}{30}{\the\pgf@yc}%
				}%
				\pgf@marshal%
			}
			{%
				\pgf@yc2.0\pgf@yc%
				\edef\pgf@marshal{%
					\noexpand\pgfpatharc{-30}{-90}{\the\pgf@yc}%
				}%
				\pgf@marshal%
			}
			\pgfpathlineto{\pgfqpoint{-1.16666\pgf@xc}{-\pgf@yc}}%
			{%
				\pgf@yc2.66666\pgf@yc%
				\pgfpatharc{-22}{0}{+1.166666\pgf@yc and +\pgf@yc}%			
			}
			{%
				\pgf@yc2.66666\pgf@yc%
				\pgfpatharc{0}{22}{+1.166666\pgf@yc and +\pgf@yc}%			
			}%
			\pgfpathclose%
			%
			% Draw the inputs.
			%
			\pgfutil@tempdima2.0\pgf@yc%
			\c@pgf@counta\numinputs%
			\advance\c@pgf@counta1\relax%
			\divide\pgfutil@tempdima\c@pgf@counta%
			\pgfmathloop%
			\ifnum\pgfmathcounter>\numinputs%
			\else%
				\advance\pgf@yc-\pgfutil@tempdima%
				\expandafter\ifx\expandafter\pgf@lib@sh@itext\csname input-\pgfmathcounter\endcsname%
					{%
						\pgfpathcircle{%
							\pgf@ya\halfside%
							\pgf@yb2.0\pgf@ya%
							\pgf@xa\pgf@yb%
							\advance\pgf@yb-\halflinewidth%
							\pgfmathdivide@{\pgfmath@tonumber{\pgf@yc}}{\pgfmath@tonumber{\pgf@yb}}%
							\pgfmathasin@{\pgfmathresult}%
							\pgfmathcos@{\pgfmathresult}%
							%
							\pgf@x-1.5\pgf@ya%
							\advance\pgf@x-.866025\pgf@xa%
							\advance\pgf@x\pgfmathresult\pgf@yb%
							\advance\pgf@x-\invertedradius%
							\pgf@y\pgf@yc%
						}{+\invertedradius}%				
					}%
				\fi%				
			\repeatpgfmathloop%
			%
			% Now, some fooling around to stop the `tail' being filled.
			% Technically it still is, but it isn't visible.
			%
			\pgf@xc\halfside%
			\pgf@yc\halfside%
			\pgfpathmoveto{\pgfqpoint{-1.5\pgf@xc}{-\pgf@yc}}%
			\pgf@yc2.0\pgf@yc%
			\pgfmathloop%
			\ifnum\pgfmathcounter<61\relax%
				{%
					\pgfextract@process\point{%
						\pgfpointadd{%
							\pgf@x\halfside%
							\pgf@x-3.232051\pgf@x% (7/6 + 2*cos(30) + 1/3) * x
							\pgf@y0pt%
						}{%
							\pgfpointpolar{\pgfmathcounter-30}{+\pgf@yc}%
						}%
					}%
					\pgfpathlineto{\point}%
					\pgfpathmoveto{\point}%
				}
			\repeatpgfmathloop%
		}%
	}%
	\anchorborder{%
		\pgfextract@process\externalpoint{}%
		\pgfextract@process\externalpoint{\pgfpointadd{\centerpoint}{\externalpoint}}%
		\pgf@xa\pgf@x%
		\pgf@ya\pgf@y%
		\centerpoint%
		\pgf@xb\pgf@x%
		\pgf@yb\pgf@y%
		\pgfmathanglebetweenpoints{\centerpoint}{\externalpoint}%
		\let\externalangle\pgfmathresult%
		\dimensions%
		\pgf@xc\halfside%
		%
		\pgf@xc-.166666\pgf@xc%
		\ifdim\pgf@xa<\pgf@xc%
			\pgfmathanglebetweenpoints{\centerpoint}%
			{%
				\pgfgateanchorsuseboundingrectangletrue%
				\csname pgf@anchor@xor gate US@north west\endcsname%
			}%
			\ifdim\externalangle pt<\pgfmathresult pt\relax%
				\pgfpointintersectionoflines{\externalpoint}{\centerpoint}%
					{%
						\pgfgateanchorsuseboundingrectangletrue%
						\csname pgf@anchor@xor gate US@north\endcsname%
					}%
					{%
						\pgfgateanchorsuseboundingrectangletrue%
						\csname pgf@anchor@xor gate US@north west\endcsname%
					}%
			\else%
				\pgfmathsubtract@{360}{\pgfmathresult}%
				\ifdim\externalangle pt>\pgfmathresult pt\relax%
					\pgfpointintersectionoflines{\externalpoint}{\centerpoint}%
					{%
						\pgfgateanchorsuseboundingrectangletrue%
						\csname pgf@anchor@xor gate US@south\endcsname%
					}%
					{%
						\pgfgateanchorsuseboundingrectangletrue%
						\csname pgf@anchor@xor gate US@south west\endcsname%
					}%
				\else%
					\ifdim\pgf@ya>\pgf@yb%
						\pgf@yc\halfheight%
						\advance\pgf@yc\halfside%
						\advance\pgf@yc-\outerxsep%
						\pgf@process{%
							\pgfmathpointintersectionoflineandarc{\centerpoint}{\externalpoint}%
							{%
								\centerpoint%
								\pgf@xa\halfside%
								\advance\pgf@x-1.166666\pgf@xa%
								\pgf@xa2.0\pgf@xa%
								\advance\pgf@x-.866025\pgf@xa%
								\advance\pgf@x-\outerxsep%
								\advance\pgf@x-.166666\pgf@xa%
							}%
							{0}{90}{+\pgf@yc}%
						}%
					\else%
						\pgf@yc\halfheight%
						\advance\pgf@yc\halfside%
						\advance\pgf@yc-\outerxsep%
						\pgf@process{%
							\pgfmathpointintersectionoflineandarc{\centerpoint}{\externalpoint}%
							{%
								\centerpoint%
								\pgf@xa\halfside%
								\advance\pgf@x-1.166666\pgf@xa%
								\pgf@xa2.0\pgf@xa%
								\advance\pgf@x-.866025\pgf@xa%
								\advance\pgf@x-\outerxsep%
								\advance\pgf@x-.166666\pgf@xa%
							}%
							{270}{360}{+\pgf@yc}%
						}%
					\fi%
				\fi%
			\fi%
		\else%
			\ifdim\pgf@y=0pt\relax%
				\csname pgf@anchor@and gate US@east\endcsname%
			\else%
				\pgf@xc\halfwidth%
				\advance\pgf@xc\halfside%
				\pgf@yc\halfheight%
				\advance\pgf@yc\halfside%
				\pgf@xb\halfside%
				\pgf@xb-.166666\pgf@xb%
				\ifdim\pgf@ya<0pt%
					\pgfmathpointintersectionoflineandarc{\externalpoint}{\centerpoint}%
					{%
						\centerpoint%
						\advance\pgf@y\halfside%	
						\advance\pgf@x\pgf@xb%		
					}%
					{270}{330}{+\pgf@yc}%
				\else%
					\pgfmathpointintersectionoflineandarc{\externalpoint}{\centerpoint}%
					{%
						\centerpoint%
						\advance\pgf@y-\halfside%	
						\advance\pgf@x\pgf@xb%
					}%
					{30}{90}{+\pgf@xc and +\pgf@yc}%
				\fi%
			\fi%
		\fi%
	}%
}




% Shape xnor gate US
%
\pgfdeclareshape{xnor gate US}{%
	\expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@xnor gate US\endcsname{%
		\pgf@lib@sh@logicgate@parseinputs{2}% 
		%
		\pgfmathloop%
		\ifnum\pgfmathcounter>\pgf@lib@sh@logicgate@numinputs%
		\else%
			\pgfutil@ifundefined{pgf@anchor@xnor gate US@input \pgfmathcounter}{%
				\expandafter\xdef\csname pgf@anchor@xnor gate US@input \pgfmathcounter\endcsname{%
					\noexpand\pgf@lib@sh@logicgate@XOR@inputanchor{\pgfmathcounter}%
				}%
			}{}%
		\repeatpgfmathloop%
		\ifnum\pgf@lib@sh@logicgate@numinputs<2\relax%
			\pgferror{An xnor gate must have two inputs}%
		\fi%
	}%
	\savedmacro\numinputs{\let\numinputs\pgf@lib@sh@logicgate@numinputs}%
	\saveddimen\invertedradius{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
	}%
	\saveddimen\halflinewidth{%
		\pgf@x.5\pgflinewidth%
	}%
	\saveddimen\outerinvertedradius{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
		\advance\pgf@x.5\pgflinewidth%
	}
	\savedmacro\dimensions{\pgf@lib@sh@logicgates@dimensions@orUS}
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+0.5ex}%
	}
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt%
	}
	\anchor{center}{\centerpoint}%
	\anchor{mid}{\midpoint}%
	\inheritanchor[from=xor gate US]{mid east}
	\inheritanchor[from=xor gate US]{mid west}
	\anchor{base}{\basepoint}%
	\inheritanchor[from=xor gate US]{base east}
	\inheritanchor[from=xor gate US]{base west}
	\inheritanchor[from=xor gate US]{base}
	\inheritanchor[from=nor gate US]{output}
	\inheritanchor[from=xor gate US]{east}
	\inheritanchor[from=xor gate US]{north east}
	\inheritanchor[from=xor gate US]{south east}
	\inheritanchor[from=xor gate US]{north}
	\inheritanchor[from=xor gate US]{south}
	\inheritanchor[from=xor gate US]{south west}
	\inheritanchor[from=xor gate US]{north west}
	\inheritanchor[from=xor gate US]{west}
	\backgroundpath{%
		\dimensions%
		\pgf@xc\halfwidth%
		\pgf@yc\halfheight%
		\advance\pgf@xc-\outerxsep%
		\advance\pgf@yc-\outerysep%
		{%
			\pgftransformshift{\centerpoint}%
			\pgfpathmoveto{\pgfqpoint{-.16666\pgf@xc}{\pgf@yc}}%
			{%
				\pgf@yc2.0\pgf@yc%
				\edef\pgf@marshal{%
					\noexpand\pgfpatharc{90}{30}{\the\pgf@yc}%
				}%
				\pgf@marshal%
			}
			{%
				\pgf@yc2.0\pgf@yc%
				\edef\pgf@marshal{%
					\noexpand\pgfpatharc{-30}{-90}{\the\pgf@yc}%
				}%
				\pgf@marshal%
			}
			\pgfpathlineto{\pgfqpoint{-1.16666\pgf@xc}{-\pgf@yc}}%
			{%
				\pgf@yc2.66666\pgf@yc%
				\pgfpatharc{-22}{0}{+1.166666\pgf@yc and +\pgf@yc}%			
			}
			{%
				\pgf@yc2.66666\pgf@yc%
				\pgfpatharc{0}{22}{+1.166666\pgf@yc and +\pgf@yc}%			
			}%
			\pgfpathclose%
			%
			% Draw the output inverter.
			%
			{%
				\pgfpathcircle{%
					\pgf@x-.166666\pgf@xc%
					\pgf@yc2.0\pgf@yc%
					\advance\pgf@x.866025\pgf@yc%
					\advance\pgf@x\outerinvertedradius%
					\pgf@y0pt%
				}{+\invertedradius}%			
			}%
			%
			% Draw the inputs.
			%
			\pgfutil@tempdima2.0\pgf@yc%
			\c@pgf@counta\numinputs%
			\advance\c@pgf@counta1\relax%
			\divide\pgfutil@tempdima\c@pgf@counta%
			\pgfmathloop%
			\ifnum\pgfmathcounter>\numinputs%
			\else%
				\advance\pgf@yc-\pgfutil@tempdima%
				\expandafter\ifx\expandafter\pgf@lib@sh@itext\csname input-\pgfmathcounter\endcsname%
					{%
						\pgfpathcircle{%
							\pgf@ya\halfside%
							\pgf@yb2.0\pgf@ya%
							\pgf@xa\pgf@yb%
							\advance\pgf@yb-\halflinewidth%
							\pgfmathdivide@{\pgfmath@tonumber{\pgf@yc}}{\pgfmath@tonumber{\pgf@yb}}%
							\pgfmathasin@{\pgfmathresult}%
							\pgfmathcos@{\pgfmathresult}%
							%
							\pgf@x-1.5\pgf@ya%
							\advance\pgf@x-.866025\pgf@xa%
							\advance\pgf@x\pgfmathresult\pgf@yb%
							\advance\pgf@x-\invertedradius%
							\pgf@y\pgf@yc%
						}{+\invertedradius}%				
					}%
				\fi%				
			\repeatpgfmathloop%
			%
			% Now, some fooling around to stop the `tail' being filled.
			%
			\pgf@xc\halfside%
			\pgf@yc\halfside%
			\pgfpathmoveto{\pgfqpoint{-1.5\pgf@xc}{-\pgf@yc}}%
			\pgf@yc2.0\pgf@yc%
			\pgfmathloop%
			\ifnum\pgfmathcounter<61\relax%
				{%
					\pgfextract@process\point{%
						\pgfpointadd{%
							\pgf@x\halfside%
							\pgf@x-3.232051\pgf@x% (7/6 + 2*cos(30) + 1/3) * x
							\pgf@y0pt%
						}{%
							\pgfpointpolar{\pgfmathcounter-30}{+\pgf@yc}%
						}%
					}%
					\pgfpathlineto{\point}%
					\pgfpathmoveto{\point}%
				}
			\repeatpgfmathloop%
		}%
	}%
	\inheritanchorborder[from=xor gate US]
}






% Shape not gate US
%
\pgfdeclareshape{not gate US}{%
  \expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@not gate US\endcsname{%
    \pgf@lib@sh@logicgate@parseinputs{1}% 
    \ifnum\pgf@lib@sh@logicgate@numinputs=0\relax%
      \pgferror{A not gate must have one input}%
    \fi%
  }%
  \savedmacro\numinputs{\let\numinputs\pgf@lib@sh@logicgate@numinputs}%
  \saveddimen\invertedradius{%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
  }%
  \saveddimen\halflinewidth{%
    \pgf@x.5\pgflinewidth%
  }%
  \saveddimen\outerinvertedradius{%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
    \advance\pgf@x.5\pgflinewidth%
  }
  \savedmacro\dimensions{\pgf@lib@sh@logicgates@dimensions@orUS}
  \savedanchor\centerpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y.5\ht\pgfnodeparttextbox%
    \advance\pgf@y-.5\dp\pgfnodeparttextbox%
  }
  \savedanchor\midpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@y{+0.5ex}%
  }
  \savedanchor\basepoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y0pt%
  }
  \anchor{center}{\centerpoint}%
  \anchor{mid}{\midpoint}%
  \anchor{mid east}{%
    \midpoint%
    \pgfutil@tempdima\pgf@y%
    \csname pgf@anchor@not gate US@east\endcsname%
    \pgf@y\pgfutil@tempdima%
  }
  \anchor{mid west}{%
    \dimensions%
    \pgf@xc\halfside%
    \pgf@xc-.833333\pgf@xc%
    \advance\pgf@xc-\outerxsep%
    \midpoint%
    \advance\pgf@x\pgf@xc%	
  }%
  \anchor{base}{\basepoint}%
  \anchor{base east}{%
    \basepoint%
    \pgfutil@tempdima\pgf@y%
    \csname pgf@anchor@not gate US@east\endcsname%
    \pgf@y\pgfutil@tempdima%
  }
  \anchor{base west}{%
    \dimensions%
    \pgf@xc\halfside%
    \pgf@xc-.833333\pgf@xc%
    \advance\pgf@xc-\outerxsep%
    \basepoint%
    \advance\pgf@x\pgf@xc%	
  }%
  \inheritanchor[from=and gate US]{base}
  \anchor{output}{%
    \dimensions%
    \pgf@xc\halfside%
    \centerpoint%
    \advance\pgf@x-.166666\pgf@xc%
    \pgf@xc2.0\pgf@xc%
    \advance\pgf@x.866025\pgf@xc%
    \advance\pgf@x\invertedradius%
    \advance\pgf@x\outerinvertedradius%
    \advance\pgf@x\outerxsep%
  }
  \anchor{east}{%
    \dimensions%
    \tipanchor%
    \pgf@xa\pgf@x%
    \centerpoint%
    \advance\pgf@x\pgf@xa%
  }%
  \anchor{north}{%
    \dimensions%
    \ifpgfgateanchorsuseboundingrectangle%
      \csname pgf@anchor@not gate US@north west\endcsname%
      \pgf@ya\pgf@y%
      \centerpoint%
      \pgf@y\pgf@ya%
    \else%
      \pgfpointintersectionoflines{\centerpoint}{\centerpoint\advance\pgf@y1pt}%
      {\csname pgf@anchor@not gate US@north west\endcsname}%
      {%
        \pgfpointadd{\centerpoint}{%
          \tipanchor%
          \pgf@xa\outerxsep%
          \advance\pgf@x2.350943\pgf@xa%	
        }%
      }%	
    \fi%
  }
  \anchor{south}{%
    \dimensions%
    \ifpgfgateanchorsuseboundingrectangle%
      \csname pgf@anchor@not gate US@south west\endcsname%
      \pgf@ya\pgf@y%
      \centerpoint%
      \pgf@y\pgf@ya%
    \else%
      \pgfpointintersectionoflines{\centerpoint}{\centerpoint\advance\pgf@y-1pt}%
      {\csname pgf@anchor@not gate US@south west\endcsname}%
      {%
        \pgfpointadd{\centerpoint}{%
          \tipanchor%
          \pgf@xa\outerxsep%
          \advance\pgf@x2.350943\pgf@xa%	
        }%
      }%	
    \fi%
  }
  \anchor{south east}{%
    \dimensions%
    \ifpgfgateanchorsuseboundingrectangle%
      \csname pgf@anchor@not gate US@south west\endcsname%
      \pgf@ya\pgf@y%
      \pgf@process{%	
        \dimensions%
        \tipanchor%
        \pgf@xa\pgf@x%
        \centerpoint%
        \advance\pgf@x\pgf@xa%
      }%
      \pgf@y\pgf@ya%
    \else%
      \pgfpointintersectionoflines{\centerpoint}{\centerpoint\advance\pgf@x1pt\advance\pgf@y-1pt}%
      {\csname pgf@anchor@not gate US@south west\endcsname}%
      {%
        \pgfpointadd{\centerpoint}{%
          \tipanchor%
          \pgf@xa\outerxsep%
          \advance\pgf@x2.350943\pgf@xa%	
        }%
      }%	
    \fi%
  }
  \anchor{north east}{%
    \dimensions%
    \ifpgfgateanchorsuseboundingrectangle%
      \csname pgf@anchor@not gate US@north west\endcsname%
      \pgf@ya\pgf@y%
      \pgf@process{%	
        \dimensions%
        \tipanchor%
        \pgf@xa\pgf@x%
        \centerpoint%
        \advance\pgf@x\pgf@xa%
      }%
      \pgf@y\pgf@ya%
    \else%
      \pgfpointintersectionoflines{\centerpoint}{\centerpoint\advance\pgf@x1pt\advance\pgf@y1pt}%
      {\csname pgf@anchor@not gate US@north west\endcsname}%
      {%
        \pgfpointadd{\centerpoint}{%
          \tipanchor%
          \pgf@xa\outerxsep%
          \advance\pgf@x2.350943\pgf@xa%	
        }%
      }%	
    \fi%
  }
  \anchor{south west}{%
    \dimensions%
    \pgf@xa\halfside%
    \centerpoint%
    \advance\pgf@x-.833333\pgf@xa
    \advance\pgf@x-\outerxsep%
    \advance\pgf@y-1.166666\pgf@xa%
    \pgf@ya\outerysep%
    \advance\pgf@y-1.565\pgf@ya% Selected by trial and error.	
  }%
  \anchor{north west}{%
    \dimensions%
    \pgf@xa\halfside%
    \centerpoint%
    \advance\pgf@x-.833333\pgf@xa
    \advance\pgf@x-\outerxsep%
    \advance\pgf@y1.166666\pgf@xa%
    \pgf@ya\outerysep%
    \advance\pgf@y1.565\pgf@ya% Selected by trial and error.	
  }%
  \anchor{input}{%
    \dimensions%
    \pgf@lib@sh@logicgate@AND@inputanchor{1}%
    \pgf@xc\halfside%
    \advance\pgf@x.333333\pgf@xc%
  }%
  \anchor{west}{%
    \dimensions%
    \pgf@xc\halfside%
    \pgf@xc-.833333\pgf@xc%
    \advance\pgf@xc-\outerxsep%
    \centerpoint%
    \advance\pgf@x\pgf@xc%
  }
  \backgroundpath{%
    \dimensions%
    \pgf@xc\halfwidth%
    \pgf@yc\halfheight%
    \advance\pgf@xc-\outerxsep%
    \advance\pgf@yc-\outerysep%
    {%
      \pgftransformshift{\centerpoint}%
      \pgfpathmoveto{\tipanchor}%
      \pgfpathlineto{\pgfqpoint{-.833333\pgf@xc}{1.166666\pgf@yc}}%
      \pgfpathlineto{\pgfqpoint{-.833333\pgf@xc}{-1.166666\pgf@yc}}%
      \pgfpathlineto{\tipanchor}%
      % 
      % Draw the output inverter.
      % 
      {%
        \pgfpathcircle{%
          \pgf@x-.166666\pgf@xc%
          \pgf@yc2.0\pgf@yc%
          \advance\pgf@x.866025\pgf@yc%
          \advance\pgf@x\outerinvertedradius%
          \pgf@y0pt%
        }{+\invertedradius}%			
      }%
      % 
      % Draw the input.
      % 
      \expandafter\ifx\expandafter\pgf@lib@sh@itext\csname input-1\endcsname%
      {%
        \pgfpathcircle{%
          \pgf@xa\halfside%
          \pgf@x-.833333\pgf@xa%
          \advance\pgf@x-.5\pgflinewidth%
          \advance\pgf@x-\invertedradius%
          \pgf@y0pt%
        }{+\invertedradius}%				
      }%
      \fi%				
    }%
  }%
  \anchorborder{%
    \pgf@lib@gates@not@buffer@border{not gate US}
  }
}

\def\pgf@lib@gates@not@buffer@border#1{
  \pgfextract@process\externalpoint{}%
  \pgfextract@process\externalpoint{\pgfpointadd{\centerpoint}{\externalpoint}}%
  \pgfmathanglebetweenpoints{\centerpoint}{\externalpoint}%
  \ifx\pgfmathresult\pgf@lib@zero@text%
    \csname pgf@anchor@#1@output\endcsname%
  \else%
    \ifx\pgfmathresult\pgf@lib@onehundredeighty@text%
      \csname pgf@anchor@#1@input\endcsname%
    \else%
      \let\externalangle\pgfmathresult%
      \dimensions%
      \pgfmathanglebetweenpoints{\centerpoint}{\csname pgf@anchor@not gate US@north west\endcsname}%
      \ifdim\externalangle pt<\pgfmathresult pt%
        \pgfpointintersectionoflines{\centerpoint}{\externalpoint}%
        {\csname pgf@anchor@not gate US@north west\endcsname}%
        {%
          \pgfpointadd{\centerpoint}{%
            \tipanchor%
            \pgf@xa\outerxsep%
            \advance\pgf@x2.350943\pgf@xa%	
          }%
        }%	
      \else%
        \pgfmathanglebetweenpoints{\centerpoint}{\csname pgf@anchor@not gate US@south west\endcsname}%
        \ifdim\externalangle pt<\pgfmathresult pt%
          \pgfpointintersectionoflines{\externalpoint}{\centerpoint}%
          {\csname pgf@anchor@not gate US@north west\endcsname}%
          {\csname pgf@anchor@not gate US@south west\endcsname}%
        \else%
          \pgfpointintersectionoflines{\centerpoint}{\externalpoint}%
          {\csname pgf@anchor@not gate US@south west\endcsname}%
          {%
            \pgfpointadd{\centerpoint}{%
              \tipanchor%
              \pgf@xa\outerxsep%
              \advance\pgf@x2.350943\pgf@xa%	
            }%
          }%	
        \fi%
      \fi%
    \fi%
  \fi%
}%


\def\pgf@lib@zero@text{0.0}
\def\pgf@lib@onehundredeighty@text{180.0}




% Shape buffer gate US.
%
\pgfdeclareshape{buffer gate US}{%
	\expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@buffer gate US\endcsname{%
		\pgf@lib@sh@logicgate@parseinputs{1}% 
		\ifnum\pgf@lib@sh@logicgate@numinputs=0\relax%
			\pgferror{A buffer gate must have one input}%
		\fi%
	}%
	\savedmacro\numinputs{\let\numinputs\pgf@lib@sh@logicgate@numinputs}%
	\saveddimen\invertedradius{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
	}%
	\saveddimen\halflinewidth{%
		\pgf@x.5\pgflinewidth%
	}%
	\saveddimen\outerinvertedradius{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
		\advance\pgf@x.5\pgflinewidth%
	}
	\savedmacro\dimensions{\pgf@lib@sh@logicgates@dimensions@orUS}
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+0.5ex}%
	}
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt%
	}
	\anchor{center}{\centerpoint}%
	\anchor{mid}{\midpoint}%
	\anchor{mid east}{%
		\midpoint%
		\pgfutil@tempdima\pgf@y%
		\csname pgf@anchor@buffer gate US@east\endcsname%
		\pgf@y\pgfutil@tempdima%
	}
	\anchor{mid west}{%
		\dimensions%
		\pgf@xc\halfside%
		\pgf@xc-.833333\pgf@xc%
		\advance\pgf@xc-\outerxsep%
		\midpoint%
		\advance\pgf@x\pgf@xc%	
	}%
	\anchor{base}{\basepoint}%
	\anchor{base east}{%
		\basepoint%
		\pgfutil@tempdima\pgf@y%
		\csname pgf@anchor@buffer gate US@east\endcsname%
		\pgf@y\pgfutil@tempdima%
	}
	\inheritanchor[from=not gate US]{base west}
	\inheritanchor[from=and gate US]{base}
	\anchor{output}{\csname pgf@anchor@buffer gate US@east\endcsname}
	\anchor{east}{%
		\dimensions%
		\pgfpointadd{\centerpoint}{%
			\tipanchor%
			\pgf@xa\outerxsep%
			\advance\pgf@x2.350943\pgf@xa%	
		}%
	}%
	\anchor{north}{%
		\dimensions%
		\ifpgfgateanchorsuseboundingrectangle%
			\csname pgf@anchor@not gate US@north west\endcsname%
			\pgf@ya\pgf@y%
			\centerpoint%
			\pgf@y\pgf@ya%
		\else%
			\pgfpointintersectionoflines{\centerpoint}{\centerpoint\advance\pgf@y1pt}%
				{\csname pgf@anchor@buffer gate US@north west\endcsname}%
				{%
					\pgfpointadd{\centerpoint}{%
						\tipanchor%
						\pgf@xa\outerxsep%
						\advance\pgf@x2.350943\pgf@xa%	
					}%
				}%	
		\fi%
	}
	\anchor{south}{%
		\dimensions%
		\ifpgfgateanchorsuseboundingrectangle%
			\csname pgf@anchor@not gate US@south west\endcsname%
			\pgf@ya\pgf@y%
			\centerpoint%
			\pgf@y\pgf@ya%
		\else%
			\pgfpointintersectionoflines{\centerpoint}{\centerpoint\advance\pgf@y-1pt}%
				{\csname pgf@anchor@not gate US@south west\endcsname}%
				{%
					\pgfpointadd{\centerpoint}{%
						\tipanchor%
						\pgf@xa\outerxsep%
						\advance\pgf@x2.350943\pgf@xa%	
					}%
				}%	
		\fi%
	}
	\anchor{south east}{%
		\dimensions%
		\ifpgfgateanchorsuseboundingrectangle%
			\csname pgf@anchor@not gate US@south west\endcsname%
			\pgfutil@tempdima\pgf@y%
			\csname pgf@anchor@buffer gate US@east\endcsname%
			\pgf@y\pgfutil@tempdima%
		\else%
			\pgfpointintersectionoflines{\centerpoint}{\centerpoint\advance\pgf@x1pt\advance\pgf@y-1pt}%
				{\csname pgf@anchor@buffer gate US@south west\endcsname}%
				{%
					\pgfpointadd{\centerpoint}{%
						\tipanchor%
						\pgf@xc\outerxsep%
						\advance\pgf@x2.350943\pgf@xc%	
					}%
				}%	
		\fi%
	}
	\anchor{north east}{%
		\dimensions%
		\ifpgfgateanchorsuseboundingrectangle%
			\csname pgf@anchor@not gate US@north west\endcsname%
			\pgfutil@tempdima\pgf@y%
			\csname pgf@anchor@buffer gate US@east\endcsname%
			\pgf@y\pgfutil@tempdima%
		\else%
			\pgfpointintersectionoflines{\centerpoint}{\centerpoint\advance\pgf@x1pt\advance\pgf@y1pt}%
				{\csname pgf@anchor@buffer gate US@north west\endcsname}%
				{%
					\pgfpointadd{\centerpoint}{%
						\tipanchor%
						\pgf@xa\outerxsep%
						\advance\pgf@x2.350943\pgf@xa%	
					}%
				}%	
		\fi%
	}
	\inheritanchor[from=not gate US]{south west}
	\inheritanchor[from=not gate US]{north west}
	\inheritanchor[from=not gate US]{input}
	\inheritanchor[from=not gate US]{west}
	\backgroundpath{%
		\dimensions%
		\pgf@xc\halfwidth%
		\pgf@yc\halfheight%
		\advance\pgf@xc-\outerxsep%
		\advance\pgf@yc-\outerysep%
		{%
			\pgftransformshift{\centerpoint}%
			\pgfpathmoveto{\tipanchor}%
			\pgfpathlineto{\pgfqpoint{-.833333\pgf@xc}{1.166666\pgf@yc}}%
			\pgfpathlineto{\pgfqpoint{-.833333\pgf@xc}{-1.166666\pgf@yc}}%
			\pgfpathclose%
			%
			% Draw the input.
			%
			\expandafter\ifx\expandafter\pgf@lib@sh@itext\csname input-1\endcsname%
				{%
					\pgfpathcircle{%
						\pgf@xa\halfside%
						\pgf@x-.833333\pgf@xa%
						\advance\pgf@x-.5\pgflinewidth%
						\advance\pgf@x-\invertedradius%
						\pgf@y0pt%
					}{+\invertedradius}%				
				}%
			\fi%				
		}%
	}%
  \anchorborder{%
    \pgf@lib@gates@not@buffer@border{buffer gate US}
  }
}





\pgfdeclareshape{and gate CDH}{%
	\expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@and gate CDH\endcsname{%
		\pgf@lib@sh@logicgate@parseinputs{1024}% Maximum 1024 (!) inputs.
		%
		\pgfmathloop%
		\ifnum\pgfmathcounter>\pgf@lib@sh@logicgate@numinputs%
		\else%
			\pgfutil@ifundefined{pgf@anchor@and gate CDH@input \pgfmathcounter}{%
				\expandafter\xdef\csname pgf@anchor@and gate CDH@input \pgfmathcounter\endcsname{%
					\noexpand\pgf@lib@sh@logicgate@AND@inputanchor{\pgfmathcounter}%
				}%
			}{}%
		\repeatpgfmathloop%
		\ifnum\pgf@lib@sh@logicgate@numinputs<2\relax%
			\pgferror{An and gate must have at least two inputs}%
		\fi%
	}%
	\savedmacro\numinputs{\let\numinputs\pgf@lib@sh@logicgate@numinputs}%
	\saveddimen\invertedradius{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
	}%
	\saveddimen\outerinvertedradius{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
		\advance\pgf@x.5\pgflinewidth%
	}
	\savedmacro\dimensions{\pgf@lib@sh@logicgates@dimensions@orUS}
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+0.5ex}%
	}
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt%
	}
	\anchor{center}{\centerpoint}%
	\anchor{mid}{\midpoint}%
	\anchor{mid east}{%
		\csname pgf@anchor@and gate CDH@east\endcsname%
		\pgf@xa\pgf@x%
		\midpoint%
		\pgf@x\pgf@xa}
	\anchor{mid west}{%
		\csname pgf@anchor@and gate CDH@west\endcsname%
		\pgf@xa\pgf@x%
		\midpoint%
		\pgf@x\pgf@xa}
	\anchor{base}{\basepoint}%
	\anchor{base east}{%
		\csname pgf@anchor@and gate CDH@east\endcsname%
		\pgf@xa\pgf@x%
		\basepoint%
		\pgf@x\pgf@xa}
	\anchor{base west}{%
		\csname pgf@anchor@and gate CDH@west\endcsname%
		\pgf@xa\pgf@x%
		\basepoint%
		\pgf@x\pgf@xa}
	\anchor{east}{%
		\dimensions%
		\pgfpointadd{\centerpoint}{\tipanchor}%
	}
	\anchor{output}{\csname pgf@anchor@and gate CDH@east\endcsname}
	\anchor{north east}{%
		\dimensions%
		\ifpgfgateanchorsuseboundingrectangle%
			\tipanchor%
			\pgf@xa\pgf@x%
			\centerpoint%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y\halfheight%
		\else%
			\centerpoint%
			\pgf@xa\halfwidth%
			\pgf@ya\halfheight%
			\pgf@xb\halfside%
			\advance\pgf@x-.166666\pgf@xb%
			\advance\pgf@xa\pgf@xb%
			\advance\pgf@x.5\pgf@xa%
			\advance\pgf@y-\pgf@xb%
			\advance\pgf@ya\pgf@xb%
			\advance\pgf@y.866025\pgf@ya%
		\fi%
	}
	\anchor{south east}{%
		\dimensions%
		\ifpgfgateanchorsuseboundingrectangle%
			\tipanchor%
			\pgf@xa\pgf@x%
			\centerpoint%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y-\halfheight%
		\else
			\centerpoint%
			\pgf@xa\halfwidth%
			\pgf@ya\halfheight%
			\pgf@xb\halfside%
			\advance\pgf@x-.166666\pgf@xb%
			\advance\pgf@xa\pgf@xb%
			\advance\pgf@x.5\pgf@xa%
			\advance\pgf@y\pgf@xb%
			\advance\pgf@ya\pgf@xb%
			\advance\pgf@y-.866025\pgf@ya%
		\fi%
	}
	\anchor{north}{%
		\dimensions%
		\centerpoint%
		\ifpgfgateanchorsuseboundingrectangle%
			\advance\pgf@y\halfheight%
		\else%
			\pgf@ya\halfheight%
			\advance\pgf@y.993043\pgf@ya%
		\fi%	
	}
	\anchor{south}{%
		\dimensions%
		\centerpoint%
		\ifpgfgateanchorsuseboundingrectangle%
			\advance\pgf@y-\halfheight%
		\else%
			\pgf@ya\halfheight%
			\advance\pgf@y-.993043\pgf@ya%
		\fi%	
	}
	\anchor{south west}{%
		\dimensions%
		\centerpoint%
		\pgf@xa\halfside%
		\advance\pgf@x-1.16666\pgf@xa%
		\advance\pgf@x-\outerxsep%
		\advance\pgf@y-\halfheight%
	}
	\anchor{north west}{%
		\dimensions%
		\centerpoint%
		\pgf@xa\halfside%
		\advance\pgf@x-1.16666\pgf@xa%
		\advance\pgf@x-\outerxsep%
		\advance\pgf@y\halfheight%
	}
	\anchor{west}{%
		\dimensions%
		\centerpoint%
		\pgf@xa\halfside%
		\advance\pgf@x-1.16666\pgf@xa%
		\advance\pgf@x-\outerxsep%
	}
	\backgroundpath{%
		\dimensions%
		\pgf@xc\halfwidth%
		\pgf@yc\halfheight%
		\advance\pgf@xc-\outerxsep%
		\advance\pgf@yc-\outerysep%
		{%
			\pgftransformshift{\centerpoint}%
			\pgfpathmoveto{\pgfqpoint{-.16666\pgf@xc}{\pgf@yc}}%
			{%
				\pgf@yc2.0\pgf@yc%
				\edef\pgf@marshal{%
					\noexpand\pgfpatharc{90}{30}{\the\pgf@yc}%
				}%
				\pgf@marshal%
			}
			{%
				\pgf@yc2.0\pgf@yc%
				\edef\pgf@marshal{%
					\noexpand\pgfpatharc{-30}{-90}{\the\pgf@yc}%
				}%
				\pgf@marshal%
			}
			\pgfpathlineto{\pgfqpoint{-1.16666\pgf@xc}{-\pgf@yc}}%
			\pgfpathlineto{\pgfqpoint{-1.16666\pgf@xc}{\pgf@yc}}%
			\pgfpathclose%
			%
			% Draw the inputs.
			%
			\pgfutil@tempdima2.0\pgf@yc%
			\c@pgf@counta\numinputs%
			\advance\c@pgf@counta1\relax%
			\divide\pgfutil@tempdima\c@pgf@counta%
			\pgfmathloop%
			\ifnum\pgfmathcounter>\numinputs%
			\else%
				\advance\pgf@yc-\pgfutil@tempdima%
				\expandafter\ifx\expandafter\pgf@lib@sh@itext\csname input-\pgfmathcounter\endcsname%
					{%
						\pgfpathcircle{%
							\pgf@xa\halfside%
							\pgf@x-1.16666\pgf@xa%
							\advance\pgf@x-.5\pgflinewidth%
							\advance\pgf@x-\invertedradius%
							\pgf@y\pgf@yc%
						}{+\invertedradius}%				
					}%
				\fi%				
			\repeatpgfmathloop%
		}%
	}%
	\anchorborder{%
		\pgfextract@process\externalpoint{}%
		\pgf@xa\pgf@x%
		\pgf@ya\pgf@y%
		\dimensions%
		\pgf@xb\halfside%
		%
		\pgf@xb-.166666\pgf@xb%
		\ifdim\pgf@xa<\pgf@xb%
			\pgfpointadd{\centerpoint}{%
				\pgfpointborderrectangle{\externalpoint}{%
					\pgf@xc\halfside%
					\pgf@xc.166666\pgf@xc%
					\advance\pgf@xc\halfwidth%
					\pgfqpoint{\pgf@xc}{\halfheight}%
				}%
			}%
		\else%
			\ifdim\pgf@y=0pt\relax%
				\csname pgf@anchor@and gate CDH@east\endcsname%
			\else%
				\pgfextract@process\externalpoint{\pgfpointadd{\centerpoint}{\externalpoint}}%
				\pgf@xc\halfwidth%
				\advance\pgf@xc\halfside%
				\pgf@yc\halfheight%
				\advance\pgf@yc\halfside%
				\ifdim\pgf@ya<0pt%
					\pgfmathpointintersectionoflineandarc{\externalpoint}{\centerpoint}%
					{%
						\centerpoint%
						\advance\pgf@y\halfside%	
						\advance\pgf@x\pgf@xb%		
					}%
					{270}{330}{+\pgf@yc}%
				\else%
					\pgfmathpointintersectionoflineandarc{\externalpoint}{\centerpoint}%
					{%
						\centerpoint%
						\advance\pgf@y-\halfside%	
						\advance\pgf@x\pgf@xb%
					}%
					{30}{90}{+\pgf@xc and +\pgf@yc}%
				\fi%
			\fi%
		\fi%
	}
}


\pgfdeclareshape{nand gate CDH}{%
	\expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@nand gate CDH\endcsname{%
		\pgf@lib@sh@logicgate@parseinputs{1024}% Maximum 1024 (!) inputs.
		%
		\pgfmathloop%
		\ifnum\pgfmathcounter>\pgf@lib@sh@logicgate@numinputs%
		\else%
			\pgfutil@ifundefined{pgf@anchor@nand gate CDH@input \pgfmathcounter}{%
				\expandafter\xdef\csname pgf@anchor@nand gate CDH@input \pgfmathcounter\endcsname{%
					\noexpand\pgf@lib@sh@logicgate@AND@inputanchor{\pgfmathcounter}%
				}%
			}{}%
		\repeatpgfmathloop%
		\ifnum\pgf@lib@sh@logicgate@numinputs<2\relax%
			\pgferror{A nand gate must have at least two inputs}%
		\fi%
	}%
	\savedmacro\numinputs{\let\numinputs\pgf@lib@sh@logicgate@numinputs}%
	\saveddimen\invertedradius{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
	}%
	\saveddimen\outerinvertedradius{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/logic gate inverted radius}}%
		\advance\pgf@x.5\pgflinewidth%
	}
	\savedmacro\dimensions{\pgf@lib@sh@logicgates@dimensions@orUS}
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+0.5ex}%
	}
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt%
	}
	\anchor{center}{\centerpoint}%
	\anchor{mid}{\midpoint}%
	\inheritanchor[from=and gate CDH]{mid east}
	\inheritanchor[from=and gate CDH]{mid west}
	\anchor{base}{\basepoint}%
	\inheritanchor[from=and gate CDH]{base east}
	\inheritanchor[from=and gate CDH]{base west}
	\anchor{output}{%
		\dimensions
		\pgfpointadd{\centerpoint}{%
			\pgf@xa\halfside%
			\pgf@x-.166666\pgf@xa%
			\pgf@xb2.0\pgf@xa%
			\advance\pgf@x.866025\pgf@xb%
			\advance\pgf@x\invertedradius%
			\advance\pgf@x\outerinvertedradius%
			\advance\pgf@x\outerxsep%
			\pgf@y0pt%
		}%
	}
	\inheritanchor[from=and gate CDH]{east}
	\inheritanchor[from=and gate CDH]{north east}
	\inheritanchor[from=and gate CDH]{south east}
	\inheritanchor[from=and gate CDH]{north}
	\inheritanchor[from=and gate CDH]{south}
	\inheritanchor[from=and gate CDH]{south west}
	\inheritanchor[from=and gate CDH]{north west}
	\inheritanchor[from=and gate CDH]{west}
	\backgroundpath{%
		\dimensions%
		\pgf@xc\halfwidth%
		\pgf@yc\halfheight%
		\advance\pgf@xc-\outerxsep%
		\advance\pgf@yc-\outerysep%
		{%
			\pgftransformshift{\centerpoint}%
			\pgfpathmoveto{\pgfqpoint{-.16666\pgf@xc}{\pgf@yc}}%
			{%
				\pgf@yc2.0\pgf@yc%
				\edef\pgf@marshal{%
					\noexpand\pgfpatharc{90}{30}{\the\pgf@yc}%
				}%
				\pgf@marshal%
			}
			{%
				\pgf@yc2.0\pgf@yc%
				\edef\pgf@marshal{%
					\noexpand\pgfpatharc{-30}{-90}{\the\pgf@yc}%
				}%
				\pgf@marshal%
			}
			\pgfpathlineto{\pgfqpoint{-1.16666\pgf@xc}{-\pgf@yc}}%
			\pgfpathlineto{\pgfqpoint{-1.16666\pgf@xc}{\pgf@yc}}%
			\pgfpathclose%
			%
			% Draw the output inverter.
			%
			{%
				\pgfpathcircle{%
					\pgf@x-.166666\pgf@xc%
					\pgf@yc2.0\pgf@yc%
					\advance\pgf@x.866025\pgf@yc%
					\advance\pgf@x\outerinvertedradius%
					\pgf@y0pt%
				}{+\invertedradius}%			
			}%
			%
			% Draw the inputs.
			%
			\pgfutil@tempdima2.0\pgf@yc%
			\c@pgf@counta\numinputs%
			\advance\c@pgf@counta1\relax%
			\divide\pgfutil@tempdima\c@pgf@counta%
			\pgfmathloop%
			\ifnum\pgfmathcounter>\numinputs%
			\else%
				\advance\pgf@yc-\pgfutil@tempdima%
				\expandafter\ifx\expandafter\pgf@lib@sh@itext\csname input-\pgfmathcounter\endcsname%
					{%
						\pgfpathcircle{%
							\pgf@xa\halfside%
							\pgf@x-1.16666\pgf@xa%
							\advance\pgf@x-.5\pgflinewidth%
							\advance\pgf@x-\invertedradius%
							\pgf@y\pgf@yc%
						}{+\invertedradius}%				
					}%
				\fi%				
			\repeatpgfmathloop%
		}%
	}%
	\inheritanchorborder[from=and gate CDH]
}
pgflibraryshapes.geometric.code.tex
% Copyright 2006 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.

\ProvidesFileRCS[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/libraries/shapes/pgflibraryshapes.geometric.code.tex,v 1.1 2008/06/26 16:55:55 tantau Exp $

\pgfdeclareshape{ellipse}
%
% 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%
  }
  \savedanchor\radius{%
    % 
    % Caculate ``height radius''
    % 
    \pgf@y=.5\ht\pgfnodeparttextbox%
    \advance\pgf@y by.5\dp\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@yb{\pgfkeysvalueof{/pgf/inner ysep}}%
    \advance\pgf@y by\pgf@yb%
    % 
    % Caculate ``width radius''
    % 
    \pgf@x=.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@xb{\pgfkeysvalueof{/pgf/inner xsep}}%
    \advance\pgf@x by\pgf@xb%
    % 
    % Adjust
    % 
    \pgf@x=1.4142136\pgf@x%
    \pgf@y=1.4142136\pgf@y%
    % 
    % Adjust hieght, if necessary
    % 
    \pgfmathsetlength\pgf@yc{\pgfkeysvalueof{/pgf/minimum height}}%
    \ifdim\pgf@y<.5\pgf@yc%
      \pgf@y=.5\pgf@yc%
    \fi%
    % 
    % Adjust width, if necessary
    % 
    \pgfmathsetlength\pgf@xc{\pgfkeysvalueof{/pgf/minimum width}}%
    \ifdim\pgf@x<.5\pgf@xc%
      \pgf@x=.5\pgf@xc%
    \fi%
    % 
    % Add outer sep
    % 
    \pgfmathsetlength{\pgf@xb}{\pgfkeysvalueof{/pgf/outer xsep}}%  
    \pgfmathsetlength{\pgf@yb}{\pgfkeysvalueof{/pgf/outer ysep}}%  
    \advance\pgf@x by\pgf@xb%
    \advance\pgf@y by\pgf@yb%
  }

  %
  % Anchors
  % 
  \anchor{center}{\centerpoint}
  \anchor{mid}{\centerpoint\pgfmathsetlength\pgf@y{.5ex}}
  \anchor{base}{\centerpoint\pgf@y=0pt}
  \anchor{north}
  {
    \pgf@process{\radius}
    \pgf@ya=\pgf@y%
    \pgf@process{\centerpoint}
    \advance\pgf@y by\pgf@ya
  }
  \anchor{south}
  {
    \pgf@process{\radius}
    \pgf@ya=\pgf@y%
    \pgf@process{\centerpoint}
    \advance\pgf@y by-\pgf@ya
  }
  \anchor{west}
  {
    \pgf@process{\radius}
    \pgf@xa=\pgf@x%
    \pgf@process{\centerpoint}
    \advance\pgf@x by-\pgf@xa
  }
  \anchor{mid west}
  {%
    \pgf@process{\radius}
    \pgf@xa=\pgf@x%
    \pgf@process{\centerpoint}
    \advance\pgf@x by-\pgf@xa%
    \pgfmathsetlength\pgf@y{.5ex}
  }
  \anchor{base west}
  {%
    \pgf@process{\radius}
    \pgf@xa=\pgf@x%
    \pgf@process{\centerpoint}
    \advance\pgf@x by-\pgf@xa%
    \pgf@y=0pt
  }
  \anchor{north west}
  {
    \pgf@process{\radius}
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgf@process{\centerpoint}
    \advance\pgf@x by-0.707107\pgf@xa
    \advance\pgf@y by0.707107\pgf@ya
  }
  \anchor{south west}
  {
    \pgf@process{\radius}
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgf@process{\centerpoint}
    \advance\pgf@x by-0.707107\pgf@xa
    \advance\pgf@y by-0.707107\pgf@ya
  }
  \anchor{east}
  {%
    \pgf@process{\radius}
    \pgf@xa=\pgf@x%
    \pgf@process{\centerpoint}
    \advance\pgf@x by\pgf@xa
  }
  \anchor{mid east}
  {%
    \pgf@process{\radius}
    \pgf@xa=\pgf@x%
    \pgf@process{\centerpoint}
    \advance\pgf@x by\pgf@xa%
    \pgfmathsetlength\pgf@y{.5ex}
  }
  \anchor{base east}
  {%
    \pgf@process{\radius}
    \pgf@xa=\pgf@x%
    \pgf@process{\centerpoint}
    \advance\pgf@x by\pgf@xa%
    \pgf@y=0pt
  }
  \anchor{north east}
  {
    \pgf@process{\radius}
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgf@process{\centerpoint}
    \advance\pgf@x by0.707107\pgf@xa
    \advance\pgf@y by0.707107\pgf@ya
  }
  \anchor{south east}
  {
    \pgf@process{\radius}
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgf@process{\centerpoint}
    \advance\pgf@x by0.707107\pgf@xa
    \advance\pgf@y by-0.707107\pgf@ya
  }
  \anchorborder{
    \edef\pgf@marshal{%
      \noexpand\pgfpointborderellipse
      {\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}
      {\noexpand\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
  {
    \pgf@process{\radius}%
    \pgfutil@tempdima=\pgf@x%
    \pgfutil@tempdimb=\pgf@y%
    \pgfmathsetlength{\pgf@xb}{\pgfkeysvalueof{/pgf/outer xsep}}%  
    \pgfmathsetlength{\pgf@yb}{\pgfkeysvalueof{/pgf/outer ysep}}%  
    \advance\pgfutil@tempdima by-\pgf@xb%
    \advance\pgfutil@tempdimb by-\pgf@yb%
    \pgfpathellipse{\centerpoint}{\pgfqpoint{\pgfutil@tempdima}{0pt}}{\pgfqpoint{0pt}{\pgfutil@tempdimb}}%
  }
}




% Set the recommended shape aspect ratio
%
% #1 = aspect ratio
%
% Example:
%
% \pgfsetshapeaspect{1.5}

% Keys for shape aspect ratio.
%
% /pgf/aspect         : recommended width/height quotient.
%
\pgfkeys{/pgf/.cd,
	aspect/.code={\pgfsetshapeaspect{#1}},% this for tikz...
	shape aspect/.initial=1,% but this is consistent with other pgfset stuff. 
	shape aspect/.code={%
		\pgfkeys{/pgf/aspect=#1}%
		\pgfkeyssetvalue{/pgf/shape aspect}{#1}
	}%
}
	

\def\pgfsetshapeaspect#1{%
  \def\pgfshapeaspect{#1}%
  % Invert
  \pgfutil@tempdima=#1pt%
  \pgfutil@tempdima=.125\pgfutil@tempdima%
  \c@pgf@counta=\pgfutil@tempdima\relax% 8192*determinant
  \pgfutil@tempdima=8192pt%
  \divide\pgfutil@tempdima by\c@pgf@counta%
  \edef\pgfshapeaspectinverse{\pgf@sys@tonumber{\pgfutil@tempdima}}
}

\pgfsetshapeaspect{1}

\pgfdeclareshape{diamond}
{
  \savedanchor\outernortheast{%
    %
    % Calculate width and height of the inner rectangle
    %
    \pgf@xa=.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@xc{\pgfkeysvalueof{/pgf/inner xsep}}%
    \advance\pgf@xa by\pgf@xc%
    \pgf@ya=.5\ht\pgfnodeparttextbox%
    \advance\pgf@ya by.5\dp\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@yc{\pgfkeysvalueof{/pgf/inner ysep}}%
    \advance\pgf@ya by\pgf@yc%
    %
    % Calculate width and height of diamond
    %
    \pgf@x=\pgf@xa%
    \advance\pgf@x by\pgfshapeaspect\pgf@ya%
    \pgf@y=\pgfshapeaspectinverse\pgf@xa%
    \advance\pgf@y by\pgf@ya%
    %
    % Check against minimum height/width
    %
    \pgfmathsetlength\pgf@xb{\pgfkeysvalueof{/pgf/minimum width}}%
    \pgf@xb=.5\pgf@xb%   
    \ifdim\pgf@x<\pgf@xb%
      % yes, too small. Enlarge...
      \pgf@x=\pgf@xb%
    \fi%
    \pgfmathsetlength\pgf@yb{\pgfkeysvalueof{/pgf/minimum height}}%
    \pgf@yb=.5\pgf@yb%   
    \ifdim\pgf@y<\pgf@yb%
      % yes, too small. Enlarge...
      \pgf@y=\pgf@yb%
    \fi%
    %
    % Add outer border
    %
    \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/outer xsep}}%
    \advance\pgf@x by\pgf@xa%
    \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/outer ysep}}%
    \advance\pgf@y by\pgf@ya%
  }
  \savedanchor\text{%
    \pgf@x=-.5\wd\pgfnodeparttextbox%
    \pgf@y=-.5\ht\pgfnodeparttextbox%
    \advance\pgf@y by.5\dp\pgfnodeparttextbox%
  }

  %
  % Anchors
  %
  \anchor{text}{\text}%
  \anchor{center}{\pgfpointorigin}%
  \anchor{mid}{%
    \pgf@process{\text}%
    \pgf@x=0pt%
    \pgfmathsetlength\pgf@ya{.5ex}
    \advance\pgf@y by\pgf@ya%
  }
  \anchor{base}{\pgf@process{\text}\pgf@x=0pt  }
  \anchor{north}{\pgf@process{\outernortheast}\pgf@x=0pt}
  \anchor{south}{\pgf@process{\outernortheast}\pgf@x=0pt\pgf@y=-\pgf@y}
  \anchor{west}{\pgf@process{\outernortheast}\pgf@x=-\pgf@x\pgf@y=0pt}
  \anchor{north west}{\pgf@process{\outernortheast}\pgf@x=-.5\pgf@x\pgf@y=.5\pgf@y}
  \anchor{south west}{\pgf@process{\outernortheast}\pgf@x=-.5\pgf@x\pgf@y=-.5\pgf@y}
  \anchor{east}{\pgf@process{\outernortheast}\pgf@y=0pt}
  \anchor{north east}{\pgf@process{\outernortheast}\pgf@x=.5\pgf@x\pgf@y=.5\pgf@y}
  \anchor{south east}{\pgf@process{\outernortheast}\pgf@x=.5\pgf@x\pgf@y=-.5\pgf@y}
  \anchorborder{%
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgf@process{\outernortheast}%
    \ifdim\pgf@xa>0pt%
    \else%
      \pgf@x=-\pgf@x%
    \fi%
    \ifdim\pgf@ya>0pt%
    \else%
      \pgf@y=-\pgf@y%
    \fi%
    \edef\pgf@marshal{%
      \noexpand\pgfpointintersectionoflines
      {\noexpand\pgfpointorigin}
      {\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}
      {\noexpand\pgfqpoint{\the\pgf@x}{0pt}}
      {\noexpand\pgfqpoint{0pt}{\the\pgf@y}}%
    }%
    \pgf@process{\pgf@marshal}%
  }

  %
  % Background path
  %
  \backgroundpath{
    \pgf@process{\outernortheast}%
    \pgf@xc=\pgf@x%
    \pgf@yc=\pgf@y%
    \pgfmathsetlength{\pgf@xa}{\pgfkeysvalueof{/pgf/outer xsep}}%
    \pgfmathsetlength{\pgf@ya}{\pgfkeysvalueof{/pgf/outer ysep}}%
    \advance\pgf@xc by-1.414213\pgf@xa%
    \advance\pgf@yc by-1.414213\pgf@ya%
    \pgfpathmoveto{\pgfqpoint{\pgf@xc}{0pt}}%
    \pgfpathlineto{\pgfqpoint{0pt}{\pgf@yc}}%
    \pgfpathlineto{\pgfqpoint{-\pgf@xc}{0pt}}%
    \pgfpathlineto{\pgfqpoint{0pt}{-\pgf@yc}}%
    \pgfpathclose%
  }
}






\newif\ifpgf@lib@shapes@starouterradiususesratio
\pgf@lib@shapes@starouterradiususesratiotrue

% Keys for star shape
%
% /pgf/star points       : Number of points on the star.
% /pgf/star point height : The height of the outer star points.
% /pgf/star point ratio  : The ratio of the outer point and inner point radii.

\pgfkeys{/pgf/.cd,
	star points/.initial=5,
	star point height/.initial=.5cm,
	star point height/.code={%
		\def\pgf@lib@temp{#1}%
		\pgfkeyslet{/pgf/star point height}{\pgf@lib@temp}%
		\pgf@lib@shapes@starouterradiususesratiofalse%	
	},
	star point ratio/.initial=1.5,
	star point ratio/.code={%
		\def\pgf@lib@temp{#1}%
		\pgfkeyslet{/pgf/star point ratio}{\pgf@lib@temp}%
		\pgf@lib@shapes@starouterradiususesratiotrue%	
	},%
	star rotate/.style={/pgf/shape border rotate=#1}% For compatability with 1.18
}


% Shape star.
%
\pgfdeclareshape{star}{
	\savedmacro\totalstarpoints{%
		\pgfmathsetcounter{pgf@counta}{\pgfkeysvalueof{/pgf/star points}}%
		\multiply\c@pgf@counta2\relax%
		\edef\totalstarpoints{\the\c@pgf@counta}%
	}
	\savedmacro\anglestep{%
		\pgfmathdivide{180}{\pgfkeysvalueof{/pgf/star points}}%
		\let\anglestep\pgfmathresult%
	}
	\savedmacro\calculateradii{%
		%
		% Get the node dimensions.
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
		\advance\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
		\advance\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y.5\dp\pgfnodeparttextbox%
		\ifdim\pgf@y>\pgf@x%
			\pgf@x\pgf@y%
		\fi%
		%
		% Calculate the incircle radius.
		%
		\pgf@x1.41421\pgf@x%
		\edef\innerradius{\the\pgf@x}%
		%
		% Calculate the circumcircle radius.
		%
		% Use the star point height or the star point ratio?
		%
		\ifpgf@lib@shapes@starouterradiususesratio%
			\pgfmathparse{\pgfkeysvalueof{/pgf/star point ratio}}%
			\expandafter\pgf@x\pgfmathresult\pgf@x%
		\else%
			\pgfmathaddtolength\pgf@x{\pgfkeysvalueof{/pgf/star point height}}%
		\fi%
		\pgf@xc\pgf@x%
		%
		% Accommodate the larger of the minimum height/width.
		%
		\pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/minimum width}}%
		\pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/minimum height}}%
		\ifdim\pgf@ya>\pgf@xa%
			\pgf@xa\pgf@ya%
		\fi%
		\ifdim\pgf@x<.5\pgf@xa%
	   	\pgf@x.5\pgf@xa%
	   \fi%
	   \edef\outerradius{\the\pgf@x}%
	   %
	   % If the outer radius has been enlarged, adjust the inner radius...
	   %
	   \ifdim\pgf@x>\pgf@xc%
	   	%
	   	% ...using the star point ratio, or...
	   	%
	   	\ifpgf@lib@shapes@starouterradiususesratio%
	   		\pgfmathreciprocal{\pgfkeysvalueof{/pgf/star point ratio}}%
	   		\pgf@xa\pgfmathresult\pgf@x\relax%
	   		\edef\innerradius{\the\pgf@xa}%
			\else%
				%
				% The star point height.
				%
				\pgf@xa\pgf@x\relax%
				\pgfmathaddtolength\pgf@xa{-\pgfkeysvalueof{/pgf/star point height}}%
				\edef\innerradius{\the\pgf@xa}%
			\fi%
		\fi%
		\edef\outerradius{\the\pgf@x}%
		%
		% Now calculate the anchor radii from the outer sep.
		%
		\pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/outer xsep}}%
		\pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/outer ysep}}%
		\ifdim\pgf@ya>\pgf@xa%
			\pgf@xa\pgf@ya%
		\fi
		%
		% Take into account the miter length...
		%
		\pgfmathdivide{180}{\pgfkeysvalueof{/pgf/star points}}%
		\let\angletofirstpoint\pgfmathresult%
		\pgfmathmultiply@{\angletofirstpoint}{2}%
		\let\angletosecondpoint\pgfmathresult%
		%
		% ...for the outer radius...
		%
		\pgfmathanglebetweenlines%
			{\pgfqpointpolar{\angletofirstpoint}{\outerradius}}%
			{\pgfqpointpolar{\angletosecondpoint}{\innerradius}}%
			{\pgfqpointpolar{\angletofirstpoint}{\outerradius}}%		
			{\pgfqpointpolar{0}{\innerradius}}%		
		\pgfmathdivide@{\pgfmathresult}{2}%
		\pgfmathcosec@{\pgfmathresult}%
		\pgf@x\outerradius\relax%
		\advance\pgf@x\pgfmathresult\pgf@xa%
		\edef\anchorouterradius{\the\pgf@x}%
		%
		% ...and for the inner radius.
		%
		\pgfmathanglebetweenlines%
			{\pgfqpointpolar{\angletofirstpoint}{\innerradius}}%		
			{\pgfqpointpolar{0}{\outerradius}}%	
			{\pgfqpointpolar{\angletofirstpoint}{\innerradius}}%
			{\pgfqpointpolar{\angletosecondpoint}{\outerradius}}%						
		\pgfmathdivide@{\pgfmathresult}{2}%
		\pgfmathcosec@{\pgfmathresult}%
		\pgf@x\innerradius\relax%
		\advance\pgf@x\pgfmathresult\pgf@xa%
		\edef\anchorinnerradius{\the\pgf@x}%
		%	
		% Save all radii.
		%
		\addtosavedmacro{\innerradius}%
		\addtosavedmacro{\outerradius}%
		\addtosavedmacro{\anchorinnerradius}%
		\addtosavedmacro{\anchorouterradius}%
	}
	\savedmacro\startangle{%
		\pgfmathadd{90}{\pgfkeysvalueof{/pgf/shape border rotate}}%
		\let\startangle\pgfmathresult%
	}
	%
	% Saved anchors.
	%
	\savedanchor{\centerpoint}{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}%
	\savedanchor{\midpoint}{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+.5ex}%
	}%	
	%
	% Other anchors.
	%
%
	% Other anchors.
	%
	\anchor{center}{\centerpoint}%
	\anchor{mid}{\centerpoint\pgfmathsetlength\pgf@y{.5ex}}%
 	\anchor{base}{\centerpoint\pgf@y=0pt}%
 	\anchor{north}{%
 		\calculateradii%
 		\csname pgf@anchor@star@border\endcsname{\pgfqpoint{0pt}{\anchorouterradius}}}%
 	\anchor{south}{%
 		\calculateradii%
 		\csname pgf@anchor@star@border\endcsname{\pgfqpoint{0pt}{-\anchorouterradius}}}%
 	\anchor{east}{%
 		\calculateradii%
 		\csname pgf@anchor@star@border\endcsname{\pgfqpoint{\anchorouterradius}{0pt}}}%
 	\anchor{west}{%
 		\calculateradii%
 		\csname pgf@anchor@star@border\endcsname{\pgfqpoint{-\anchorouterradius}{0pt}}}%
 	\anchor{north east}{%
 		\calculateradii%
 		\csname pgf@anchor@star@border\endcsname{\pgfqpoint{\anchorouterradius}{\anchorouterradius}}}%
 	\anchor{north west}{%
 		\calculateradii%
 		\csname pgf@anchor@star@border\endcsname{\pgfqpoint{-\anchorouterradius}{\anchorouterradius}}}%
 	\anchor{south east}{%
 		\calculateradii%
 		\csname pgf@anchor@star@border\endcsname{\pgfqpoint{\anchorouterradius}{-\anchorouterradius}}}%
 	\anchor{south west}{%
 		\calculateradii%
 		\csname pgf@anchor@star@border\endcsname{\pgfqpoint{-\anchorouterradius}{-\anchorouterradius}}}%	 	
 	%
 	% Background path.
 	%
	\backgroundpath{%
		\calculateradii%
		\let\angle\startangle%
		\pgfpathmoveto{\pgfpointadd{\centerpoint}{\pgfqpointpolar{\startangle}{\outerradius}}}%
		\pgfmathloop%
			\pgfmathadd@{\angle}{\anglestep}%
			\let\angle\pgfmathresult%
		\ifnum\pgfmathcounter=\totalstarpoints%
			\pgfpathclose%
		\else%
			\ifodd\pgfmathcounter
				\pgfpathlineto{\pgfpointadd{\centerpoint}{\pgfqpointpolar{\angle}{\innerradius}}}%
			\else%
				\pgfpathlineto{\pgfpointadd{\centerpoint}{\pgfqpointpolar{\angle}{\outerradius}}}%
			\fi%
		\repeatpgfmathloop%
	}%
	%
	% Define points on the anchor border.
	%
	\anchorborder{%
		%
		% Save x and y.
		%
		\edef\externalx{\the\pgf@x}%
		\edef\externaly{\the\pgf@y}%
		%
		% Adjust the location of the external 
		% point relative to \centerpoint.
		%
		\centerpoint%
		\pgf@xa\externalx\relax%
		\pgf@ya\externaly\relax%
		\advance\pgf@xa\pgf@x%
		\advance\pgf@ya\pgf@y%
		\edef\externalx{\the\pgf@xa}%
		\edef\externaly{\the\pgf@ya}%
		%
		% Get the angle of the external point to the \centerpoint.
		%
		\pgfmathanglebetweenpoints{\centerpoint}{\pgfqpoint{\externalx}{\externaly}}%
		%
		% Locate the appropriate sides on the star border...
		%
		\pgfmathsubtract@{\pgfmathresult}{\startangle}%
		\ifdim\pgfmathresult pt<0pt\relax%
			\pgfmathadd@{\pgfmathresult}{360}%
		\fi%
		\pgfmathdivide@{\pgfmathresult}{\anglestep}%
		\pgfmathfloor@{\pgfmathresult}%
		\afterassignment\pgfmath@gobbletilpgfmath@
		\c@pgf@counta\pgfmathresult\relax\pgfmath@
		\pgfmathmultiply@{\pgfmathresult}{\anglestep}%
		\pgfmathadd@{\pgfmathresult}{\startangle}%
		\let\firstangle\pgfmathresult%
		\pgfmathadd@{\pgfmathresult}{\anglestep}%
		\let\secondangle\pgfmathresult%
		\calculateradii%
		%
		% ...and thus, the point on the star border.
		%
		\ifodd\c@pgf@counta
			\pgfpointintersectionoflines{\centerpoint}{\pgfpoint{+\externalx}{+\externaly}}%
				{%
					\pgfpointadd{\centerpoint}%
						{\pgfqpointpolar{+\firstangle}{+\anchorinnerradius}}%
					}%	
					{%
						\pgfpointadd{\centerpoint}%
							{\pgfqpointpolar{+\secondangle}{+\anchorouterradius}}%
					}%	
		\else%
			\pgfpointintersectionoflines{\centerpoint}{\pgfpoint{+\externalx}{+\externaly}}%
				{%
					\pgfpointadd{\centerpoint}%
						{\pgfqpointpolar{+\firstangle}{+\anchorouterradius}}%
					}%	
					{%
						\pgfpointadd{\centerpoint}%
							{\pgfqpointpolar{+\secondangle}{+\anchorinnerradius}}%
					}%	
		\fi%
	}
	%
	% Some hackery. This is needed if a star is positioned using 
	% a `...point <n+1>' anchor, where n is the maximum number of 
	% points of any previously drawn star.
	%
	\pgfutil@g@addto@macro\pgf@sh@s@star{%
		\c@pgf@counta\totalstarpoints\relax%
		\divide\c@pgf@counta2\relax%
		\pgfmathloop%
			\ifnum\c@pgf@counta>0\relax%
				\c@pgf@countb\c@pgf@counta\relax%
				\advance\c@pgf@countb-1\relax%
				\pgfutil@ifundefined{pgf@anchor@star@inner point\space\the\c@pgf@counta}{%
					\expandafter\xdef\csname pgf@anchor@star@inner point\space\the\c@pgf@counta\endcsname{%
						\noexpand\calculateradii%
						\noexpand\pgfmathmultiply@{\the\c@pgf@countb}{\noexpand\anglestep}%
						\noexpand\pgfmathmultiply@{\noexpand\pgfmathresult}{2}%
						\noexpand\pgfmathadd@{\noexpand\pgfmathresult}{\noexpand\anglestep}%
						\noexpand\pgfmathadd@{\noexpand\pgfmathresult}{\noexpand\startangle}%
						\noexpand\let\noexpand\angle\noexpand\pgfmathresult%
						\noexpand\pgfpointadd{\noexpand\centerpoint}%
							{\noexpand\pgfqpointpolar{\noexpand\angle}{\noexpand\anchorinnerradius}}%
					}%
					\expandafter\xdef\csname pgf@anchor@star@outer point\space\the\c@pgf@counta\endcsname{%
						\noexpand\calculateradii%
						\noexpand\pgfmathmultiply@{\the\c@pgf@countb}{\noexpand\anglestep}%
						\noexpand\pgfmathmultiply@{\noexpand\pgfmathresult}{2}%
						\noexpand\pgfmathadd@{\noexpand\pgfmathresult}{\noexpand\startangle}%
						\noexpand\let\noexpand\angle\noexpand\pgfmathresult%
						\noexpand\pgfpointadd{\noexpand\centerpoint}%
							{\noexpand\pgfqpointpolar{\noexpand\angle}{\noexpand\anchorouterradius}}%
					}%
				}{\c@pgf@counta0\relax}%
			\advance\c@pgf@counta-1\relax%
		\repeatpgfmathloop%	
	}%
}




% Keys for shape regular polygon
%
% /pgf/regular polygon sides 
%
\pgfkeys{/pgf/.cd,
	regular polygon sides/.initial=5,
	regular polygon rotate/.style={/pgf/shape border rotate=#1}% For compatability with 1.18
}


% Shape Regular Polygon.
%
\pgfdeclareshape{regular polygon}{
	\savedmacro\sides{%
		\pgfmathtruncatemacro\sides{\pgfkeysvalueof{/pgf/regular polygon sides}}%
	}
	\savedmacro\anglestep{%
		\pgfmathdivide{360}{\pgfkeysvalueof{/pgf/regular polygon sides}}%
		\let\anglestep\pgfmathresult%
	}
	\savedmacro\calculateradii{%
		%
		% Get the node dimensions.
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
		\advance\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
		\advance\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y.5\dp\pgfnodeparttextbox%
		\ifdim\pgf@y>\pgf@x%
			\pgf@x\pgf@y%
		\fi%
		%
		% Calculate i, the incircle radius 
		%
		\pgf@x1.41421\pgf@x%
		%
		% Calculate r, the polygon radius
		%
		% r = i / cos(360 / s / 2)
		%
		% (s = polygon sides)
		%
		\pgfmathdivide{180}{\pgfkeysvalueof{/pgf/regular polygon sides}}%
		\pgfmathsec@{\pgfmathresult}%
		\pgf@x\pgfmathresult\pgf@x%
		%
		% Accommodate the minimum width/height.
		%
		\pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/minimum width}}%
		\pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/minimum height}}%
		\ifdim\pgf@ya>\pgf@xa%
			\pgf@xa\pgf@ya%
		\fi%
		\ifdim\pgf@x<.5\pgf@xa%
			\pgf@x.5\pgf@xa%
		\fi%
		\edef\radius{\the\pgf@x}%
		%
		% Now calculate the anchor radius from the outer sep.
		%
		\pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/outer xsep}}%
		\pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/outer ysep}}%
		\ifdim\pgf@ya>\pgf@xa%
			\pgf@xa\pgf@ya%
		\fi
		%
		% Take into account the miter length.
		%
		% m = o / sin (90 - (360 / s / 2))
		%
		% (o = outer sep, s = sides)
		%
		\pgfmathdivide{180}{\pgfkeysvalueof{/pgf/regular polygon sides}}%
		\pgfmathsubtract@{90}{\pgfmathresult}%
		\pgfmathcosec@{\pgfmathresult}%
		\advance\pgf@x\pgfmathresult\pgf@xa%
		\edef\anchorradius{\the\pgf@x}%
		%
		% Save both radii.
		%
		\addtosavedmacro{\radius}%
		\addtosavedmacro{\anchorradius}%
	}
	\savedmacro\startangle{%
		\pgfmathdivide{360}{\pgfkeysvalueof{/pgf/regular polygon sides}}%
		\let\anglestep\pgfmathresult%
		\pgfmathtruncatemacro\sides{\pgfkeysvalueof{/pgf/regular polygon sides}}%
		\expandafter\ifodd\sides\relax%
			\edef\pgfmathresult{90}%
		\else%
			\pgfmathdivide@{\anglestep}{2}%
			\pgfmathsubtract@{90}{\pgfmathresult}%
		\fi%
		\pgfmathadd{\pgfmathresult}{\pgfkeysvalueof{/pgf/shape border rotate}}%
		\let\startangle\pgfmathresult%
	}
	%
	% Saved anchors.
	%
	\savedanchor{\centerpoint}{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}%
	\savedanchor{\midpoint}{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+.5ex}%
	}%	
	%
	% Other anchors.
	%
	\anchor{center}{\centerpoint}%
	\anchor{mid}{\midpoint}%
 	\anchor{base}{\centerpoint\pgf@y=0pt}%
 	\anchor{north}{%
 		\calculateradii%
 		\csname pgf@anchor@regular polygon@border\endcsname{\pgfqpoint{0pt}{\anchorradius}}}%
 	\anchor{south}{%
 		\calculateradii%
 		\csname pgf@anchor@regular polygon@border\endcsname{\pgfqpoint{0pt}{-\anchorradius}}}%
 	\anchor{east}{%
 		\calculateradii%
 		\csname pgf@anchor@regular polygon@border\endcsname{\pgfqpoint{\anchorradius}{0pt}}}%
 	\anchor{west}{%
 		\calculateradii%
 		\csname pgf@anchor@regular polygon@border\endcsname{\pgfqpoint{-\anchorradius}{0pt}}}%
 	\anchor{north east}{%
 		\calculateradii%
 		\csname pgf@anchor@regular polygon@border\endcsname{\pgfqpoint{\anchorradius}{\anchorradius}}}%
 	\anchor{north west}{%
 		\calculateradii%
 		\csname pgf@anchor@regular polygon@border\endcsname{\pgfqpoint{-\anchorradius}{\anchorradius}}}%
 	\anchor{south east}{%
 		\calculateradii%
 		\csname pgf@anchor@regular polygon@border\endcsname{\pgfqpoint{\anchorradius}{-\anchorradius}}}%
 	\anchor{south west}{%
 		\calculateradii%
 		\csname pgf@anchor@regular polygon@border\endcsname{\pgfqpoint{-\anchorradius}{-\anchorradius}}}%	
 	%
 	% Background path.
 	%
	\backgroundpath{%
		\calculateradii%
		\pgfpathmoveto{%
			\pgfpointadd{\centerpoint}{\pgfqpointpolar{\startangle}{\radius}}%
		}%
		\let\angle\startangle%
		\pgfmathloop%
			\ifnum\pgfmathcounter=\sides\relax% 
				\pgfpathclose%
			\else%
				\pgfmathadd@{\angle}{\anglestep}%
				\let\angle\pgfmathresult%
				\pgfpathlineto{%
					\pgfpointadd{\centerpoint}{\pgfqpointpolar{\angle}{\radius}}%
				}%
		\repeatpgfmathloop%	
	}%
	\anchorborder{%
		%
		% Save x and y.
		%
		\edef\externalx{\the\pgf@x}%
		\edef\externaly{\the\pgf@y}%
		%
		% Adjust the location of the external 
		% point relative to \centerpoint.
		%
		\centerpoint%
		\pgf@xa\externalx\relax%
		\pgf@ya\externaly\relax%
		\advance\pgf@xa\pgf@x%
		\advance\pgf@ya\pgf@y%
		\edef\externalx{\the\pgf@xa}%
		\edef\externaly{\the\pgf@ya}%
		%
		% Get the angle of the external point to the \centerpoint.
		%
		\pgfmathanglebetweenpoints{\centerpoint}{\pgfqpoint{\externalx}{\externaly}}%
		%
		% Locate the appropriate sides on the polygon border...
		%
		\pgfmathsubtract@{\pgfmathresult}{\startangle}%
		\ifdim\pgfmathresult pt<0pt\relax%
			\pgfmathadd@{\pgfmathresult}{360}%
		\fi%
		\pgfmathdivide@{\pgfmathresult}{\anglestep}%
		\pgfmathfloor@{\pgfmathresult}%
		\pgfmathmultiply@{\pgfmathresult}{\anglestep}%
		\pgfmathadd@{\pgfmathresult}{\startangle}%
		\let\firstangle\pgfmathresult%
		\pgfmathadd@{\pgfmathresult}{\anglestep}%
		\let\secondangle\pgfmathresult%
		\calculateradii%
		%
		% ...and thus, the point on the polygon border.
		%
		\pgfpointintersectionoflines{\centerpoint}{\pgfpoint{+\externalx}{+\externaly}}%
			{%
				\pgfpointadd{\centerpoint}%
					{\pgfqpointpolar{+\firstangle}{+\anchorradius}}%
				}%	
				{%
					\pgfpointadd{\centerpoint}%
						{\pgfqpointpolar{+\secondangle}{+\anchorradius}}%
				}%	
	}
	%
	% More hackery for when the recuglar polygon is positioned using 
	% a `corner <n+1>' or `side <n+1>' anchor, where n is the maximum 
	% number of sides of any previously drawn regular polygon.
	%
	\expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@regular polygon\endcsname{%
		\c@pgf@counta\sides\relax%
		\pgfmathloop%
			\ifnum\c@pgf@counta>0\relax%
				\pgfutil@ifundefined{pgf@anchor@regular polygon@corner\space\the\c@pgf@counta}{%
				%
				% ...(manually \xdef as \gdef is normally used by \anchor)...
				%
				\expandafter\xdef\csname pgf@anchor@regular polygon@corner\space\the\c@pgf@counta\endcsname{%
					\noexpand\calculateradii%
					\noexpand\pgfmathsubtract@{\the\c@pgf@counta}{1}%
					\noexpand\pgfmathmultiply@{\noexpand\pgfmathresult}{\noexpand\anglestep}%
					\noexpand\pgfmathadd@{\noexpand\pgfmathresult}{\noexpand\startangle}%
					\noexpand\let\noexpand\angle\noexpand\pgfmathresult%
					\noexpand\pgfpointadd{\noexpand\centerpoint}%
						{\noexpand\pgfqpointpolar{\noexpand\angle}{\noexpand\anchorradius}}%
				}%
				\expandafter\xdef\csname pgf@anchor@regular polygon@side\space\the\c@pgf@counta\endcsname{%
					\noexpand\calculateradii%
					\noexpand\pgfmathsubtract@{\the\c@pgf@counta}{1}%
					\noexpand\pgfmathmultiply@{\noexpand\pgfmathresult}{\noexpand\anglestep}%
					\noexpand\pgfmathadd@{\noexpand\pgfmathresult}{\noexpand\startangle}%
					\noexpand\let\noexpand\firstangle\noexpand\pgfmathresult%
					\noexpand\pgfmathadd@{\noexpand\pgfmathresult}{\noexpand\anglestep}%
					\noexpand\let\noexpand\secondangle\noexpand\pgfmathresult%
					\noexpand\pgfpointlineattime{0.5}%
						{\noexpand\pgfpointadd{\noexpand\centerpoint}%
							{\noexpand\pgfqpointpolar{\noexpand\firstangle}{\noexpand\anchorradius}}}%
						{\noexpand\pgfpointadd{\noexpand\centerpoint}%
							{\noexpand\pgfqpointpolar{\noexpand\secondangle}{\noexpand\anchorradius}}}%
				}%
			}{\c@pgf@counta0\relax}% 
			\advance\c@pgf@counta-1\relax%
		\repeatpgfmathloop%	
	}%
}



% Keys for shape trapezium
%
% /pgf/trapezium left angle  : angle of the left side.
% /pgf/trapezium right angle : angle of the right side.

\pgfkeys{/pgf/.cd,
	trapezium left angle/.initial=60,
	trapezium right angle/.initial=60,
	trapezium angle/.style={
		/pgf/trapezium left angle=#1,
		/pgf/trapezium right angle=#1
	},%
	trapezium stretches/.is if=pgf@lib@sh@trapeziumstretches,%
	trapezium stretches body/.is if=pgf@lib@sh@trapeziumstretchesbody%
}

\newif\ifpgf@lib@sh@trapeziumstretchesbody
\newif\ifpgf@lib@sh@trapeziumstretches


% Shape trapezium.
%
\pgfdeclareshape{trapezium}{
	\savedmacro\installtrapeziumparameters{%
		%
		% Get the node dimensions.
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
		\advance\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
		\advance\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y.5\dp\pgfnodeparttextbox%
		\ifpgfshapeborderusesincircle%
			%
			% Get the rotation (no rounding).
			%
			\pgfmathsetmacro\rotate{\pgfkeysvalueof{/pgf/shape border rotate}}%
			%
			% Use the radius of the incircle if required...
			%
			\ifdim\pgf@x<\pgf@y%
				\pgf@x\pgf@y%
			\fi%			
			\pgf@x1.41421\pgf@x%
			\pgf@y\pgf@x%
		\else%
			%
			% Get the rotation (with rounding).
			%
			\pgfmathmod{\pgfkeysvalueof{/pgf/shape border rotate}}{360}%
			\afterassignment\pgfmath@gobbletilpgfmath@%
			\expandafter\c@pgf@counta\pgfmathresult\relax\pgfmath@%
			\advance\c@pgf@counta45\relax%
			\divide\c@pgf@counta90\relax%
			\multiply\c@pgf@counta90\relax%
			\ifnum\c@pgf@counta<0\relax%
				\advance\c@pgf@counta360\relax%
			\fi%
			\edef\rotate{\the\c@pgf@counta}%
			%
			% Calculate the width and height of the node
			% contents, according to any border rotation.
			%
			\ifnum\c@pgf@counta=90\relax%
				\pgf@xc\pgf@x%
				\pgf@x\pgf@y%
				\pgf@y\pgf@xc%
			\else%
				\ifnum\c@pgf@counta=270\relax%
					\pgf@xc\pgf@x%
					\pgf@x\pgf@y%
					\pgf@y\pgf@xc%
				\fi%
			\fi%
		\fi%
		\pgfmathmod{\pgfkeysvalueof{/pgf/trapezium left angle}}{360}%
		\ifdim\pgfmathresult pt<0pt\relax%
			\pgfmathadd@{\pgfmathresult}{360}%
		\fi%
		\let\leftangle\pgfmathresult%
		\ifdim\leftangle pt=0pt\relax%
			\def\pgfmathresult{0}%
		\else%
			\pgfmathcot@{\leftangle}%
		\fi%
		\pgf@xa2\pgf@y%
		\pgf@xa\pgfmathresult\pgf@xa%
		\pgfmathmod{\pgfkeysvalueof{/pgf/trapezium right angle}}{360}%
		\ifdim\pgfmathresult pt<0pt\relax%
			\pgfmathadd@{\pgfmathresult}{360}%
		\fi%
		\let\rightangle\pgfmathresult%
		\ifdim\rightangle pt=0pt\relax%
			\def\pgfmathresult{0}%
		\else%
			\pgfmathcot@{\rightangle}%
		\fi%
		\pgf@xb2\pgf@y%
		\pgf@xb\pgfmathresult\pgf@xb%
		%
		% Take into account minimum height and width.
		%
		\pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/minimum height}}%
		\ifdim\pgf@y<.5\pgf@ya%
			\ifpgf@lib@sh@trapeziumstretches%
				\pgf@y.5\pgf@ya%
			\else%
				\ifpgf@lib@sh@trapeziumstretchesbody%
					\pgf@y.5\pgf@ya%
				\else%
					\pgfmathreciprocal@{\pgfmath@tonumber{\pgf@y}}%
					\pgf@yb.5\pgf@ya%
					\pgf@yb\pgfmathresult\pgf@yb%
					\pgf@y.5\pgf@ya%
					\pgf@x\pgfmath@tonumber{\pgf@yb}\pgf@x%
					\pgf@xa\pgfmath@tonumber{\pgf@yb}\pgf@xa%
					\pgf@xb\pgfmath@tonumber{\pgf@yb}\pgf@xb%
				\fi%
			\fi%
		\fi%
		\pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/minimum width}}%
		\pgf@xc2\pgf@x%
		\ifdim\pgf@xa<0pt\relax%
			\advance\pgf@xc-\pgf@xa%
		\else%
			\advance\pgf@xc\pgf@xa%
		\fi%
		\ifdim\pgf@xb<0pt\relax%
			\advance\pgf@xc-\pgf@xb%
		\else%
			\advance\pgf@xc\pgf@xb%
		\fi%
		\ifdim\pgf@xc<\pgf@ya%
			\ifpgf@lib@sh@trapeziumstretchesbody%
				\pgf@xc-\pgf@xc%
				\advance\pgf@xc\pgf@ya%
				\advance\pgf@x.5\pgf@xc%
			\else%
				\pgfmathreciprocal@{\pgfmath@tonumber{\pgf@xc}}%
				\pgf@ya\pgfmathresult\pgf@ya%
				\pgf@x\pgfmath@tonumber{\pgf@ya}\pgf@x%
				\pgf@xa\pgfmath@tonumber{\pgf@ya}\pgf@xa%
				\pgf@xb\pgfmath@tonumber{\pgf@ya}\pgf@xb%
				\ifpgf@lib@sh@trapeziumstretches%	
				\else%					
					\pgf@y\pgfmath@tonumber{\pgf@ya}\pgf@y%
				\fi%				
			\fi%
		\fi%
		\edef\halfheight{\the\pgf@y}%
		\edef\halfwidth{\the\pgf@x}%
		\edef\leftextension{\the\pgf@xa}%
		\edef\rightextension{\the\pgf@xb}%
		\pgf@xc2\pgf@x%
		%
		% Take the larger of the outer sep.
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/outer ysep}}%
		\ifdim\pgf@y>\pgf@x%
			\pgf@x\pgf@y%
		\fi%
		\edef\outersep{\the\pgf@x}%
		%
		% The \externalradius is a length that is
		% guarenteed to produce a point outside the trapezium.
		%
		\advance\pgf@xc2.0\pgf@x%
		\pgf@yc\halfheight\relax%
		\multiply\pgf@yc2\relax%
		\advance\pgf@yc2.0\pgf@x%
		\ifdim\pgf@xc<\pgf@yc%
			\edef\externalradius{\the\pgf@yc}%
		\else%
			\edef\externalradius{\the\pgf@xc}%
		\fi%
		%
		% Calculate the centre base and mid poins of the node.
		%
		\pgfextract@process\centerpoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgf@y.5\ht\pgfnodeparttextbox%
			\advance\pgf@y-.5\dp\pgfnodeparttextbox%
		}%
		\pgfextract@process\basepoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgf@y0pt\relax%
		}%
		\pgfextract@process\midpoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgfmathsetlength\pgf@y{+.5ex}%
		}%
		%
		% Calculate each point on the trapezium (without rotation).
		%
		\pgfextract@process\lowerleftpoint{%
			\centerpoint%
			\advance\pgf@x-\halfwidth\relax%
			\ifdim\leftextension>0pt\relax%
				\advance\pgf@x-\leftextension\relax%
			\fi%
			\advance\pgf@y-\halfheight\relax%
		}%
		\pgfextract@process\upperleftpoint{%
			\centerpoint%
			\advance\pgf@x-\halfwidth\relax%
			\ifdim\leftextension<0pt\relax%
				\advance\pgf@x\leftextension\relax%
			\fi%
			\advance\pgf@y\halfheight\relax%
		}%
		\pgfextract@process\upperrightpoint{%
			\centerpoint%
			\advance\pgf@x\halfwidth\relax%
			\ifdim\rightextension<0pt\relax%
				\advance\pgf@x-\rightextension\relax%
			\fi%
			\advance\pgf@y\halfheight\relax%
		}%
		\pgfextract@process\lowerrightpoint{%
			\centerpoint%
			\advance\pgf@x\halfwidth\relax%
			\ifdim\rightextension>0pt\relax%
				\advance\pgf@x\rightextension\relax%
			\fi%
			\advance\pgf@y-\halfheight\relax%
		}%
		%
		% Now calculate the adjustment for the miter length at each corner 
		% of the trapezium. This ensures more accurate anchor positioning
		% when the line width is particularly thick.
		%
		\pgfextract@process\lowerleftmiter{%
			\pgfmathanglebetweenlines{\lowerleftpoint}{\lowerrightpoint}{\lowerleftpoint}{\upperleftpoint}%
			\pgfmathmultiply@{\pgfmathresult}{.5}%
			\pgfmathtan@{\pgfmathresult}%	
			\pgfmathreciprocal@{\pgfmathresult}%
			\pgf@x-\outersep\relax%
			\pgf@x\pgfmathresult\pgf@x%
			\pgf@y-\outersep\relax%
		}%
		\pgfextract@process\upperleftmiter{%
			\pgfmathanglebetweenlines{\upperleftpoint}{\lowerleftpoint}{\upperleftpoint}{\upperrightpoint}%
			\pgfmathmultiply@{\pgfmathresult}{.5}%
			\pgfmathtan@{\pgfmathresult}%
			\pgfmathreciprocal@{\pgfmathresult}%
			\pgf@x-\outersep\relax%
			\pgf@x\pgfmathresult\pgf@x%
			\pgf@y\outersep\relax%
		}%
		\pgfextract@process\upperrightmiter{%
			\pgfmathanglebetweenlines{\upperrightpoint}{\upperleftpoint}{\upperrightpoint}{\lowerrightpoint}%
			\pgfmathmultiply@{\pgfmathresult}{.5}%
			\pgfmathtan@{\pgfmathresult}%
			\pgfmathreciprocal@{\pgfmathresult}%
			\pgf@x\outersep\relax%
			\pgf@x\pgfmathresult\pgf@x%
			\pgf@y\outersep\relax%
		}%
		\pgfextract@process\lowerrightmiter{%
			\pgfmathanglebetweenlines{\lowerrightpoint}{\upperrightpoint}{\lowerrightpoint}{\lowerleftpoint}%
			\pgfmathmultiply@{\pgfmathresult}{.5}%
			\pgfmathtan@{\pgfmathresult}%
			\pgfmathreciprocal@{\pgfmathresult}%
			\pgf@x\outersep\relax%
			\pgf@x\pgfmathresult\pgf@x%
			\pgf@y-\outersep\relax%
		}%
		%
		% Now calculate the corners for determining anchor border
		% points, by adding the adjustment for the miter length.
		%
		\pgfextract@process\lowerleftborderpoint{%
			\pgfpointadd{\lowerleftpoint}{\lowerleftmiter}%
		}%
		\pgfextract@process\upperleftborderpoint{%
			\pgfpointadd{\upperleftpoint}{\upperleftmiter}%
		}%
		\pgfextract@process\upperrightborderpoint{%
			\pgfpointadd{\upperrightpoint}{\upperrightmiter}%
		}%
		\pgfextract@process\lowerrightborderpoint{%
			\pgfpointadd{\lowerrightpoint}{\lowerrightmiter}%
		}%
		%
		% Calulate the angle from the centerpoint to each corner.
		% Rotation is not important here (see \anchorborder code).
		%
		\pgfmathanglebetweenpoints{\centerpoint}{\lowerleftborderpoint}%
		\let\angletolowerleft\pgfmathresult%
		\pgfmathanglebetweenpoints{\centerpoint}{\upperleftborderpoint}%
		\let\angletoupperleft\pgfmathresult%
		\pgfmathanglebetweenpoints{\centerpoint}{\upperrightborderpoint}%
		\let\angletoupperright\pgfmathresult%
		\pgfmathanglebetweenpoints{\centerpoint}{\lowerrightborderpoint}%
		\let\angletolowerright\pgfmathresult%
		%
		% Do the same for the *inversely rotated* base point...
		%
		\pgfextract@process\rotatedbasepoint{%
			\pgfmathrotatepointaround{\basepoint}{\centerpoint}{-\rotate}%
		}%
		\pgfmathanglebetweenpoints{\rotatedbasepoint}{\lowerleftborderpoint}%
		\let\baseangletolowerleft\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedbasepoint}{\upperleftborderpoint}%
		\let\baseangletoupperleft\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedbasepoint}{\upperrightborderpoint}%
		\let\baseangletoupperright\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedbasepoint}{\lowerrightborderpoint}%
		\let\baseangletolowerright\pgfmathresult%
		%
		% And the *inversely rotated* mid point...
		%
		\pgfextract@process\rotatedmidpoint{%
			\pgfmathrotatepointaround{\midpoint}{\centerpoint}{-\rotate}%
		}%
		\pgfmathanglebetweenpoints{\rotatedmidpoint}{\lowerleftborderpoint}%
		\let\midangletolowerleft\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedmidpoint}{\upperleftborderpoint}%
		\let\midangletoupperleft\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedmidpoint}{\upperrightborderpoint}%
		\let\midangletoupperright\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedmidpoint}{\lowerrightborderpoint}%
		\let\midangletolowerright\pgfmathresult%
		%
		% Now rotate the border points around the centerpoint...
		%
		\pgfextract@process\lowerleftborderpoint{%
			\pgfmathrotatepointaround%
				{\lowerleftborderpoint}%
				{\centerpoint}%
				{\rotate}%
		}%
		\pgfextract@process\upperleftborderpoint{%
			\pgfmathrotatepointaround%
				{\upperleftborderpoint}%
				{\centerpoint}%
				{\rotate}%
		}%
		\pgfextract@process\upperrightborderpoint{%
			\pgfmathrotatepointaround%
				{\upperrightborderpoint}%
				{\centerpoint}%
				{\rotate}%
		}%
		\pgfextract@process\lowerrightborderpoint{%
			\pgfmathrotatepointaround%
				{\lowerrightborderpoint}%
				{\centerpoint}%
				{\rotate}%
		}%
		%
		% ...and the points for drawing the border (i.e. no outer sep).
		%
		\pgfextract@process\lowerleftpoint{%
			\pgfmathrotatepointaround{\lowerleftpoint}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\upperleftpoint{%
			\pgfmathrotatepointaround{\upperleftpoint}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\upperrightpoint{%
			\pgfmathrotatepointaround{\upperrightpoint}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\lowerrightpoint{%
			\pgfmathrotatepointaround{\lowerrightpoint}{\centerpoint}{\rotate}%
		}%			
		%
		% And finally, save all the relevant stuff.
		%
		\addtosavedmacro{\lowerleftpoint}%
		\addtosavedmacro{\upperleftpoint}%
		\addtosavedmacro{\upperrightpoint}%
		\addtosavedmacro{\lowerrightpoint}%
    %
		\addtosavedmacro{\lowerleftborderpoint}%
		\addtosavedmacro{\upperleftborderpoint}%
		\addtosavedmacro{\upperrightborderpoint}%
		\addtosavedmacro{\lowerrightborderpoint}%
    %
		\addtosavedmacro{\angletolowerleft}%
		\addtosavedmacro{\angletoupperleft}%
		\addtosavedmacro{\angletoupperright}%
		\addtosavedmacro{\angletolowerright}%
		%
		\addtosavedmacro{\baseangletolowerleft}%
		\addtosavedmacro{\baseangletoupperleft}%
		\addtosavedmacro{\baseangletoupperright}%
		\addtosavedmacro{\baseangletolowerright}%
		%
		\addtosavedmacro{\midangletolowerleft}%
		\addtosavedmacro{\midangletoupperleft}%
		\addtosavedmacro{\midangletoupperright}%
		\addtosavedmacro{\midangletolowerright}%
    %
    \addtosavedmacro{\rotate}%
    \addtosavedmacro{\externalradius}%
	}
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}%
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt\relax%
	}%
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+.5ex}%
	}%
	\anchor{center}{\centerpoint}%
	\anchor{base}{\basepoint}%
	\anchor{base east}{%
		\installtrapeziumparameters%
		\let\pgf@trapeziumanchorborderreferencepoint\basepoint%
		\csname pgf@anchor@trapezium@border\endcsname{\pgfqpoint{\externalradius}{0pt}}%
	}
	\anchor{base west}{%
		\installtrapeziumparameters%
		\let\pgf@trapeziumanchorborderreferencepoint\basepoint%
		\csname pgf@anchor@trapezium@border\endcsname{\pgfqpoint{-\externalradius}{0pt}}%
	}%
	\anchor{mid}{\midpoint}%
	\anchor{mid east}{%
		\installtrapeziumparameters%
		\let\pgf@trapeziumanchorborderreferencepoint\midpoint%
		\csname pgf@anchor@trapezium@border\endcsname{\pgfqpoint{\externalradius}{0pt}}%
	}
	\anchor{mid west}{%
		\installtrapeziumparameters%
		\let\pgf@trapeziumanchorborderreferencepoint\midpoint%
		\csname pgf@anchor@trapezium@border\endcsname{\pgfqpoint{-\externalradius}{0pt}}%
	}%
	\anchor{north}{%
		\installtrapeziumparameters%
		\csname pgf@anchor@trapezium@border\endcsname{\pgfqpoint{0pt}{\externalradius}}%
	}
	\anchor{south}{%
		\installtrapeziumparameters%
		\csname pgf@anchor@trapezium@border\endcsname{\pgfqpoint{0pt}{-\externalradius}}%
	}
	\anchor{east}{%
		\installtrapeziumparameters%
		\csname pgf@anchor@trapezium@border\endcsname{\pgfqpoint{\externalradius}{0pt}}%
	}
	\anchor{west}{%
		\installtrapeziumparameters%
		\csname pgf@anchor@trapezium@border\endcsname{\pgfqpoint{-\externalradius}{0pt}}%
	}
	\anchor{north east}{%
		\installtrapeziumparameters%
		\csname pgf@anchor@trapezium@border\endcsname{\pgfqpoint{\externalradius}{\externalradius}}%
	}
	\anchor{south west}{%
		\installtrapeziumparameters%
		\csname pgf@anchor@trapezium@border\endcsname{\pgfqpoint{-\externalradius}{-\externalradius}}%
	}
	\anchor{south east}{%
		\installtrapeziumparameters%
		\csname pgf@anchor@trapezium@border\endcsname{\pgfqpoint{\externalradius}{-\externalradius}}%
	}
	\anchor{north west}{%
		\installtrapeziumparameters%
		\csname pgf@anchor@trapezium@border\endcsname{\pgfqpoint{-\externalradius}{\externalradius}}%
	}
	\anchor{bottom left corner}{%
		\installtrapeziumparameters%
		\lowerleftborderpoint%
	}%
	\anchor{top left corner}{%
		\installtrapeziumparameters%
		\upperleftborderpoint%
	}%
	\anchor{top right corner}{%
		\installtrapeziumparameters%
		\upperrightborderpoint%
	}%
	\anchor{bottom right corner}{%
		\installtrapeziumparameters%
		\lowerrightborderpoint%
	}%	
	\anchor{left side}{%
		\installtrapeziumparameters%
		\pgfpointlineattime{0.5}{\lowerleftborderpoint}{\upperleftborderpoint}%
	}%	
	\anchor{right side}{%
		\installtrapeziumparameters%
		\pgfpointlineattime{0.5}{\lowerrightborderpoint}{\upperrightborderpoint}%
	}%	
	\anchor{top side}{%
		\installtrapeziumparameters%
		\pgfpointlineattime{0.5}{\upperleftborderpoint}{\upperrightborderpoint}%
	}%	
	\anchor{bottom side}{%
		\installtrapeziumparameters%
		\pgfpointlineattime{0.5}{\lowerleftborderpoint}{\lowerrightborderpoint}%
	}%		
	\backgroundpath{%
		\installtrapeziumparameters%
		\pgfpathmoveto{\lowerleftpoint}%
		\pgfpathlineto{\upperleftpoint}%
		\pgfpathlineto{\upperrightpoint}%
		\pgfpathlineto{\lowerrightpoint}%
		\pgfpathclose%			
	}
	\anchorborder{%
		%
		% Save x and y.
		%
		\edef\externalx{\the\pgf@x}%
		\edef\externaly{\the\pgf@y}%
		%
		% This allows anchors base east, base west, mid east and mid west,
		% to redefine the `center' of the node to correctly calculate the
		% border points.
		%
		\pgfutil@ifundefined{pgf@trapeziumanchorborderreferencepoint}%
			{\let\referencepoint\centerpoint}%
			{\let\referencepoint\pgf@trapeziumanchorborderreferencepoint}%
		%
		% Adjust the location of the external 
		% point relative to the reference point.
		%
		\referencepoint%
		\pgf@xa\externalx\relax%
		\pgf@ya\externaly\relax%
		\advance\pgf@xa\pgf@x%
		\advance\pgf@ya\pgf@y%
		\edef\externalx{\the\pgf@xa}%
		\edef\externaly{\the\pgf@ya}%
		%
		% Install the required points and angles.
		%
		\installtrapeziumparameters%
		%
		% Get the angle of the external point to the \referencepoint.
		%
		\pgfmathanglebetweenpoints{\referencepoint}{\pgfqpoint{\externalx}{\externaly}}%
		%
		% *Subtract* the rotation from the external angle. This is 
		% why the border point angles do not neeed to be rotated.
		%
		\pgfmathsubtract@{\pgfmathresult}{\rotate}%
		\ifdim\pgfmathresult pt<0pt\relax%
			\pgfmathadd@{\pgfmathresult}{360}%
		\fi%
		%
		% Get the relevant angles for the reference point.
		%
		\let\externalangle\pgfmathresult%
		\ifx\referencepoint\basepoint%
			\let\angletoupperright\baseangletoupperright%
			\let\angletoupperleft\baseangletoupperleft%
			\let\angletolowerright\baseangletolowerright%
			\let\angletolowerleft\baseangletolowerleft%
		\else%
			\ifx\referencepoint\midpoint%
				\let\angletoupperright\midangletoupperright%
				\let\angletoupperleft\midangletoupperleft%
				\let\angletolowerright\midangletolowerright%
				\let\angletolowerleft\midangletolowerleft%
		\fi\fi%
		%
		% Find the line on the border...
		%			
		\ifdim\externalangle pt<\angletoupperright pt\relax%
			\let\firstpoint\upperrightborderpoint%
			\let\secondpoint\lowerrightborderpoint%
		\else%
			\ifdim\externalangle pt<\angletoupperleft pt\relax%
				\let\firstpoint\upperleftborderpoint%
				\let\secondpoint\upperrightborderpoint%
			\else%
				\ifdim\externalangle pt<\angletolowerleft pt\relax%
					\let\firstpoint\upperleftborderpoint%
					\let\secondpoint\lowerleftborderpoint%
				\else%
					\ifdim\externalangle pt<\angletolowerright pt\relax%
						\let\firstpoint\lowerleftborderpoint%
						\let\secondpoint\lowerrightborderpoint%
					\else%
						\let\firstpoint\upperrightborderpoint%
						\let\secondpoint\lowerrightborderpoint%
					\fi%
				\fi%
			\fi%
		\fi%
		%
		% ...and thus the point on the border.
		%
		\pgfpointintersectionoflines{\referencepoint}{\pgfqpoint{\externalx}{\externaly}}%
				{\firstpoint}{\secondpoint}%
	}%
}




% Shape semicircle.
%
\pgfdeclareshape{semicircle}{
	\savedmacro\installsemicircleparameters{%
		%
		% Get the larger of the outer sep.
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/outer ysep}}%
		\ifdim\pgf@x<\pgf@y%
			\pgf@x\pgf@y%
		\fi%
		\edef\outersep{\the\pgf@x}%
		%
		% Get the node dimensions.
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
		\advance\pgf@x+.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
		\advance\pgf@y+.5\ht\pgfnodeparttextbox%
		\advance\pgf@y+.5\dp\pgfnodeparttextbox%
		%
		% Use the radius of the incircle if required...
		%
		\ifpgfshapeborderusesincircle%
			%
			% Get the rotation (no rounding).
			%
			\pgfmathsetmacro\rotate{\pgfkeysvalueof{/pgf/shape border rotate}}%
			\ifdim\pgf@x<\pgf@y%
				\pgf@x\pgf@y%
			\fi%			
			\pgf@x1.41421\pgf@x%
			\edef\halfheight{\the\pgf@x}%
			\advance\pgf@x\pgf@x%
		\else%
			%
			% Get the rotation (with rounding).
			%
			\pgfmathmod{\pgfkeysvalueof{/pgf/shape border rotate}}{360}%
			\afterassignment\pgfmath@gobbletilpgfmath@%
			\expandafter\c@pgf@counta\pgfmathresult\relax\pgfmath@%
			\advance\c@pgf@counta45\relax%
			\divide\c@pgf@counta90\relax%
			\multiply\c@pgf@counta90\relax%
			\ifnum\c@pgf@counta<0\relax%
				\advance\c@pgf@counta360\relax%
			\fi%
			\edef\rotate{\the\c@pgf@counta}%
			%
			% Calculate the width and height of the node
			% contents, according to any border rotation.
			%
			\ifnum\c@pgf@counta=90\relax%
				\pgf@xc\pgf@x%
				\pgf@x\pgf@y%
				\pgf@y\pgf@xc%
			\else%
				\ifnum\c@pgf@counta=270\relax%
					\pgf@xc\pgf@x%
					\pgf@x\pgf@y%
					\pgf@y\pgf@xc%
				\fi%
			\fi%
			\advance\pgf@y\pgf@y%
			\pgfmathveclen@{\pgfmath@tonumber{\pgf@x}}{\pgfmath@tonumber{\pgf@y}}%
			\pgf@x\pgfmathresult pt\relax%
			\pgf@y.5\pgf@y%
			\edef\halfheight{\the\pgf@y}%
		\fi%
		\edef\defaultradius{\the\pgf@x}%
		%
		% Take into account minimum height and width.
		%
		\pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/minimum width}}%
		\ifdim\pgf@x<.5\pgf@xa%
			\pgf@x.5\pgf@xa%
		\fi%
		\pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/minimum height}}%
		\ifdim\pgf@x<\pgf@ya%
			\pgf@x\pgf@ya%
		\fi%
		\edef\semicircleradius{\the\pgf@x}%
		%
		% Find the center/base/mid of the semi circle node.
		%		
		\pgfextract@process\centerpoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgf@y.5\ht\pgfnodeparttextbox%
			\advance\pgf@y+-.5\dp\pgfnodeparttextbox%
		}%
		\pgfextract@process\basepoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgf@y0pt\relax%
		}%
		\pgfextract@process\midpoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgfmathsetlength\pgf@y{+.5ex}%
		}%
		\pgfextract@process\semicirclecenterpoint{%
			\centerpoint%
			\pgf@ya\semicircleradius\relax%
			\advance\pgf@ya-\defaultradius\relax%
			%
			% The point is adjusted to make the node contents
			% appear more centered if the node is enlarged to
			% some minimum size. The factor .4 just seems OK.
			%
			\pgf@ya.4\pgf@ya% 
			\advance\pgf@y-\pgf@ya%
			\pgf@ya\halfheight\relax%
			\advance\pgf@y-\pgf@ya%	
		}%
		%
		% Add the outer sep to the radius here.
		%
		\pgf@x\semicircleradius\relax%
		\advance\pgf@x\outersep\relax%
		\edef\semicircleradius{\the\pgf@x}%
		\pgfpointdiff{\centerpoint}{\semicirclecenterpoint}%
		\ifdim\pgf@y<0pt\pgf@y-\pgf@y\fi%
		\edef\centerpointdiff{\the\pgf@y}%
		%
		% Calculate the start and end points on the border.
		%		
		\pgfextract@process\arcstartborder{%
			\semicirclecenterpoint%
			\advance\pgf@x\semicircleradius\relax%
		}%
		\pgfextract@process\arcendborder{%
			\semicirclecenterpoint%
			\advance\pgf@x-\semicircleradius\relax%
		}%
		%
		% Calculate the start and end *corner* points on the border.
		% This is needed to accommodate the outer sep.
		%
		\pgfextract@process\arcstartcorner{%
			\arcstartborder%
			\advance\pgf@y-\outersep\relax%
		}%
		\pgfextract@process\arcendcorner{%
			\arcendborder%
			\advance\pgf@y-\outersep\relax%
		}
		%
		% Now calculate all the relevant angles.
		%
		% For the center point.
		%
		\pgfmathanglebetweenpoints{\centerpoint}{\arcstartborder}%
		\let\angletoarcstartborder\pgfmathresult%
		\pgfmathanglebetweenpoints{\centerpoint}{\arcendborder}%
		\let\angletoarcendborder\pgfmathresult%
		\pgfmathanglebetweenpoints{\centerpoint}{\arcstartcorner}%
		\let\angletoarcstartcorner\pgfmathresult%
		\pgfmathanglebetweenpoints{\centerpoint}{\arcendcorner}%
		\let\angletoarcendcorner\pgfmathresult%
		%
		% For the basepoint (rotated about the center point).
		%
		\pgfextract@process\rotatedbasepoint{%
			\pgfmathrotatepointaround{\basepoint}{\centerpoint}{-\rotate}%
		}%
		\pgfmathanglebetweenpoints{\rotatedbasepoint}{\arcstartborder}%
		\let\baseangletoarcstartborder\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedbasepoint}{\arcendborder}%
		\let\baseangletoarcendborder\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedbasepoint}{\arcstartcorner}%
		\let\baseangletoarcstartcorner\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedbasepoint}{\arcendcorner}%
		\let\baseangletoarcendcorner\pgfmathresult%
		%
		% For the midpoint (rotated about the center point).
		%
		\pgfextract@process\rotatedmidpoint{%
			\pgfmathrotatepointaround{\midpoint}{\centerpoint}{-\rotate}%
		}%
		\pgfmathanglebetweenpoints{\rotatedmidpoint}{\arcstartborder}%
		\let\midangletoarcstartborder\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedmidpoint}{\arcendborder}%
		\let\midangletoarcendborder\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedmidpoint}{\arcstartcorner}%
		\let\midangletoarcstartcorner\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedmidpoint}{\arcendcorner}%
		\let\midangletoarcendcorner\pgfmathresult%
		%
		% Now, rotate the semicircle points around the centerpoint.
		%
		\pgfextract@process\semicirclecenterpoint{%
			\pgfmathrotatepointaround{\semicirclecenterpoint}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\arcstartborder{%
			\pgfmathrotatepointaround{\arcstartborder}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\arcendborder{%
			\pgfmathrotatepointaround{\arcendborder}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\arcstartcorner{%
			\pgfmathrotatepointaround{\arcstartcorner}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\arcendcorner{%
			\pgfmathrotatepointaround{\arcendcorner}{\centerpoint}{\rotate}%
		}%
		%
		% Calculate the distance between the base point and the (rotated) semicircle center.
		%
		\pgfpointdiff{\basepoint}{\semicirclecenterpoint}%
		\pgfmathveclen@{\pgfmath@tonumber{\pgf@x}}{\pgfmath@tonumber{\pgf@y}}%
		\edef\basesemicirclecenterdiff{\pgfmathresult pt}%
		%
		% Calculate the distance between the base point and the (rotated) semicircle center.
		%
		\pgfpointdiff{\midpoint}{\semicirclecenterpoint}%
		\pgfmathveclen@{\pgfmath@tonumber{\pgf@x}}{\pgfmath@tonumber{\pgf@y}}%
		\edef\midsemicirclecenterdiff{\pgfmathresult pt}%
		%
		% And save all the stuff.
		%
		\addtosavedmacro{\rotate}%
		\addtosavedmacro{\outersep}%
		\addtosavedmacro{\semicircleradius}%
		%
		\addtosavedmacro{\arcstartborder}%
		\addtosavedmacro{\arcendborder}%
		\addtosavedmacro{\arcstartcorner}%
		\addtosavedmacro{\arcendcorner}%
		\addtosavedmacro{\semicirclecenterpoint}%
		%
		\addtosavedmacro{\angletoarcstartborder}%
		\addtosavedmacro{\angletoarcendborder}%
		\addtosavedmacro{\angletoarcstartcorner}%
		\addtosavedmacro{\angletoarcendcorner}%
		%
		\addtosavedmacro{\centerpointdiff}%
		\addtosavedmacro{\basesemicirclecenterdiff}%
		\addtosavedmacro{\midsemicirclecenterdiff}%
		%
		\addtosavedmacro{\baseangletoarcstartborder}%
		\addtosavedmacro{\baseangletoarcendborder}%
		\addtosavedmacro{\baseangletoarcstartcorner}%
		\addtosavedmacro{\baseangletoarcendcorner}%
		%
		\addtosavedmacro{\midangletoarcstartborder}%
		\addtosavedmacro{\midangletoarcendborder}%
		\addtosavedmacro{\midangletoarcstartcorner}%
		\addtosavedmacro{\midangletoarcendcorner}%
	}
	\savedanchor{\centerpoint}{%
		\pgfmathsetlength\pgf@x{+.5\wd\pgfnodeparttextbox}%
		\pgfmathsetlength\pgf@y{+.5\ht\pgfnodeparttextbox}%
		\pgfmathaddtolength\pgf@y{-.5\dp\pgfnodeparttextbox}%	
	}
	\savedanchor{\basepoint}{%
		\pgfmathsetlength\pgf@x{+.5\wd\pgfnodeparttextbox}%
		\pgf@y0pt\relax%
	}
	\savedanchor{\midpoint}{%
		\pgfmathsetlength\pgf@x{+.5\wd\pgfnodeparttextbox}%
		\pgfmathsetlength\pgf@y{+.5ex}%
	}
	\anchor{center}{\centerpoint}
	\anchor{base}{\basepoint}
	\anchor{base west}{%
		\installsemicircleparameters%
		\let\pgf@semicirclereferencepoint\basepoint%
		\csname pgf@anchor@semicircle@border\endcsname{\pgfqpoint{-\semicircleradius}{0pt}}%
	}
	\anchor{base east}{%
		\installsemicircleparameters%
		\let\pgf@semicirclereferencepoint\basepoint%
		\csname pgf@anchor@semicircle@border\endcsname{\pgfqpoint{\semicircleradius}{0pt}}%
	}
	\anchor{mid}{\midpoint}
	\anchor{mid west}{%
		\installsemicircleparameters%
		\let\pgf@semicirclereferencepoint\midpoint%
		\csname pgf@anchor@semicircle@border\endcsname{\pgfqpoint{-\semicircleradius}{0pt}}%
	}
	\anchor{mid east}{%
		\installsemicircleparameters%
		\let\pgf@semicirclereferencepoint\midpoint%
		\csname pgf@anchor@semicircle@border\endcsname{\pgfqpoint{\semicircleradius}{0pt}}%
	}
	\anchor{apex}{%
		\installsemicircleparameters%
		\pgfmathadd@{\rotate}{90}%
		\let\angle\pgfmathresult%
		\pgfpointadd{\semicirclecenterpoint}{\pgfqpointpolar{\angle}{\semicircleradius}}%
	}
	\anchor{arc start}{%
		\installsemicircleparameters%
		\arcstartcorner%
	}
	\anchor{arc end}{%
		\installsemicircleparameters%
		\arcendcorner%
	}
	\anchor{chord center}{%
		\installsemicircleparameters%
		\pgfpointlineattime{0.5}{\arcstartcorner}{\arcendcorner}%
	}
	\anchor{north}{%
		\installsemicircleparameters%
		\csname pgf@anchor@semicircle@border\endcsname{\pgfqpointpolar{90}{\semicircleradius}}%
	}
	\anchor{south}{%
		\installsemicircleparameters%
		\csname pgf@anchor@semicircle@border\endcsname{\pgfqpointpolar{270}{\semicircleradius}}%
	}
	\anchor{east}{%
		\installsemicircleparameters%
		\csname pgf@anchor@semicircle@border\endcsname{\pgfqpointpolar{0}{\semicircleradius}}%
	}
	\anchor{west}{%
		\installsemicircleparameters%
		\csname pgf@anchor@semicircle@border\endcsname{\pgfqpointpolar{180}{\semicircleradius}}%
	}
	\anchor{north west}{%
		\installsemicircleparameters%
		\csname pgf@anchor@semicircle@border\endcsname{\pgfqpointpolar{135}{\semicircleradius}}%
	}
	\anchor{south west}{%
		\installsemicircleparameters%
		\csname pgf@anchor@semicircle@border\endcsname{\pgfqpointpolar{225}{\semicircleradius}}%
	}
	\anchor{north east}{%
		\installsemicircleparameters%
		\csname pgf@anchor@semicircle@border\endcsname{\pgfqpointpolar{45}{\semicircleradius}}%
	}
	\anchor{south east}{%
		\installsemicircleparameters%
		\csname pgf@anchor@semicircle@border\endcsname{\pgfqpointpolar{315}{\semicircleradius}}%
	}
	\backgroundpath{%
		\installsemicircleparameters%
		\pgf@x\semicircleradius\relax%
		\advance\pgf@x-\outersep\relax%
		\edef\semicircleradius{\the\pgf@x}%
		\pgfpathmoveto{\pgfpointadd{\semicirclecenterpoint}{\pgfqpointpolar{\rotate}{\semicircleradius}}}%
		{%
			\pgftransformrotate{\rotate}%
			\pgfpatharc{0}{180}{\semicircleradius}%
			\pgfpathclose%	
		}%
	}
	\anchorborder{%
		%
		% Save x and y.
		%
		\edef\externalx{\the\pgf@x}%
		\edef\externaly{\the\pgf@y}%
		%
		% Check if a reference point has been defined (i.e. \midpoint or \basepoint).
		%
		\pgfutil@ifundefined{pgf@semicirclereferencepoint}%
			{\let\referencepoint\centerpoint}%
			{\let\referencepoint\pgf@semicirclereferencepoint}%
		%
		% Adjust the location of the external  point relative to the reference point.
		%
		\referencepoint%
		\pgf@xa\externalx\relax%
		\pgf@ya\externaly\relax%
		\advance\pgf@xa\pgf@x%
		\advance\pgf@ya\pgf@y%
		\edef\externalx{\the\pgf@xa}%
		\edef\externaly{\the\pgf@ya}%
		%
		% Install the required points and angles.
		%
		\installsemicircleparameters%
		%
		% Get the angle of the external point to the \referencepoint.
		%
		\pgfmathanglebetweenpoints{\referencepoint}{\pgfqpoint{\externalx}{\externaly}}%
		\let\externalangle\pgfmathresult%
		%
		% *Subtract* the rotation from the external angle.
		%
		\pgfmathsubtract@{\pgfmathresult}{\rotate}%
		\ifdim\pgfmathresult pt<0pt\relax%
			\pgfmathadd@{\pgfmathresult}{360}%
		\fi%
		\let\angle\pgfmathresult%
		\ifx\referencepoint\basepoint%
			\let\angletoarcstartborder\baseangletoarcstartborder%
			\let\angletoarcendborder\baseangletoarcendborder%
			\let\angletoarcstartcorner\baseangletoarcstartcorner%
			\let\angletoarcendcorner\baseangletoarcendcorner%
			\let\centerpointdiff\basesemicirclecenterdiff%
		\else%
			\ifx\referencepoint\midpoint%
				\let\angletoarcstartborder\midangletoarcstartborder%
				\let\angletoarcendborder\midangletoarcendborder%
				\let\angletoarcstartcorner\midangletoarcstartcorner%
				\let\angletoarcendcorner\midangletoarcendcorner%
				\let\centerpointdiff\midsemicirclecenterdiff%
		\fi\fi%
		%
		% Determine if the line will cross the semicircle arc, or the chord.
		% 
		\ifdim\angle pt>\angletoarcstartborder pt\relax%
			\let\firstpoint\pgfutil@empty%
			\let\secondpoint\pgfutil@empty%
		\else%
			\ifdim\angle pt>\angletoarcstartcorner pt\relax%
				\let\firstpoint\arcstartcorner%
				\let\secondpoint\arcstartborder%
			\else%
				\ifdim\angle pt>\angletoarcendcorner pt\relax%
					\let\firstpoint\arcendcorner%
					\let\secondpoint\arcstartcorner%
				\else%
					\ifdim\angle pt>\angletoarcendborder pt\relax%
						\let\firstpoint\arcendborder%
						\let\secondpoint\arcendcorner%
					\else%
						\let\firstpoint\pgfutil@empty%
						\let\secondpoint\pgfutil@empty%
					\fi%
				\fi%
			\fi%
		\fi%
		\ifx\firstpoint\pgfutil@empty
			%
			% Calculate the angle from the centre of the semicircle to the
			% point on the semicircle arc which intersects the line from 
			% the external point to the reference point...
			%
			\pgfmathanglebetweenlines{\referencepoint}{\pgfqpoint{\externalx}{\externaly}}%
				{\semicirclecenterpoint}{\referencepoint}%
			\pgfmathsin@{\pgfmathresult}%
			\let\sineangle\pgfmathresult%
			\pgf@x\semicircleradius\relax%
			\pgfmathreciprocal@{\pgfmath@tonumber{\pgf@x}}%
			\let\reciprocalradius\pgfmathresult%
			\pgf@x\centerpointdiff\relax%
			\pgf@x\sineangle\pgf@x%
			\pgf@x\reciprocalradius\pgf@x%
			\pgfmathasin@{\pgfmath@tonumber{\pgf@x}}%
			\pgf@x\pgfmathresult pt\relax%
			\advance\pgf@x\externalangle pt\relax%
			\edef\angle{\pgfmath@tonumber{\pgf@x}}%
			%
			% ...and thus the point on the border.
			%
			\pgfpointadd{\semicirclecenterpoint}{\pgfqpointpolar{\angle}{\semicircleradius}}%
		\else%
			%
			% Calculate the the point where the semicircle chord intersects 
			% the line from the external point to the reference point.
			%
			\pgfpointintersectionoflines{\referencepoint}{\pgfqpoint{\externalx}{\externaly}}%
				{\firstpoint}{\secondpoint}%
		\fi%
	}		
}


% Keys for shape isosceles triangle
%
% /pgf/isosceles triangle apex angle : angle at the apex of the triangle.
\pgfkeys{/pgf/.cd,
	isosceles triangle apex angle/.initial=45,
	isosceles triangle stretches/.is if=pgf@lib@sh@isosceslestrianglestretches
}
\newif\ifpgf@lib@sh@isosceslestrianglestretches

\pgfdeclareshape{isosceles triangle}{
	\savedmacro\trianglepoints{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/isosceles triangle apex angle}}%
		\divide\pgf@x2\relax%
		\edef\halfapexangle{\pgfmath@tonumber{\pgf@x}}%
		\addtosavedmacro\halfapexangle%
		%
		\pgfmathtan@{\halfapexangle}%
		\let\tanhalfapexangle\pgfmathresult%
		%
		\pgfmathcot@{\halfapexangle}%
		\let\cothalfapexangle\pgfmathresult%
		%
		\pgfmathsin@{\halfapexangle}%
		\let\sinhalfapexangle\pgfmathresult%
		%
		\pgfmathreciprocal@{\pgfmathresult}%
		\let\cosechalfapexangle\pgfmathresult%
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
		\advance\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
		\advance\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y.5\dp\pgfnodeparttextbox%
		%
		\ifpgfshapeborderusesincircle%
			\pgfmathsetmacro\rotate{\pgfkeysvalueof{/pgf/shape border rotate}}%
			\ifdim\pgf@x<\pgf@y%
				\pgf@x\pgf@y%
			\else%
				\pgf@y\pgf@x%
			\fi%
			\pgf@x1.414213\pgf@x%
			\pgf@y1.414213\pgf@y%
			%
			\pgf@xa\pgf@x%
			\advance\pgf@xa\cosechalfapexangle\pgf@x%
			\pgf@ya\tanhalfapexangle\pgf@xa%
		\else%
			\pgfmathmod{\pgfkeysvalueof{/pgf/shape border rotate}}{360}%
			\ifdim\pgfmathresult pt<0pt\relax%
				\pgfmathadd@{\pgfmathresult}{360}%
			\fi%
			\pgfmathsetcount\c@pgf@counta{+\pgfmathresult}%
			\advance\c@pgf@counta45\relax%
			\divide\c@pgf@counta90\relax%
			\multiply\c@pgf@counta90\relax%
			\edef\rotate{\the\c@pgf@counta}%
			\ifnum\c@pgf@counta=90\relax%
				\pgf@xa\pgf@x%
				\pgf@x\pgf@y%
				\pgf@y\pgf@xa%
			\else%
				\ifnum\c@pgf@counta=270\relax%
					\pgf@xa\pgf@x%
					\pgf@x\pgf@y%
					\pgf@y\pgf@xa%
				\fi%
			\fi%
			%
			\pgf@xa2.0\pgf@x%
			\pgf@ya\tanhalfapexangle\pgf@xa%
			\advance\pgf@xa\cothalfapexangle\pgf@y%
			\advance\pgf@ya\pgf@y%			
		\fi%
		\addtosavedmacro\rotate%
		\ifdim\pgf@xa=0pt\relax%
			\pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/minimum height}}%
		\fi%
		% Adjust for minimum height and width.
		%
		\pgfmathsetlength\pgf@yb{\pgfkeysvalueof{/pgf/minimum width}}%
		\ifdim\pgf@ya<.5\pgf@yb%
			\ifpgf@lib@sh@isosceslestrianglestretches%
				\pgf@ya.5\pgf@yb%
				%
				\pgfmathdivide@{\pgfmath@tonumber{\pgf@ya}}{\pgfmath@tonumber{\pgf@xa}}%
				\pgfmathatan@{\pgfmathresult}%
				\let\halfapexangle\pgfmathresult%
				%				
			\else%
				\pgf@ya.5\pgf@yb%
				\pgf@xa\cothalfapexangle\pgf@ya%
			\fi%
		\fi%
		%
		\pgfmathsetlength\pgf@xb{\pgfkeysvalueof{/pgf/minimum height}}%
		\ifdim\pgf@xa<\pgf@xb%
			\ifpgf@lib@sh@isosceslestrianglestretches%
				\pgf@xa\pgf@xb%
				%
				\pgfmathdivide@{\pgfmath@tonumber{\pgf@ya}}{\pgfmath@tonumber{\pgf@xa}}%
				\pgfmathatan@{\pgfmathresult}%
				\let\halfapexangle\pgfmathresult%
				%		
			\else%
				\pgf@xa\pgf@xb%
				\pgf@ya\tanhalfapexangle\pgf@xa%
			\fi%
		\fi%
		%
		%
		% Now find the ``offset height'' (h'). This is the distance from the
		% center of the node contents to the base of the triangle. 
		%
		\ifpgfshapeborderusesincircle%
			%
			% h' = H*sin(a/2) / (1+sin(a/2))
			%
			% where:
			%   H = the height of the triangle.
			%   a = the apex angle.
			%
			\pgf@xc\pgf@xa%
			\pgfmathsin@{\halfapexangle}%
			\pgf@xc\pgfmathresult\pgf@xc%
			\pgf@yc1pt\relax%
			\advance\pgf@yc\pgfmathresult pt\relax%
			\pgfmathdivide@{\pgfmath@tonumber{\pgf@xc}}{\pgfmath@tonumber{\pgf@yc}}
			\pgfutil@tempdima\pgfmathresult pt\relax%
		\else%
			%
			% h' = 0.5*h + (0.5*(W-w)*cos(a/2) - h*sin(a/2))/(1+sin(a/2))
			%
			% where:
			%   h = the height of the node contents.
			%   w = the width of the node contents.
			%   W = the width of the triangle.
			%   a = the apex angle.
			%
			\pgf@xc\pgf@ya%
			\advance\pgf@xc-\pgf@y%
			\pgfmathcos@{\halfapexangle}%
			\pgf@xc\pgfmathresult\pgf@xc%
			\pgfmathsin@{\halfapexangle}%
			\advance\pgf@xc-\pgfmathresult\pgf@x%
			\advance\pgf@xc-\pgfmathresult\pgf@x%
			\pgf@yc\pgfmathresult pt\relax%
			\advance\pgf@yc1pt\relax%
			\pgfmathdivide@{\pgfmath@tonumber{\pgf@xc}}{\pgfmath@tonumber{\pgf@yc}}%
			\pgfutil@tempdima\pgfmathresult pt\relax%
			\advance\pgfutil@tempdima\pgf@x%	
		\fi%
		\pgfextract@process\apex{%
			\pgf@y0pt%
			\pgf@x\pgf@xa%
			\advance\pgf@x-\pgfutil@tempdima%
		}%
		\addtosavedmacro\apex%
		%
		\pgfextract@process\lowerleft{%
			\pgf@y\pgf@ya%
			\pgf@x-\pgfutil@tempdima%
		}%
		\addtosavedmacro\lowerleft%
		%
		\pgfmathsetlength\pgf@xb{\pgfkeysvalueof{/pgf/outer xsep}}%
		\pgfmathsetlength\pgf@yb{\pgfkeysvalueof{/pgf/outer ysep}}%
		\ifdim\pgf@xb<\pgf@yb%
			\pgf@xb\pgf@yb%
		\fi%
		\pgfextract@process\apexanchor{%
			\apex%
			\advance\pgf@x\cosechalfapexangle\pgf@xb%
		}%
		\addtosavedmacro\apexanchor%
		%
		\pgf@yc-\halfapexangle pt\relax%
		\advance\pgf@yc90pt\relax%
		\divide\pgf@yc2\relax%
		\pgfmathcot@{\pgfmath@tonumber{\pgf@yc}}%
		\pgfextract@process\lowerleftanchor{%
			\lowerleft%
			\advance\pgf@y\pgfmathresult\pgf@xb%
			\advance\pgf@x-\pgf@xb%
		}%
		\addtosavedmacro\lowerleftanchor%	
		%
		\pgfextract@process\lowerrightanchor{%
			\lowerleftanchor%
			\pgf@y-\pgf@y%
		}%	
		\addtosavedmacro\lowerrightanchor%	
	}
	\anchor{apex}{%
		\trianglepoints%
		\pgfpointadd{\centerpoint}{%
			\pgfmathrotatepointaround{\apexanchor}{\pgfpointorigin}{\rotate}%
		}%
	}%
	\anchor{left corner}{%
		\trianglepoints%
		\pgfpointadd{\centerpoint}{%
			\pgfmathrotatepointaround{\lowerleftanchor}{\pgfpointorigin}{\rotate}%
		}%
	}%
	\anchor{right corner}{%
		\trianglepoints%
		\pgfpointadd{\centerpoint}{%
			\pgfmathrotatepointaround{\lowerrightanchor}{\pgfpointorigin}{\rotate}%
		}%
	}%
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}%
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+.5ex}%
	}%
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt%
	}%
	\anchor{center}{\centerpoint}%
	\anchor{mid}{\midpoint}%
	\anchor{mid west}{%
		\trianglepoints%
		\let\pgf@isoscelestriangle@referencepoint\midpoint%
		\csname pgf@anchor@isosceles triangle@border\endcsname{\pgfqpoint{-1pt}{0pt}}%
	}%
	\anchor{mid east}{%
		\trianglepoints%
		\let\pgf@isoscelestriangle@referencepoint\midpoint%
		\csname pgf@anchor@isosceles triangle@border\endcsname{\pgfqpoint{1pt}{0pt}}%
	}%
	\anchor{base}{\basepoint}%
	\anchor{base west}{%
		\trianglepoints%
		\let\pgf@isoscelestriangle@referencepoint\basepoint%
		\csname pgf@anchor@isosceles triangle@border\endcsname{\pgfqpoint{-1pt}{0pt}}%
	}%
	\anchor{base east}{%
		\trianglepoints%
		\let\pgf@isoscelestriangle@referencepoint\basepoint%
		\csname pgf@anchor@isosceles triangle@border\endcsname{\pgfqpoint{1pt}{0pt}}%
	}%
	\anchor{north}{%
		\trianglepoints%
		\csname pgf@anchor@isosceles triangle@border\endcsname{\pgfqpoint{0pt}{1pt}}%
	}
	\anchor{south}{%
		\trianglepoints%
		\csname pgf@anchor@isosceles triangle@border\endcsname{\pgfqpoint{0pt}{-1pt}}%
	}
	\anchor{east}{%
		\trianglepoints%
		\csname pgf@anchor@isosceles triangle@border\endcsname{\pgfqpoint{1pt}{0pt}}%
	}
	\anchor{west}{%
		\trianglepoints%
		\csname pgf@anchor@isosceles triangle@border\endcsname{\pgfqpoint{-1pt}{0pt}}%
	}
	\anchor{north east}{%
		\trianglepoints%
		\csname pgf@anchor@isosceles triangle@border\endcsname{\pgfqpoint{1pt}{1pt}}%
	}
	\anchor{south west}{%
		\trianglepoints%
		\csname pgf@anchor@isosceles triangle@border\endcsname{\pgfqpoint{-1pt}{-1pt}}%
	}
	\anchor{south east}{%
		\trianglepoints%
		\csname pgf@anchor@isosceles triangle@border\endcsname{\pgfqpoint{1pt}{-1pt}}%
	}
	\anchor{north west}{%
		\trianglepoints%
		\csname pgf@anchor@isosceles triangle@border\endcsname{\pgfqpoint{-1pt}{1pt}}%
	}
	\anchor{left side}{%
		\trianglepoints%
		\pgfmathrotatepointaround{%
			\pgfpointadd{\pgfpointlineattime{0.5}{\lowerleftanchor}{\apexanchor}}{\centerpoint}}%
				{\centerpoint}{\rotate}%
	}
	\anchor{right side}{%
		\trianglepoints%
		\pgfmathrotatepointaround{%
			\pgfpointadd{\pgfpointlineattime{0.5}{\lowerrightanchor}{\apexanchor}}{\centerpoint}}%
				{\centerpoint}{\rotate}%
	}
	\anchor{lower side}{%
		\trianglepoints%
		\pgfmathrotatepointaround{%
			\pgfpointadd{\pgfpointlineattime{0.5}{\lowerleftanchor}{\lowerrightanchor}}{\centerpoint}}%
				{\centerpoint}{\rotate}%
	}
	\backgroundpath{%
		\trianglepoints%
		{%
			\pgftransformshift{\centerpoint}%
			\pgftransformrotate{\rotate}%
			\pgfpathmoveto{\apex}%
			\pgfpathlineto{\lowerleft}%
			\pgfpathlineto{\lowerleft\pgf@y-\pgf@y}%
			\pgfpathclose%
		}%
	}
	\anchorborder{%
		\pgfutil@ifundefined{pgf@isoscelestriangle@referencepoint}{\let\referencepoint\centerpoint}%
			{\let\referencepoint\pgf@isoscelestriangle@referencepoint}%
		\pgfextract@process\externalpoint{%
			\pgf@xa\pgf@x%
			\pgf@ya\pgf@y%
			\referencepoint%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y\pgf@ya%
		}%		
		\trianglepoints%
		\pgfmathanglebetweenpoints{\referencepoint}{\externalpoint}%
		\pgfmathsubtract@{\pgfmathresult}{\rotate}%
			\pgfmathmod@{\pgfmathresult}{360}%
		\ifdim\pgfmathresult pt<0pt\relax%
			\pgfmathadd@{\pgfmathresult}{360}%
		\fi%
		\let\externalangle\pgfmathresult%
		%
		\pgfmathanglebetweenpoints{\referencepoint}{\pgfpointadd{\centerpoint}{\lowerrightanchor}}%
		\ifdim\externalangle pt<\pgfmathresult pt\relax%
			\pgfmathanglebetweenpoints{\referencepoint}{\pgfpointadd{\centerpoint}{\lowerleftanchor}}%
			\ifdim\externalangle pt<\pgfmathresult pt\relax%
				\pgfmathanglebetweenpoints{\referencepoint}{\pgfpointadd{\centerpoint}{\apexanchor}}%
				\ifdim\externalangle pt>\pgfmathresult pt\relax%
					\let\firstpoint\apexanchor%
					\let\secondpoint\lowerleftanchor%
				\else%
					\let\firstpoint\apexanchor%
					\let\secondpoint\lowerrightanchor%
				\fi%
			\else%
				\let\firstpoint\lowerleftanchor%
				\let\secondpoint\lowerrightanchor%
			\fi%
		\else%
			\let\firstpoint\lowerrightanchor%
			\let\secondpoint\apexanchor%
		\fi%
		\pgfpointintersectionoflines{\referencepoint}{\externalpoint}%
			{\pgfmathrotatepointaround{\pgfpointadd{\centerpoint}{\firstpoint}}{\centerpoint}{\rotate}}%
			{\pgfmathrotatepointaround{\pgfpointadd{\centerpoint}{\secondpoint}}{\centerpoint}{\rotate}}%	
	}%
}




% Keys for shape kite
%
%
\pgfkeys{/pgf/.cd,
	kite upper vertex angle/.initial=120,
	kite lower vertex angle/.initial=60,
	kite vertex angles/.code={%
		\pgfutil@in@{and}{#1}%
		\ifpgfutil@in@%
			\def\pgf@marshal##1and##2\@@{%
				\pgfkeys{/pgf/kite upper vertex angle=##1}%
				\pgfkeys{/pgf/kite lower vertex angle=##2}%
			}%
			\expandafter\pgf@marshal#1\@@%
		\else%
			\pgfkeys{/pgf/kite upper vertex angle=#1}%
			\pgfkeys{/pgf/kite lower vertex angle=#1}%
		\fi%
	}%
}

% Shape kite.
%
\pgfdeclareshape{kite}{
	\savedmacro\installkiteparameters{%
		%
		% Get the larger of the outer sep.
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/outer ysep}}%
		\ifdim\pgf@x<\pgf@y%
			\pgf@x\pgf@y%
		\fi%
		\edef\outersep{\the\pgf@x}%
		%
		% Calculate the centre, base and mid points of the node.
		%
		\pgfextract@process\centerpoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgf@y.5\ht\pgfnodeparttextbox%
			\advance\pgf@y-.5\dp\pgfnodeparttextbox%
		}%
		\pgfextract@process\basepoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgf@y0pt\relax%
		}%
		\pgfextract@process\midpoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgfmathsetlength\pgf@y{+.5ex}%
		}%
		%
		% Halve the vertex angles.
		%
		\pgfmathdivide{\pgfkeysvalueof{/pgf/kite upper vertex angle}}{2}%
		\let\halfuppervertexangle\pgfmathresult%
		\pgfmathdivide{\pgfkeysvalueof{/pgf/kite lower vertex angle}}{2}%
		\let\halflowervertexangle\pgfmathresult%
		%
		% Get the node dimensions.
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
		\advance\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
		\advance\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y.5\dp\pgfnodeparttextbox%
		\ifpgfshapeborderusesincircle%
			%
			% Get the rotation.
			%
			\pgfmathsetmacro\rotate{\pgfkeysvalueof{/pgf/shape border rotate}}%
			%
			% Get the radis of the incircle.
			%
			\ifdim\pgf@x<\pgf@y%
				\pgf@x\pgf@y%
			\fi%			
			\pgf@x1.41421\pgf@x%
			%
			% Get the distances from the upper and lower verticies
			% to the center of the incircle.
			%
			\pgfmathsin@{\halfuppervertexangle}%
			\let\sinehalfuppervertexangle\pgfmathresult%
			\pgfmathreciprocal@{\pgfmathresult}%
			\let\cosechalfuppervertexangle\pgfmathresult%
			\pgf@ya\pgfmathresult\pgf@x%
			\pgfmathsin@{\halflowervertexangle}%
			\let\sinehalflowervertexangle\pgfmathresult%
			\pgfmathreciprocal@{\pgfmathresult}%
			\pgf@yb\pgfmathresult\pgf@x%
			%
			% Now calculate vertical offset (yc) between the center of 
			% the incircle, and the intersection of the kite diagonals.
			%
		   % yc = x * cosec(a/2) - x * cot(a/2) * (sin(a/2) + sin(b/2)) * cosec(a/2 + b/2)
		   %
		   % where:
		   %   x = the incircle radius.
		   %   a = the upper vertex angle.
		   %   b = the lower vertex angle.
		   %
		   \pgf@yc\pgf@x%
		   \pgfmathadd@{\halfuppervertexangle}{\halflowervertexangle}%
		   \pgfmathcosec@{\pgfmathresult}%
		   \pgf@yc\pgfmathresult\pgf@yc%
		   \pgfmathadd@{\sinehalfuppervertexangle}{\sinehalflowervertexangle}%
        \pgf@yc\pgfmathresult\pgf@yc%
		  	\pgfmathcos@{\halfuppervertexangle}%
		  	\pgf@yc\pgfmathresult\pgf@yc%
		  	\pgf@yc-\cosechalfuppervertexangle\pgf@yc%
		  	\advance\pgf@yc\cosechalfuppervertexangle\pgf@x%
			\edef\deltay{\the\pgf@yc}%
			%
			% Now calculate the height of the kite...
			%
			\advance\pgf@ya-\pgf@yc%
			%
			% ...and the depth.
			%
			\advance\pgf@yb\pgf@yc%
			%
			% Get the half width of the widest part of the kite.
			%
			\pgfmathtan@{\halfuppervertexangle}%
			\pgf@xa\pgfmathresult\pgf@ya%			
		\else%
			\multiply\pgf@x2\relax%
			\multiply\pgf@y2\relax%
			%
			% Get the rotation (with rounding).
			%
			\pgfmathmod{\pgfkeysvalueof{/pgf/shape border rotate}}{360}%
			\afterassignment\pgfmath@gobbletilpgfmath@%
			\expandafter\c@pgf@counta\pgfmathresult\relax\pgfmath@%
			\advance\c@pgf@counta45\relax%
			\divide\c@pgf@counta90\relax%
			\multiply\c@pgf@counta90\relax%
			\ifnum\c@pgf@counta<0\relax%
				\advance\c@pgf@counta360\relax%
			\fi%
			\edef\rotate{\the\c@pgf@counta}%
			%
			% Calculate the width and height of the node
			% contents, according to any border rotation.
			%
			\ifnum\c@pgf@counta=90\relax%
				\pgf@xc\pgf@x%
				\pgf@x\pgf@y%
				\pgf@y\pgf@xc%
			\else%
				\ifnum\c@pgf@counta=270\relax%
					\pgf@xc\pgf@x%
					\pgf@x\pgf@y%
					\pgf@y\pgf@xc%
				\fi%
			\fi%
			%
			% The node contents (total height y) extends a distance ya into the 
			% upper isosceles triangle of the kite and a distance yb into the 
			% lower isosceles triangle. Thus, the following relationships hold:
			%
			%   ya/yb = tan(b/2)/tan(a/2)
			%
			% and   y = ya + yb
			%
			% so   ya = y * sin(a/2 + b/2) / (cos(a/2) * sin(b/2))
			%
			% where:
			%   a = upper vertex angle.
			%   b = lower vertex angle.
			%
			\pgfmathadd@{\halfuppervertexangle}{\halflowervertexangle}%
			\pgfmathsin@{\pgfmathresult}%
			\pgfmathreciprocal@{\pgfmathresult}%
			\pgf@ya\pgfmathresult\pgf@y%
			\pgfmathcos@{\halfuppervertexangle}%
			\pgf@ya\pgfmathresult\pgf@ya%
			\pgfmathsin@{\halflowervertexangle}%
			\pgf@ya\pgfmathresult\pgf@ya%
			\pgf@yb\pgf@y%
			\advance\pgf@yb-\pgf@ya%
			%
			% The vertical offset between the center of the node, and
			% the intersection of the kite diagonals is given by:
			% 
			% yc = y/2 - ya
			%
			\pgf@yc.5\pgf@y%
			\advance\pgf@yc-\pgf@ya%
			\edef\deltay{\the\pgf@yc}%
			%
			% Get the half width of the widest part of the kite.
			%
			\pgfmathtan@{\halfuppervertexangle}%
			\pgf@xa.5\pgf@x%
			\advance\pgf@xa\pgfmathresult\pgf@ya%
			%
			% Now calculate the height of the kite...
			%
			\pgf@xb.5\pgf@x%
			\pgfmathreciprocal@{\pgfmathresult}%
			\advance\pgf@ya\pgfmathresult\pgf@xb%
			%
			% ...and the depth.
			%
			\pgfmathtan@{\halflowervertexangle}%
			\pgfmathreciprocal@{\pgfmathresult}%
			\advance\pgf@yb\pgfmathresult\pgf@xb%
		\fi%
		%
		% Take into account minimum height and width.
		%
		% ya is the kite height.
		% yb is the kite depth.
		% xa is the kite (half) width.
		%
		\pgfmathsetlength\pgf@yc{\pgfkeysvalueof{/pgf/minimum height}}%
		\pgf@y\pgf@ya%
		\advance\pgf@y\pgf@yb%
		\ifdim\pgf@y<\pgf@yc%
			\pgfmathreciprocal@{\pgfmath@tonumber{\pgf@y}}%
			\pgf@yc\pgfmathresult\pgf@yc%
			\pgf@xa\pgfmath@tonumber{\pgf@yc}\pgf@xa%
			\pgf@ya\pgfmath@tonumber{\pgf@yc}\pgf@ya%
			\pgf@yb\pgfmath@tonumber{\pgf@yc}\pgf@yb%
		\fi%
		\pgf@x2.0\pgf@xa%	
		\pgfmathsetlength\pgf@xc{\pgfkeysvalueof{/pgf/minimum width}}%
		\ifdim\pgf@x<\pgf@xc%
			\pgfmathreciprocal@{\pgfmath@tonumber{\pgf@x}}%
			\pgf@xc\pgfmathresult\pgf@xc%
			\pgf@xa\pgfmath@tonumber{\pgf@xc}\pgf@xa%
			\pgf@ya\pgfmath@tonumber{\pgf@xc}\pgf@ya%
			\pgf@yb\pgfmath@tonumber{\pgf@xc}\pgf@yb%
		\fi%
		\edef\kitehalfwidth{\the\pgf@xa}%
		\edef\kiteheight{\the\pgf@ya}%
		\edef\kitedepth{\the\pgf@yb}%
		%
		% Calculate the basic points on the kite (for the background path).
		%
		\pgfextract@process\toppoint{%
			\centerpoint%
			\advance\pgf@y\deltay\relax%
			\advance\pgf@y\kiteheight%
		}%
		\pgfextract@process\bottompoint{%
			\centerpoint%
			\advance\pgf@y\deltay\relax%
			\advance\pgf@y-\kitedepth%
		}%
		\pgfextract@process\leftpoint{%
			\centerpoint%
			\advance\pgf@y\deltay\relax%
			\advance\pgf@x-\kitehalfwidth%
		}%
		\pgfextract@process\rightpoint{%
			\centerpoint%
			\advance\pgf@y\deltay\relax%
				\advance\pgf@x\kitehalfwidth%
		}%
		%
		% Now calculate the miter length. At the top...
		%
		\pgfmathsin@{\halfuppervertexangle}%
		\pgfmathreciprocal@{\pgfmathresult}%
		\pgf@y\outersep\relax%
		\pgf@y\pgfmathresult\pgf@y%
		\edef\topmiter{\the\pgf@y}%
		%
		% ...at the bottom...
		%
		\pgfmathsin@{\halflowervertexangle}%
		\pgfmathreciprocal@{\pgfmathresult}%
		\pgf@y\outersep\relax%
		\pgf@y\pgfmathresult\pgf@y%
		\edef\bottommiter{\the\pgf@y}%
		%
		% ...to the right...
		%
		\pgfmathsubtract@{180}{\halflowervertexangle}%
		\pgfmathsubtract@{\pgfmathresult}{\halfuppervertexangle}%
		\pgfmathdivide@{\pgfmathresult}{2}%
		\pgfmathsin@{\pgfmathresult}%
		\pgfmathreciprocal@{\pgfmathresult}%
		\pgf@xa\outersep\relax%
		\pgf@xa\pgfmathresult\pgf@xa%
		\pgfmathsubtract@{\halfuppervertexangle}{\halflowervertexangle}%
		\pgfmathdivide@{\pgfmathresult}{2}%
		\let\angle\pgfmathresult%
		\pgfextract@process\rightmiter{%
			\pgfqpointpolar{\angle}{\the\pgf@xa}%
		}%
		%
		% ...and to the left.
		%
		\pgfmathsubtract@{180}{\angle}%
		\let\angle\pgfmathresult%
		\pgfextract@process\leftmiter{%
			\pgfqpointpolar{\angle}{\the\pgf@xa}%
		}%
		%
		% Create the border points.
		%
		\pgfextract@process\topborderpoint{%
			\toppoint%
			\advance\pgf@y\topmiter\relax%
		}%
		\pgfextract@process\bottomborderpoint{%
			\bottompoint%
			\advance\pgf@y-\bottommiter\relax%
		}%
		\pgfextract@process\leftborderpoint{%
			\leftpoint%
			\pgf@xa\pgf@x%
			\pgf@ya\pgf@y%
			\leftmiter%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y\pgf@ya%
		}%
		\pgfextract@process\rightborderpoint{%
			\rightpoint%
			\pgf@xa\pgf@x%
			\pgf@ya\pgf@y%
			\rightmiter%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y\pgf@ya%
		}%
		%
		% Get the angle from the \centerpoint to the *unrotated points*.
		%
		\pgfmathanglebetweenpoints{\centerpoint}{\topborderpoint}%
		\let\angletotoppoint\pgfmathresult%
		\pgfmathanglebetweenpoints{\centerpoint}{\leftborderpoint}%
		\let\angletoleftpoint\pgfmathresult%
		\pgfmathanglebetweenpoints{\centerpoint}{\bottomborderpoint}%
		\let\angletobottompoint\pgfmathresult%
		\pgfmathanglebetweenpoints{\centerpoint}{\rightborderpoint}%
		\let\angletorightpoint\pgfmathresult%
		%
		% ...from the *inversly rotated* \basepoint...
		%
		\pgfextract@process\rotatedbasepoint{%
			\pgfmathrotatepointaround{\basepoint}{\centerpoint}{-\rotate}%
		}%
		\pgfmathanglebetweenpoints{\rotatedbasepoint}{\topborderpoint}%
		\let\baseangletotoppoint\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedbasepoint}{\leftborderpoint}%
		\let\baseangletoleftpoint\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedbasepoint}{\bottomborderpoint}%
		\let\baseangletobottompoint\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedbasepoint}{\rightborderpoint}%
		\let\baseangletorightpoint\pgfmathresult%
		%
		% ...and from the *inversely rotated* \midpoint.
		%
		\pgfextract@process\rotatedmidpoint{%
			\pgfmathrotatepointaround{\midpoint}{\centerpoint}{-\rotate}%
		}%
		\pgfmathanglebetweenpoints{\rotatedmidpoint}{\topborderpoint}%
		\let\midangletotoppoint\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedmidpoint}{\leftborderpoint}%
		\let\midangletoleftpoint\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedmidpoint}{\bottomborderpoint}%
		\let\midangletobottompoint\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedmidpoint}{\rightborderpoint}%
		\let\midangletorightpoint\pgfmathresult%
		%
		% Calculate a radius guaranteed to be outside the kite.
		%
		\pgfextractx\pgf@xa{\pgfpointdiff{\leftborderpoint}{\rightborderpoint}}%
		\ifdim\pgf@xa<0pt\relax%
			\pgf@xa-\pgf@xa%
		\fi%
		\pgfextracty\pgf@ya{\pgfpointdiff{\topborderpoint}{\bottomborderpoint}}%
		\ifdim\pgf@ya<0pt\relax%
			\pgf@ya-\pgf@ya%
		\fi%
		\ifdim\pgf@ya>\pgf@xa%
			\edef\externalradius{\the\pgf@ya}%
		\else%
			\edef\externalradius{\the\pgf@xa}%
		\fi%
		%
		% Now rotate the points...
		%
		\pgfextract@process\toppoint{%
			\pgfmathrotatepointaround{\toppoint}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\bottompoint{%
			\pgfmathrotatepointaround{\bottompoint}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\leftpoint{%
			\pgfmathrotatepointaround{\leftpoint}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\rightpoint{%
			\pgfmathrotatepointaround{\rightpoint}{\centerpoint}{\rotate}%
		}%
		%
		% ...and the border points.
		%
		\pgfextract@process\topborderpoint{%
			\pgfmathrotatepointaround{\topborderpoint}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\bottomborderpoint{%
			\pgfmathrotatepointaround{\bottomborderpoint}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\leftborderpoint{%
			\pgfmathrotatepointaround{\leftborderpoint}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\rightborderpoint{%
			\pgfmathrotatepointaround{\rightborderpoint}{\centerpoint}{\rotate}%
		}%
		%
		% Now save it all.
		%
		\addtosavedmacro{\rotate}%
		\addtosavedmacro{\externalradius}%
		%
		\addtosavedmacro\toppoint%
		\addtosavedmacro\bottompoint%
		\addtosavedmacro\leftpoint%
		\addtosavedmacro\rightpoint%
		%
		\addtosavedmacro\topborderpoint%
		\addtosavedmacro\bottomborderpoint%
		\addtosavedmacro\leftborderpoint%
		\addtosavedmacro\rightborderpoint%
		%
		\addtosavedmacro\angletotoppoint%
		\addtosavedmacro\angletobottompoint%
		\addtosavedmacro\angletoleftpoint%
		\addtosavedmacro\angletorightpoint%
		%
		\addtosavedmacro\baseangletotoppoint%
		\addtosavedmacro\baseangletobottompoint%
		\addtosavedmacro\baseangletoleftpoint%
		\addtosavedmacro\baseangletorightpoint%
		%
		\addtosavedmacro\midangletotoppoint%
		\addtosavedmacro\midangletobottompoint%
		\addtosavedmacro\midangletoleftpoint%
		\addtosavedmacro\midangletorightpoint%			
	}
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}%
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt\relax%
	}%
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+.5ex}%
	}%
	\anchor{center}{\centerpoint}%
	\anchor{base}{\basepoint}%
	\anchor{base west}{%
		\installkiteparameters%
		\let\pgf@kiteanchorborderreferencepoint\basepoint%
		\csname pgf@anchor@kite@border\endcsname{\pgfqpoint{-\externalradius}{0pt}}%
	}%
	\anchor{base east}{%
		\installkiteparameters%
		\let\pgf@kiteanchorborderreferencepoint\basepoint%
		\csname pgf@anchor@kite@border\endcsname{\pgfqpoint{\externalradius}{0pt}}%
	}%
	\anchor{mid}{\midpoint}%
	\anchor{mid west}{%
		\installkiteparameters%
		\let\pgf@kiteanchorborderreferencepoint\midpoint%
		\csname pgf@anchor@kite@border\endcsname{\pgfqpoint{-\externalradius}{0pt}}%
	}%
	\anchor{mid east}{%
		\installkiteparameters%
		\let\pgf@kiteanchorborderreferencepoint\midpoint%
		\csname pgf@anchor@kite@border\endcsname{\pgfqpoint{\externalradius}{0pt}}%
	}%
	\anchor{north}{%
		\installkiteparameters%
		\csname pgf@anchor@kite@border\endcsname{\pgfqpoint{0pt}{\externalradius}}%
	}
	\anchor{south}{%
		\installkiteparameters%
		\csname pgf@anchor@kite@border\endcsname{\pgfqpoint{0pt}{-\externalradius}}%
	}
	\anchor{east}{%
		\installkiteparameters%
		\csname pgf@anchor@kite@border\endcsname{\pgfqpoint{\externalradius}{0pt}}%
	}
	\anchor{west}{%
		\installkiteparameters%
		\csname pgf@anchor@kite@border\endcsname{\pgfqpoint{-\externalradius}{0pt}}%
	}
	\anchor{north east}{%
		\installkiteparameters%
		\csname pgf@anchor@kite@border\endcsname{\pgfqpoint{\externalradius}{\externalradius}}%
	}
	\anchor{south west}{%
		\installkiteparameters%
		\csname pgf@anchor@kite@border\endcsname{\pgfqpoint{-\externalradius}{-\externalradius}}%
	}
	\anchor{south east}{%
		\installkiteparameters%
		\csname pgf@anchor@kite@border\endcsname{\pgfqpoint{\externalradius}{-\externalradius}}%
	}
	\anchor{north west}{%
		\installkiteparameters%
		\csname pgf@anchor@kite@border\endcsname{\pgfqpoint{-\externalradius}{\externalradius}}%
	}
	\anchor{upper vertex}{%
		\installkiteparameters%
		\topborderpoint}
	\anchor{lower vertex}{%
		\installkiteparameters%
		\bottomborderpoint}
	\anchor{left vertex}{%
		\installkiteparameters%
		\leftborderpoint}
	\anchor{right vertex}{%
		\installkiteparameters%
		\rightborderpoint}
	\anchor{upper left side}{%
		\installkiteparameters%
		\pgfpointlineattime{0.5}{\topborderpoint}{\leftborderpoint}}
	\anchor{lower left side}{%
		\installkiteparameters%
		\pgfpointlineattime{0.5}{\bottomborderpoint}{\leftborderpoint}}
	\anchor{upper right side}{%
		\installkiteparameters%
		\pgfpointlineattime{0.5}{\topborderpoint}{\rightborderpoint}}
	\anchor{lower right side}{%
		\installkiteparameters%
		\pgfpointlineattime{0.5}{\bottomborderpoint}{\rightborderpoint}}
	\backgroundpath{%
		\installkiteparameters%
		\pgfpathmoveto{\toppoint}%
		\pgfpathlineto{\leftpoint}%
		\pgfpathlineto{\bottompoint}%
		\pgfpathlineto{\rightpoint}%
		\pgfpathclose%
	}
	\anchorborder{%
		%
		% Save x and y.
		%
		\edef\externalx{\the\pgf@x}%
		\edef\externaly{\the\pgf@y}%
		%
		% This allows anchors base east, base west, mid east and mid west,
		% to redefine the `center' of the node to correctly calculate the
		% border points.
		%
		\pgfutil@ifundefined{pgf@kiteanchorborderreferencepoint}%
			{\let\referencepoint\centerpoint}%
			{\let\referencepoint\pgf@kiteanchorborderreferencepoint}%
		%
		% Adjust the location of the external 
		% point relative to the reference point.
		%
		\referencepoint%
		\pgf@xa\externalx\relax%
		\pgf@ya\externaly\relax%
		\advance\pgf@xa\pgf@x%
		\advance\pgf@ya\pgf@y%
		\edef\externalx{\the\pgf@xa}%
		\edef\externaly{\the\pgf@ya}%
		%
		% Install the required points and angles.
		%
		\installkiteparameters%
		%
		% Get the angle of the external point relative to \referencepoint.
		%
		\pgfmathanglebetweenpoints{\referencepoint}{\pgfqpoint{\externalx}{\externaly}}%
		%
		% *Subtract* the rotation from the external angle.
		%
		\pgfmathsubtract@{\pgfmathresult}{\rotate}%
		\ifdim\pgfmathresult pt<0pt\relax%
			\pgfmathadd@{\pgfmathresult}{360}%
		\fi%
		\let\externalangle\pgfmathresult%
		\ifx\referencepoint\basepoint%
			\let\angletotoppoint\baseangletotoppoint%
			\let\angletobottompoint\baseangletobottompoint%
			\let\angletoleftpoint\baseangletoleftpoint%
			\let\angletorightpoint\baseangletorightpoint%
		\else%
			\ifx\referencepoint\midpoint%
				\let\angletotoppoint\midangletotoppoint%
				\let\angletobottompoint\midangletobottompoint%
				\let\angletoleftpoint\midangletoleftpoint%
				\let\angletorightpoint\midangletorightpoint%
		\fi\fi%
		%
		%  Depending on the rotation, the angle to \rightborderpoint
		%  may be smaller than the angle to \topborderpoint.
		%
		\ifdim\angletorightpoint pt<\angletotoppoint pt\relax%
			\ifdim\externalangle pt<\angletorightpoint pt\relax%
				\let\firstpoint\rightborderpoint%
				\let\secondpoint\bottomborderpoint%
			\else%
				\ifdim\externalangle pt<\angletotoppoint pt\relax%
					\let\firstpoint\rightborderpoint%
					\let\secondpoint\topborderpoint%
				\else%
					\ifdim\externalangle pt<\angletoleftpoint pt\relax%
						\let\firstpoint\topborderpoint%
						\let\secondpoint\leftborderpoint%
					\else%
						\ifdim\externalangle pt<\angletobottompoint pt\relax%
							\let\firstpoint\leftborderpoint%
							\let\secondpoint\bottomborderpoint%
						\else%
							\let\firstpoint\rightborderpoint%
							\let\secondpoint\bottomborderpoint%
						\fi%
					\fi%
				\fi%
			\fi%
		\else%
			\ifdim\externalangle pt<\angletotoppoint pt\relax%
				\let\firstpoint\rightborderpoint%
				\let\secondpoint\topborderpoint%
			\else%
				\ifdim\externalangle pt<\angletoleftpoint pt\relax%
					\let\firstpoint\leftborderpoint%
					\let\secondpoint\topborderpoint%
				\else%
					\ifdim\externalangle pt<\angletobottompoint pt\relax%
						\let\firstpoint\bottomborderpoint%
						\let\secondpoint\leftborderpoint%
					\else%
						\ifdim\externalangle pt<\angletorightpoint pt\relax%
							\let\firstpoint\rightborderpoint%
							\let\secondpoint\bottomborderpoint%
						\else%
							\let\firstpoint\rightborderpoint%
							\let\secondpoint\topborderpoint%
						\fi%
					\fi%
				\fi%
			\fi%
		\fi%
		\pgfpointintersectionoflines{\referencepoint}{\pgfqpoint{\externalx}{\externaly}}%
				{\firstpoint}{\secondpoint}%
	}
}




% Keys for shape dart.
%
%

\pgfkeys{/pgf/.cd,
	dart tip angle/.initial=45,
	dart tail angle/.initial=135
}

% Shape dart.
%
\pgfdeclareshape{dart}{%
	\savedmacro\installdartparameters{%
		%
		% Get the halved angles (more useful).
		%
		\pgfmathdivide{\pgfkeysvalueof{/pgf/dart tip angle}}{2}%
		\let\halftipangle\pgfmathresult%
		\pgfmathdivide{\pgfkeysvalueof{/pgf/dart tail angle}}{2}%
		\let\halftailangle\pgfmathresult%
		%
		% Calculate some common results.
		%
		\pgfmathcot@{\halftipangle}%
		\let\cothalftipangle\pgfmathresult%
		%
		% Get the larger of the outer sep.
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/outer ysep}}%
		\ifdim\pgf@x<\pgf@y%
			\pgf@x\pgf@y%
		\fi%
		\edef\outersep{\the\pgf@x}%
		%
		% Calculate the centre, base and mid points of the node.
		%
		\pgfextract@process\centerpoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgf@y.5\ht\pgfnodeparttextbox%
			\advance\pgf@y-.5\dp\pgfnodeparttextbox%
		}%
		\pgfextract@process\basepoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgf@y0pt\relax%
		}%
		\pgfextract@process\midpoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgfmathsetlength\pgf@y{+.5ex}%
		}%
		%
		% Get the (halved) dimension of the node.
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
		\advance\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
		\advance\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y.5\dp\pgfnodeparttextbox%
		%
		% Get the length of the dart tip.
		%
		\ifpgfshapeborderusesincircle%
			%
			% Get the (unrounded) rotation.
			%
			\pgfmathsetmacro\rotate{\pgfkeysvalueof{/pgf/shape border rotate}}%
			%
			% Get the radius of the incircle.
			%
			\ifdim\pgf@x<\pgf@y%
				\pgf@x\pgf@y%
			\fi%			
			\pgf@x1.41421\pgf@x%
			%
			% Calculate the length of the dart tip.
			%
			\pgf@xa\cothalftipangle\pgf@x%
			\advance\pgf@xa\pgf@x%
		\else%
			%
			% Get the rotation (with rounding).
			%
			\pgfmathmod{\pgfkeysvalueof{/pgf/shape border rotate}}{360}%
			\afterassignment\pgfmath@gobbletilpgfmath@%
			\expandafter\c@pgf@counta\pgfmathresult\relax\pgfmath@%
			\advance\c@pgf@counta45\relax%
			\divide\c@pgf@counta90\relax%
			\multiply\c@pgf@counta90\relax%
			\ifnum\c@pgf@counta<0\relax%
				\advance\c@pgf@counta360\relax%
			\fi%
			\edef\rotate{\the\c@pgf@counta}%
			%
			% Flip the width and height of the node contents, 
			% according to the appropriate border rotation.
			%
			\ifnum\c@pgf@counta=90\relax%
				\pgf@xc\pgf@x%
				\pgf@x\pgf@y%
				\pgf@y\pgf@xc%
			\else%
				\ifnum\c@pgf@counta=270\relax%
					\pgf@xc\pgf@x%
					\pgf@x\pgf@y%
					\pgf@y\pgf@xc%
				\fi%
			\fi%
			%
			% Calculate the length of the dart tip.
			%
			\pgf@xa\cothalftipangle\pgf@y%
			\advance\pgf@xa2.0\pgf@x% 
		\fi%
		%
		% Get the (half) separation of the dart tails.
		%
		\pgfmathsubtract@{\halftailangle}{\halftipangle}%
		\pgfmathcosec@{\pgfmathresult}%
		\pgf@ya\pgfmathresult\pgf@xa%
		\pgfmathsin@{\halftipangle}%
		\pgf@ya\pgfmathresult\pgf@ya%
		\pgfmathcos@{\halftipangle}%
		\pgf@ya\pgfmathresult\pgf@ya%
		%
		% Get the total length of the dart...
		%
		\pgf@xb\cothalftipangle\pgf@ya%
		%
		% and hence the length of the tails. 
		%
		\pgf@xc-\pgf@xa%
		\advance\pgf@xc\pgf@xb%
		%
		% Adjust for minimum height (length of the dart).
		%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/minimum height}}%
		\ifdim\pgf@xb<\pgf@y%
			\pgfmathreciprocal@{\pgfmath@tonumber{\pgf@xb}}%
			\pgf@y\pgfmathresult\pgf@y%
			\pgf@xa\pgfmath@tonumber{\pgf@y}\pgf@xa%
			\pgf@xc\pgfmath@tonumber{\pgf@y}\pgf@xc%
			\pgf@ya\pgfmath@tonumber{\pgf@y}\pgf@ya%
			\pgf@x\pgfmath@tonumber{\pgf@y}\pgf@x%
		\fi%
		%
		% Adjust for minimum width (tail separation length).
		%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/minimum width}}%
		\pgf@y.5\pgf@y%
		\ifdim\pgf@ya<\pgf@y%
			\pgfmathreciprocal@{\pgfmath@tonumber{\pgf@ya}}%
			\pgf@ya\pgf@y%
			\pgf@y\pgfmathresult\pgf@y%
			\pgf@xa\pgfmath@tonumber{\pgf@y}\pgf@xa%
			\pgf@xc\pgfmath@tonumber{\pgf@y}\pgf@xc%
			\pgf@x\pgfmath@tonumber{\pgf@y}\pgf@x%
		\fi%
		\edef\dartlength{\the\pgf@xa}%
		\edef\deltax{\the\pgf@x}%
		\edef\taillength{\the\pgf@xc}%
		\edef\halftailseparation{\the\pgf@ya}
		%
		% Create the basic points on the dart (for the backgroundo path).
		%
		\pgfextract@process\tippoint{%
			\centerpoint%
			\advance\pgf@x\dartlength\relax%
			\advance\pgf@x-\deltax\relax%
		}%
		\pgfextract@process\tailcenterpoint{%
			\centerpoint%
			\advance\pgf@x-\deltax\relax%
		}%
		\pgfextract@process\lefttailpoint{%
			\centerpoint%
			\advance\pgf@x-\deltax\relax%
			\advance\pgf@x-\taillength\relax%
			\advance\pgf@y\halftailseparation\relax%
		}%
		\pgfextract@process\righttailpoint{%
			\centerpoint%
			\advance\pgf@x-\deltax\relax%
			\advance\pgf@x-\taillength\relax%
			\advance\pgf@y-\halftailseparation\relax%
		}%
		%
		% Calculate the miter vectors. At the dart tip...
		%
		\pgfextract@process\tipmiter{%
			\pgfmathcosec@{\halftipangle}%
			\pgf@x\outersep\relax%
			\pgf@x\pgfmathresult\pgf@x%
			\pgf@y0pt\relax%
		}%
		%
		% ...at the tail center...
		%
		\pgfextract@process\tailcentermiter{%
			\pgfmathcosec@{\halftailangle}%
			\pgf@x-\outersep\relax%
			\pgf@x\pgfmathresult\pgf@x%
			\pgf@y0pt\relax%
		}%
		%
		% ...at the left tail...
		%
		\pgfmathsubtract@{\halftailangle}{\halftipangle}%
		\pgfmathdivide@{\pgfmathresult}{2}%
		\let\angle\pgfmathresult%
		\pgfmathcosec@{\pgfmathresult}%
		\pgf@x\outersep\relax%
		\pgf@x\pgfmathresult\pgf@x%
		\pgfmathadd@{\angle}{90}%
		\pgfmathsubtract{\pgfmathresult}{\halftailangle}%
		\pgfmathsincos@{\pgfmathresult}%
		\pgf@ya\pgfmathresultx\pgf@x%
		\pgf@xa\pgfmathresulty\pgf@x%
		\pgfextract@process\lefttailmiter{%
			\pgf@x-\pgf@xa%
			\pgf@y\pgf@ya%
		}%
		%
		% ...and the right tail.
		%
		\pgfextract@process\righttailmiter{%
			\pgf@x-\pgf@xa%
			\pgf@y-\pgf@ya%
		}%
		%
		% Create the border points.
		%
		\pgfextract@process\tipborderpoint{%
			\pgfpointadd{\tippoint}{\tipmiter}
		}%
		\pgfextract@process\tailcenterborderpoint{%
			\pgfpointadd{\tailcenterpoint}{\tailcentermiter}%
		}%
		\pgfextract@process\lefttailborderpoint{%
			\pgfpointadd{\lefttailpoint}{\lefttailmiter}%
		}%
		\pgfextract@process\righttailborderpoint{%
			\pgfpointadd{\righttailpoint}{\righttailmiter}%
		}%
		%
		% Calculate the angles between the centerpoint
		% and the *unrotated* borderpoints.
		%
		\pgfmathanglebetweenpoints{\centerpoint}{\tipborderpoint}%
		\let\angletotip\pgfmathresult%
		\pgfmathanglebetweenpoints{\centerpoint}{\tailcenterborderpoint}%
		\let\angletotailcenter\pgfmathresult%
		\pgfmathanglebetweenpoints{\centerpoint}{\lefttailborderpoint}%
		\let\angletolefttail\pgfmathresult%
		\pgfmathanglebetweenpoints{\centerpoint}{\righttailborderpoint}%
		\let\angletorighttail\pgfmathresult%
		%
		% Calculate the angles between the *inversly rotated* 
		% basepoint and the *unrotated* borderpoints.
		%
		\pgfextract@process\rotatedbasepoint{%
			\pgfmathrotatepointaround{\basepoint}{\centerpoint}{-\rotate}%
		}%
		\pgfmathanglebetweenpoints{\rotatedbasepoint}{\tipborderpoint}%
		\let\baseangletotip\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedbasepoint}{\tailcenterborderpoint}%
		\let\baseangletotailcenter\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedbasepoint}{\lefttailborderpoint}%
		\let\baseangletolefttail\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedbasepoint}{\righttailborderpoint}%
		\let\baseangletorighttail\pgfmathresult%
		%
		% Calculate the angles between the *inversly rotated* 
		% midpoint and the *unrotated* borderpoints.
		%
		\pgfextract@process\rotatedmidpoint{%
			\pgfmathrotatepointaround{\midpoint}{\centerpoint}{-\rotate}%
		}%
		\pgfmathanglebetweenpoints{\rotatedmidpoint}{\tipborderpoint}%
		\let\midangletotip\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedmidpoint}{\tailcenterborderpoint}%
		\let\midangletotailcenter\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedmidpoint}{\lefttailborderpoint}%
		\let\midangletolefttail\pgfmathresult%
		\pgfmathanglebetweenpoints{\rotatedmidpoint}{\righttailborderpoint}%
		\let\midangletorighttail\pgfmathresult%
		%
		% Rotate the background path points.
		%
		\pgfextract@process\tippoint{%
			\pgfmathrotatepointaround{\tippoint}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\tailcenterpoint{%
			\pgfmathrotatepointaround{\tailcenterpoint}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\lefttailpoint{%
			\pgfmathrotatepointaround{\lefttailpoint}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\righttailpoint{%
			\pgfmathrotatepointaround{\righttailpoint}{\centerpoint}{\rotate}%
		}%
		%
		% Calculate a radius guaranteed to be outside the dart.
		%
		\pgfextractx\pgf@xa{\pgfpointdiff{\lefttailborderpoint}{\tipborderpoint}}%
		\pgfextracty\pgf@ya{\pgfpointdiff{\lefttailborderpoint}{\righttailborderpoint}}%
		\ifdim\pgf@xa<0pt\relax%
			\pgf@xa-\pgf@xa%
		\fi%
		\ifdim\pgf@ya<0pt\relax%
			\pgf@ya-\pgf@ya%
		\fi%
		\ifdim\pgf@xa>\pgf@ya%
			\edef\externalradius{\the\pgf@xa}%
		\else%
			\edef\externalradius{\the\pgf@ya}%
		\fi%
		%
		% Rotate the border anchor points.
		%
		\pgfextract@process\tipborderpoint{%
			\pgfmathrotatepointaround{\tipborderpoint}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\tailcenterborderpoint{%
			\pgfmathrotatepointaround{\tailcenterborderpoint}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\lefttailborderpoint{%
			\pgfmathrotatepointaround{\lefttailborderpoint}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\righttailborderpoint{%
			\pgfmathrotatepointaround{\righttailborderpoint}{\centerpoint}{\rotate}%
		}%
		%
		% Save everything.
		%
		\addtosavedmacro{\rotate}%
		\addtosavedmacro{\externalradius}%
		%
		\addtosavedmacro{\tippoint}%
		\addtosavedmacro{\tailcenterpoint}%
		\addtosavedmacro{\lefttailpoint}%
		\addtosavedmacro{\righttailpoint}%
		%
		\addtosavedmacro{\tipborderpoint}%
		\addtosavedmacro{\tailcenterborderpoint}%
		\addtosavedmacro{\lefttailborderpoint}%
		\addtosavedmacro{\righttailborderpoint}%
		%
		\addtosavedmacro{\angletotip}%
		\addtosavedmacro{\angletotailcenter}%
		\addtosavedmacro{\angletolefttail}%
		\addtosavedmacro{\angletorighttail}%
		%
		\addtosavedmacro{\baseangletotip}%
		\addtosavedmacro{\baseangletotailcenter}%
		\addtosavedmacro{\baseangletolefttail}%
		\addtosavedmacro{\baseangletorighttail}%
		%
		\addtosavedmacro{\midangletotip}%
		\addtosavedmacro{\midangletotailcenter}%
		\addtosavedmacro{\midangletolefttail}%
		\addtosavedmacro{\midangletorighttail}%
	}
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}%
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt\relax%
	}%
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+.5ex}%
	}%
	\anchor{center}{\centerpoint}%
	\anchor{base}{\basepoint}%
	\anchor{base west}{%
		\installdartparameters%
		\let\pgf@dartanchorborderreferencepoint\basepoint%
		\csname pgf@anchor@dart@border\endcsname{\pgfqpoint{-\externalradius}{0pt}}%
	}
	\anchor{base east}{%
		\installdartparameters%
		\let\pgf@dartanchorborderreferencepoint\basepoint%
		\csname pgf@anchor@dart@border\endcsname{\pgfqpoint{\externalradius}{0pt}}%
	}
	\anchor{mid}{\midpoint}%
	\anchor{mid west}{%
		\installdartparameters%
		\let\pgf@dartanchorborderreferencepoint\midpoint%
		\csname pgf@anchor@dart@border\endcsname{\pgfqpoint{-\externalradius}{0pt}}%
	}
	\anchor{mid east}{%
		\installdartparameters%
		\let\pgf@dartanchorborderreferencepoint\midpoint%
		\csname pgf@anchor@dart@border\endcsname{\pgfqpoint{\externalradius}{0pt}}%
	}
	\anchor{north}{%
		\installdartparameters%
		\csname pgf@anchor@dart@border\endcsname{\pgfqpoint{0pt}{\externalradius}}%
	}
	\anchor{south}{%
		\installdartparameters%
		\csname pgf@anchor@dart@border\endcsname{\pgfqpoint{0pt}{-\externalradius}}%
	}
	\anchor{east}{%
		\installdartparameters%
		\csname pgf@anchor@dart@border\endcsname{\pgfqpoint{\externalradius}{0pt}}%
	}
	\anchor{west}{%
		\installdartparameters%
		\csname pgf@anchor@dart@border\endcsname{\pgfqpoint{-\externalradius}{0pt}}%
	}
	\anchor{north east}{%
		\installdartparameters%
		\csname pgf@anchor@dart@border\endcsname{\pgfqpoint{\externalradius}{\externalradius}}%
	}
	\anchor{south west}{%
		\installdartparameters%
		\csname pgf@anchor@dart@border\endcsname{\pgfqpoint{-\externalradius}{-\externalradius}}%
	}
	\anchor{south east}{%
		\installdartparameters%
		\csname pgf@anchor@dart@border\endcsname{\pgfqpoint{\externalradius}{-\externalradius}}%
	}
	\anchor{north west}{%
		\installdartparameters%
		\csname pgf@anchor@dart@border\endcsname{\pgfqpoint{-\externalradius}{\externalradius}}%
	}
	\anchor{tip}{%
		\installdartparameters%
		\tipborderpoint}
	\anchor{left tail}{%
		\installdartparameters%
		\lefttailborderpoint}
	\anchor{right tail}{%
		\installdartparameters%
		\righttailborderpoint}
	\anchor{tail center}{%
		\installdartparameters%
		\tailcenterborderpoint}
	\anchor{left side}{%
		\installdartparameters%
		\pgfpointlineattime{0.5}{\tipborderpoint}{\lefttailborderpoint}}
	\anchor{right side}{%
		\installdartparameters%
		\pgfpointlineattime{0.5}{\tipborderpoint}{\righttailborderpoint}}
	\backgroundpath{%
		\installdartparameters%
		\pgfpathmoveto{\tippoint}%
		\pgfpathlineto{\lefttailpoint}%
		\pgfpathlineto{\tailcenterpoint}%
		\pgfpathlineto{\righttailpoint}%
		\pgfpathclose%
	}
	\anchorborder{%
		%
		% Save x and y.
		%
		\edef\externalx{\the\pgf@x}%
		\edef\externaly{\the\pgf@y}%
		%
		% This allows anchors base east, base west, mid east and mid west,
		% to redefine the `center' of the node to correctly calculate the
		% border points.
		%
		\pgfutil@ifundefined{pgf@dartanchorborderreferencepoint}%
			{\let\referencepoint\centerpoint}%
			{\let\referencepoint\pgf@dartanchorborderreferencepoint}%
		%
		% Adjust the location of the external 
		% point relative to the reference point.
		%
		\referencepoint%
		\pgf@xa\externalx\relax%
		\pgf@ya\externaly\relax%
		\advance\pgf@xa\pgf@x%
		\advance\pgf@ya\pgf@y%
		\edef\externalx{\the\pgf@xa}%
		\edef\externaly{\the\pgf@ya}%
		%
		% Install the required points and angles.
		%
		\installdartparameters%
		%
		% Get the angle of the external point relative to \referencepoint.
		%
		\pgfmathanglebetweenpoints{\referencepoint}{\pgfqpoint{\externalx}{\externaly}}%
		%
		% *Subtract* the rotation from the external angle.
		%
		\pgfmathsubtract@{\pgfmathresult}{\rotate}%
		\ifdim\pgfmathresult pt<0pt\relax%
			\pgfmathadd@{\pgfmathresult}{360}%
		\fi%
		\let\externalangle\pgfmathresult%
		%
		% Get the set of angles for the appropriate border point.
		%
		\ifx\referencepoint\basepoint%
			\let\angletotip\baseangletotip%
			\let\angletotailcenter\baseangletotailcenter%
			\let\angletolefttail\baseangletolefttail%
			\let\angletorighttail\baseangletorighttail%
		\else%
			\ifx\referencepoint\midpoint%
				\let\angletotip\midangletotip%
				\let\angletotailcenter\midangletotailcenter%
				\let\angletolefttail\midangletolefttail%
				\let\angletorighttail\midangletorighttail%
		\fi\fi%
		%
		% Locate the appropriate line on the border...
		%
		\ifdim\externalangle pt<\angletotip pt\relax%
			\let\firstpoint\tipborderpoint%
			\let\secondpoint\righttailborderpoint%
		\else%
			\ifdim\externalangle pt<\angletolefttail pt\relax%
				\let\firstpoint\lefttailborderpoint%
				\let\secondpoint\tipborderpoint%
			\else%
				\ifdim\externalangle pt<\angletotailcenter pt\relax%
					\let\firstpoint\lefttailborderpoint%
					\let\secondpoint\tailcenterborderpoint%
				\else%
					\ifdim\externalangle pt<\angletorighttail pt\relax%
						\let\firstpoint\righttailborderpoint%
						\let\secondpoint\tailcenterborderpoint%
					\else%
						\let\firstpoint\tipborderpoint%
						\let\secondpoint\righttailborderpoint%
					\fi%
				\fi%
			\fi%
		\fi%
		%
		% ...and thus the point on the border.
		%
		\pgfpointintersectionoflines{\referencepoint}{\pgfqpoint{\externalx}{\externaly}}%
				{\firstpoint}{\secondpoint}%
	}%
}



% Keys for shape circular sector:
%
% /pgf/circular sector angle : the angle at the center of the sector.
%
\pgfkeys{/pgf/circular sector angle/.initial=60}

% Shape circular sector
%
\pgfdeclareshape{circular sector}{%
	\savedmacro\installcircularsectorparameters{%
		%
		% Define a \centerpoint, \basepoint and \midpoint.
		%
		\pgfextract@process\centerpoint{%
			\pgf@x.5\wd\pgfnodeparttextbox%
			\pgf@y.5\ht\pgfnodeparttextbox%
			\advance\pgf@y-.5\dp\pgfnodeparttextbox%
		}%
		%
		% Get the larger of the outer sep.
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/outer ysep}}%
		\ifdim\pgf@x<\pgf@y%
			\pgf@x\pgf@y%
		\fi%
		\edef\outersep{\the\pgf@x}%
		%
		% Half of the sector angle is more useful.
		%
		\pgfmathmod{\pgfkeysvalueof{/pgf/circular sector angle}}{360}%
		\ifdim\pgfmathresult pt<0pt\relax%
			\pgfmathadd@{\pgfmathresult}{360}%
		\fi%
		\let\angle\pgfmathresult%
		\pgfmathdivide@{\pgfmathresult}{2}%
		\let\halfangle\pgfmathresult%
		%
		% Get some useful trigonometric stuff.
		%
		\pgfmathsin@{\halfangle}%
		\let\sinehalfangle\pgfmathresult%
		\pgfmathreciprocal@{\pgfmathresult}%
		\let\cosechalfangle\pgfmathresult%
		\pgfmathabs@{\halfangle}%
		\pgfmathcos@{\pgfmathresult}%
		\let\coshalfangle\pgfmathresult%
		\pgf@x\pgfmathresult pt\relax%
		\pgf@x\cosechalfangle\pgf@x%
		\edef\cothalfangle{\pgfmath@tonumber{\pgf@x}}%
		%
		% Calculate the miter length at the center, 
		% according to the outer sep.
		%
		\pgf@x\outersep\relax%
		\pgf@x\cosechalfangle\pgf@x%
		\edef\centermiter{\the\pgf@x}%
		%
		% Get the start and end angles of the arc.
		%
		\pgfmathsubtract@{180}{\halfangle}%
		\let\startangle\pgfmathresult%
		\pgfmathadd@{180}{\halfangle}%
		\let\endangle\pgfmathresult%
		%
		% Get (half) the node dimensions.
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
		\advance\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
		\advance\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y.5\dp\pgfnodeparttextbox%
		%
		% Calculate the radius of the sector and the `center offset', 
		% which is the distance between the center of the node and the 
		% center of the sector.
		%
		\ifpgfshapeborderusesincircle%
			%
			% Get the rotation.
			%
			\pgfmathsetmacro\rotate{\pgfkeysvalueof{/pgf/shape border rotate}}%
			%
			% Calculate the incircle radius.
			%	
			\ifdim\pgf@x<\pgf@y%
				\pgf@x\pgf@y%
			\fi%
			\pgf@x1.41421\pgf@x%
			\pgf@xa\cosechalfangle\pgf@x% 
			%
			% xa is the radius, xb the offset.
			%
			\pgf@xb\pgf@xa%
			\advance\pgf@xa\pgf@x%
		\else%
			%
			% Get the rotation (with rounding).
			%
			\pgfmathmod{\pgfkeysvalueof{/pgf/shape border rotate}}{360}%
			\afterassignment\pgfmath@gobbletilpgfmath@%
			\expandafter\c@pgf@counta\pgfmathresult\relax\pgfmath@%
			\advance\c@pgf@counta45\relax%
			\divide\c@pgf@counta90\relax%
			\multiply\c@pgf@counta90\relax%
			\ifnum\c@pgf@counta<0\relax%
				\advance\c@pgf@counta360\relax%
			\fi%
			\edef\rotate{\the\c@pgf@counta}%
			%
			% Swap the height and width for relevant angles.
			%
			\ifnum\c@pgf@counta=90\relax%
				\pgf@xc\pgf@x%
				\pgf@x\pgf@y%
				\pgf@y\pgf@xc%
			\else%
				\ifnum\c@pgf@counta=270\relax%
					\pgf@xc\pgf@x%
					\pgf@x\pgf@y%
					\pgf@y\pgf@xc%
				\fi%
			\fi%
			%
			% xa is the radius, xb the offset.
			%
			\pgf@xa\cosechalfangle\pgf@y%
			\pgf@xa\coshalfangle\pgf@xa%
			\advance\pgf@xa\pgf@x%
			\pgf@xb\pgf@xa% 
			\advance\pgf@xa\pgf@x%
			\pgfmathveclen@{\pgfmath@tonumber{\pgf@xa}}{\pgfmath@tonumber{\pgf@y}}%
			\pgf@xa\pgfmathresult pt\relax% 
		\fi%
		%
		% Adjust for minimum height and width.
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/minimum width}}%
		\pgf@x.5\pgf@x%
		\pgfmathsec@{\halfangle}%
		\pgf@xc\pgfmathresult\pgf@xb%
		\ifdim\pgf@xc<0pt\relax%
			\pgf@xc-\pgf@xc%
		\fi%
		\ifdim\pgf@xc<\pgf@x%
			\pgfmathreciprocal{\pgfmath@tonumber{\pgf@xc}}% 
			\pgf@xc\pgfmathresult\pgf@x% Increase by ratio.
			\pgf@xa\pgfmath@tonumber{\pgf@xc}\pgf@xa%
			\pgf@xb\pgfmath@tonumber{\pgf@xc}\pgf@xb%
		\fi%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/minimum height}}%
		\ifdim\pgf@xa<\pgf@y%
			\pgfmathreciprocal{\pgfmath@tonumber{\pgf@xa}}%
			\pgf@xc\pgfmathresult\pgf@y% Increase by ratio.
			\pgf@xa\pgf@y%
			\pgf@xb\pgfmath@tonumber{\pgf@xc}\pgf@xb%
		\fi%
		\edef\centeroffset{\the\pgf@xb}%
		\edef\radius{\the\pgf@xa}%
		%
		% Calculate the radius at sector border and the arc corners.
		%
		\advance\pgf@xa\outersep\relax%
		\edef\borderradius{\the\pgf@xa}%
		\pgf@x\outersep\relax%
		\pgf@x\cosechalfangle\pgf@x%
		\pgf@x\coshalfangle\pgf@x%
		\advance\pgf@xa\pgf@x%		
		\edef\cornerradius{\the\pgf@xa}%
		%
		% Calculate the *unrotated* points for the background path.
		%
		\pgfextract@process\sectorcenter{%
			\centerpoint%
			\advance\pgf@x\centeroffset%
		}%
		\pgfextract@process\arcstart{%
			\pgfqpointpolar{\startangle}{\radius}%
			\pgf@xa\pgf@x%
			\pgf@ya\pgf@y%
			\sectorcenter%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y\pgf@ya%
		}%
		%
		% Calculate the *unrotated* points for the anchor border.
		%
		\pgfextract@process\sectorcenterborder{%
			\sectorcenter%
			\advance\pgf@x\centermiter\relax%
		}%
		\pgfextract@process\arcstartborder{%
			\pgfqpointpolar{\startangle}{\borderradius}%
			\pgf@xa\pgf@x%
			\pgf@ya\pgf@y%
			\sectorcenter%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y\pgf@ya%
		}%
		\pgfextract@process\arcendborder{%
			\pgfqpointpolar{\endangle}{\borderradius}%
			\pgf@xa\pgf@x%
			\pgf@ya\pgf@y%
			\sectorcenter%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y\pgf@ya%
		}%
		\pgfextract@process\arcstartcorner{%
			\pgfqpointpolar{\startangle}{\cornerradius}%
			\pgf@xa\pgf@x%
			\pgf@ya\pgf@y%
			\sectorcenterborder%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y\pgf@ya%
		}%
		\pgfextract@process\arcendcorner{%
			\pgfqpointpolar{\endangle}{\cornerradius}%
			\pgf@xa\pgf@x%
			\pgf@ya\pgf@y%
			\sectorcenterborder%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y\pgf@ya%
		}%
		%
		% Calculate the *unrotated* corner angles to the \centerpoint.
		%
		\pgfmathanglebetweenpoints{\centerpoint}{\sectorcenterborder}%
		\let\angletosectorcenterborder\pgfmathresult%
		\pgfmathanglebetweenpoints{\centerpoint}{\arcstartborder}%
		\let\angletoarcstartborder\pgfmathresult%
		\pgfmathanglebetweenpoints{\centerpoint}{\arcendborder}%
		\let\angletoarcendborder\pgfmathresult%
		\pgfmathanglebetweenpoints{\centerpoint}{\arcstartcorner}%
		\let\angletoarcstartcorner\pgfmathresult%
		\pgfmathanglebetweenpoints{\centerpoint}{\arcendcorner}%
		\let\angletoarcendcorner\pgfmathresult%
		%
		% Rotate the background path points around the note center.
		%
		\pgfextract@process\sectorcenter{%
			\pgfmathrotatepointaround{\sectorcenter}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\arcstart{%
			\pgfmathrotatepointaround{\arcstart}{\centerpoint}{\rotate}%
		}%
		%
		% Rotate the border points around the note center.
		%
		\pgfextract@process\sectorcenterborder{%
			\pgfmathrotatepointaround{\sectorcenterborder}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\arcstartborder{%
			\pgfmathrotatepointaround{\arcstartborder}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\arcendborder{%
			\pgfmathrotatepointaround{\arcendborder}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\arcstartcorner{%
			\pgfmathrotatepointaround{\arcstartcorner}{\centerpoint}{\rotate}%
		}%
		\pgfextract@process\arcendcorner{%
			\pgfmathrotatepointaround{\arcendcorner}{\centerpoint}{\rotate}%
		}%
		%
		% Add the rotation to the start and end angles.
		%
		\pgfmathadd@{\startangle}{\rotate}%
		\let\startangle\pgfmathresult%
		\pgfmathadd@{\endangle}{\rotate}%
		\let\endangle\pgfmathresult%
		%
		% Save everything. 
		%
		% NB \addtosavedmacro is currently experimental. May get changed.
		%
		\addtosavedmacro{\rotate}%
		\addtosavedmacro{\centeroffset}%
		%
		\addtosavedmacro{\radius}%
		\addtosavedmacro{\borderradius}%
		\addtosavedmacro{\cornerradius}%
		%
		\addtosavedmacro{\endangle}%
		\addtosavedmacro{\startangle}%
		%
		\addtosavedmacro{\sectorcenter}%
		\addtosavedmacro{\arcstart}%
		%
		\addtosavedmacro{\sectorcenterborder}%
		\addtosavedmacro{\arcstartborder}%
		\addtosavedmacro{\arcendborder}%
		\addtosavedmacro{\arcstartcorner}%
		\addtosavedmacro{\arcendcorner}%
		%
		\addtosavedmacro{\angletosectorcenterborder}%
		\addtosavedmacro{\angletoarcstartborder}%
		\addtosavedmacro{\angletoarcendborder}%
		\addtosavedmacro{\angletoarcstartcorner}%
		\addtosavedmacro{\angletoarcendcorner}%
	}%
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}%
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt\relax%
	}%
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+.5ex}%
	}%
	\anchor{center}{\centerpoint}
	\anchor{base}{\basepoint}
	\anchor{mid}{\midpoint}	
	\anchor{arc start}{%
		\installcircularsectorparameters%
		\arcstartcorner%
	}
	\anchor{arc end}{%
		\installcircularsectorparameters%
		\arcendcorner%
	}
	\anchor{sector center}{%
		\installcircularsectorparameters%
		\sectorcenterborder%
	}
	\anchor{arc center}{%
		\installcircularsectorparameters%
		\pgfmathadd@{\rotate}{180}%
		\let\angle\pgfmathresult%
		\csname pgf@anchor@circular sector@border\endcsname{\pgfqpointpolar{\angle}{\cornerradius}}%
	}
	\anchor{north}{%
		\installcircularsectorparameters%
		\csname pgf@anchor@circular sector@border\endcsname{\pgfqpoint{0pt}{\cornerradius}}%
	}
	\anchor{south}{%
		\installcircularsectorparameters%
		\csname pgf@anchor@circular sector@border\endcsname{\pgfqpoint{0pt}{-\cornerradius}}%
	}
	\anchor{east}{%
		\installcircularsectorparameters%
		\csname pgf@anchor@circular sector@border\endcsname{\pgfqpoint{\cornerradius}{0pt}}%
	}
	\anchor{west}{%
		\installcircularsectorparameters%
		\csname pgf@anchor@circular sector@border\endcsname{\pgfqpoint{-\cornerradius}{0pt}}%
	}
	\anchor{north west}{%
		\installcircularsectorparameters%
		\csname pgf@anchor@circular sector@border\endcsname{\pgfqpoint{-\cornerradius}{\cornerradius}}%
	}
	\anchor{south west}{%
		\installcircularsectorparameters%
		\csname pgf@anchor@circular sector@border\endcsname{\pgfqpoint{-\cornerradius}{-\cornerradius}}%
	}
	\anchor{north east}{%
		\installcircularsectorparameters%
		\csname pgf@anchor@circular sector@border\endcsname{\pgfqpoint{\cornerradius}{\cornerradius}}%
	}
	\anchor{south east}{%
		\installcircularsectorparameters%
		\csname pgf@anchor@circular sector@border\endcsname{\pgfqpoint{\cornerradius}{-\cornerradius}}%
	}
	\backgroundpath{%
		\installcircularsectorparameters%
		\pgfpathmoveto{\sectorcenter}%
		\pgfpathlineto{\arcstart}%
		\ifdim\endangle pt>360pt\relax%
			\ifdim\startangle pt>360pt\relax%
				\pgfpatharc{\startangle}{\endangle}{\radius}%
			\else%
				\pgfpatharc{\startangle}{360}{\radius}%
				\pgfpatharc{0}{\endangle}{\radius}%
			\fi%
		\else%
			\pgfpatharc{\startangle}{\endangle}{\radius}%
		\fi%
		\pgfpathclose%
	}%
	\anchorborder{%
		%
		% Save x and y.
		%
		\edef\externalx{\the\pgf@x}%
		\edef\externaly{\the\pgf@y}%
		%
		% Adjust the location of the external  point relative to \centerpoint.
		%
		\centerpoint%
		\pgf@xa\externalx\relax%
		\pgf@ya\externaly\relax%
		\advance\pgf@xa\pgf@x%
		\advance\pgf@ya\pgf@y%
		\edef\externalx{\the\pgf@xa}%
		\edef\externaly{\the\pgf@ya}%
		%
		% Install the required points and angles.
		%
		\installcircularsectorparameters%
		%
		% Get the angle of the external point to the \centerpoint.
		%
		\pgfmathanglebetweenpoints{\centerpoint}{\pgfqpoint{\externalx}{\externaly}}%
		\let\externalangle\pgfmathresult%
		%
		% *Subtract* the rotation from the external angle.
		%
		\pgfmathsubtract@{\pgfmathresult}{\rotate}%
		\ifdim\pgfmathresult pt<0pt\relax%
			\pgfmathadd@{\pgfmathresult}{360}%
		\fi%
		\let\angle\pgfmathresult%
		%
		% Determine if the line will cross the sector arc.
		% 
		\ifdim\angle pt>\angletoarcendcorner pt\relax%
			\let\firstpoint\arcendcorner%
			\let\secondpoint\sectorcenterborder%
		\else%
			\ifdim\angle pt>\angletoarcendborder pt\relax%
				\let\firstpoint\arcendborder%
				\let\secondpoint\arcendcorner%
			\else%
				\ifdim\angle pt>\angletoarcstartborder pt\relax%
					\let\firstpoint\pgfutil@empty%
					\let\secondpoint\pgfutil@empty%
				\else%
					\ifdim\angle pt>\angletoarcstartcorner pt\relax%
						\let\firstpoint\arcstartborder
						\let\secondpoint\arcstartcorner
					\else%		
						\let\firstpoint\sectorcenterborder%
						\let\secondpoint\arcstartcorner%
					\fi%
				\fi%
			\fi%
		\fi%
		\ifx\firstpoint\pgfutil@empty
			%
			% Calculate the angle from the centre of the semicircle to the
			% point on the semicircle arc which intersects the line from 
			% the external point to the reference point...
			%
			\pgfmathanglebetweenlines{\centerpoint}{\pgfqpoint{\externalx}{\externaly}}%
				{\sectorcenter}{\centerpoint}%
			\pgfmathsin@{\pgfmathresult}%
			\let\sineangle\pgfmathresult%
			\pgf@x\borderradius\relax%
			\pgfmathreciprocal@{\pgfmath@tonumber{\pgf@x}}%
			\let\reciprocalradius\pgfmathresult%
			\pgf@x\centeroffset\relax%
			\pgf@x\sineangle\pgf@x%
			\pgf@x\reciprocalradius\pgf@x%
			\pgfmathasin@{\pgfmath@tonumber{\pgf@x}}%
			\pgf@x\pgfmathresult pt\relax%
			\advance\pgf@x\externalangle pt\relax%
			\edef\angle{\pgfmath@tonumber{\pgf@x}}%
			%
			% ...and thus the point on the border.
			%
			\pgfpointadd{\sectorcenter}{\pgfqpointpolar{\angle}{\borderradius}}%
		\else%
			%
			% Calculate the the point where the semicircle chord intersects 
			% the line from the external point to the reference point.
			%
			\pgfpointintersectionoflines{\centerpoint}{\pgfqpoint{\externalx}{\externaly}}%
				{\firstpoint}{\secondpoint}%
		\fi%		
	}%
}



% Keys for shape cylinder
%
% /pgf/shape aspect              : Ratio between the x and y radii of the cylinder end.
% /pgf/cylinder uses custom fill : Use a custom fill for the cylinder.
% /pgf/cylinder end fill         : Custom color for the cylinder end.
% /pgf/cylinder body fill        : Custom color for the cylinderbody.
%

\newif\ifpgfcylinderusescustomfill
\pgfkeys{/pgf/.cd,
	cylinder uses custom fill/.is if=pgfcylinderusescustomfill,
	cylinder end fill/.initial=white,
	cylinder body fill/.initial=white
}


\pgfdeclareshape{cylinder}{%
	\savedmacro\getcylinderpoints{%
		\pgfmathsetlength\pgf@xc{\pgfkeysvalueof{/pgf/inner xsep}}%
		\pgf@x\pgf@xc%
		\advance\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@yc{\pgfkeysvalueof{/pgf/inner ysep}}%
		\pgf@y\pgf@yc%
		\advance\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y.5\dp\pgfnodeparttextbox%
		\ifpgfshapeborderusesincircle%
			\pgfmathsetmacro\rotate{\pgfkeysvalueof{/pgf/shape border rotate}}%
			\ifdim\pgf@x<\pgf@y%
				\pgf@x\pgf@y%
			\else%
				\pgf@y\pgf@x%
			\fi%
			\pgf@x1.414213\pgf@x%
			\pgf@y1.414213\pgf@y%			
		\else%
			\pgfmathmod{\pgfkeysvalueof{/pgf/shape border rotate}}{360}%
			\ifdim\pgfmathresult pt<0pt\relax%
				\pgfmathadd@{\pgfmathresult}{360}%
			\fi%
			\pgfmathsetcount\c@pgf@counta{+\pgfmathresult}%
			\advance\c@pgf@counta45\relax%
			\divide\c@pgf@counta90\relax%
			\multiply\c@pgf@counta90\relax%
			\edef\rotate{\the\c@pgf@counta}%
			\ifnum\c@pgf@counta=90\relax%
				\pgf@xa\pgf@x%
				\pgf@x\pgf@y%
				\pgf@y\pgf@xa%
				\pgf@yc\pgf@xc%
			\else%
				\ifnum\c@pgf@counta=270\relax%
					\pgf@xa\pgf@x%
					\pgf@x\pgf@y%
					\pgf@y\pgf@xa%
					\pgf@yc\pgf@xc%
				\fi%
			\fi%
		\fi%
		\addtosavedmacro\rotate%
		\pgf@xa\pgf@x%
		\pgf@ya\pgf@y%
		\pgfutil@tempdima\pgfshapeaspect\pgf@ya%
		\pgfutil@tempdimb\pgf@ya%
		%
		% Adjust for minimum height.
		%
		\pgfmathsetlength\pgf@xc{\pgfkeysvalueof{/pgf/minimum width}}%
		\ifdim\pgfutil@tempdimb<.5\pgf@xc\relax%
			\pgfutil@tempdimb.5\pgf@xc%
			\pgf@ya\pgfutil@tempdimb%
		\fi%
		%
		% Calculate how far the node contents can extend into the cylinder bottom.
		%
		\pgf@yb\pgfutil@tempdimb%
		\advance\pgf@yb-\pgf@yc%
		\pgfmathdivide@{\pgfmath@tonumber{\pgf@yb}}{\pgfmath@tonumber{\pgfutil@tempdimb}}%
		\pgfmathasin@{\pgfmathresult}%
		\pgfmathcos@{\pgfmathresult}%
		\let\angle\pgfmathresult%
		\pgf@xb\pgfmathresult\pgfutil@tempdima%
		%
		% Adjust for minimum width.
		%
		\pgf@x.5\pgflinewidth%
		\advance\pgf@x2.0\pgf@xa%
		\advance\pgf@x3.0\pgfutil@tempdima%
		\advance\pgf@x-\pgf@xb%
		\pgfmathsetlength\pgf@xc{\pgfkeysvalueof{/pgf/minimum height}}%
		\ifdim\pgf@x<\pgf@xc%
			\advance\pgf@xc-\pgf@x%
			\advance\pgf@xa.5\pgf@xc%
		\fi%		
		%
		% Add the larger of the outer sep to the radii.
		%
		\pgf@x\pgfutil@tempdima\relax%
		\pgf@y\pgfutil@tempdimb\relax%
		\pgfmathsetlength\pgf@xc{\pgfkeysvalueof{/pgf/outer xsep}}%
		\pgfmathsetlength\pgf@yc{\pgfkeysvalueof{/pgf/outer ysep}}%
		\ifdim\pgf@xc>\pgf@yc%
			\advance\pgf@x\pgf@xc%
			\advance\pgf@y\pgf@xc%
			\edef\outersep{\the\pgf@xc}%
		\else%
			\advance\pgf@x\pgf@yc%
			\advance\pgf@y\pgf@yc%
			\edef\outersep{\the\pgf@yc}%
		\fi%
		\edef\xradius{\the\pgf@x}%
		\edef\yradius{\the\pgf@y}%
		\addtosavedmacro\xradius%
		\addtosavedmacro\yradius%
		\addtosavedmacro\outersep%
		%
		\pgfextract@process\cylindercenter{%
			\pgf@x\pgfutil@tempdima%
			\advance\pgf@x.5\pgflinewidth%
			\advance\pgf@x\pgf@xb%
			\pgf@x.5\pgf@x%	
			\pgf@y0pt%
		}%
		\addtosavedmacro\cylindercenter%
		%
		\pgfextract@process\beforetop{%
			\pgf@x\pgf@xa%
			\advance\pgf@x\pgfutil@tempdima%
			\advance\pgf@x.5\pgflinewidth%
			\pgf@y\pgf@ya%
		}%
		\pgfextract@process\afterbottom{%
			\pgf@x-\pgf@xa%
			\advance\pgf@x\pgf@xb%
			\pgf@y\pgf@ya%
		}%
		\addtosavedmacro\beforetop%
		\addtosavedmacro\afterbottom%		
		\pgfmathsetlength\pgf@yc{\pgfkeysvalueof{/pgf/outer ysep}}%
		\pgfextract@process\beforetopanchor{%
			\beforetop%
			\advance\pgf@y\pgf@yc%
		}%
		\pgfextract@process\afterbottomanchor{%
			\afterbottom%
			\advance\pgf@y\pgf@yc%
		}%
		\addtosavedmacro\beforetopanchor%		
		\addtosavedmacro\afterbottomanchor%	
		%
		\beforetopanchor%
		\advance\pgf@x\xradius\relax%
		\ifdim\pgf@x>\pgf@y%
			\edef\externalradius{\the\pgf@x}%
		\else%
			\edef\externalradius{\the\pgf@y}%
		\fi%
		\addtosavedmacro\externalradius%
	}
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}%
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+0.5ex}%
	}%
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt%
	}%
	\anchor{center}{\centerpoint}
	\anchor{shape center}{%
		\getcylinderpoints%
		\pgfmathrotatepointaround{\pgfpointadd{\cylindercenter}{\centerpoint}}%
			{\centerpoint}{\rotate}%	
	}%
	\anchor{mid}{\midpoint}%
	\anchor{mid east}{%
		\getcylinderpoints%
		\let\pgf@cylinder@referencepoint\midpoint%
		\pgf@anchor@cylinder@border{\pgfqpoint{\externalradius}{0pt}}%
	}%
	\anchor{mid west}{%
		\getcylinderpoints%
		\let\pgf@cylinder@referencepoint\midpoint%
		\pgf@anchor@cylinder@border{\pgfqpoint{-\externalradius}{0pt}}%
	}%
	\anchor{base}{\basepoint}%
	\anchor{base east}{%
		\getcylinderpoints%
		\let\pgf@cylinder@referencepoint\basepoint%
		\pgf@anchor@cylinder@border{\pgfqpoint{\externalradius}{0pt}}%
	}%
	\anchor{base west}{%
		\getcylinderpoints%
		\let\pgf@cylinder@referencepoint\basepoint%
		\pgf@anchor@cylinder@border{\pgfqpoint{-\externalradius}{0pt}}%
	}%
	\anchor{north}{%
		\getcylinderpoints%
		\pgf@anchor@cylinder@border{\pgfqpoint{0pt}{\externalradius}}%
	}%
	\anchor{south}{%
		\getcylinderpoints%
		\pgf@anchor@cylinder@border{\pgfqpoint{0pt}{-\externalradius}}%
	}%
	\anchor{east}{%
		\getcylinderpoints%
		\pgf@anchor@cylinder@border{\pgfqpoint{\externalradius}{0pt}}%
	}%
	\anchor{west}{%
		\getcylinderpoints%
		\pgf@anchor@cylinder@border{\pgfqpoint{-\externalradius}{0pt}}%
	}%
	\anchor{north east}{%
		\getcylinderpoints%
		\pgf@anchor@cylinder@border{\pgfqpoint{\externalradius}{\externalradius}}%
	}%
	\anchor{south west}{%
		\getcylinderpoints%
		\pgf@anchor@cylinder@border{\pgfqpoint{-\externalradius}{-\externalradius}}%
	}%
	\anchor{south east}{%
		\getcylinderpoints%
		\pgf@anchor@cylinder@border{\pgfqpoint{\externalradius}{-\externalradius}}%
	}%
	\anchor{north west}{%
		\getcylinderpoints%
		\pgf@anchor@cylinder@border{\pgfqpoint{-\externalradius}{\externalradius}}%
	}%
	\anchor{before top}{%
		\getcylinderpoints%
		\pgfmathrotatepointaround{\pgfpointadd{\beforetopanchor}{\centerpoint}}{\centerpoint}{\rotate}%
	}
	\anchor{top}{%
		\getcylinderpoints%
		\pgfmathrotatepointaround{%
			\pgfpointadd{%
				\beforetop%
				\pgf@y0pt\relax%
				\advance\pgf@x\xradius\relax%
			}{\centerpoint}}{\centerpoint}{\rotate}%
	}
	\anchor{after top}{%
		\getcylinderpoints%
		\pgfmathrotatepointaround{\pgfpointadd{\beforetopanchor\pgf@y-\pgf@y}{\centerpoint}}{\centerpoint}{\rotate}%
	}
	\anchor{before bottom}{%
		\getcylinderpoints%
		\pgfmathrotatepointaround{\pgfpointadd{\afterbottomanchor\pgf@y-\pgf@y}{\centerpoint}}{\centerpoint}{\rotate}%
	}
	\anchor{bottom}{%
		\getcylinderpoints%
		\pgfmathrotatepointaround{%
			\pgfpointadd{%
				\afterbottom%
				\pgf@y0pt\relax%
				\advance\pgf@x-\xradius\relax%
			}{\centerpoint}}{\centerpoint}{\rotate}%
	}
	\anchor{after bottom}{%
		\getcylinderpoints%
		\pgfmathrotatepointaround{\pgfpointadd{\afterbottomanchor}{\centerpoint}}{\centerpoint}{\rotate}%
	}	
	\backgroundpath{%
		\getcylinderpoints%
		{%
			\pgf@x\xradius\relax%
			\advance\pgf@x-\outersep\relax%
			\edef\xradius{\the\pgf@x}%
			\pgf@y\yradius\relax%
			\advance\pgf@y-\outersep\relax%
			\edef\yradius{\the\pgf@y}%
			\pgftransformshift{\centerpoint}%
			\pgftransformrotate{\rotate}%
			\pgfpathmoveto{\afterbottom}%
			\pgfpatharc{90}{270}{\xradius and \yradius}%
			\pgfpathlineto{\beforetop\pgf@y-\pgf@y}%
			\pgfpatharc{-90}{90}{\xradius and \yradius}%
			\pgfpathclose%
			\pgfpathmoveto{\beforetop}%
			\pgfpatharc{90}{270}{\xradius and \yradius}%
		}%
	}%
	\behindbackgroundpath{%
		\ifpgfcylinderusescustomfill%
			\getcylinderpoints%
			\pgf@x\xradius\relax%
			\advance\pgf@x-\outersep\relax%
			\edef\xradius{\the\pgf@x}%
			\pgf@y\yradius\relax%
			\advance\pgf@y-\outersep\relax%
			\edef\yradius{\the\pgf@y}%
			{%				
				\pgftransformshift{\centerpoint}%
				\pgftransformrotate{\rotate}%
				\pgfpathmoveto{\afterbottom}%
				\pgfpatharc{90}{270}{\xradius and \yradius}%
				\pgfpathlineto{\beforetop\pgf@y-\pgf@y}%
				\pgfpatharc{270}{90}{\xradius and \yradius}%
				\pgfpathclose%
				\expandafter\pgfsetfillcolor\expandafter{\pgfkeysvalueof{/pgf/cylinder body fill}}%
				\pgfusepath{fill}%
				%
				\pgfpathmoveto{\beforetop}%
				\pgfpatharc{90}{-270}{\xradius and \yradius}%
				\pgfpathclose
				\expandafter\pgfsetfillcolor\expandafter{\pgfkeysvalueof{/pgf/cylinder end fill}}%
				\pgfusepath{fill}%
			}%		
		\fi%	
	}%
	\anchorborder{%
		\pgfextract@process\externalpoint{}%
		\getcylinderpoints%
		\pgfutil@ifundefined{pgf@cylinder@referencepoint}{\let\referencepoint\centerpoint}{%
			\let\referencepoint\pgf@cylinder@referencepoint}%
		\pgfextract@process\externalpoint{%
			\externalpoint%
			\pgf@xa\pgf@x%
			\pgf@ya\pgf@y%
			\referencepoint%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y\pgf@ya%
		}%
		\pgfmathanglebetweenpoints{\centerpoint}{\externalpoint}%
		\pgfmathsubtract@{\pgfmathresult}{\rotate}%
		\ifdim\pgfmathresult pt<0pt\relax%
			\pgfmathadd@{\pgfmathresult}{360}%
		\fi%
		\let\externalangle\pgfmathresult%
		%
		\pgfmathanglebetweenpoints{\referencepoint}{\pgfpointadd{\afterbottomanchor}{\centerpoint}}%
		\ifdim\externalangle pt<\pgfmathresult pt\relax%
			\pgfmathanglebetweenpoints{\referencepoint}{\pgfpointadd{\beforetopanchor}{\centerpoint}}%
			\ifdim\externalangle pt<\pgfmathresult pt\relax%
				\pgfmathrotatepointaround{%
					\pgfmathpointintersectionoflineandarc%
						{\pgfmathrotatepointaround{\externalpoint}{\centerpoint}{-\rotate}}%
						{\pgfmathrotatepointaround{\referencepoint}{\centerpoint}{-\rotate}}%
						{%
							\beforetop%
							\pgf@xa\pgf@x%
							\centerpoint%
							\advance\pgf@x\pgf@xa%
						}%
						{0}{90}{\xradius and \yradius}%
					}{\centerpoint}{\rotate}%
			\else%
				\pgfpointintersectionoflines{%
					\pgfmathrotatepointaround{\pgfpointadd{\afterbottomanchor}{\centerpoint}}%
						{\centerpoint}{\rotate}}{%
					\pgfmathrotatepointaround{\pgfpointadd{\beforetopanchor}{\centerpoint}}%
						{\centerpoint}{\rotate}}%
					{\referencepoint}{\externalpoint}%
			\fi%
		\else%
			\pgfmathanglebetweenpoints{\referencepoint}{\pgfpointadd{\afterbottomanchor\pgf@y-\pgf@y}{\centerpoint}}%
			\ifdim\externalangle pt>\pgfmathresult pt\relax%
				\pgfmathanglebetweenpoints{\referencepoint}{\pgfpointadd{\beforetopanchor\pgf@y-\pgf@y}{\centerpoint}}%
				\ifdim\externalangle pt>\pgfmathresult pt\relax%
					\pgfmathrotatepointaround{%
						\pgfmathpointintersectionoflineandarc%
							{\pgfmathrotatepointaround{\externalpoint}{\centerpoint}{-\rotate}}%
							{\pgfmathrotatepointaround{\referencepoint}{\centerpoint}{-\rotate}}%
							{%
								\beforetop%
								\pgf@xa\pgf@x%
								\centerpoint
								\advance\pgf@x\pgf@xa%
							}%
							{270}{360}{\xradius and \yradius}%
						}{\centerpoint}{\rotate}%
				\else%
					\pgfpointintersectionoflines{%
						\pgfmathrotatepointaround{\pgfpointadd{\afterbottomanchor\pgf@y-\pgf@y}{\centerpoint}}%
							{\centerpoint}{\rotate}}{%
						\pgfmathrotatepointaround{\pgfpointadd{\beforetopanchor\pgf@y-\pgf@y}{\centerpoint}}%
							{\centerpoint}{\rotate}}%
						{\referencepoint}{\externalpoint}%
				\fi%
			\else%
				\pgfmathrotatepointaround{%
					\pgfmathpointintersectionoflineandarc%
						{\pgfmathrotatepointaround{\externalpoint}{\centerpoint}{-\rotate}}%
						{\pgfmathrotatepointaround{\referencepoint}{\centerpoint}{-\rotate}}%
						{%
							\afterbottom%
							\pgf@xa\pgf@x%
							\centerpoint
							\advance\pgf@x\pgf@xa%
						}%
						{90}{270}{\xradius and \yradius}%
					}{\centerpoint}{\rotate}%
			\fi%
		\fi%
	}
}

pgflibraryshapes.misc.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/shapes/pgflibraryshapes.misc.code.tex,v 1.5 2013/07/18 14:15:25 tantau Exp $


\pgfdeclareshape{cross out}
{
  \inheritsavedanchors[from=rectangle] % this is nearly a rectangle
  \inheritanchorborder[from=rectangle]
  \inheritanchor[from=rectangle]{north}
  \inheritanchor[from=rectangle]{north west}
  \inheritanchor[from=rectangle]{north east}
  \inheritanchor[from=rectangle]{center}
  \inheritanchor[from=rectangle]{west}
  \inheritanchor[from=rectangle]{east}
  \inheritanchor[from=rectangle]{mid}
  \inheritanchor[from=rectangle]{mid west}
  \inheritanchor[from=rectangle]{mid east}
  \inheritanchor[from=rectangle]{base}
  \inheritanchor[from=rectangle]{base west}
  \inheritanchor[from=rectangle]{base east}
  \inheritanchor[from=rectangle]{south}
  \inheritanchor[from=rectangle]{south west}
  \inheritanchor[from=rectangle]{south east}
  \foregroundpath{
    % store lower right in xa/ya and upper right in xb/yb
    \southwest \pgf@xa=\pgf@x \pgf@ya=\pgf@y
    \northeast \pgf@xb=\pgf@x \pgf@yb=\pgf@y
    \pgfpathmoveto{\pgfqpoint{\pgf@xa}{\pgf@ya}}
    \pgfpathlineto{\pgfqpoint{\pgf@xb}{\pgf@yb}}
    \pgfpathmoveto{\pgfqpoint{\pgf@xa}{\pgf@yb}}
    \pgfpathlineto{\pgfqpoint{\pgf@xb}{\pgf@ya}}
    \pgfsetarrowsstart{}
    \pgfsetarrowsend{}
 }
}


\pgfdeclareshape{strike out}
{
  \inheritsavedanchors[from=rectangle] % this is nearly a rectangle
  \inheritanchorborder[from=rectangle]
  \inheritanchor[from=rectangle]{north}
  \inheritanchor[from=rectangle]{north west}
  \inheritanchor[from=rectangle]{north east}
  \inheritanchor[from=rectangle]{center}
  \inheritanchor[from=rectangle]{west}
  \inheritanchor[from=rectangle]{east}
  \inheritanchor[from=rectangle]{mid}
  \inheritanchor[from=rectangle]{mid west}
  \inheritanchor[from=rectangle]{mid east}
  \inheritanchor[from=rectangle]{base}
  \inheritanchor[from=rectangle]{base west}
  \inheritanchor[from=rectangle]{base east}
  \inheritanchor[from=rectangle]{south}
  \inheritanchor[from=rectangle]{south west}
  \inheritanchor[from=rectangle]{south east}
  \foregroundpath{
    \pgfpathmoveto{\southwest}
    \pgfpathlineto{\northeast}
    \pgfsetarrowsstart{}
    \pgfsetarrowsend{}
 }
}


% Rounded rectangle


\pgfkeys{/pgf/.cd,
	rounded rectangle west arc/.initial=convex,
	rounded rectangle east arc/.initial=convex,
	rounded rectangle left arc/.style={/pgf/rounded rectangle west arc=#1},%
	rounded rectangle right arc/.style={/pgf/rounded rectangle east arc=#1},%
	rounded rectangle arc length/.initial=180%
}%

\def\pgf@lib@sh@misc@rr@text@concave{concave}%
\def\pgf@lib@sh@misc@rr@text@convex{convex}%

\pgfdeclareshape{rounded rectangle}{%
	\savedmacro\westarc{%
		\edef\westarc{\pgfkeysvalueof{/pgf/rounded rectangle west arc}}%
	}
	\savedmacro\eastarc{%
		\edef\eastarc{\pgfkeysvalueof{/pgf/rounded rectangle east arc}}%
	}
	\savedmacro\roundedrectanglepoints{%
		%
		% Get half the arc angle, a.
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/rounded rectangle arc length}}%
		\pgf@x=.5\pgf@x%
		\edef\halfarcangle{\pgfmath@tonumber{\pgf@x}}%
		\addtosavedmacro\halfarcangle%	
		%
		% Get the (half) node dimensions x & y.
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
		\edef\innerxsep{\the\pgf@x}%
		\pgf@xa=0.5\wd\pgfnodeparttextbox%
		\edef\halftextwidth{\the\pgf@xa}%
		\addtosavedmacro\halftextwidth%
		\advance\pgf@x by\pgf@xa%
		%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
		\edef\innerysep{\the\pgf@y}%
		\pgf@ya=.5\ht\pgfnodeparttextbox%
		\advance\pgf@ya by.5\dp\pgfnodeparttextbox%
		\edef\halftextheight{\the\pgf@ya}%
		\addtosavedmacro\halftextheight%
		\advance\pgf@y by\pgf@ya%
		%
		% Adjust for minimum height
		%
		\pgfmathsetlength\pgf@yb{\pgfkeysvalueof{/pgf/minimum height}}%
		\ifdim\pgf@y<.5\pgf@yb%
		  \pgf@y=.5\pgf@yb%
		\fi%
		\edef\halfheight{\the\pgf@y}%
		\addtosavedmacro\halfheight%
		%
		% Calculate the radius of the arc ends.
		%
		\pgfmathcosec@{\halfarcangle}%
		\pgf@ya=\pgfmathresult\pgf@y%
		\edef\radius{\the\pgf@ya}%
		\addtosavedmacro\radius%
		%
		% Arc width = r - r*cos(a/2).
		%
		\pgfmathcos@{\halfarcangle}%
		\pgf@xa=\pgf@ya%
		\advance\pgf@xa by-\pgfmathresult\pgf@ya%
		%
		% When the node contents are pushed inside a convex arc,
		% the resulting chord has a height r - r*cos(asin(0.5*h/r)).
		%
		\pgfmathdivide{\halftextheight}{\radius}%
		\pgfmathasin@{\pgfmathresult}%
		\pgfmathcos@{\pgfmathresult}%
		\pgf@xb=\pgf@ya%
		\advance\pgf@xb by-\pgfmathresult\pgf@ya%
		%
		% Adjust for minimum width.
		%
		\edef\westarc{\pgfkeysvalueof{/pgf/rounded rectangle west arc}}%
		\edef\eastarc{\pgfkeysvalueof{/pgf/rounded rectangle east arc}}%
		%
		\pgfutil@tempdima=2.0\pgf@x% x still holds the half width.
		\ifx\westarc\pgf@lib@sh@misc@rr@text@concave%
			\advance\pgfutil@tempdima by\pgf@xa%
		\else%
			\ifx\westarc\pgf@lib@sh@misc@rr@text@convex%
				\advance\pgfutil@tempdima by\pgf@xb%
			\fi%
		\fi%
		%
		\ifx\eastarc\pgf@lib@sh@misc@rr@text@concave%
			\advance\pgfutil@tempdima by\pgf@xa%
		\else%
			\ifx\eastarc\pgf@lib@sh@misc@rr@text@convex%
				\advance\pgfutil@tempdima by\pgf@xb%
			\fi%
		\fi%
		%
		\pgfmathsetlength\pgfutil@tempdimb{\pgfkeysvalueof{/pgf/minimum width}}%
		\ifdim\pgfutil@tempdima<\pgfutil@tempdimb%
			\advance\pgfutil@tempdimb by-\pgfutil@tempdima%
			\divide\pgfutil@tempdimb by2\relax%
			\edef\xoffset{\the\pgfutil@tempdimb}%
		\else%
			\let\xoffset=\innerxsep%
		\fi% 
		%
		% The node is made wider if convex arcs overlap.
		%
		\pgf@x=\halftextwidth\relax%
		\advance\pgf@x by\xoffset\relax%
		\pgf@xc=\pgf@ya%
		\advance\pgf@xc by-\pgf@xb%
		\ifdim\pgf@xc>\pgf@x\relax%
			\advance\pgf@xc by-\pgf@x%
			\advance\pgf@xc by\xoffset\relax%
			\edef\xoffset{\the\pgf@xc}%
		\fi%
		\addtosavedmacro\xoffset%
		%
		\pgf@x=\halftextwidth\relax%
		\advance\pgf@x by\xoffset\relax%
		\edef\halfwidth{\the\pgf@x}%
		\addtosavedmacro\halfwidth%
		%
		\edef\arcwidth{\the\pgf@xa}%	
		\addtosavedmacro\arcwidth%
		%
		\edef\chordwidth{\the\pgf@xb}%
		\addtosavedmacro\chordwidth%
		%
		\pgfmathsetlengthmacro\outerxsep{\pgfkeysvalueof{/pgf/outer xsep}}%
		\pgfmathsetlengthmacro\outerysep{\pgfkeysvalueof{/pgf/outer ysep}}%
		\addtosavedmacro\outerxsep%
		\addtosavedmacro\outerysep%	
		%
		% calculate some horizontal adjustments made for the default miter 
		% drawn when an arc meets the north or south side of the node path.
		%
		\ifdim\halfarcangle pt=90pt\relax% Avoid division by zero.
			\def\concavexshift{0pt}%
		\else%
			% For a concave arc: outer xsep * cosec((90-a/2)/2)*cos((90-a/2)/2).
			\pgfmathsubtract@{90}{\halfarcangle}%
			\pgfmathdivide@{\pgfmathresult}{2}%		
			\let\angletemp=\pgfmathresult%
			\pgf@x=\outerxsep\relax%
			\pgfmathcosec@{\angletemp}%
			\pgf@x=\pgfmathresult\pgf@x%
			\pgfmathcos@{\angletemp}%
			\pgf@x=\pgfmathresult\pgf@x%
			\edef\concavexshift{\the\pgf@x}%
		\fi%
		\addtosavedmacro\concavexshift%
		%
		\ifdim\halfarcangle pt=90pt\relax% Avoid division by zero.
			\def\convexxshift{0pt}%
		\else%
			% For a convex arc: outer xsep * cosec((90+a/2)/2)*cos((90+a/2)/2).
			\pgfmathadd@{90}{\halfarcangle}%
			\pgfmathdivide@{\pgfmathresult}{2}%	
			\let\angletemp=\pgfmathresult%
			\pgf@x=\outerxsep\relax%
			\pgfmathcosec@{\angletemp}%
			\pgf@x=\pgfmathresult\pgf@x%
			\pgfmathcos@{\angletemp}%
			\pgf@x=\pgfmathresult\pgf@x%
			\edef\convexxshift{\the\pgf@x}%
		\fi%
		\addtosavedmacro\convexxshift%		
	}%
	\saveddimen\halflinewidth{\pgf@x.5\pgflinewidth}%
	\savedanchor\centerpoint{%
		\pgf@x=.5\wd\pgfnodeparttextbox%
		\pgf@y=.5\ht\pgfnodeparttextbox%
		\advance\pgf@y by-.5\dp\pgfnodeparttextbox%		
	}	
	\savedanchor\midpoint{%
		\pgf@x=.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+0.5ex}%	
	}	
	\savedanchor\basepoint{%
		\pgf@x=.5\wd\pgfnodeparttextbox%
		\pgf@y=0pt\relax%
	}	
	\anchor{center}{\centerpoint}%
	\anchor{mid}{\midpoint}%
	\anchor{mid west}{%
		\csname pgf@anchor@rounded rectangle@west\endcsname%
		\pgf@xc=\pgf@x%
		\midpoint%
		\pgf@x=\pgf@xc%
	}%
	\anchor{mid east}{%
		\csname pgf@anchor@rounded rectangle@east\endcsname%
		\pgf@xc=\pgf@x%
		\midpoint%
		\pgf@x=\pgf@xc%
	}%
	\anchor{base}{\basepoint}%
	\anchor{base west}{%
		\csname pgf@anchor@rounded rectangle@west\endcsname%
		\pgf@xc=\pgf@x%
		\basepoint%
		\pgf@x=\pgf@xc%
	}%
	\anchor{base east}{%
		\csname pgf@anchor@rounded rectangle@east\endcsname%
		\pgf@xc=\pgf@x%
		\basepoint%
		\pgf@x=\pgf@xc%
	}%
	\anchor{north}{%
		\roundedrectanglepoints%
		\pgfpointadd{\centerpoint}{\pgfpoint{+0pt}{\halfheight+\outerysep}}%
	}%
	\anchor{south}{%
		\roundedrectanglepoints%
		\pgfpointadd{\centerpoint}{\pgfpoint{+0pt}{-\halfheight-\outerysep}}%
	}%
	\anchor{west}{%
		\roundedrectanglepoints%
		\pgfpointadd{\centerpoint}{%
			\ifx\westarc\pgf@lib@sh@misc@rr@text@concave%
				\pgfpoint{-\halfwidth-\arcwidth-\concavexshift}{+0pt}%
			\else%
				\ifx\westarc\pgf@lib@sh@misc@rr@text@convex%
					\pgfpoint{-\halfwidth-\chordwidth-\outerxsep}{+0pt}%
				\else%
					\pgfpoint{-\halfwidth-\outerxsep}{+0pt}%
				\fi%
			\fi%
		}%
	}%
	\anchor{north west}{%	
		\roundedrectanglepoints%	
		\ifx\westarc\pgf@lib@sh@misc@rr@text@convex%
			\pgfpointadd{\centerpoint}{\pgfpoint{-\halfwidth-\chordwidth+\arcwidth-\convexxshift}{+0pt}}%
		\else%
			\csname pgf@anchor@rounded rectangle@west\endcsname%
		\fi%
		\pgf@xc=\pgf@x%
		\csname pgf@anchor@rounded rectangle@north\endcsname%
		\pgf@x=\pgf@xc%
	}%
	\anchor{south west}{%
		\roundedrectanglepoints%	
		\ifx\westarc\pgf@lib@sh@misc@rr@text@convex%
			\pgfpointadd{\centerpoint}{\pgfpoint{-\halfwidth-\chordwidth+\arcwidth-\convexxshift}{+0pt}}%
		\else%
			\csname pgf@anchor@rounded rectangle@west\endcsname%
		\fi%
		\pgf@xc=\pgf@x%
		\csname pgf@anchor@rounded rectangle@south\endcsname%
		\pgf@x=\pgf@xc%
	}%
	\anchor{east}{%
		\roundedrectanglepoints%
		\pgfpointadd{\centerpoint}{%
			\ifx\eastarc\pgf@lib@sh@misc@rr@text@concave%
				\pgfpoint{\halfwidth+\arcwidth+\concavexshift}{+0pt}%
			\else%
				\ifx\eastarc\pgf@lib@sh@misc@rr@text@convex%
					\pgfpoint{\halfwidth+\chordwidth+\outerxsep}{+0pt}%
				\else%
					\pgfpoint{\halfwidth+\outerxsep}{+0pt}%
				\fi%
			\fi%
		}%
	}%
	\anchor{north east}{%	
		\roundedrectanglepoints%	
		\ifx\eastarc\pgf@lib@sh@misc@rr@text@convex%
			\pgfpointadd{\centerpoint}{\pgfpoint{\halfwidth+\chordwidth-\arcwidth+\convexxshift}{+0pt}}%
		\else%
			\csname pgf@anchor@rounded rectangle@east\endcsname%
		\fi%
		\pgf@xc=\pgf@x%
		\csname pgf@anchor@rounded rectangle@north\endcsname%
		\pgf@x=\pgf@xc%
	}%
	\anchor{south east}{%
		\roundedrectanglepoints%	
		\ifx\eastarc\pgf@lib@sh@misc@rr@text@convex%
			\pgfpointadd{\centerpoint}{\pgfpoint{\halfwidth+\chordwidth-\arcwidth+\convexxshift}{+0pt}}%
		\else%
			\csname pgf@anchor@rounded rectangle@east\endcsname%
		\fi%
		\pgf@xc=\pgf@x%
		\csname pgf@anchor@rounded rectangle@south\endcsname%
		\pgf@x=\pgf@xc%
	}%
	\backgroundpath{%
		{%
			\roundedrectanglepoints%
			\pgftransformshift{\centerpoint}%
			\pgfpathmoveto{\pgfpoint{0pt}{\halfheight}}%
			\ifx\eastarc\pgf@lib@sh@misc@rr@text@concave%
				\pgfpathlineto{\pgfpoint{\halfwidth+\arcwidth}{+\halfheight}}%
				\pgfpatharc{180-\halfarcangle}{180+\halfarcangle}{+\radius}%
			\else%
				\ifx\eastarc\pgf@lib@sh@misc@rr@text@convex%
					\pgfpathlineto{\pgfpoint{\halfwidth+\chordwidth-\arcwidth}{+\halfheight}}%
					\pgfpatharc{+\halfarcangle}{+-\halfarcangle}{+\radius}%
				\else%
					\pgfpathlineto{\pgfqpoint{\halfwidth}{\halfheight}}%
					\pgfpathlineto{\pgfqpoint{\halfwidth}{-\halfheight}}%
				\fi%
			\fi%
			\ifx\westarc\pgf@lib@sh@misc@rr@text@concave%
				\pgfpathlineto{\pgfpoint{-\halfwidth-\arcwidth}{+-\halfheight}}%
				\pgfpatharc{+-\halfarcangle}{+\halfarcangle}{+\radius}%
			\else%
				\ifx\westarc\pgf@lib@sh@misc@rr@text@convex%
					\pgfpathlineto{\pgfpoint{-\halfwidth-\chordwidth+\arcwidth}{+-\halfheight}}%
					\pgfpatharc{180+\halfarcangle}{180-\halfarcangle}{+\radius}%
				\else%
					\pgfpathlineto{\pgfqpoint{-\halfwidth}{-\halfheight}}%
					\pgfpathlineto{\pgfqpoint{-\halfwidth}{\halfheight}}%
				\fi%
			\fi%
			\pgfpathclose%
		}%
	}
	\anchorborder{%
	\pgfextract@process\externalpoint{%
		\pgfextract@process\externalpoint{}%
			\pgfpointadd{\centerpoint}{\externalpoint}%
		}%
		\roundedrectanglepoints%
		%
		\pgfmathanglebetweenpoints{\centerpoint}{\externalpoint}%
		\let\externalangle=\pgfmathresult%
		\pgfmathanglebetweenpoints{\centerpoint}{\csname pgf@anchor@rounded rectangle@north west\endcsname}%
		\ifdim\externalangle pt<\pgfmathresult pt\relax%
			\pgfmathanglebetweenpoints{\centerpoint}{\csname pgf@anchor@rounded rectangle@north east\endcsname}%
			\ifdim\externalangle pt<\pgfmathresult pt\relax%
				% Between north east and east.
				\ifx\eastarc\pgf@lib@sh@misc@rr@text@convex%
					\pgfextract@process\arccenter{%
						\pgfpointadd{\centerpoint}{\pgfpoint{\halfwidth+\chordwidth-\radius}{+0pt}}%
					}%
					\pgfmathpointintersectionoflineandarc{\externalpoint}{\centerpoint}%
						{\arccenter}{0}{\halfarcangle}{\radius+\outerxsep and \radius+\outerysep}%
				\else%
					\pgfpointintersectionoflines%
						{\csname pgf@anchor@rounded rectangle@north east\endcsname}%
						{\csname pgf@anchor@rounded rectangle@south east\endcsname}%
						{\externalpoint}{\centerpoint}%
				\fi%
			\else%
				% Between north west and north east.
				\pgfpointintersectionoflines%
					{\csname pgf@anchor@rounded rectangle@north east\endcsname}%
					{\csname pgf@anchor@rounded rectangle@north west\endcsname}%
					{\externalpoint}{\centerpoint}%
			\fi%
		\else%
			\pgfmathanglebetweenpoints{\centerpoint}{\csname pgf@anchor@rounded rectangle@south west\endcsname}%
			\ifdim\externalangle pt<\pgfmathresult pt\relax%
				% Between south west and north west.
				\ifx\westarc\pgf@lib@sh@misc@rr@text@convex%
					\pgfextract@process\arccenter{%
						\pgfpointadd{\centerpoint}{\pgfpoint{-\halfwidth-\chordwidth+\radius}{+0pt}}%
					}%
					\pgfmathpointintersectionoflineandarc{\externalpoint}{\centerpoint}%
						{\arccenter}{180-\halfarcangle}{180+\halfarcangle}{\radius+\outerxsep and \radius+\outerysep}%
				\else%
					\pgfpointintersectionoflines%
						{\csname pgf@anchor@rounded rectangle@north west\endcsname}%
						{\csname pgf@anchor@rounded rectangle@south west\endcsname}%
						{\externalpoint}{\centerpoint}%
				\fi%
			\else%
				\pgfmathanglebetweenpoints{\centerpoint}{\csname pgf@anchor@rounded rectangle@south east\endcsname}%
				\ifdim\externalangle pt<\pgfmathresult pt\relax%
					% Between south east and south west.
					\pgfpointintersectionoflines%
						{\csname pgf@anchor@rounded rectangle@south east\endcsname}%
						{\csname pgf@anchor@rounded rectangle@south west\endcsname}%
						{\externalpoint}{\centerpoint}%
				\else%
					% Between east and south east.
					\ifx\eastarc\pgf@lib@sh@misc@rr@text@convex%
						\pgfextract@process\arccenter{%
							\pgfpointadd{\centerpoint}{\pgfpoint{\halfwidth+\chordwidth-\radius}{+0pt}}%
						}%
						\pgfmathpointintersectionoflineandarc{\externalpoint}{\centerpoint}%
							{\arccenter}{360-\halfarcangle}{360}{\radius+\outerxsep and \radius+\outerysep}%
					\else%
						\pgfpointintersectionoflines%
							{\csname pgf@anchor@rounded rectangle@north east\endcsname}%
							{\csname pgf@anchor@rounded rectangle@south east\endcsname}%
							{\externalpoint}{\centerpoint}%
					\fi%
				\fi%
			\fi%
		\fi%
	}
}



% Keys for chamfered rectangle
%
% /pgf/chamfered rectangle corners : specify the corners to chamfer.
% /pgf/chamfered rectangle angle   : set the angle of the chamfer.
% /pgf/chamfered rectangle xsep    : set the extent of the x chamferling.
% /pgf/chamfered rectangle ysep    : set the extent of the y chamferling.

\pgfkeys{/pgf/chamfered rectangle corners/.store in=\pgf@lib@sh@misc@cr@corners}
\pgfkeys{/tikz/chamfered rectangle corners/.store in=\pgf@lib@sh@misc@cr@corners}

\def\pgf@lib@sh@misc@cr@chamferall{chamfer all}%
\def\pgf@lib@sh@misc@cr@chamfer{chamfer}
\let\pgf@lib@sh@misc@cr@corners\pgf@lib@sh@misc@cr@chamferall


\def\pgf@lib@sh@misc@cr@getcorners{%
	\let\northeastcorner\pgfutil@empty%
	\let\southeastcorner\pgfutil@empty%
	\let\southwestcorner\pgfutil@empty%
	\let\northwestcorner\pgfutil@empty%
	\expandafter\pgfutil@in@\expandafter{\pgf@lib@sh@misc@cr@corners}{chamfer all}%
	\ifpgfutil@in@%
		\let\northeastcorner\pgf@lib@sh@misc@cr@round%
		\let\southeastcorner\pgf@lib@sh@misc@cr@round%
		\let\southwestcorner\pgf@lib@sh@misc@cr@round%
		\let\northwestcorner\pgf@lib@sh@misc@cr@round%
		\let\pgf@next\relax%
	\else%	
		\let\pgf@next\pgf@lib@sh@misc@cr@parsecorners%
	\fi%
	\pgf@next}

\def\pgf@lib@sh@misc@cr@parsecorners{%
	\expandafter\pgf@@chamferedrectangle@parsecorners\pgf@lib@sh@misc@cr@corners,\pgf@stop,%
}
		
\def\pgf@@chamferedrectangle@parsecorners#1,{%
	\ifx#1\pgf@stop%
		\let\pgf@next\relax%
	\else%
		\pgfutil@in@{@#1@}{@north east@@top left@}%
		\ifpgfutil@in@%
			\let\northeastcorner\pgf@lib@sh@misc@cr@chamfer%
		\else%
			\pgfutil@in@{@#1@}{@south east@@bottom right@}%
			\ifpgfutil@in@%
				\let\southeastcorner\pgf@lib@sh@misc@cr@chamfer%
			\else%
				\pgfutil@in@{@#1@}{@south west@@bottom left@}%
				\ifpgfutil@in@%
					\let\southwestcorner\pgf@lib@sh@misc@cr@chamfer%
				\else%
					\pgfutil@in@{@#1@}{@north west@@top right@}%
					\ifpgfutil@in@%
						\let\northwestcorner\pgf@lib@sh@misc@cr@round%
					\fi%
				\fi%
			\fi%
		\fi%
		\let\pgf@next\pgf@@@chamferedrectangle@parsecorners%
	\fi%
	\pgf@next%
}
\def\pgf@@@chamferedrectangle@parsecorners{%
	\pgfutil@ifnextchar x{\pgf@@chamferedrectangle@parsecorners}{\pgf@@chamferedrectangle@parsecorners}%
}%

\pgfkeys{/pgf/.cd,
	chamfered rectangle angle/.initial=45,%
	chamfered rectangle xsep/.initial=.666ex,%
	chamfered rectangle ysep/.initial=.666ex%
}
 \pgfkeys{/pgf/chamfered rectangle sep/.style={%
	/pgf/chamfered rectangle xsep=#1,/pgf/chamfered rectangle ysep=#1}%
}




% Shape chamfered rectangle.
%
%
\pgfdeclareshape{chamfered rectangle}{%
	\savedmacro\getchamferedrectanglepoints{%
		\pgf@lib@sh@misc@cr@getcorners%
		%
		% Get the node dimensions.
		%
		\pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/inner xsep}}%
		\advance\pgf@xa.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/inner ysep}}%
		\advance\pgf@ya.5\ht\pgfnodeparttextbox%
		\advance\pgf@ya.5\dp\pgfnodeparttextbox%
		%
		% Get chamfer stuff. 
		%
		\pgfmathsetlength\pgfutil@tempdima{\pgfkeysvalueof{/pgf/chamfered rectangle angle}}%
		\ifdim\pgfutil@tempdima<89pt\relax%
			\ifdim\pgfutil@tempdima<1pt\relax%
				\pgfutil@tempdima1pt\relax%
			\fi%
		\else%		
			\pgfutil@tempdima89pt\relax%
		\fi%
		\pgfutil@tempdima-\pgfutil@tempdima%
		\advance\pgfutil@tempdima90pt\relax%
		\pgfmathtan@{\pgfmath@tonumber{\pgfutil@tempdima}}%
		\let\tanangle\pgfmathresult%
		\pgfmathcot@{\pgfmath@tonumber{\pgfutil@tempdima}}%
		\let\cotangle\pgfmathresult%
		\pgfmathsetlength\pgf@xb{\pgfkeysvalueof{/pgf/chamfered rectangle xsep}}%
		\pgf@yc\tanangle\pgf@xb%
		\ifdim\pgf@yc>\pgf@ya%
			\pgf@yc\pgf@ya%
			\pgf@xb\cotangle\pgf@yc%
		\fi%
		\pgfmathcot@{\pgfmath@tonumber{\pgfutil@tempdima}}%
		\pgfmathsetlength\pgf@yb{\pgfkeysvalueof{/pgf/chamfered rectangle ysep}}%
		\pgf@xc\cotangle\pgf@yb%
			\ifdim\pgf@xc>\pgf@xa%
			\pgf@xc\pgf@xa%
			\pgf@yb\tanangle\pgf@xc%
		\fi%
		%
		% Check for minimum width and height%
		%
		\pgfutil@tempdima\pgf@xa%
		\advance\pgfutil@tempdima\pgf@xb%
		\pgfmathsetlength\pgfutil@tempdimb{\pgfkeysvalueof{/pgf/minimum width}}%
		\ifdim\pgfutil@tempdima<.5\pgfutil@tempdimb%
			\pgf@xa.5\pgfutil@tempdimb%
			\advance\pgf@xa-\pgf@xb%
		\fi%
		\pgfutil@tempdima\pgf@ya%
		\advance\pgfutil@tempdima\pgf@yb%
		\pgfmathsetlength\pgfutil@tempdimb{\pgfkeysvalueof{/pgf/minimum height}}%
		\ifdim\pgfutil@tempdima<.5\pgfutil@tempdimb%
			\pgf@ya.5\pgfutil@tempdimb%
			\advance\pgf@ya-\pgf@yb%
		\fi%		
		%
		% Define the background path points.
		%
		\pgfextract@process\centerpoint{%
			\pgfmathsetlength\pgf@x{+.5\wd\pgfnodeparttextbox}%
			\pgfmathsetlength\pgf@y{+.5\ht\pgfnodeparttextbox}%
			\pgfmathaddtolength\pgf@y{+-.5\dp\pgfnodeparttextbox}%
		}%
		\pgfextract@process\beforenortheast{%
			\centerpoint%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@x\pgf@xb%
			\advance\pgf@y\pgf@ya%
			\advance\pgf@y-\pgf@yc%
		}%
		\pgfextract@process\northeast{%
			\centerpoint%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y\pgf@ya%
			\ifx\northeastcorner\pgfutil@empty%
				\advance\pgf@x\pgf@xb%
				\advance\pgf@y\pgf@yb%
			\fi%
		}%
		\pgfextract@process\afternortheast{%
			\centerpoint%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@x-\pgf@xc%
			\advance\pgf@y\pgf@ya%
			\advance\pgf@y\pgf@yb%
		}%	
		\pgfextract@process\northwest{%
			\centerpoint%
			\advance\pgf@x-\pgf@xa%
			\advance\pgf@y\pgf@ya%
			\ifx\northwestcorner\pgfutil@empty%
				\advance\pgf@x-\pgf@xb%
				\advance\pgf@y\pgf@yb%
			\fi%
		}%
		\pgfextract@process\beforesouthwest{%
			\centerpoint%
			\advance\pgf@x-\pgf@xa%
			\advance\pgf@x-\pgf@xb%
			\advance\pgf@y-\pgf@ya%
			\advance\pgf@y\pgf@yc%
		}%
		\pgfextract@process\southwest{%
			\centerpoint%
			\advance\pgf@x-\pgf@xa%
			\advance\pgf@y-\pgf@ya%
			\ifx\southwestcorner\pgfutil@empty%
				\advance\pgf@x-\pgf@xb%
				\advance\pgf@y-\pgf@yb%
			\fi%
		}%
		\pgfextract@process\aftersouthwest{%
			\centerpoint%
			\advance\pgf@x-\pgf@xa%
			\advance\pgf@x\pgf@xc%
			\advance\pgf@y-\pgf@ya%
			\advance\pgf@y-\pgf@yb%
		}%
		\pgfextract@process\southeast{%
			\centerpoint%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y-\pgf@ya%
			\ifx\southeastcorner\pgfutil@empty%
				\advance\pgf@x\pgf@xb%
				\advance\pgf@y-\pgf@yb%
			\fi%
		}%
		%
		% Calculate the `miter' vectors.
		%
		\pgfmathanglebetweenlines{\beforenortheast}{\afternortheast}{\beforenortheast}%
			{\beforesouthwest\pgf@ya\pgf@y\beforenortheast\pgf@y\pgf@ya}%
		\pgfutil@tempdima\pgfmathresult pt\relax%
		\ifdim\pgfutil@tempdima>180pt\relax%
			\advance\pgfutil@tempdima-180pt\relax%
		\fi%
		\pgfmathsetlength\pgfutil@tempdimb{\pgfkeysvalueof{/pgf/outer xsep}}%
		\ifdim\pgfutil@tempdima<90pt\relax%
			\pgfmathcosec@{\pgfmath@tonumber{\pgfutil@tempdima}}%
			\pgfutil@tempdimb\pgfmathresult\pgfutil@tempdimb%
			\pgfutil@tempdima0pt\relax%
		\else%
			\pgfutil@tempdima.5\pgfutil@tempdima%
			\pgfmathcosec@{\pgfmath@tonumber{\pgfutil@tempdima}}%
			\pgfutil@tempdimb\pgfmathresult\pgfutil@tempdimb%
			\pgfutil@tempdima-\pgfutil@tempdima%
			\advance\pgfutil@tempdima90pt\relax%
		\fi%
		\pgfextract@process\before@ne@anchor{%
			\beforenortheast%
			\pgf@xa\pgf@x%
			\pgf@ya\pgf@y%
			\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y\pgf@ya%
		}%
		\pgfutil@tempdima-\pgfutil@tempdima%
		\advance\pgfutil@tempdima180pt\relax%
		\pgfextract@process\before@sw@anchor{%
			\beforesouthwest%
			\pgf@xa\pgf@x%
			\pgf@ya\pgf@y%
			\pgfqpointpolar{-\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y\pgf@ya%
		}%
		%
		\pgfmathanglebetweenlines{\afternortheast}{\aftersouthwest\pgf@xa\pgf@x\afternortheast\pgf@x\pgf@xa}%
			{\afternortheast}{\beforenortheast}%
		\pgfutil@tempdima\pgfmathresult pt\relax%
		\ifdim\pgfutil@tempdima>270pt\relax%
			\advance\pgfutil@tempdima-270pt\relax%
		\fi%
		\pgfmathsetlength\pgfutil@tempdimb{\pgfkeysvalueof{/pgf/outer ysep}}%
		\ifdim\pgfutil@tempdima<90pt\relax%
			\pgfmathcosec@{\pgfmath@tonumber{\pgfutil@tempdima}}%
			\pgfutil@tempdimb\pgfmathresult\pgfutil@tempdimb%
			\pgfutil@tempdima90pt\relax%
		\else%
			\pgfutil@tempdima.5\pgfutil@tempdima%
			\pgfmathcosec@{\pgfmath@tonumber{\pgfutil@tempdima}}%
			\pgfutil@tempdimb\pgfmathresult\pgfutil@tempdimb%
		\fi%		
		%
		\pgfextract@process\after@ne@anchor{%
			\afternortheast%
			\pgf@xa\pgf@x%
			\pgf@ya\pgf@y%
			\pgfqpointpolar{\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y\pgf@ya%
		}%
		\pgfutil@tempdima-\pgfutil@tempdima%
		\advance\pgfutil@tempdima180pt\relax%
		\pgfextract@process\after@sw@anchor{%
			\aftersouthwest
			\pgf@xa\pgf@x%
			\pgf@ya\pgf@y%
			\pgfqpointpolar{-\pgfmath@tonumber{\pgfutil@tempdima}}{\the\pgfutil@tempdimb}%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y\pgf@ya%
		}%
		\addtosavedmacro\before@ne@anchor%
		\addtosavedmacro\after@ne@anchor%
		\addtosavedmacro\before@sw@anchor%
		\addtosavedmacro\after@sw@anchor%
		\pgfextract@process\ne@anchor{%
			\ifx\northeastcorner\pgfutil@empty%
				\northeast%
				\pgfmathaddtolength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
				\pgfmathaddtolength\pgf@y{\pgfkeysvalueof{/pgf/outer ysep}}%
			\else%
				\pgfpointlineattime{0.5}{\before@ne@anchor}{\after@ne@anchor}%
			\fi%
		}%
		\pgfextract@process\nw@anchor{%
			\ifx\northwestcorner\pgfutil@empty%
				\northwest%
				\pgfmathaddtolength\pgf@x{-\pgfkeysvalueof{/pgf/outer xsep}}%
				\pgfmathaddtolength\pgf@y{\pgfkeysvalueof{/pgf/outer ysep}}%
			\else%
				\pgfpointlineattime{0.5}{%
					\before@ne@anchor%
					\pgf@ya\pgf@y
					\before@sw@anchor%
					\pgf@y\pgf@ya%
				}{%
					\after@ne@anchor%
					\pgf@ya\pgf@y
					\after@sw@anchor%
					\pgf@y\pgf@ya%
				}%
			\fi%
		}%
		\pgfextract@process\sw@anchor{%
			\ifx\southwestcorner\pgfutil@empty%
				\southwest%
				\pgfmathaddtolength\pgf@x{-\pgfkeysvalueof{/pgf/outer xsep}}%
				\pgfmathaddtolength\pgf@y{-\pgfkeysvalueof{/pgf/outer ysep}}%
			\else%
				\pgfpointlineattime{0.5}{\before@sw@anchor}{\after@sw@anchor}%
			\fi%
		}%
		\pgfextract@process\se@anchor{%
			\ifx\southeastcorner\pgfutil@empty%
				\southeast%
				\pgfmathaddtolength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
				\pgfmathaddtolength\pgf@y{-\pgfkeysvalueof{/pgf/outer ysep}}%
			\else%
				\pgfpointlineattime{0.5}{%
					\before@ne@anchor%
					\pgf@xa\pgf@x
					\before@sw@anchor%
					\pgf@x\pgf@xa%
				}{%
					\after@ne@anchor%
					\pgf@xa\pgf@x
					\after@sw@anchor%
					\pgf@x\pgf@xa%
				}%
			\fi%
		}%
		\addtosavedmacro\ne@anchor%
		\addtosavedmacro\nw@anchor%
		\addtosavedmacro\sw@anchor%
		\addtosavedmacro\se@anchor%
	}%
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y.5\ht\pgfnodeparttextbox%
		\advance\pgf@y-.5\dp\pgfnodeparttextbox%
	}%
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+.5ex}%
	}%
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt%
	}%
	\anchor{center}{\centerpoint}%
	\anchor{mid}{\midpoint}%
	\anchor{mid east}{%
		\getchamferedrectanglepoints%
		\midpoint%
		\pgf@ya\pgf@y%
		\pgf@process{%
			\before@sw@anchor%
			\pgf@ya\pgf@y%
			\before@ne@anchor%
			\pgf@y\pgf@ya		
		}%
		\ifdim\pgf@ya<\pgf@y%
			\pgfpointintersectionoflines{\midpoint}{\midpoint\pgf@ya\pgf@y\before@ne@anchor\pgf@y\pgf@ya}%
				{\before@sw@anchor\pgf@ya\pgf@y\before@ne@anchor\pgf@y\pgf@ya}%
				{\after@sw@anchor\pgf@ya\pgf@y\after@ne@anchor\pgf@y\pgf@ya}%
		\else%
			\pgf@process{\before@ne@anchor}%
			\ifdim\pgf@ya<\pgf@y%
				\pgfpointintersectionoflines{\midpoint}{\midpoint\pgf@ya\pgf@y\before@ne@anchor\pgf@y\pgf@ya}%
					{\before@sw@anchor\pgf@ya\pgf@y\before@ne@anchor\pgf@y\pgf@ya}%
					{\before@ne@anchor}%
			\else%
				\pgfpointintersectionoflines{\midpoint}{\midpoint\pgf@ya\pgf@y\before@ne@anchor\pgf@y\pgf@ya}%
					{\before@ne@anchor}%
					{\after@ne@anchor}%
			\fi%
		\fi%			
	}%
	\anchor{mid west}{%
		\getchamferedrectanglepoints%
		\midpoint%
		\pgf@ya\pgf@y%
		\pgf@process{\before@sw@anchor}%
		\ifdim\pgf@ya<\pgf@y%
			\pgfpointintersectionoflines{\midpoint}{\midpoint\pgf@ya\pgf@y\before@sw@anchor\pgf@y\pgf@ya}%
				{\before@sw@anchor}{\after@sw@anchor}%
		\else%
			\pgf@process{\before@ne@anchor\pgf@ya\pgf@y\before@sw@anchor\pgf@y\pgf@ya}%
			\ifdim\pgf@ya<\pgf@y%
				\pgfpointintersectionoflines{\midpoint}{\midpoint\pgf@ya\pgf@y\before@sw@anchor\pgf@y\pgf@ya}%
					{\before@ne@anchor\pgf@ya\pgf@y\before@sw@anchor\pgf@y\pgf@ya}%
					{\before@sw@anchor}%
			\else%
				\pgfpointintersectionoflines{\midpoint}{\midpoint\pgf@ya\pgf@y\before@sw@anchor\pgf@y\pgf@ya}%
					{\before@ne@anchor\pgf@ya\pgf@y\before@sw@anchor\pgf@y\pgf@ya}%
					{\after@ne@anchor\pgf@ya\pgf@y\after@sw@anchor\pgf@y\pgf@ya}%
			\fi%
		\fi%			
	}%
	\anchor{base}{\basepoint}%
	\anchor{base east}{%
		\getchamferedrectanglepoints%
		\basepoint%
		\pgf@ya\pgf@y%
		\pgf@process{%
			\before@sw@anchor%
			\pgf@ya\pgf@y%
			\before@ne@anchor%
			\pgf@y\pgf@ya		
		}%
		\ifdim\pgf@ya<\pgf@y%
			\pgfpointintersectionoflines{\basepoint}{\basepoint\pgf@ya\pgf@y\before@ne@anchor\pgf@y\pgf@ya}%
				{\before@sw@anchor\pgf@ya\pgf@y\before@ne@anchor\pgf@y\pgf@ya}%
				{\after@sw@anchor\pgf@ya\pgf@y\after@ne@anchor\pgf@y\pgf@ya}%
		\else%
			\pgf@process{\before@ne@anchor}%
			\ifdim\pgf@ya<\pgf@y%
				\pgfpointintersectionoflines{\basepoint}{\basepoint\pgf@ya\pgf@y\before@ne@anchor\pgf@y\pgf@ya}%
					{\before@sw@anchor\pgf@ya\pgf@y\before@ne@anchor\pgf@y\pgf@ya}%
					{\before@ne@anchor}%
			\else%
				\pgfpointintersectionoflines{\basepoint}{\basepoint\pgf@ya\pgf@y\before@ne@anchor\pgf@y\pgf@ya}%
					{\before@ne@anchor}%
					{\after@ne@anchor}%
			\fi%
		\fi%			
	}%
	\anchor{base west}{%
		\getchamferedrectanglepoints%
		\basepoint%
		\pgf@ya\pgf@y%
		\pgf@process{\before@sw@anchor}%
		\ifdim\pgf@ya<\pgf@y%
			\pgfpointintersectionoflines{\basepoint}{\basepoint\pgf@ya\pgf@y\before@sw@anchor\pgf@y\pgf@ya}%
				{\before@sw@anchor}{\after@sw@anchor}%
		\else%
			\pgf@process{\before@ne@anchor\pgf@ya\pgf@y\before@sw@anchor\pgf@y\pgf@ya}%
			\ifdim\pgf@ya<\pgf@y%
				\pgfpointintersectionoflines{\basepoint}{\basepoint\pgf@ya\pgf@y\before@sw@anchor\pgf@y\pgf@ya}%
					{\before@ne@anchor\pgf@ya\pgf@y\before@sw@anchor\pgf@y\pgf@ya}%
					{\before@sw@anchor}%
			\else%
				\pgfpointintersectionoflines{\basepoint}{\basepoint\pgf@ya\pgf@y\before@sw@anchor\pgf@y\pgf@ya}%
					{\before@ne@anchor\pgf@ya\pgf@y\before@sw@anchor\pgf@y\pgf@ya}%
					{\after@ne@anchor\pgf@ya\pgf@y\after@sw@anchor\pgf@y\pgf@ya}%
			\fi%
		\fi%			
	}%
	\anchor{before north east}{\getchamferedrectanglepoints\before@ne@anchor}%
	\anchor{north east}{\getchamferedrectanglepoints\ne@anchor}%
	\anchor{after north east}{\getchamferedrectanglepoints\after@ne@anchor}%
	\anchor{north}{%
		\getchamferedrectanglepoints%
		\centerpoint%
		\pgf@xa\pgf@x%
		\after@ne@anchor%
		\pgf@x\pgf@xa}%	
	\anchor{before north west}{%
		\getchamferedrectanglepoints%
		\after@sw@anchor%
		\pgf@xa\pgf@x%
		\after@ne@anchor%
		\pgf@x\pgf@xa}%
	\anchor{north west}{\getchamferedrectanglepoints\nw@anchor}%
	\anchor{after north west}{%
		\getchamferedrectanglepoints%
		\before@sw@anchor%
		\pgf@xa\pgf@x%
		\before@ne@anchor%
		\pgf@x\pgf@xa}%
	\anchor{west}{%
		\getchamferedrectanglepoints%
		\centerpoint%
		\pgf@ya\pgf@y%
		\before@sw@anchor%
		\pgf@y\pgf@ya}%	
	\anchor{before south west}{\getchamferedrectanglepoints\before@sw@anchor}%
	\anchor{south west}{\getchamferedrectanglepoints\sw@anchor}%
	\anchor{after south west}{\getchamferedrectanglepoints\after@sw@anchor}%
		\anchor{south}{%
		\getchamferedrectanglepoints%
		\centerpoint%
		\pgf@xa\pgf@x%
		\after@sw@anchor%
		\pgf@x\pgf@xa}%	
	\anchor{before south east}{%
		\getchamferedrectanglepoints%
		\after@sw@anchor%
		\pgf@ya\pgf@y%
		\after@ne@anchor%
		\pgf@y\pgf@ya}%
	\anchor{south east}{\getchamferedrectanglepoints\se@anchor}%
	\anchor{after south east}{%
		\getchamferedrectanglepoints%
		\before@sw@anchor%
		\pgf@ya\pgf@y%
		\before@ne@anchor%
		\pgf@y\pgf@ya}%
	\anchor{east}{%
		\getchamferedrectanglepoints%
		\centerpoint%
		\pgf@ya\pgf@y%
		\before@ne@anchor%
		\pgf@y\pgf@ya}%	
	\backgroundpath{%
		\pgfpathmoveto{\beforenortheast}%
		\pgfpathlineto{\northeast}%
		\pgfpathlineto{\afternortheast}%
		\pgfpathlineto{\aftersouthwest\pgf@xa\pgf@x\afternortheast\pgf@x\pgf@xa}%
		\pgfpathlineto{\northwest}%
		\pgfpathlineto{\beforesouthwest\pgf@xa\pgf@x\beforenortheast\pgf@x\pgf@xa}%
		\pgfpathlineto{\beforesouthwest}%
		\pgfpathlineto{\southwest}%
		\pgfpathlineto{\aftersouthwest}%
		\pgfpathlineto{\aftersouthwest\pgf@ya\pgf@y\afternortheast\pgf@y\pgf@ya}%
		\pgfpathlineto{\southeast}%
		\pgfpathlineto{\beforesouthwest\pgf@ya\pgf@y\beforenortheast\pgf@y\pgf@ya}%		
		\pgfpathclose%
	}
	\anchorborder{%
		\pgfextract@process\externalpoint{%
			\pgf@xa\pgf@x%
			\pgf@ya\pgf@y%
			\centerpoint%
			\advance\pgf@x\pgf@xa%
			\advance\pgf@y\pgf@ya%
		}%
		\pgfmathanglebetweenpoints{\centerpoint}{\externalpoint}%
		\let\externalangle\pgfmathresult%
		\getchamferedrectanglepoints%
		\pgfmathanglebetweenpoints{\centerpoint}{\centerpoint\pgf@ya\pgf@y\before@sw@anchor\pgf@y\pgf@ya}%
		\ifdim\externalangle pt<\pgfmathresult pt\relax% west.
			\pgfmathanglebetweenpoints{\centerpoint}{\centerpoint\pgf@xa\pgf@x\after@ne@anchor\pgf@x\pgf@xa}%
			\ifdim\externalangle pt<\pgfmathresult pt\relax% north.
				\pgfmathanglebetweenpoints{\centerpoint}{\ne@anchor}%
				\ifdim\externalangle pt<\pgfmathresult pt\relax% north east.
					\pgfmathanglebetweenpoints{\centerpoint}{\before@ne@anchor}%
					\ifdim\externalangle pt<\pgfmathresult pt\relax% before north east.
						\pgfpointintersectionoflines{\centerpoint}{\externalpoint}%
							{\centerpoint\pgf@ya\pgf@y\before@ne@anchor\pgf@y\pgf@ya}{\before@ne@anchor}%
					\else% 
						\pgfpointintersectionoflines{\centerpoint}{\externalpoint}%
							{\before@ne@anchor}{\ne@anchor}%
					\fi%
				\else%
					\pgfmathanglebetweenpoints{\centerpoint}{\after@ne@anchor}%
					\ifdim\externalangle pt<\pgfmathresult pt\relax% after north east.
							\pgfpointintersectionoflines{\centerpoint}{\externalpoint}%
							{\ne@anchor}{\after@ne@anchor}%
					\else% 
						\pgfpointintersectionoflines{\centerpoint}{\externalpoint}%
							{\after@ne@anchor}{\centerpoint\pgf@xa\pgf@x\after@ne@anchor\pgf@x\pgf@xa}%
					\fi%
				\fi%
			\else%
				\pgfmathanglebetweenpoints{\centerpoint}{\nw@anchor}%
				\ifdim\externalangle pt<\pgfmathresult pt\relax% north west.
					\pgfmathanglebetweenpoints{\centerpoint}{\after@sw@anchor\pgf@xa\pgf@x\after@ne@anchor\pgf@x\pgf@xa}%
					\ifdim\externalangle pt<\pgfmathresult pt\relax% before north west.
						\pgfpointintersectionoflines{\centerpoint}{\externalpoint}%
							{\centerpoint\pgf@xa\pgf@x\after@ne@anchor\pgf@x\pgf@xa}%
							{\after@sw@anchor\pgf@xa\pgf@x\after@ne@anchor\pgf@x\pgf@xa}%
					\else%
						\pgfpointintersectionoflines{\centerpoint}{\externalpoint}%
							{\after@sw@anchor\pgf@xa\pgf@x\after@ne@anchor\pgf@x\pgf@xa}%
							{\nw@anchor}%
					\fi%
				\else%
					\pgfmathanglebetweenpoints{\centerpoint}{\before@sw@anchor\pgf@xa\pgf@x\before@ne@anchor\pgf@x\pgf@xa}%
					\ifdim\externalangle pt<\pgfmathresult pt\relax% after north west.
						\pgfpointintersectionoflines{\centerpoint}{\externalpoint}%
							{\nw@anchor}{\before@sw@anchor\pgf@xa\pgf@x\before@ne@anchor\pgf@x\pgf@xa}%
					\else%
						\pgfpointintersectionoflines{\centerpoint}{\externalpoint}%
							{\before@sw@anchor\pgf@xa\pgf@x\before@ne@anchor\pgf@x\pgf@xa}%
							{\before@sw@anchor\pgf@xa\pgf@x\centerpoint\pgf@x\pgf@xa}%
					\fi%
				\fi%
			\fi%
		\else%
			\pgfmathanglebetweenpoints{\centerpoint}{\centerpoint\pgf@xa\pgf@x\after@sw@anchor\pgf@x\pgf@xa}%
			\ifdim\externalangle pt<\pgfmathresult pt\relax% south.
				\pgfmathanglebetweenpoints{\centerpoint}{\sw@anchor}%
				\ifdim\externalangle pt<\pgfmathresult pt\relax% south west.
					\pgfmathanglebetweenpoints{\centerpoint}{\before@sw@anchor}%
					\ifdim\externalangle pt<\pgfmathresult pt\relax% before south west.
						\pgfpointintersectionoflines{\centerpoint}{\externalpoint}%
							{\before@sw@anchor\pgf@xa\pgf@x\centerpoint\pgf@x\pgf@xa}%
							{\before@sw@anchor}%
					\else%
						\pgfpointintersectionoflines{\centerpoint}{\externalpoint}%
							{\before@sw@anchor}{\sw@anchor}%
					\fi%
				\else%
					\pgfmathanglebetweenpoints{\centerpoint}{\after@sw@anchor}%
					\ifdim\externalangle pt<\pgfmathresult pt\relax% after south west.
						\pgfpointintersectionoflines{\centerpoint}{\externalpoint}%
							{\sw@anchor}{\after@sw@anchor}%
					\else%
						\pgfpointintersectionoflines{\centerpoint}{\externalpoint}%
							{\after@sw@anchor}{\centerpoint\pgf@xa\pgf@x\after@sw@anchor\pgf@x\pgf@xa}%
					\fi%
				\fi%
			\else%
				\pgfmathanglebetweenpoints{\centerpoint}{\se@anchor}%
				\ifdim\externalangle pt<\pgfmathresult pt\relax% south east.
					\pgfmathanglebetweenpoints{\centerpoint}{\after@ne@anchor\pgf@xa\pgf@x\after@sw@anchor\pgf@x\pgf@xa}%
					\ifdim\externalangle pt<\pgfmathresult pt\relax% before south east.
						\pgfpointintersectionoflines{\centerpoint}{\externalpoint}%
							{\after@ne@anchor\pgf@xa\pgf@x\after@sw@anchor\pgf@x\pgf@xa}%
							{\centerpoint\pgf@xa\pgf@x\after@sw@anchor\pgf@x\pgf@xa}%
					\else%
						\pgfpointintersectionoflines{\centerpoint}{\externalpoint}%
							{\after@ne@anchor\pgf@xa\pgf@x\after@sw@anchor\pgf@x\pgf@xa}{\se@anchor}
					\fi%
				\else%
					\pgfmathanglebetweenpoints{\centerpoint}{\before@ne@anchor\pgf@xa\pgf@x\before@sw@anchor\pgf@x\pgf@xa}%
					\ifdim\externalangle pt<\pgfmathresult pt\relax% after south east.
						\pgfpointintersectionoflines{\centerpoint}{\externalpoint}%
							{\se@anchor}{\before@ne@anchor\pgf@xa\pgf@x\before@sw@anchor\pgf@x\pgf@xa}%					
					\else%
						\pgfpointintersectionoflines{\centerpoint}{\externalpoint}%
							{\before@ne@anchor\pgf@xa\pgf@x\before@sw@anchor\pgf@x\pgf@xa}%
							{\centerpoint\pgf@ya\pgf@y\before@ne@anchor\pgf@y\pgf@ya}%
					\fi%
				\fi%
			\fi%			
		\fi%
	}%			
}


\endinput

pgflibraryshapes.multipart.code.tex
% Copyright 2007 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.

\ProvidesFileRCS[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/libraries/shapes/pgflibraryshapes.multipart.code.tex,v 1.2 2010/01/07 01:12:23 vibrovski Exp $

\newbox\pgfnodepartlowerbox

%
% A circle that is split in the middle into an upper and a lower part.
%
% This node consists of two parts: The upper (main) part is shown in
% the upper half of the circle. The second part is the (optional)
% lower part.
%
% Parts: text, lower

\pgfdeclareshape{circle split}
{
  %
  % Node parts
  %
  \nodeparts{text,lower}

  %
  % Anchors
  %
  \savedanchor\centerpoint{%
    \pgf@x=.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength{\pgf@y}{\pgfkeysvalueof{/pgf/inner ysep}}%
    \pgf@y=-\pgf@y%
    \advance\pgf@y by-\dp\pgfnodeparttextbox%
    \advance\pgf@y by-.5\pgflinewidth%
  }%
  \savedanchor\loweranchor{%
    \pgf@x=-.5\wd\pgfnodepartlowerbox%
    \advance\pgf@x by.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength{\pgf@y}{\pgfkeysvalueof{/pgf/inner ysep}}%
    \pgf@y=-2\pgf@y%
    \advance\pgf@y by-\ht\pgfnodepartlowerbox%
    \advance\pgf@y by-.5\pgflinewidth%
    \advance\pgf@y by-\dp\pgfnodeparttextbox%
    \advance\pgf@y by-.5\pgflinewidth%
  }
    
  \saveddimen\radius{%
    % 
    % Caculate ``height radius''
    %
    %\pgf@ya=.5\ht\pgfnodeparttextbox%
%    \advance\pgf@ya by.5\dp\pgfnodeparttextbox%
%    \advance\pgf@ya by.5\ht\pgfnodepartlowerbox%
%    \advance\pgf@ya by.5\dp\pgfnodepartlowerbox%
%    \advance\pgf@ya by.5\pgflinewidth%
		%
		% MW: Suggested correction for above calculation:	Use the tallest box * 2.
		%
		\pgf@ya=.5\ht\pgfnodeparttextbox%
		\advance\pgf@ya by.5\dp\pgfnodeparttextbox%
		\pgf@yb=.5\ht\pgfnodepartlowerbox%
		\advance\pgf@yb by.5\dp\pgfnodepartlowerbox%
		\ifdim\pgf@ya>\pgf@yb\relax%
			\pgf@ya2.0\pgf@ya\relax%
		\else%
			\pgf@ya2.0\pgf@yb\relax%
		\fi%
		\advance\pgf@ya by.5\pgflinewidth%
    \pgfmathsetlength\pgf@yb{\pgfkeysvalueof{/pgf/inner ysep}}%
    \advance\pgf@ya by2\pgf@yb%
    % 
    % Caculate ``width radius''
    % 
    \pgf@xa=.5\wd\pgfnodeparttextbox%
    \ifdim\pgf@xa<.5\wd\pgfnodepartlowerbox%
      \pgf@xa=.5\wd\pgfnodepartlowerbox%
    \fi%
    \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
  % 
  \inheritanchorborder[from=circle]
  \inheritanchor[from=circle]{north}
  \inheritanchor[from=circle]{north west}
  \inheritanchor[from=circle]{north east}
  \inheritanchor[from=circle]{center}
  \inheritanchor[from=circle]{west}
  \inheritanchor[from=circle]{east}
  \inheritanchor[from=circle]{mid}
  \inheritanchor[from=circle]{mid west}
  \inheritanchor[from=circle]{mid east}
  \inheritanchor[from=circle]{base}
  \inheritanchor[from=circle]{base west}
  \inheritanchor[from=circle]{base east}
  \inheritanchor[from=circle]{south}
  \inheritanchor[from=circle]{south west}
  \inheritanchor[from=circle]{south east}
  \anchor{lower}{\loweranchor}

  %
  % Background path
  %
  \inheritbackgroundpath[from=circle]
  \beforebackgroundpath{
    \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%
    \advance\pgfutil@tempdima by-.5\pgflinewidth%  
    \pgfsetshortenstart{0pt}%
    \pgfsetshortenend{0pt}%
    \pgfsetarrows{-}%  
    \pgfpathmoveto{\pgfpointadd{\centerpoint}{\pgfqpoint{-1\pgfutil@tempdima}{0pt}}}%
    \pgfpathlineto{\pgfpointadd{\centerpoint}{\pgfqpoint{\pgfutil@tempdima}{0pt}}}%
    \pgfusepath{stroke}%
  }
}


%
% A circle that is split diagonally into an upper and a lower part.
%
% Parts: text, lower

\pgfdeclareshape{circle solidus}{%
  % Node parts
  \nodeparts{text,lower}% 
  % Anchors
  % solidus slants at 45 degrees
  % text placement minimizes the required radius,
  % this is achieved placing the "outer" corner
  % of each box in the line orthogonal to the
  % solidus which passes through circle center
  \savedanchor\centerpoint{%
    \pgf@x=0.5\wd\pgfnodeparttextbox%
    \advance\pgf@x by0.5\dp\pgfnodeparttextbox%
    \advance\pgf@x by0.5\ht\pgfnodeparttextbox%
    \pgf@y=-\pgf@x%
    \advance\pgf@y by\ht\pgfnodeparttextbox%
    \advance\pgf@x by0.3536\pgflinewidth%
    \advance\pgf@y by-0.3536\pgflinewidth%
    \pgfmathsetlength{\pgf@xa}{\pgfkeysvalueof{/pgf/inner xsep}}%
    \advance\pgf@x by\pgf@xa%
    \pgfmathsetlength{\pgf@ya}{\pgfkeysvalueof{/pgf/inner ysep}}%
    \advance\pgf@y by-\pgf@ya%
  }%
  \savedanchor\loweranchor{%
    \pgf@x=0.5\wd\pgfnodeparttextbox%
    \advance\pgf@x by0.5\dp\pgfnodeparttextbox%
    \advance\pgf@x by0.5\ht\pgfnodeparttextbox%
    \pgf@y=-\pgf@x%
    \advance\pgf@y by\ht\pgfnodeparttextbox%
    \advance\pgf@x by0.5\ht\pgfnodepartlowerbox%
    \advance\pgf@x by0.5\dp\pgfnodepartlowerbox%
    \advance\pgf@x by-0.5\wd\pgfnodepartlowerbox%
    \advance\pgf@y by-0.5\ht\pgfnodepartlowerbox%
    \advance\pgf@y by0.5\dp\pgfnodepartlowerbox%
    \advance\pgf@y by-0.5\wd\pgfnodepartlowerbox%
    \advance\pgf@x by0.7071\pgflinewidth%
    \advance\pgf@y by-0.7071\pgflinewidth%
    \pgfmathsetlength{\pgf@xa}{\pgfkeysvalueof{/pgf/inner xsep}}%
    \advance\pgf@x by2\pgf@xa%
    \pgfmathsetlength{\pgf@ya}{\pgfkeysvalueof{/pgf/inner ysep}}%
    \advance\pgf@y by-2\pgf@ya%
  }%
  \saveddimen\radius{%
    % "top" radius
    \pgf@x=\ht\pgfnodeparttextbox%
    \advance\pgf@x by\dp\pgfnodeparttextbox%
    \advance\pgf@x by\wd\pgfnodeparttextbox%
    % "bottom" radius
    \pgf@y=\ht\pgfnodepartlowerbox%
    \advance\pgf@y by\dp\pgfnodepartlowerbox%
    \advance\pgf@y by\wd\pgfnodepartlowerbox%
    % use the larger
    \ifdim\pgf@x<\pgf@y%
      \pgf@x=\pgf@y%
    \fi%
    \pgf@x=0.7071\pgf@x%
    % add spacings
    \advance\pgf@x by0.5\pgflinewidth%
    \pgfmathsetlength{\pgf@xa}{\pgfkeysvalueof{/pgf/inner xsep}}%
    \pgfmathsetlength{\pgf@ya}{\pgfkeysvalueof{/pgf/inner ysep}}%
    \pgfmathaddtolength{\pgf@x}{veclen(2\pgf@xa,2\pgf@ya)}%
    % If necessary, adjust radius so that the size requirements are
    % met:
    \pgfmathsetlength{\pgf@xa}{\pgfkeysvalueof{/pgf/minimum width}}%
    \pgfmathsetlength{\pgf@ya}{\pgfkeysvalueof{/pgf/minimum height}}%
    \ifdim\pgf@x<.5\pgf@xa%
      \pgf@x=.5\pgf@xa%
    \fi%
    \ifdim\pgf@x<.5\pgf@ya%
      \pgf@x=.5\pgf@ya%
    \fi%
    % Now, add larger of outer separations.
    \pgfmathsetlength{\pgf@xa}{\pgfkeysvalueof{/pgf/outer xsep}}%
    \pgfmathsetlength{\pgf@ya}{\pgfkeysvalueof{/pgf/outer ysep}}%
    \ifdim\pgf@xa<\pgf@ya%
      \advance\pgf@x by\pgf@ya%
    \else%
      \advance\pgf@x by\pgf@xa%
    \fi%
  }%
  % Anchors
  \inheritanchorborder[from=circle]%
  \inheritanchor[from=circle]{north}%
  \inheritanchor[from=circle]{north west}%
  \inheritanchor[from=circle]{north east}%
  \inheritanchor[from=circle]{center}%
  \inheritanchor[from=circle]{west}%
  \inheritanchor[from=circle]{east}%
  \inheritanchor[from=circle]{mid}%
  \inheritanchor[from=circle]{mid west}%
  \inheritanchor[from=circle]{mid east}%
  \inheritanchor[from=circle]{base}%
  \inheritanchor[from=circle]{base west}%
  \inheritanchor[from=circle]{base east}%
  \inheritanchor[from=circle]{south}%
  \inheritanchor[from=circle]{south west}%
  \inheritanchor[from=circle]{south east}%
  \anchor{lower}{\loweranchor}%
  % Background path
  \inheritbackgroundpath[from=circle]%
  \beforebackgroundpath{%
    \pgfutil@tempdima=\radius%
    \pgfmathsetlength{\pgf@xa}{\pgfkeysvalueof{/pgf/outer xsep}}%
    \pgfmathsetlength{\pgf@ya}{\pgfkeysvalueof{/pgf/outer ysep}}%
    \ifdim\pgf@xa<\pgf@ya%
      \advance\pgfutil@tempdima by-\pgf@ya%
    \else%
      \advance\pgfutil@tempdima by-\pgf@xa%
    \fi%
    \advance\pgfutil@tempdima by-.5\pgflinewidth%
    \pgfsetshortenstart{0pt}%
    \pgfsetshortenend{0pt}%
    \pgfsetarrows{-}%
    % solidus slants at 45 degrees and its length is
    % the golden section of the diameter
    \pgfpathmoveto{\pgfpointadd{\centerpoint}{\pgfqpoint{-0.437\pgfutil@tempdima}{-0.437\pgfutil@tempdima}}}%
    \pgfpathlineto{\pgfpointadd{\centerpoint}{\pgfqpoint{0.437\pgfutil@tempdima}{0.437\pgfutil@tempdima}}}%
    \pgfusepath{stroke}%
  }%
}


\def\pgf@lib@sh@newbox{\csname newbox\endcsname}% Get round outer.

\def\pgf@lib@sh@toalpha#1{%
	\ifcase#1\relax%
		\or one\or two\or three\or four\or five\or six\or seven\or eight\or nine\or ten%
		\or eleven\or twelve\or thirteen\or fourteen\or fifteen%
		\or sixteen\or seventeen\or eighteen\or nineteen\or twenty%
	\else%
		twenty%
	\fi%
}   


\def\pgf@lib@sh@getalpha#1#2{\expandafter\edef\expandafter#1\expandafter{\pgf@lib@sh@toalpha{#2}}}

\newbox\pgfnodeparttwobox
\newbox\pgfnodepartthreebox
\newbox\pgfnodepartfourbox

\let\pgfnodepartonebox=\pgfnodeparttextbox
\let\pgfnodepartsecondbox=\pgfnodeparttwobox
\let\pgfnodepartthirdbox=\pgfnodepartthreebox
\let\pgfnodepartfourthbox=\pgfnodepartfourbox

\def\pgf@lib@sh@allocateboxes#1{%
	\c@pgf@counta=#1\relax%
	\pgfmathloop%
		\ifnum\c@pgf@counta>4\relax%
		\pgfutil@ifundefined{pgfnodepart\pgf@lib@sh@toalpha{\c@pgf@counta}box}%
		{%
			\expandafter\pgf@lib@sh@newbox\csname pgfnodepart\pgf@lib@sh@toalpha{\c@pgf@counta}box\endcsname%
		}%
		{}%
		\advance\c@pgf@counta by-1\relax%
	\repeatpgfmathloop%
}

\def\pgf@lib@sh@rs@lefttext{left}
\def\pgf@lib@sh@rs@righttext{right}
\def\pgf@lib@sh@rs@centertext{center}
\def\pgf@lib@sh@rs@bottomtext{bottom}
\def\pgf@lib@sh@rs@toptext{top}
\def\pgf@lib@sh@rs@basetext{base}
\def\pgf@lib@sh@rs@nonetext{none}


\newif\ifpgfrectanglesplithorizontal
\newif\ifpgfrectanglesplitdrawsplits\pgfrectanglesplitdrawsplitstrue
\newif\ifpgfrectanglesplitignoreemptyparts
\newif\ifpgfrectanglesplitusecustomfill

\let\pgf@lib@sh@rs@every@emptypart=\pgfutil@empty
\let\pgf@lib@sh@rs@every@part=\pgfutil@empty
\def\pgf@lib@sh@rs@list@fill{none}

\pgfkeys{/pgf/.cd,
	rectangle split parts/.initial=4,
	rectangle split part align/.initial=center,
	rectangle split horizontal/.is if=pgfrectanglesplithorizontal,
	rectangle split ignore empty parts/.is if=pgfrectanglesplitignoreemptyparts,
	rectangle split empty part width/.code={%
		\pgfmathsetlength\pgf@x{#1}
		\edef\pgf@lib@sh@rs@temp{\noexpand\vrule width\the\pgf@x height0ptdepth0pt\relax}%
		\def\pgf@lib@sh@rs@@temp{\def\pgf@lib@sh@rs@every@emptypart}%
		\expandafter\expandafter\expandafter\pgf@lib@sh@rs@@temp\expandafter\expandafter\expandafter{%
			\expandafter\pgf@lib@sh@rs@every@emptypart\pgf@lib@sh@rs@temp}%
	},%
	rectangle split empty part width=1ex,
	rectangle split empty part height/.code={%
		\pgfmathsetlength\pgf@x{#1}
		\edef\pgf@lib@sh@rs@temp{\noexpand\vrule width0ptheight\the\pgf@x depth0pt\relax}%
		\def\pgf@lib@sh@rs@@temp{\def\pgf@lib@sh@rs@every@emptypart}%
		\expandafter\expandafter\expandafter\pgf@lib@sh@rs@@temp\expandafter\expandafter\expandafter{%
			\expandafter\pgf@lib@sh@rs@every@emptypart\pgf@lib@sh@rs@temp}%
	},%
	rectangle split empty part height=1ex,
	rectangle split empty part depth/.code={%
		\pgfmathsetlength\pgf@x{#1}
		\edef\pgf@lib@sh@rs@temp{\noexpand\vrule width0ptheight0ptdepth\the\pgf@x\relax}%
		\def\pgf@lib@sh@rs@@temp{\def\pgf@lib@sh@rs@every@emptypart}%
		\expandafter\expandafter\expandafter\pgf@lib@sh@rs@@temp\expandafter\expandafter\expandafter{%
			\expandafter\pgf@lib@sh@rs@every@emptypart\pgf@lib@sh@rs@temp}%
	},%
	rectangle split empty part depth=0ex,
	rectangle split every empty part/.store in=\pgf@lib@sh@rs@every@emptypart,
	rectangle split part fill/.code=\def\pgf@lib@sh@rs@list@fill{#1}\pgfrectanglesplitusecustomfilltrue,
	rectangle split uses custom fill/.is if=pgfrectanglesplitusecustomfill,
	rectangle split draw splits/.is if=pgfrectanglesplitdrawsplits,
	rectangle split allocate boxes/.code=\pgf@lib@sh@allocateboxes{#1}
}


\def\pgf@lib@sh@rs@process@list#1#2{%
	\c@pgf@counta=1\relax%
	\c@pgf@countb=#2\relax%
	\edef\pgf@lib@sh@rs@temp{#1}%
	\expandafter\pgf@lib@sh@rs@@process@list\pgf@lib@sh@rs@temp,\pgf@stop,}

\def\pgf@lib@sh@rs@@process@list{%
	\pgfutil@ifnextchar x{\pgf@lib@sh@rs@@@process@list}%
		{\pgf@lib@sh@rs@@@process@list}}
		
\def\pgf@lib@sh@rs@@@process@list#1,{%
	\ifx#1\pgf@stop%
		\let\pgf@next\pgf@lib@sh@rs@@@@process@list%
	\else%
		\pgf@lib@sh@getalpha\pgf@lib@sh@rs@number{\c@pgf@counta}%
		\def\pgf@lib@sh@rs@lastalign{#1}%
		\pgfutil@namedef{pgf@lib@sh@rs@\pgf@lib@sh@toalpha{\c@pgf@counta}@item}{#1}%
		\let\pgf@next\pgf@lib@sh@rs@@process@list%
		\advance\c@pgf@counta by1\relax%
	\fi%
	\pgf@next}

\def\pgf@lib@sh@rs@@@@process@list{%
	\pgfmathloop%
		\ifnum\c@pgf@counta>\c@pgf@countb%
		\else%
			\expandafter\edef\csname pgf@lib@sh@rs@\pgf@lib@sh@toalpha{\c@pgf@counta}@item\endcsname%
				{\pgf@lib@sh@rs@lastalign}%
			\advance\c@pgf@counta by1\relax%
	\repeatpgfmathloop%
}

\pgf@lib@sh@allocateboxes{20}

\pgfdeclareshape{rectangle split}{%
	\savedmacro\rectanglesplitparameters{%
		\pgfmathsetcount\c@pgf@counta{\pgfkeysvalueof{/pgf/rectangle split parts}}%
		\edef\parts{\the\c@pgf@counta}%
		\addtosavedmacro\parts%
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
		\edef\innerxsep{\the\pgf@x}%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
		\edef\innerysep{\the\pgf@y}%
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
		\edef\outerxsep{\the\pgf@x}%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/outer ysep}}%
		\edef\outerysep{\the\pgf@y}%
		\addtosavedmacro\outerxsep%
		\addtosavedmacro\outerysep%
		%
		\pgf@x=0pt\relax% Widest box.
		\pgf@y=0pt\relax% Tallest box.
		%
		\pgfutil@tempdima=0pt\relax% Maximum box height.
		\pgfutil@tempdimb=0pt\relax% Maximum box depth.
		%
		% Get the dimensions of the boxes...
		%
		\pgfmathloop%
			\ifnum\pgfmathcounter>\parts%
			\else%
				\pgf@lib@sh@getalpha\pgf@lib@sh@rs@number{\pgfmathcounter}%
				%
				\expandafter\let\expandafter\pgf@lib@sh@box\expandafter=%
					\csname pgfnodepart\pgf@lib@sh@rs@number box\endcsname%
				\pgf@xa=\wd\pgf@lib@sh@box%
				\pgf@ya=\ht\pgf@lib@sh@box%
				\pgf@yb=\dp\pgf@lib@sh@box%
				%
				% Test to see if the box is empty...
				%
				\expandafter\def\csname pgf@lib@sh@rs@empty@\pgf@lib@sh@rs@number\endcsname{\relax}%
				\ifdim\pgf@xa=0pt\relax%
					\ifdim\pgf@ya=0pt\relax%
						\ifdim\pgf@yb=0pt\relax%
							%
							% ...It is. So...
							%
							\ifpgfrectanglesplitignoreemptyparts%
								%
								% ...flag this if we are ignoring parts... 
								%
								\expandafter\let\csname pgf@lib@sh@rs@empty@\pgf@lib@sh@rs@number\endcsname=\pgfutil@empty%
							\else%
								%
								% ...otherwise insert the code for every empty part.
								%
								\setbox\pgf@lib@sh@box=\hbox{{\pgf@lib@sh@rs@every@emptypart}}%
								\pgf@xa=\wd\pgf@lib@sh@box%
								\pgf@ya=\ht\pgf@lib@sh@box%
								\pgf@yb=\dp\pgf@lib@sh@box%
							\fi%								
						\fi%
					\fi%
				\fi%	
				\expandafter\edef\csname pgf@lib@sh@rs@width@\pgf@lib@sh@rs@number\endcsname{\the\pgf@xa}%
				\expandafter\edef\csname pgf@lib@sh@rs@height@\pgf@lib@sh@rs@number\endcsname{\the\pgf@ya}%
				\expandafter\edef\csname pgf@lib@sh@rs@depth@\pgf@lib@sh@rs@number\endcsname{\the\pgf@yb}%
				\expandafter\addtosavedmacro\csname pgf@lib@sh@rs@empty@\pgf@lib@sh@rs@number\endcsname%
				%
				% ...saving the widest box...
				%
				\ifdim\pgf@xa>\pgf@x%
					\pgf@x=\pgf@xa%
				\fi%
				%
				% ...the maximum height and depth...
				%
				\ifdim\pgf@ya>\pgfutil@tempdima%
					\pgfutil@tempdima=\pgf@ya%
				\fi%
				\ifdim\pgf@yb>\pgfutil@tempdimb%
					\pgfutil@tempdimb=\pgf@yb%
				\fi%
				%
				% ...and the tallest box.
				%
				\pgf@yc=\pgfutil@tempdima%
				\advance\pgf@yc by\pgfutil@tempdimb%
				\ifdim\pgf@yc>\pgf@y%
					\pgf@y=\pgf@yc%
				\fi%
		\repeatpgfmathloop%
		%
		\edef\pgf@lib@sh@rs@max@width{\the\pgf@x}%
		\edef\pgf@lib@sh@rs@max@totalheight{\the\pgf@y}%
		%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/minimum width}}%
		\advance\pgf@x by-\innerxsep\relax%
		\advance\pgf@x by-\innerxsep\relax%
		\pgf@xa=\pgf@x%			
		\advance\pgf@xa by-\pgf@lib@sh@rs@max@width\relax%
		\ifdim\pgf@xa>0pt\relax%
			\edef\pgf@lib@sh@rs@max@width{\the\pgf@x}%
		\fi%	
		%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/minimum height}}%
		\advance\pgf@y by-\innerysep\relax%
		\advance\pgf@y by-\innerysep\relax%
		\pgf@ya=\pgf@y%			
		\advance\pgf@ya by-\pgf@lib@sh@rs@max@totalheight\relax%
		\ifdim\pgf@ya>0pt\relax%
			\edef\pgf@lib@sh@rs@max@totalheight{\the\pgf@y}%
		\fi%		
		%
		% Get the alignment of each node part box.
		%
		\pgf@lib@sh@rs@process@list{\pgfkeysvalueof{/pgf/rectangle split part align}}{\parts}%
		%
		% Are we splitting horizontally or vertically?
		%
		\ifpgfrectanglesplithorizontal%
			%
			% Calculate the origins of each node part box.
			%
			\pgf@x=0pt\relax%
			\pgfmathloop%
				\ifnum\pgfmathcounter>\parts%
				\else%
					\pgf@lib@sh@getalpha\pgf@lib@sh@rs@number{\pgfmathcounter}%
					%
					\expandafter\let\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number\endcsname=\pgfutil@empty%
					\expandafter\ifx\csname pgf@lib@sh@rs@empty@\pgf@lib@sh@rs@number\endcsname\pgfutil@empty%
						\ifpgfrectanglesplitignoreemptyparts%
							\expandafter\let\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number\endcsname=%
								\pgf@lib@sh@rs@lastanchor%
						\fi%
					\fi%
					%
					% Adjust for alignment.
					%
					\expandafter\ifx\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number\endcsname\pgfutil@empty%
						\expandafter\ifx\csname pgf@lib@sh@rs@\pgf@lib@sh@rs@number @item\endcsname%
								\pgf@lib@sh@rs@bottomtext%
							\pgf@y=\csname pgf@lib@sh@rs@depth@\pgf@lib@sh@rs@number\endcsname\relax%
						\else%
							\expandafter\ifx\csname pgf@lib@sh@rs@\pgf@lib@sh@rs@number @item\endcsname%
									\pgf@lib@sh@rs@toptext%
								\pgf@y=-\csname pgf@lib@sh@rs@height@\pgf@lib@sh@rs@number\endcsname\relax%
								\advance\pgf@y by\pgf@lib@sh@rs@max@totalheight\relax%
							\else%
								\expandafter\ifx\csname pgf@lib@sh@rs@\pgf@lib@sh@rs@number @item\endcsname%
										\pgf@lib@sh@rs@basetext%
									\pgf@y=\pgf@lib@sh@rs@max@totalheight\relax%
									\advance\pgf@y by-\pgfutil@tempdima%
									\advance\pgf@y by\pgfutil@tempdimb%
									\divide\pgf@y by2\relax%
								\else%
									\pgf@y=\pgf@lib@sh@rs@max@totalheight\relax%
									\advance\pgf@y by-\csname pgf@lib@sh@rs@height@\pgf@lib@sh@rs@number\endcsname\relax%
									\advance\pgf@y by\csname pgf@lib@sh@rs@depth@\pgf@lib@sh@rs@number\endcsname\relax%
									\divide\pgf@y by2\relax%
								\fi%
							\fi%				
						\fi%
						%
						% Re-adjust as the first box is at the origin.
						%
						\ifnum\pgfmathcounter=1\relax%
							\edef\pgf@lib@sh@rs@yoffset{\the\pgf@y}%
							\pgf@y=0pt\relax%
							\pgfextract@process\pgf@lib@sh@rs@anchor@one{}%
							\addtosavedmacro\pgf@lib@sh@rs@anchor@one%
							\let\pgf@lib@sh@rs@lastanchor=\pgf@lib@sh@rs@anchor@one%
							\let\pgf@lib@sh@rs@lastnumber=\pgf@lib@sh@rs@number%
						\else
							\advance\pgf@y by-\pgf@lib@sh@rs@yoffset\relax%
							\advance\pgf@x by\csname pgf@lib@sh@rs@width@\pgf@lib@sh@rs@lastnumber\endcsname\relax%
							\advance\pgf@x by\innerxsep\relax%
							\advance\pgf@x by\pgflinewidth%
							\advance\pgf@x by\innerxsep\relax%
							\expandafter\pgfextract@process\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number\endcsname{}%
							\expandafter\let\expandafter\pgf@lib@sh@rs@lastanchor\expandafter=%
								\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number\endcsname%
							\let\pgf@lib@sh@rs@lastnumber=\pgf@lib@sh@rs@number%
							\expandafter\addtosavedmacro\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number\endcsname%
						\fi%
					\fi%
			\repeatpgfmathloop%
			%
			% Calculate some anchors.
			%
			\pgfextract@process\northeast{%
				\pgf@lib@sh@rs@lastanchor%
				\advance\pgf@x by\csname pgf@lib@sh@rs@width@\pgf@lib@sh@rs@lastnumber\endcsname\relax%
				\advance\pgf@x by\innerxsep\relax%
				\advance\pgf@x by\outerxsep\relax%
				\pgf@y=\pgf@lib@sh@rs@max@totalheight\relax%
				\advance\pgf@y by-\pgf@lib@sh@rs@yoffset\relax%
				\advance\pgf@y by\innerysep\relax%
				\advance\pgf@y by\outerysep\relax%
			}%
			\addtosavedmacro\northeast%
			\pgfextract@process\southwest{%
				\pgf@lib@sh@rs@anchor@one%
				\advance\pgf@x by-\innerxsep\relax%
				\advance\pgf@x by-\outerxsep\relax%
				\pgf@y=-\pgf@lib@sh@rs@yoffset\relax%
				\advance\pgf@y by-\innerysep\relax%
				\advance\pgf@y by-\outerysep\relax%
			}%
			\addtosavedmacro\southwest%	
			%
			\pgfextract@process\centerpoint{%
				\pgfpointadd{\southwest}{\northeast}%
				\divide\pgf@x by2\relax%
				\divide\pgf@y by2\relax%
			}%
			\addtosavedmacro\centerpoint%	
			%
			\pgfmathloop%
				\ifnum\pgfmathcounter>\parts%
				\else%
					\pgf@lib@sh@getalpha\pgf@lib@sh@rs@number{\pgfmathcounter}%
					%
					\expandafter\ifx\csname pgf@lib@sh@rs@empty@\pgf@lib@sh@rs@number\endcsname\pgfutil@empty%
					\else%
						\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number\endcsname%
						\pgf@xa=\pgf@x%
						\pgf@xb=\csname pgf@lib@sh@rs@width@\pgf@lib@sh@rs@number\endcsname\relax%
						\advance\pgf@xa by0.5\pgf@xb% 
						\expandafter\pgfextract@process\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @south\endcsname{%
							\southwest%
							\pgf@x=\pgf@xa%
						}%
						\expandafter\pgfextract@process\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @north\endcsname{%
							\northeast%
							\pgf@x=\pgf@xa%
						}%
						\expandafter\addtosavedmacro\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @north\endcsname%
						\expandafter\addtosavedmacro\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @south\endcsname%
						\ifnum\pgfmathcounter=\parts%
						\else%
							\advance\pgf@xa by0.5\pgf@xb%
							\advance\pgf@xa by\innerxsep\relax%
							\advance\pgf@xa by.5\pgflinewidth%
							\expandafter\pgfextract@process\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @split@south\endcsname{%
								\southwest%
								\pgf@x=\pgf@xa%
							}%
							\expandafter\pgfextract@process\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @split@north\endcsname{%
								\northeast%
								\pgf@x=\pgf@xa%
							}%
							\expandafter\pgfextract@process\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @split\endcsname{%
								\centerpoint%
								\pgf@x=\pgf@xa%
							}%
							\expandafter\addtosavedmacro\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @split@north\endcsname%
							\expandafter\addtosavedmacro\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @split@south\endcsname%
							\expandafter\addtosavedmacro\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @split\endcsname%
						\fi%	
					\fi%
			\repeatpgfmathloop%
		\else%
			%
			% Calculate the origins of each node part box.
			%
			\pgf@y=0pt\relax%
			\pgfmathloop%
				\ifnum\pgfmathcounter>\parts%
				\else%
					\pgf@lib@sh@getalpha\pgf@lib@sh@rs@number{\pgfmathcounter}%
					%
					\expandafter\let\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number\endcsname=\pgfutil@empty%
					\expandafter\ifx\csname pgf@lib@sh@rs@empty@\pgf@lib@sh@rs@number\endcsname\pgfutil@empty%
						\ifpgfrectanglesplitignoreemptyparts%
							\expandafter\let\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number\endcsname=%
								\pgf@lib@sh@rs@lastanchor%
						\fi%
					\fi%
					%
					% Adjust for alignment.
					%
					\expandafter\ifx\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number\endcsname\pgfutil@empty%
						\expandafter\ifx\csname pgf@lib@sh@rs@\pgf@lib@sh@rs@number @item\endcsname%
								\pgf@lib@sh@rs@lefttext%
							\pgf@x=0pt\relax%
						\else%
							\expandafter\ifx\csname pgf@lib@sh@rs@\pgf@lib@sh@rs@number @item\endcsname%
									\pgf@lib@sh@rs@righttext%
								\pgf@x=-\csname pgf@lib@sh@rs@width@\pgf@lib@sh@rs@number\endcsname\relax%
								\advance\pgf@x by\pgf@lib@sh@rs@max@width\relax%
							\else%
								\pgf@x=-\csname pgf@lib@sh@rs@width@\pgf@lib@sh@rs@number\endcsname\relax%
								\advance\pgf@x by\pgf@lib@sh@rs@max@width\relax%
								\divide\pgf@x by2\relax%
						\fi%				
					\fi%
					%
					% Re-adjust as the first box is at the origin.
					%
					\ifnum\pgfmathcounter=1\relax%
						\edef\pgf@lib@sh@rs@xoffset{\the\pgf@x}%
						\pgf@x=0pt\relax%
						\pgfextract@process\pgf@lib@sh@rs@anchor@one{}%
						\addtosavedmacro\pgf@lib@sh@rs@anchor@one%
						\let\pgf@lib@sh@rs@lastanchor=\pgf@lib@sh@rs@anchor@one%
						\let\pgf@lib@sh@rs@lastnumber=\pgf@lib@sh@rs@number%
					\else
						\advance\pgf@x by-\pgf@lib@sh@rs@xoffset\relax%
						\advance\pgf@y by-\csname pgf@lib@sh@rs@depth@\pgf@lib@sh@rs@lastnumber\endcsname\relax%
						\advance\pgf@y by-\innerysep\relax%
						\advance\pgf@y by-\pgflinewidth%
						\advance\pgf@y by-\innerysep\relax%
						\advance\pgf@y by-\csname pgf@lib@sh@rs@height@\pgf@lib@sh@rs@number\endcsname\relax%
						\expandafter\pgfextract@process\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number\endcsname{}%
						\expandafter\let\expandafter\pgf@lib@sh@rs@lastanchor\expandafter=%
							\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number\endcsname%
						\let\pgf@lib@sh@rs@lastnumber=\pgf@lib@sh@rs@number%
						\expandafter\addtosavedmacro\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number\endcsname%
					\fi%
				\fi%
			\repeatpgfmathloop%
			%			
			% Calculate some anchors.
			%
			\pgfextract@process\northeast{%
				\pgf@x=\pgf@lib@sh@rs@max@width\relax%
				\advance\pgf@x by-\pgf@lib@sh@rs@xoffset\relax%
				\advance\pgf@x by\innerxsep\relax%
				\advance\pgf@x by\outerxsep\relax%
				\pgf@y=\pgf@lib@sh@rs@height@one\relax%
				\advance\pgf@y by\innerysep\relax%
				\advance\pgf@y by\outerysep\relax%
				\advance\pgf@y by.5\pgflinewidth%
			}%
			\addtosavedmacro\northeast%
			\pgfextract@process\southwest{%
				\pgf@lib@sh@rs@lastanchor%
				\pgf@x=-\pgf@lib@sh@rs@xoffset\relax%
				\advance\pgf@x by-\innerxsep\relax%
				\advance\pgf@x by-\outerxsep\relax%
				\advance\pgf@y by-\csname pgf@lib@sh@rs@depth@\pgf@lib@sh@rs@lastnumber\endcsname\relax%
				\advance\pgf@y by-\innerysep\relax%
				\advance\pgf@y by-\outerysep\relax%
				\advance\pgf@y by-.5\pgflinewidth%
			}%
			\addtosavedmacro\southwest%	
			%
			\pgfextract@process\centerpoint{%
				\pgfpointadd{\southwest}{\northeast}%
				\divide\pgf@x by2\relax%
				\divide\pgf@y by2\relax%
			}%
			\addtosavedmacro\centerpoint%	
			%			
			\pgfmathloop%
				\ifnum\pgfmathcounter>\parts%
				\else%
					\pgf@lib@sh@getalpha\pgf@lib@sh@rs@number{\pgfmathcounter}%
					%
					\expandafter\ifx\csname pgf@lib@sh@rs@empty@\pgf@lib@sh@rs@number\endcsname\pgfutil@empty%
					\else%
						\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number\endcsname%
						\pgf@ya=\csname pgf@lib@sh@rs@height@\pgf@lib@sh@rs@number\endcsname\relax%
						\advance\pgf@y by0.5\pgf@ya%
						\pgf@ya=\csname pgf@lib@sh@rs@depth@\pgf@lib@sh@rs@number\endcsname\relax%
						\advance\pgf@y by-0.5\pgf@ya%
						\pgf@ya=\pgf@y%
						\expandafter\pgfextract@process\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @west\endcsname{%
							\southwest%
							\pgf@y=\pgf@ya%
						}%
						\expandafter\pgfextract@process\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @east\endcsname{%
							\northeast%
							\pgf@y=\pgf@ya%
						}%
						\expandafter\addtosavedmacro\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @east\endcsname%
						\expandafter\addtosavedmacro\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @west\endcsname%
						\ifnum\pgfmathcounter=\parts%
						\else%
							\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number\endcsname%
							\pgf@ya=\pgf@y%
							\advance\pgf@ya by-\csname pgf@lib@sh@rs@depth@\pgf@lib@sh@rs@number\endcsname\relax%
							\advance\pgf@ya by-\innerysep\relax%
							\advance\pgf@ya by-.5\pgflinewidth%
							\expandafter\pgfextract@process\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @split@west\endcsname{%
								\southwest%
								\pgf@y=\pgf@ya%
							}%
							\expandafter\pgfextract@process\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @split@east\endcsname{%
								\northeast%
								\pgf@y=\pgf@ya%
							}%
							\expandafter\pgfextract@process\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @split\endcsname{%
								\centerpoint%
								\pgf@y=\pgf@ya%
							}%
							\expandafter\addtosavedmacro\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @split@east\endcsname%
							\expandafter\addtosavedmacro\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @split@west\endcsname%
							\expandafter\addtosavedmacro\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @split\endcsname%
						\fi%	
					\fi%
			\repeatpgfmathloop%
		\fi%
	}%
	\savedanchor\basepoint{%
		\pgf@x=0.5\wd\pgfnodeparttextbox%
		\pgf@y=0pt\relax%
	}
	\savedanchor\midpoint{%
		\pgf@x=0.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{+0.5ex}%
	}
	\anchor{center}{%
		\rectanglesplitparameters%
		\centerpoint%
	}%
	\anchor{base}{\basepoint}
	\anchor{base east}{%
		\rectanglesplitparameters%
		\northeast%
		\pgf@y=0pt\relax%
	}%
	\anchor{base west}{%
		\rectanglesplitparameters%
		\southwest%
		\pgf@y=0pt\relax%
	}%
	\anchor{mid}{\midpoint}%
	\anchor{mid east}{%
		\rectanglesplitparameters%
		\northeast%
		\pgf@xa=\pgf@x%
		\midpoint%
		\pgf@x=\pgf@xa%
	}%
	\anchor{mid west}{%
		\rectanglesplitparameters%
		\southwest%
		\pgf@xa=\pgf@x%
		\midpoint%
		\pgf@x=\pgf@xa%
	}%
	\anchor{north}{%
		\rectanglesplitparameters%
		\centerpoint%
		\pgf@xa=\pgf@x%
		\northeast%
		\pgf@x=\pgf@xa%
	}
	\anchor{south}{%
		\rectanglesplitparameters%
		\centerpoint%
		\pgf@xa=\pgf@x%
		\southwest%
		\pgf@x=\pgf@xa%
	}
	\anchor{east}{%
		\rectanglesplitparameters%
		\centerpoint%
		\pgf@ya=\pgf@y%
		\northeast%
		\pgf@y=\pgf@ya%
	}
	\anchor{west}{%
		\rectanglesplitparameters%
		\centerpoint%
		\pgf@ya=\pgf@y%
		\southwest%
		\pgf@y=\pgf@ya%
	}
	\anchor{north east}{%
		\rectanglesplitparameters%
		\northeast%
	}
	\anchor{north west}{%
		\rectanglesplitparameters%
		\northeast%
		\pgf@ya=\pgf@y%
		\southwest%
		\pgf@y=\pgf@ya%
	}
	\anchor{south west}{%
		\rectanglesplitparameters%
		\southwest%
	}
	\anchor{south east}{%
		\rectanglesplitparameters%
		\southwest%
		\pgf@ya=\pgf@y%
		\northeast%
		\pgf@y=\pgf@ya%
	}
	\behindbackgroundpath{%
		\ifpgfrectanglesplitusecustomfill%
			\pgf@lib@sh@rs@process@list{\pgf@lib@sh@rs@list@fill}{\parts}%
			{%
				\ifpgfrectanglesplithorizontal%
					\expandafter\let\expandafter\pgf@lib@sh@rs@fill@bottomleft\expandafter=%
						\csname pgf@anchor@rectangle split@south west\endcsname%
					\pgfmathloop%
						\ifnum\pgfmathcounter>\parts%
						\else%
							\pgf@lib@sh@getalpha\pgf@lib@sh@rs@number{\pgfmathcounter}%
							\ifnum\pgfmathcounter=\parts%
								\expandafter\let\expandafter\pgf@lib@sh@rs@fill@topright\expandafter=%
									\csname pgf@anchor@rectangle split@north east\endcsname%
							\else%								
								\expandafter\let\expandafter\pgf@lib@sh@rs@fill@topright\expandafter=%
									\csname pgf@anchor@rectangle split@\pgf@lib@sh@rs@number\space split north\endcsname%
							\fi%
							\expandafter\ifx\csname pgf@lib@sh@rs@empty@\pgf@lib@sh@rs@number\endcsname\pgfutil@empty%
							\else%
								\expandafter\ifx\csname pgf@lib@sh@rs@\pgf@lib@sh@rs@number @item\endcsname\pgf@lib@sh@rs@nonetext%
								\else%
									\pgfextract@process\pgf@lib@sh@rs@fill@bottomleft{%
										\pgf@lib@sh@rs@fill@bottomleft%
										\advance\pgf@y by\outerysep\relax%
										\ifnum\pgfmathcounter=1\relax%
											\advance\pgf@x by\outerxsep\relax%
										\fi%								
									}%
									\pgfextract@process\pgf@lib@sh@rs@fill@topright{%
										\pgf@lib@sh@rs@fill@topright%
										\advance\pgf@y by-\outerysep\relax%
										\ifnum\pgfmathcounter=\parts\relax%
											\advance\pgf@x by-\outerxsep\relax%
										\fi%									
									}%
									\ifnum\pgfmathcounter>1\relax%
										\begingroup\pgfsetcornersarced{\pgfpointorigin}%
									\fi%
									\pgfpathmoveto{%
										\pgf@lib@sh@rs@fill@topright%
										\pgf@xa=\pgf@x%
										\pgf@lib@sh@rs@fill@bottomleft%
										\pgf@x=\pgf@xa%	
									}%
									\pgfpathlineto{\pgf@lib@sh@rs@fill@bottomleft}%
									\pgfpathlineto{%
										\pgf@lib@sh@rs@fill@bottomleft%
										\pgf@xa=\pgf@x%
										\pgf@lib@sh@rs@fill@topright%
										\pgf@x=\pgf@xa%									
									}%
									\ifnum\pgfmathcounter>1\relax%
										\endgroup%
									\fi%
									\ifnum\pgfmathcounter<\parts%
										\begingroup\pgfsetcornersarced{\pgfpointorigin}%
									\fi%
									\pgfpathlineto{\pgf@lib@sh@rs@fill@topright}%
									\pgfpathclose%
									\ifnum\pgfmathcounter<\parts%
										\endgroup%
									\fi%
									\pgfsetfillcolor{\csname pgf@lib@sh@rs@\pgf@lib@sh@rs@number @item\endcsname}%
									\pgfusepath{fill}%
								\fi%
							\fi%
							\pgfextract@process\pgf@lib@sh@rs@fill@bottomleft{%
								\pgf@lib@sh@rs@fill@bottomleft%
								\pgf@ya=\pgf@y%
								\pgf@lib@sh@rs@fill@topright%
								\pgf@y=\pgf@ya%
								\advance\pgf@y by-\outerysep%
							}%
					\repeatpgfmathloop%	
				\else%
					\expandafter\let\expandafter\pgf@lib@sh@rs@fill@topright\expandafter=%
						\csname pgf@anchor@rectangle split@north east\endcsname%
					\pgfmathloop%
						\ifnum\pgfmathcounter>\parts%
						\else%
							\pgf@lib@sh@getalpha\pgf@lib@sh@rs@number{\pgfmathcounter}%
							\ifnum\pgfmathcounter=\parts%
								\expandafter\let\expandafter\pgf@lib@sh@rs@fill@bottomleft\expandafter=%
									\csname pgf@anchor@rectangle split@south west\endcsname%
							\else%								
								\expandafter\let\expandafter\pgf@lib@sh@rs@fill@bottomleft\expandafter=%
									\csname pgf@anchor@rectangle split@\pgf@lib@sh@rs@number\space split west\endcsname%
							\fi%
							\expandafter\ifx\csname pgf@lib@sh@rs@empty@\pgf@lib@sh@rs@number\endcsname\pgfutil@empty%
							\else%
								\expandafter\ifx\csname pgf@lib@sh@rs@\pgf@lib@sh@rs@number @item\endcsname\pgf@lib@sh@rs@nonetext%
								\else%
									\pgfextract@process\pgf@lib@sh@rs@fill@bottomleft{%
										\pgf@lib@sh@rs@fill@bottomleft%
										\advance\pgf@x by\outerxsep\relax%
										\ifnum\parts=1\relax%
											\advance\pgf@y by\outerysep\relax%
										\else%
											\ifnum\pgfmathcounter=\parts
												\advance\pgf@y by\outerysep\relax%
											\fi%
										\fi%									
									}%
									\pgfextract@process\pgf@lib@sh@rs@fill@topright{%
										\pgf@lib@sh@rs@fill@topright%
										\advance\pgf@x by-\outerxsep\relax%
										\ifnum\parts=1\relax%
											\advance\pgf@y by-\outerysep\relax%
										\else%
											\ifnum\pgfmathcounter=1\relax%
												\advance\pgf@y by-\outerysep\relax%
											\fi%
										\fi%									
									}%
									\pgfpathmoveto{\pgf@lib@sh@rs@fill@bottomleft}%
									\ifnum\pgfmathcounter>1\relax%
										\begingroup\pgfsetcornersarced{\pgfpointorigin}%
									\fi%
									\pgfpathlineto{%
										\pgf@lib@sh@rs@fill@bottomleft%
										\pgf@xa=\pgf@x%
										\pgf@lib@sh@rs@fill@topright%
										\pgf@x=\pgf@xa%									
									}%
									\pgfpathlineto{\pgf@lib@sh@rs@fill@topright}%
									\ifnum\pgfmathcounter>1\relax%
										\endgroup%%
									\fi%
									\ifnum\pgfmathcounter<\parts%
										\begingroup\pgfsetcornersarced{\pgfpointorigin}%
									\fi%
									\pgfpathlineto{%
										\pgf@lib@sh@rs@fill@topright%
										\pgf@xa=\pgf@x%
										\pgf@lib@sh@rs@fill@bottomleft%
										\pgf@x=\pgf@xa%									
									}%
									\pgfpathclose%
									\ifnum\pgfmathcounter<\parts%
										\endgroup%
									\fi%
									\pgfsetfillcolor{\csname pgf@lib@sh@rs@\pgf@lib@sh@rs@number @item\endcsname}%
									\pgfusepath{fill}%
								\fi%
							\fi%
							\pgfextract@process\pgf@lib@sh@rs@fill@topright{%
								\pgf@lib@sh@rs@fill@topright%
								\pgf@xa=\pgf@x%
								\pgf@lib@sh@rs@fill@bottomleft%
								\pgf@x=\pgf@xa%	
								\advance\pgf@x by\outerxsep\relax%						
							}%
					\repeatpgfmathloop%	
				\fi%	
			}%
		\fi%
	}%
	\backgroundpath{%
		\begingroup%
			\pgfextract@process\southwest{%
				\southwest%
				\advance\pgf@x by\outerxsep\relax%
				\advance\pgf@y by\outerysep\relax%
			}%
			\pgfextract@process\northeast{%
				\northeast%
				\advance\pgf@x by-\outerxsep\relax%
				\advance\pgf@y by-\outerysep\relax%
			}%
			\pgfpathrectangle{\southwest}{\pgfpointdiff{\southwest}{\northeast}}%
		\endgroup%
		\ifpgfrectanglesplitdrawsplits%
			\pgfmathloop%
				\ifnum\pgfmathcounter=\parts%
				\else%
					\pgf@lib@sh@getalpha\pgf@lib@sh@rs@number{\pgfmathcounter}%
					%
					\expandafter\ifx\csname pgf@lib@sh@rs@empty@\pgf@lib@sh@rs@number\endcsname\pgfutil@empty%
					\else%
						\pgfpathmoveto{%
							\ifpgfrectanglesplithorizontal%
								\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @split@north\endcsname%
								\advance\pgf@y by-\outerysep\relax%
							\else%
								\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @split@east\endcsname%
								\advance\pgf@x by-\outerxsep\relax%
							\fi%
						}%
						\pgfpathlineto{%
							\ifpgfrectanglesplithorizontal%
								\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @split@south\endcsname%
								\advance\pgf@y by\outerysep\relax%
							\else%
								\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@number @split@west\endcsname%
								\advance\pgf@x by\outerxsep\relax%
							\fi%
						}%	
					\fi%
			\repeatpgfmathloop%
		\fi%
	}%
	\anchorborder{%
  	\pgfutil@tempdima\pgf@x%
  	\pgfutil@tempdimb\pgf@y%
  	\rectanglesplitparameters%
  	\pgfpointdiff{\southwest}{\northeast}%
  	\pgf@x.5\pgf@x%
  	\pgf@y.5\pgf@y%
  	\edef\pgf@marshall{%
  		\noexpand\pgfpointborderrectangle{%
  				\noexpand\pgfqpoint{\the\pgfutil@tempdima}{\the\pgfutil@tempdimb}%
  			}%
      	{%
      		\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}%
      	}%
    }%
    \pgf@marshall%
    \pgf@xa\pgf@x%
    \pgf@ya\pgf@y%
    \centerpoint%
    \advance\pgf@x\pgf@xa%
    \advance\pgf@y\pgf@ya%
   }%
	%
	% Hackery to install the correct number of node parts.
	%
	\expandafter\pgfutil@g@addto@macro\csname pgf@sh@s@rectangle split\endcsname{%
		\let\pgf@lib@sh@rs@temp=\pgfutil@empty%
		\pgfmathloop%
			\ifnum\pgfmathcounter=\parts%
				\expandafter\edef\csname pgf@sh@boxes@rectangle split\endcsname%
					{\pgf@lib@sh@rs@temp\pgf@lib@sh@toalpha{\pgfmathcounter}}%
			\else%
				\edef\pgf@lib@sh@rs@temp{\pgf@lib@sh@rs@temp\pgf@lib@sh@toalpha{\pgfmathcounter},}%
		\repeatpgfmathloop%
	}%	
}

\pgfutil@for\pgf@lib@sh@rs@temp:={one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen,twenty}\do{%
	\expandafter\xdef\csname pgf@anchor@rectangle split@\pgf@lib@sh@rs@temp\endcsname{%
		\noexpand\rectanglesplitparameters%
		\noexpand\pgfutil@ifundefined{pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp}{\noexpand\pgf@lib@sh@rs@anchor@one}%
			{\noexpand\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp\noexpand\endcsname}%
	}%
	\expandafter\xdef\csname pgf@anchor@rectangle split@\pgf@lib@sh@rs@temp\space split\endcsname{%
		\noexpand\rectanglesplitparameters%
		\noexpand\pgfutil@ifundefined{pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp @split}%
		{\noexpand\centerpoint}%
		{\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp @split\noexpand\endcsname}%
	}%
	\expandafter\xdef\csname pgf@anchor@rectangle split@\pgf@lib@sh@rs@temp\space split north\endcsname{%
		\noexpand\rectanglesplitparameters%
		\noexpand\pgfutil@ifundefined{pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp @split@north}%
		{\noexpand\csname pgf@anchor@rectangle split@north\noexpand\endcsname}%
		{\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp @split@north\noexpand\endcsname}%
	}%
	\expandafter\xdef\csname pgf@anchor@rectangle split@\pgf@lib@sh@rs@temp\space split south\endcsname{%
		\noexpand\rectanglesplitparameters%
		\noexpand\pgfutil@ifundefined{pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp @split@south}%
		{\noexpand\csname pgf@anchor@rectangle split@south\noexpand\endcsname}%
		{\noexpand\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp @split@south\noexpand\endcsname}%
	}%
	\expandafter\xdef\csname pgf@anchor@rectangle split@\pgf@lib@sh@rs@temp\space north\endcsname{%
		\noexpand\rectanglesplitparameters%
		\noexpand\pgfutil@ifundefined{pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp @north}%
		{\noexpand\csname pgf@anchor@rectangle split@north\noexpand\endcsname}%
		{\noexpand\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp @north\noexpand\endcsname}%
	}%
	\expandafter\xdef\csname pgf@anchor@rectangle split@\pgf@lib@sh@rs@temp\space south\endcsname{%
		\noexpand\rectanglesplitparameters%
		\noexpand\pgfutil@ifundefined{pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp @south}%
		{\noexpand\csname pgf@anchor@rectangle split@south\noexpand\endcsname}%
		{\noexpand\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp @south\noexpand\endcsname}%
	}%
	\expandafter\xdef\csname pgf@anchor@rectangle split@\pgf@lib@sh@rs@temp\space split east\endcsname{%
		\noexpand\rectanglesplitparameters%
		\noexpand\pgfutil@ifundefined{pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp @split@east}%
		{\noexpand\csname pgf@anchor@rectangle split@east\noexpand\endcsname}%
		{\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp @split@east\noexpand\endcsname}%
	}%
	\expandafter\xdef\csname pgf@anchor@rectangle split@\pgf@lib@sh@rs@temp\space split west\endcsname{%
		\noexpand\rectanglesplitparameters%
		\noexpand\pgfutil@ifundefined{pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp @split@west}%
		{\noexpand\csname pgf@anchor@rectangle split@west\noexpand\endcsname}%
		{\noexpand\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp @split@west\noexpand\endcsname}%
	}%
	\expandafter\xdef\csname pgf@anchor@rectangle split@\pgf@lib@sh@rs@temp\space east\endcsname{%
		\noexpand\rectanglesplitparameters%
		\noexpand\pgfutil@ifundefined{pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp @east}%
		{\noexpand\csname pgf@anchor@rectangle split@east\noexpand\endcsname}%
		{\noexpand\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp @east\noexpand\endcsname}%
	}%
	\expandafter\xdef\csname pgf@anchor@rectangle split@\pgf@lib@sh@rs@temp\space west\endcsname{%
		\noexpand\rectanglesplitparameters%
		\noexpand\pgfutil@ifundefined{pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp @west}%
		{\noexpand\csname pgf@anchor@rectangle split@west\noexpand\endcsname}%
		{\noexpand\csname pgf@lib@sh@rs@anchor@\pgf@lib@sh@rs@temp @west\noexpand\endcsname}%
	}%
}%


\pgfutil@namelet{pgf@anchor@rectangle split@text east}{pgf@anchor@rectangle split@one east}
\pgfutil@namelet{pgf@anchor@rectangle split@text west}{pgf@anchor@rectangle split@one west}
\pgfutil@namelet{pgf@anchor@rectangle split@text split}{pgf@anchor@rectangle split@one split}
\pgfutil@namelet{pgf@anchor@rectangle split@text split east}{pgf@anchor@rectangle split@one split east}
\pgfutil@namelet{pgf@anchor@rectangle split@text split west}{pgf@anchor@rectangle split@one split west}

\pgfutil@namelet{pgf@anchor@rectangle split@second}{pgf@anchor@rectangle split@two}
\pgfutil@namelet{pgf@anchor@rectangle split@second east}{pgf@anchor@rectangle split@two east}
\pgfutil@namelet{pgf@anchor@rectangle split@second west}{pgf@anchor@rectangle split@two west}
\pgfutil@namelet{pgf@anchor@rectangle split@second split}{pgf@anchor@rectangle split@two split}
\pgfutil@namelet{pgf@anchor@rectangle split@second split east}{pgf@anchor@rectangle split@two split east}
\pgfutil@namelet{pgf@anchor@rectangle split@second split west}{pgf@anchor@rectangle split@two split west}

\pgfutil@namelet{pgf@anchor@rectangle split@third}{pgf@anchor@rectangle split@three}
\pgfutil@namelet{pgf@anchor@rectangle split@third east}{pgf@anchor@rectangle split@three east}
\pgfutil@namelet{pgf@anchor@rectangle split@third west}{pgf@anchor@rectangle split@three west}
\pgfutil@namelet{pgf@anchor@rectangle split@third split}{pgf@anchor@rectangle split@three split}
\pgfutil@namelet{pgf@anchor@rectangle split@third split east}{pgf@anchor@rectangle split@three split east}
\pgfutil@namelet{pgf@anchor@rectangle split@third split west}{pgf@anchor@rectangle split@three split west}

\pgfutil@namelet{pgf@anchor@rectangle split@fourth}{pgf@anchor@rectangle split@four}
\pgfutil@namelet{pgf@anchor@rectangle split@fourth east}{pgf@anchor@rectangle split@four east}
\pgfutil@namelet{pgf@anchor@rectangle split@fourth west}{pgf@anchor@rectangle split@four west}
\pgfutil@namelet{pgf@anchor@rectangle split@fourth split}{pgf@anchor@rectangle split@four split}
\pgfutil@namelet{pgf@anchor@rectangle split@fourth split east}{pgf@anchor@rectangle split@four split east}
\pgfutil@namelet{pgf@anchor@rectangle split@fourth split west}{pgf@anchor@rectangle split@four split west}




% Shape: ellipse split.
%
\pgfdeclareshape{ellipse split}{%
	\nodeparts{text,lower}
	\savedanchor\radii{%
		\pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
		\pgf@y2.0\pgf@y%
		\advance\pgf@y.5\pgflinewidth%
		\pgf@xa.5\wd\pgfnodeparttextbox%
		\pgf@xb.5\wd\pgfnodepartlowerbox%
		\advance\pgf@xa\pgf@x%
		\advance\pgf@xb\pgf@x%
		\pgf@ya\ht\pgfnodeparttextbox%
		\advance\pgf@ya\dp\pgfnodeparttextbox%
		\pgf@yb\ht\pgfnodepartlowerbox%
		\advance\pgf@yb\dp\pgfnodepartlowerbox%
		\advance\pgf@ya\pgf@y%
		\advance\pgf@yb\pgf@y%
		\ifdim\pgf@xa>\pgf@xb%
			\pgf@x1.414213\pgf@xa%
		\else%
			\pgf@x1.414213\pgf@xb%
		\fi%
		\ifdim\pgf@ya>\pgf@yb%
			\pgf@y1.414213\pgf@ya%
		\else%
			\pgf@y1.414213\pgf@yb%
		\fi%
		\pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/minimum width}}%
		\pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/minimum height}}%
		\ifdim\pgf@x<.5\pgf@xa%
			\pgf@x.5\pgf@xa%
		\fi%
		\ifdim\pgf@y<.5\pgf@ya%
			\pgf@y.5\pgf@ya%
		\fi%
		\pgfmathaddtolength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
		\pgfmathaddtolength\pgf@y{\pgfkeysvalueof{/pgf/outer ysep}}%
	}
	\savedanchor\lower{%
		\pgf@x-.5\wd\pgfnodepartlowerbox%
		\advance\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
		\pgf@y-2.0\pgf@y%
		\advance\pgf@y-\pgflinewidth%
		\advance\pgf@y-\dp\pgfnodeparttextbox%
		\advance\pgf@y-\ht\pgfnodepartlowerbox%
	}
	\savedanchor\centerpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{-\pgfkeysvalueof{/pgf/inner ysep}}%
		\advance\pgf@y-\dp\pgfnodeparttextbox%
		\advance\pgf@y-.5\pgflinewidth%
	}%
	\savedanchor\basepoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgf@y0pt\relax%
	}%
	\savedanchor\midpoint{%
		\pgf@x.5\wd\pgfnodeparttextbox%
		\pgfmathsetlength\pgf@y{.5ex}%
	}%
	\anchor{center}{\centerpoint}
	\anchor{lower}{\lower}
	\anchor{mid}{\midpoint}
	\anchor{mid east}{\radii\pgf@xa\pgf@x\midpoint\advance\pgf@x\pgf@xa}
	\anchor{mid west}{\radii\pgf@xa\pgf@x\midpoint\advance\pgf@x-\pgf@xa}
	\anchor{base}{\basepoint}
	\anchor{base east}{\radii\pgf@xa\pgf@x\basepoint\advance\pgf@x\pgf@xa}
	\anchor{base west}{\radii\pgf@xa\pgf@x\basepoint\advance\pgf@x-\pgf@xa}
	\anchor{north}{\pgfpointadd{\centerpoint}{\radii\pgf@x0pt}}%
	\anchor{south}{\pgfpointadd{\centerpoint}{\radii\pgf@x0pt\pgf@y-\pgf@y}}%
	\anchor{east}{\pgfpointadd{\centerpoint}{\radii\pgf@y0pt}}%
	\anchor{west}{\pgfpointadd{\centerpoint}{\radii\pgf@x-\pgf@x\pgf@y0pt}}%	
	\anchor{north west}{\pgfpointadd{\centerpoint}{\radii\pgf@x-0.707106\pgf@x\pgf@y0.707106\pgf@y}}%
	\anchor{south west}{\pgfpointadd{\centerpoint}{\radii\pgf@x-0.707106\pgf@x\pgf@y-0.707106\pgf@y}}%
	\anchor{north east}{\pgfpointadd{\centerpoint}{\radii\pgf@x0.707106\pgf@x\pgf@y0.707106\pgf@y}}%
	\anchor{south east}{\pgfpointadd{\centerpoint}{\radii\pgf@x0.707106\pgf@x\pgf@y-0.707106\pgf@y}}%
	\backgroundpath{%
		\radii%
		\pgfmathaddtolength\pgf@x{-\pgfkeysvalueof{/pgf/outer xsep}}%
		\pgfmathaddtolength\pgf@y{-\pgfkeysvalueof{/pgf/outer ysep}}%
		\pgfutil@tempdima\pgf@x%
		\pgfutil@tempdimb\pgf@y%
		\pgfpathellipse{\centerpoint}{\pgfqpoint{\the\pgfutil@tempdima}{0pt}}{\pgfqpoint{0pt}{\the\pgfutil@tempdimb}}%
		\pgfpathmoveto{\centerpoint\advance\pgf@x-\pgfutil@tempdima}%
		\pgfpathlineto{\centerpoint\advance\pgf@x\pgfutil@tempdima}%
	}
	\anchorborder{%
  	\pgfextract@process\externalpoint{}%
  	\radii%
  	\edef\pgf@marshal{%
   		\noexpand\pgfpointadd{\noexpand\pgfpointborderellipse{\noexpand\externalpoint}%
   			{\noexpand\pgfpoint{\the\pgf@x}{\the\pgf@y}}}{\noexpand\centerpoint}%
   	}%  
   	\pgf@marshal%		
  }%
}

\endinput

pgflibraryshapes.symbols.code.tex
% Copyright 2007 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.

\ProvidesFileRCS[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/libraries/shapes/pgflibraryshapes.symbols.code.tex,v 1.6 2013/09/11 06:15:59 vibrovski Exp $

\pgfdeclareshape{forbidden sign}
{
  \inheritsavedanchors[from=circle] % this is nearly a circle
  \inheritanchorborder[from=circle]
  \inheritanchor[from=circle]{north}
  \inheritanchor[from=circle]{north west}
  \inheritanchor[from=circle]{north east}
  \inheritanchor[from=circle]{center}
  \inheritanchor[from=circle]{west}
  \inheritanchor[from=circle]{east}
  \inheritanchor[from=circle]{mid}
  \inheritanchor[from=circle]{mid west}
  \inheritanchor[from=circle]{mid east}
  \inheritanchor[from=circle]{base}
  \inheritanchor[from=circle]{base west}
  \inheritanchor[from=circle]{base east}
  \inheritanchor[from=circle]{south}
  \inheritanchor[from=circle]{south west}
  \inheritanchor[from=circle]{south east}
  \inheritbackgroundpath[from=circle]
  \foregroundpath{
    \centerpoint%
    \pgf@xc=\pgf@x%
    \pgf@yc=\pgf@y%
    \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%
    \pgfpathmoveto{\pgfpointadd{\pgfqpoint{\pgf@xc}{\pgf@yc}}{\pgfqpoint{-0.707107\pgfutil@tempdima}{-0.707107\pgfutil@tempdima}}}
    \pgfpathlineto{\pgfpointadd{\pgfqpoint{\pgf@xc}{\pgf@yc}}{\pgfqpoint{0.707107\pgfutil@tempdima}{0.707107\pgfutil@tempdima}}}
    \pgfsetarrowsstart{}
    \pgfsetarrowsend{}
  }
}


\pgfdeclareshape{correct forbidden sign}
{
  \inheritsavedanchors[from=circle] % this is nearly a circle
  \inheritanchorborder[from=circle]
  \inheritanchor[from=circle]{north}
  \inheritanchor[from=circle]{north west}
  \inheritanchor[from=circle]{north east}
  \inheritanchor[from=circle]{center}
  \inheritanchor[from=circle]{west}
  \inheritanchor[from=circle]{east}
  \inheritanchor[from=circle]{mid}
  \inheritanchor[from=circle]{mid west}
  \inheritanchor[from=circle]{mid east}
  \inheritanchor[from=circle]{base}
  \inheritanchor[from=circle]{base west}
  \inheritanchor[from=circle]{base east}
  \inheritanchor[from=circle]{south}
  \inheritanchor[from=circle]{south west}
  \inheritanchor[from=circle]{south east}
  \inheritbackgroundpath[from=circle]
  \foregroundpath{
    \centerpoint%
    \pgf@xc=\pgf@x%
    \pgf@yc=\pgf@y%
    \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%
    \pgfpathmoveto{\pgfpointadd{\pgfqpoint{\pgf@xc}{\pgf@yc}}{\pgfqpoint{0.707107\pgfutil@tempdima}{-0.707107\pgfutil@tempdima}}}
    \pgfpathlineto{\pgfpointadd{\pgfqpoint{\pgf@xc}{\pgf@yc}}{\pgfqpoint{-0.707107\pgfutil@tempdima}{0.707107\pgfutil@tempdima}}}
    \pgfsetarrowsstart{}
    \pgfsetarrowsend{}
  }
}





% Keys for starburst shape
%
% /pgf/starburst point height : The maximum height of the outer points.
% /pgf/starburst points       : The number of points.
% /pgf/random starburst       : The seed for the random number generator.
%
\pgfkeys{/pgf/random starburst/%
  .code={%
    \ifx\pgfkeysnovalue#1%
      \pgfmathgeneratepseudorandomnumber%
    \else%
      \pgfmathtruncatemacro\pgfmathresult{#1}%
    \fi%
    \pgfkeyslet{/pgf/random starburst}{\pgfmathresult}%
  }%
}
\pgfkeys{/pgf/random starburst=100}

\pgfkeys{/pgf/starburst point height/.value required}
\pgfkeys{/pgf/starburst point height/.code={%
    \pgfmathparse{#1}%
    \edef\pgfmathresult{\pgfmathresult pt}%
    \pgfkeyslet{/pgf/starburst point height}{\pgfmathresult}%
  }%
}%
\pgfkeys{/pgf/starburst point height=.5cm}

\pgfkeys{/pgf/starburst points/.value required}
\pgfkeys{/pgf/starburst points/.code={%
    \pgfmathtruncatemacro\pgfmathresult{#1}%
    \pgfkeyslet{/pgf/starburst points}{\pgfmathresult}%
  }%  
}%
\pgfkeys{/pgf/starburst points=17}

\pgfdeclareshape{starburst}{%
  \savedmacro\anglestep{%
    \pgfmathdivide@{180}{\pgfkeysvalueof{/pgf/starburst points}}%
    \let\anglestep\pgfmathresult%
  }
  \savedmacro\calculatestarburstpoints{%
    %
    % Get the angle step.
    %
    \pgfmathdivide@{180}{\pgfkeysvalueof{/pgf/starburst points}}%
    \let\anglestep\pgfmathresult%
    %
    % Get the total number of points.
    %
    \pgfmathsetcounter{pgf@counta}{\pgfkeysvalueof{/pgf/starburst points}}%
    \multiply\c@pgf@counta2\relax%
    \edef\totalpoints{\the\c@pgf@counta}%
    \addtosavedmacro{\totalpoints}%
    %
    % Calculate the centerpoint.
    %
    \pgfextract@process\centerpoint{%
      \pgfmathsetlength\pgf@x{+.5\wd\pgfnodeparttextbox}%
      \pgfmathsetlength\pgf@y{+.5\ht\pgfnodeparttextbox}%
      \pgfmathaddtolength\pgf@y{+-.5\dp\pgfnodeparttextbox}%
    }%
    %
    % Get the larger of the outer sep.
    %
    \pgfmathsetlength\pgf@x{+\pgfkeysvalueof{/pgf/outer xsep}}%
    \pgfmathsetlength\pgf@y{+\pgfkeysvalueof{/pgf/outer ysep}}%
    \ifdim\pgf@x<\pgf@y%
      \pgf@x\pgf@y%
    \fi%
    \edef\outersep{\the\pgf@x}%
    % 
    % Get the node dimensions.
    % 
    \pgfmathsetlength\pgf@x{+\pgfkeysvalueof{/pgf/inner xsep}}%
    \pgfmathaddtolength\pgf@x{+.5\wd\pgfnodeparttextbox}%    
    \pgfmathsetlength\pgf@y{+\pgfkeysvalueof{/pgf/inner ysep}}%
    \pgfmathaddtolength\pgf@y{+.5\ht\pgfnodeparttextbox}%
    \pgfmathaddtolength\pgf@y{+.5\dp\pgfnodeparttextbox}%
    %
    %  Calculate the inner radii.
    %
    \ifpgfshapeborderusesincircle%
      \pgfkeysgetvalue{/pgf/shape border rotate}{\rotate}%
      %
      % Use the incircle...
      %
      \ifdim\pgf@y>\pgf@x%
        \pgf@x\pgf@y%
      \fi%
      \pgf@x1.41421\pgf@x%
      \pgf@y\pgf@x%
    \else%
      %
      % Get the rotation (with rounding).
      %
      \pgfkeysgetvalue{/pgf/shape border rotate}{\rotate}%
      \pgfmathmod@{\rotate}{360}%
      \afterassignment\pgfmath@gobbletilpgfmath@%
      \expandafter\c@pgf@counta\pgfmathresult\relax\pgfmath@%
      \advance\c@pgf@counta45\relax%
      \divide\c@pgf@counta90\relax%
      \multiply\c@pgf@counta90\relax%
      \ifnum\c@pgf@counta<0\relax%
        \advance\c@pgf@counta360\relax%
      \fi%
      %
      % Calculate the width and height of the node
      % contents, according to any border rotation.
      %
      \ifnum\c@pgf@counta=90\relax%
        \pgf@xc\pgf@x%
        \pgf@x\pgf@y%
        \pgf@y\pgf@xc%
      \else%
        \ifnum\c@pgf@counta=270\relax%
          \pgf@xc\pgf@x%
          \pgf@x\pgf@y%
          \pgf@y\pgf@xc%
        \fi%
      \fi%
      \edef\rotate{\the\c@pgf@counta}%
      %
      % ...or not.
      %    
      \pgf@x=1.41421\pgf@x%
      \pgf@y=1.41421\pgf@y%
    \fi%
    \addtosavedmacro{\rotate}%
    % 
    % Adjust innerradius for minimum width and height.
    %
    \pgf@xa\pgf@x% 
    \pgfmathsetlength\pgf@xb{+\pgfkeysvalueof{/pgf/starburst point height}}%
    \advance\pgf@xa\pgf@xb%
    \pgfmathsetlength\pgf@xc{+\pgfkeysvalueof{/pgf/minimum width}}%
    \ifdim\pgf@xa<.5\pgf@xc%
      \pgf@x.5\pgf@xc%
      \advance\pgf@x-\pgf@xb%
    \fi%
    \pgf@ya\pgf@y% 
    \pgfmathsetlength\pgf@yb{+\pgfkeysvalueof{/pgf/starburst point height}}%
    \advance\pgf@ya\pgf@yb%
    \pgfmathsetlength\pgf@yc{+\pgfkeysvalueof{/pgf/minimum height}}%
    \ifdim\pgf@ya<.5\pgf@yc%
      \pgf@y.5\pgf@yc%
      \advance\pgf@y-\pgf@yb%
    \fi%  
    \edef\xinnerradius{\the\pgf@x}%
    \edef\yinnerradius{\the\pgf@y}%
    \addtosavedmacro{\xinnerradius}%
    \addtosavedmacro{\yinnerradius}%
    %
    % Calculate a radius outside the starburst.
    %
    \ifdim\pgf@y>\pgf@x%
      \pgf@x\pgf@y%
    \fi%
    \pgfmathaddtolength\pgf@x{+\pgfkeysvalueof{/pgf/starburst point height}}%
    \edef\externalradius{\the\pgf@x}%
    \addtosavedmacro{\externalradius}%
    %
    % Set the seed for the random number generator.
    %
    \pgfmathsetseed{\pgfkeysvalueof{/pgf/random starburst}}%  
    %
    % Now create the points on the shape and also 
    % the miter length and angle for each point.
    %
    \def\angle{90}% Start at the top.
    %
    % At point a, the miter length and angle are calculated for point b = a - 1.
    %
    \c@pgf@counta1\relax%
    \c@pgf@countb0\relax%
    %
    % As 3 consecutive points are required to be defined for miter
    % calculations, it is necessary to go over the first two points
    % again.
    % 
    \c@pgf@countc\totalpoints\relax%
    \advance\c@pgf@countc2\relax%
    \edef\looppoints{\the\c@pgf@countc}%
    \let\secondpoint\pgfutil@empty%
    \let\thirdpoint\pgfutil@empty%
    \pgfmathloop%
      %
      % Cycle the point definitions.
      %
      \let\firstpoint\secondpoint%  
      \let\secondpoint\thirdpoint%  
      \ifnum\pgfmathcounter>\looppoints%
      \else%
        \ifnum\pgfmathcounter>\totalpoints%
          \expandafter\let\expandafter\thirdpoint\csname point@\the\c@pgf@counta @\endcsname%
        \else%
          \ifodd\pgfmathcounter%
            %
            % An outer point.
            %
            \ifnum\pgfkeysvalueof{/pgf/random starburst}=0\relax%
              \pgf@xa\pgfkeysvalueof{/pgf/starburst point height}\relax%
            \else%
              \pgf@x\pgfkeysvalueof{/pgf/starburst point height}\relax%
              \pgf@xa.75\pgf@x%
              \pgf@xb.25\pgf@x%
              \pgfmathrnd%
              \pgf@xa\pgfmathresult\pgf@xa%
              \advance\pgf@xa\pgf@xb%
            \fi%
            \pgf@x\xinnerradius\relax%
            \advance\pgf@x\pgf@xa%
            \pgf@y\yinnerradius\relax%
            \advance\pgf@y\pgf@xa%
            \expandafter\pgfextract@process\csname point@\the\c@pgf@counta @\endcsname{%
              \pgfpointpolar{\angle}{\the\pgf@x and \the\pgf@y}%
              \pgf@xa\pgf@x%
              \pgf@ya\pgf@y%
              \centerpoint%
              \advance\pgf@x\pgf@xa%
              \advance\pgf@y\pgf@ya%
            }%
          \else%
            %
            % An inner point.
            %
            \expandafter\pgfextract@process\csname point@\the\c@pgf@counta @\endcsname{%
              \pgfpointpolar{\angle}{\xinnerradius and \yinnerradius}%
              \pgf@xa\pgf@x%
              \pgf@ya\pgf@y%
              \centerpoint%
              \advance\pgf@x\pgf@xa%
              \advance\pgf@y\pgf@ya%
            }%            
          \fi%
          %
          % Add the points to the saved macro.
          %
          \expandafter\let\expandafter\thirdpoint\csname point@\the\c@pgf@counta @\endcsname%
          \expandafter\addtosavedmacro\expandafter{\csname point@\the\c@pgf@counta @\endcsname}%
        \fi%        
        %
        % It is only possible to do the miter calculations if three points are defined.
        %
        \ifx\firstpoint\pgfutil@empty%
        \else%
          %
          % Calculate the miter length...
          %
          \pgfmathanglebetweenlines{\secondpoint}{\thirdpoint}{\secondpoint}{\firstpoint}%
          \pgfmathdivide@{\pgfmathresult}{2}%
          \let\defaultmiterangle\pgfmathresult%
          \pgfmathcosec@{\pgfmathresult}%
          \pgf@x\outersep\relax%
          \pgf@x\pgfmathresult\pgf@x%
          \edef\miterlength{\the\pgf@x}%
          %
          % ...the miter angle...
          %
          \pgfmathanglebetweenlines{\firstpoint}{\secondpoint}{\firstpoint}{\thirdpoint}%
          \pgfmathadd@{\pgfmathresult}{\defaultmiterangle}%
          \pgfmathsubtract@{180}{\pgfmathresult}%
          \let\angletemp\pgfmathresult%
          \pgfmathanglebetweenpoints{\firstpoint}{\thirdpoint}%
          \pgfmathsubtract@{180}{\pgfmathresult}%
          \pgfmathsubtract@{\angletemp}{\pgfmathresult}%
          \edef\miterangle{\pgfmathresult}%
          %
          % ...and thus the border point.
          %
          \pgfextract@process\borderpoint{%
            \secondpoint%
            \pgf@xa\pgf@x
            \pgf@ya\pgf@y%
            \pgfpointpolar{\miterangle}{\miterlength}%
            \advance\pgf@x\pgf@xa%
            \advance\pgf@y\pgf@ya%
          }%
          %
          % Get the angle from the centerpoint to the *unrotated* border points.
          %
          \pgfmathanglebetweenpoints{\centerpoint}{\borderpoint}%
          \expandafter\edef\csname angletoborderpoint@\the\c@pgf@countb @\endcsname{\pgfmathresult}%
          \expandafter\addtosavedmacro\expandafter{\csname angletoborderpoint@\the\c@pgf@countb @\endcsname}%
          %
          % Rotatee the border points and save.
          %
          \expandafter\pgfextract@process\csname borderpoint@\the\c@pgf@countb @\endcsname{%
            \pgfmathrotatepointaround{\borderpoint}{\centerpoint}{\rotate}%
          }%
          \expandafter\addtosavedmacro\expandafter{\csname borderpoint@\the\c@pgf@countb @\endcsname}%        
          %
          % Now create the anchors.
          %
          \c@pgf@countc\c@pgf@countb%
          \advance\c@pgf@countc1\relax%
          \divide\c@pgf@countc2\relax%
          \ifodd\c@pgf@countb\relax%
            \pgfutil@ifundefined{pgf@anchor@starburst@outer point\space\the\c@pgf@countc}{%
              \expandafter\xdef\csname pgf@anchor@starburst@outer point\space\the\c@pgf@countc\endcsname{%
                \noexpand\calculatestarburstpoints%
                \noexpand\csname borderpoint@\the\c@pgf@countb @\noexpand\endcsname%
              }%
            }{}%
          \else%
            \pgfutil@ifundefined{pgf@anchor@starburst@inner point\space\the\c@pgf@countc}{%
              \expandafter\xdef\csname pgf@anchor@starburst@inner point\space\the\c@pgf@countc\endcsname{%
                \noexpand\calculatestarburstpoints%
                \noexpand\csname borderpoint@\the\c@pgf@countb @\noexpand\endcsname%
              }%
            }{}%
          \fi%
        \fi%
        \pgfmathadd@{\angle}{\anglestep}%
        \pgfmathmod@{\pgfmathresult}{360}%  
        \let\angle\pgfmathresult%
        \advance\c@pgf@counta1\relax%
        \ifnum\c@pgf@counta>\totalpoints%
          \c@pgf@counta1\relax%
        \fi%
        \advance\c@pgf@countb1\relax%
        \ifnum\c@pgf@countb>\totalpoints%
          \c@pgf@countb1\relax%
        \fi%
    \repeatpgfmathloop%
  }
  \savedanchor\centerpoint{%
    \pgfmathsetlength\pgf@x{+.5\wd\pgfnodeparttextbox}%
    \pgfmathsetlength\pgf@y{+.5\ht\pgfnodeparttextbox}%
    \pgfmathaddtolength\pgf@y{+-.5\dp\pgfnodeparttextbox}%
  }%
  \savedanchor\midpoint{%
    \pgfmathsetlength\pgf@x{+.5\wd\pgfnodeparttextbox}%
    \pgfmathsetlength\pgf@y{+.5ex}%
  }%
  \savedanchor\basepoint{%
    \pgfmathsetlength\pgf@x{+.5\wd\pgfnodeparttextbox}%
    \pgf@y0pt\relax%
  }%
  \anchor{center}{\centerpoint}
  \anchor{base}{\basepoint}
  \anchor{mid}{\midpoint}
  \anchor{north}{%
    \calculatestarburstpoints%
    \csname pgf@anchor@starburst@border\endcsname{\pgfqpoint{0pt}{\externalradius}}%
  }
  \anchor{south}{%
    \calculatestarburstpoints%
    \csname pgf@anchor@starburst@border\endcsname{\pgfqpoint{0pt}{-\externalradius}}%
  }
  \anchor{east}{%
    \calculatestarburstpoints%
    \csname pgf@anchor@starburst@border\endcsname{\pgfqpoint{\externalradius}{0pt}}%
  }
  \anchor{west}{%
    \calculatestarburstpoints%
    \csname pgf@anchor@starburst@border\endcsname{\pgfqpoint{-\externalradius}{0pt}}%
  }
  \anchor{north west}{%
    \calculatestarburstpoints%
    \csname pgf@anchor@starburst@border\endcsname{\pgfqpoint{-\externalradius}{\externalradius}}%
  }
  \anchor{south west}{%
    \calculatestarburstpoints%
    \csname pgf@anchor@starburst@border\endcsname{\pgfqpoint{-\externalradius}{-\externalradius}}%
  }
  \anchor{north east}{%
    \calculatestarburstpoints%
    \csname pgf@anchor@starburst@border\endcsname{\pgfqpoint{\externalradius}{\externalradius}}%
  }
  \anchor{south east}{%
    \calculatestarburstpoints%
    \csname pgf@anchor@starburst@border\endcsname{\pgfqpoint{\externalradius}{-\externalradius}}%
  }
  \backgroundpath{%  
    \calculatestarburstpoints%
    \pgfmathloop%
      \ifnum\pgfmathcounter>\totalpoints%
      \else%
        \ifnum\pgfmathcounter=1\relax%
          \let\starburstaction\pgfpathmoveto%
        \else%
          \let\starburstaction\pgfpathlineto%
        \fi%
        \starburstaction{%
          %\pgfmathrotatepointaround{\csname point@\pgfmathcounter @\endcsname}{\centerpoint}{\rotate}}%
          \csname point@\pgfmathcounter @\endcsname}
      \repeatpgfmathloop%
    \pgfpathclose%    
  }
  \anchorborder{%
    %
    % Save x and y.
    %
    \edef\externalx{\the\pgf@x}%
    \edef\externaly{\the\pgf@y}%
    %
    % Adjust the location of the external 
    % point relative to \centerpoint.
    %
    \centerpoint%
    \pgf@xa\externalx\relax%
    \pgf@ya\externaly\relax%
    \advance\pgf@xa\pgf@x%
    \advance\pgf@ya\pgf@y%
    \edef\externalx{\the\pgf@xa}%
    \edef\externaly{\the\pgf@ya}%
    %
    % Get the starburst points.
    %
    \calculatestarburstpoints%
    %
    % Get the angle of the external point to the \centerpoint.
    %
    \pgfmathanglebetweenpoints{\centerpoint}{\pgfqpoint{\externalx}{\externaly}}%
    \pgfmathsubtract@{\pgfmathresult}{\rotate}%
    \ifdim\pgfmathresult pt<0pt\relax%
      \pgfmathadd@{\pgfmathresult}{360}%
    \fi%
    \let\externalangle\pgfmathresult%
    %
    % Locate the appropriate sides on the starburst border...
    %
    \ifdim\externalangle pt<90pt\relax%
      \c@pgf@counta0\relax%
      \c@pgf@countb\totalpoints\relax%
      \pgfmathloop%
      \ifnum\c@pgf@counta>0\relax%
      \else%
        \ifdim\csname angletoborderpoint@\the\c@pgf@countb @\endcsname pt>90pt\relax%
          \c@pgf@counta\c@pgf@countb%
        \else%
          \ifdim\externalangle pt>\csname angletoborderpoint@\the\c@pgf@countb @\endcsname pt\relax%
            \c@pgf@counta\c@pgf@countb%
          \fi%
        \fi%
        \advance\c@pgf@countb-1\relax%
      \repeatpgfmathloop%
      \edef\first{\the\c@pgf@counta}%
      \advance\c@pgf@counta1\relax%
      \ifnum\c@pgf@counta>\totalpoints\relax%
        \c@pgf@counta1\relax%
      \fi%
      \edef\second{\the\c@pgf@counta}%
    \else%
      \c@pgf@counta0\relax%
      \pgfmathloop%
      \ifnum\c@pgf@counta>0\relax%
      \else%
        \ifdim\csname angletoborderpoint@\pgfmathcounter @\endcsname pt<90pt\relax%
          \c@pgf@counta\pgfmathcounter%
        \else%
          \ifdim\externalangle pt<\csname angletoborderpoint@\pgfmathcounter @\endcsname pt\relax%
            \c@pgf@counta\pgfmathcounter%  
          \fi%
        \fi%          
      \repeatpgfmathloop%
      \edef\first{\the\c@pgf@counta}%
      \advance\c@pgf@counta-1\relax%
      \ifnum\c@pgf@counta=0\relax%
        \c@pgf@counta\totalpoints\relax%
      \fi%
      \edef\second{\the\c@pgf@counta}%
    \fi%
    %
    % ...and thus, the point on the star border.
    %
    \pgfpointintersectionoflines{\centerpoint}{\pgfqpoint{\externalx}{\externaly}}%
        {\csname borderpoint@\first @\endcsname}{\csname borderpoint@\second @\endcsname}%
  }%
}




% Keys for shape cloud.
%
% /pgf/cloud puffs    : the number of cloud puffs.
% /pgf/cloud puff arc : the length of the cloud puff arc.

\newif\ifpgfcloudanchorsuseellipse%
\newif\ifpgfcloudignoresaspect%
\pgfcloudignoresaspectfalse%
\pgfkeys{/pgf/.cd,
  cloud puffs/.initial=10,
  cloud puff arc/.initial=150,
  cloud ignores aspect/.is if=pgfcloudignoresaspect,
  cloud anchors use ellipse/.is if=pgfcloudanchorsuseellipse
}%


% If symbol library is loaded separately these need to be defined.
%
\pgfkeys{/pgf/.cd,
  aspect/.code={\pgfsetshapeaspect{#1}},% this for tikz...
  shape aspect/.initial=1,% but this is consistent with other pgfset stuff. 
  shape aspect/.code={%
    \pgfkeys{/pgf/aspect=#1}%
    \pgfkeyssetvalue{/pgf/shape aspect}{#1}
  }%
}

\def\pgfsetshapeaspect#1{%
  \def\pgfshapeaspect{#1}%
  % Invert
  \pgfutil@tempdima=#1pt%
  \pgfutil@tempdima=.125\pgfutil@tempdima%
  \c@pgf@counta=\pgfutil@tempdima\relax% 8192*determinant
  \pgfutil@tempdima=8192pt%
  \divide\pgfutil@tempdima by\c@pgf@counta%
  \edef\pgfshapeaspectinverse{\pgf@sys@tonumber{\pgfutil@tempdima}}
}

\pgfsetshapeaspect{1}
%

% Shape cloud.
%
\pgfdeclareshape{cloud}{%
  \savedmacro\getradii{%
    \pgfmathtruncatemacro\puffs{\pgfkeysvalueof{/pgf/cloud puffs}}%
    \addtosavedmacro\puffs%
    \pgfmathdivide{360}{\pgfkeysvalueof{/pgf/cloud puffs}}%
    \let\anglestep\pgfmathresult%
    \addtosavedmacro\anglestep%
    \pgfmathsetmacro\arc{\pgfkeysvalueof{/pgf/cloud puff arc}}%
    \addtosavedmacro\arc%
    %
    % x radius.
    %
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
    \advance\pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@x1.4142135\pgf@x%
    %
    % y radius.
    %
    \pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
    \advance\pgf@y.5\ht\pgfnodeparttextbox%
    \advance\pgf@y.5\dp\pgfnodeparttextbox%
    \pgf@y1.4142135\pgf@y%
    %
    % Adjust for shape aspect.
    %
    \ifpgfcloudignoresaspect%
      \pgf@xc\pgf@x%
      \pgf@yc\pgf@y%
    \else%
      \pgf@xc\pgfshapeaspect\pgf@y%
      \ifdim\pgf@xc<\pgf@x%
        \pgf@xc\pgf@x%
      \fi%
      \pgf@yc\pgfshapeaspectinverse\pgf@xc%
      \ifdim\pgf@yc<\pgf@y%
        \pgf@yc\pgf@y%
        \pgf@xc\pgfshapeaspect\pgf@y%
      \fi%
    \fi%
    %
    \edef\xinnerradius{\the\pgf@xc}%
    \edef\yinnerradius{\the\pgf@yc}%
    %
    % Get the larger of the outer sep.
    %  
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
    \pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/outer ysep}}%
    \ifdim\pgf@x<\pgf@y%
      \pgf@x\pgf@y%
    \fi%
    \edef\outersep{\the\pgf@x}%
    \addtosavedmacro\outersep%
    %
    % For a given cloud, with puff arc length a, the quotient of the
    % distance between the start and end point of a puffs circular arc
    % and the radius of that arc, is constant:
    %
    % g = .5 * sec((180-a)/2)
    % 
    \pgfmathsubtract{180}{\arc}%
    \pgfmathdivide@{\pgfmathresult}{2}%
    \let\tempangle\pgfmathresult%
    \pgfmathsec@{\pgfmathresult}%
    \pgfmathdivide@{\pgfmathresult}{2}%
    \let\arcradiusquotient\pgfmathresult%
    \addtosavedmacro\arcradiusquotient%
    %
    % In addition, the quotient of the distance between the start and
    % end point of a puffs circular arc and the height of that arc 
    % (ignoring rotation), is also constant:
    %
    % h = .5 * (1-sin((180-a)/2))/cos((180-a)/2)
    %   = g  * (1 - sin((180-a)/2))
    \pgfmathsin@{\tempangle}%
    \pgfmathsubtract@{1}{\pgfmathresult}%
    \pgfmathmultiply@{\pgfmathresult}{\arcradiusquotient}%
    \let\archeightquotient\pgfmathresult%
    \addtosavedmacro\archeightquotient%
    %
    % Minimum size is applied to the circum-ellipse (i.e. the ellipse 
    % that passes through the extremeties of each puff). Thus, the
    % relationship between the radii of the elliptical incircle ("inellipse"?) 
    % of the cloud (x and y) and the radii of the circum-ellispe (X and Y), 
    % is given by 
    %
    % X = 2(x*cos(p/2) + ky)  
    % Y = 2(y*cos(p/2) + kx)
    % 
    % where:
    % k = sin(p/2)*((1-cos(a/2))/sin(a/2))
    % p = the angle between each puff (i.e. 360/<puffs>) 
    % a = the length of arc of the puff.
    % 
    \pgfmathdivide{\arc}{2}%
    \let\halfarcangle\pgfmathresult%
    \pgfmathcos@{\pgfmathresult}%
    \pgfmathsubtract@{1}{\pgfmathresult}%
    \let\pgf@temp\pgfmathresult%
    \pgfmathsin@{\halfarcangle}%
    \pgfmathdivide@{\pgf@temp}{\pgfmathresult}%
    \let\pgf@temp\pgfmathresult%
    \pgfmathdivide@{\anglestep}{2}%
    \pgfmathsin@{\pgfmathresult}%
    \pgfmathmultiply@{\pgfmathresult}{\pgf@temp}%
    \let\k\pgfmathresult%
    %
    \pgfmathdivide@{\anglestep}{2}%
    \pgfmathcos@{\pgfmathresult}%
    \let\coshalfanglestep\pgfmathresult%
    %
    % Calculate the actual radii of the circum-ellipse.
    %
    \pgf@x\xinnerradius\relax%
    \pgf@y\yinnerradius\relax%
    \pgf@xa\coshalfanglestep\pgf@x%
    \advance\pgf@xa\k\pgf@y%
    \pgf@ya\coshalfanglestep\pgf@y%
    \advance\pgf@ya\k\pgf@x%
    %
    % Adjust for minimum height (Y').
    %
    \pgfmathsetlength\pgf@yb{\pgfkeysvalueof{/pgf/minimum height}}%
    \ifdim\pgf@ya<.5\pgf@yb%
      \pgf@ya.5\pgf@yb%
    \fi%
    %
    % Adjust for minimum width (X').
    %
    \pgfmathsetlength\pgf@xb{\pgfkeysvalueof{/pgf/minimum width}}%
    \ifdim\pgf@xa<.5\pgf@xb%
      \pgf@xa.5\pgf@xb%
    \fi%
    %
    \edef\xouterradius{\the\pgf@xa}%
    \addtosavedmacro\xouterradius%
    \edef\youterradius{\the\pgf@ya}%
    \addtosavedmacro\youterradius%
    %
    % Now recalculate `in-ellispe' radii: 
    %
    % x = (X'cos(p/2)-kY')/cos^2(p/2)-k^2, 
    % y = (Y'cos(p/2)-kX')/cos^2(p/2)-k^2, 
    %
    \pgf@xc\k pt\relax%
    \pgf@xc-\k\pgf@xc%
    \pgf@yc\coshalfanglestep pt\relax%
    \pgf@yc\coshalfanglestep\pgf@yc%
    \advance\pgf@xc\pgf@yc\relax%
    \pgfmathreciprocal@{\pgfmath@tonumber{\pgf@xc}}% cos^2(p/2)-k^2
    %
    \pgf@x\coshalfanglestep\pgf@xa%
    \advance\pgf@x-\k\pgf@ya%
    \pgf@x\pgfmathresult\pgf@x%
    \pgf@y\coshalfanglestep\pgf@ya%
    \advance\pgf@y-\k\pgf@xa%
    \pgf@y\pgfmathresult\pgf@y%
    %
    \edef\xinnerradius{\the\pgf@x}%
    \edef\yinnerradius{\the\pgf@y}%
    \addtosavedmacro\xinnerradius%
    \addtosavedmacro\yinnerradius%
    %
    % Get some useful trig. constants.
    %
    \pgfmathdivide@{\arc}{4}%
    \let\quarterarc\pgfmathresult%
    \pgfmathsubtract@{180}{\arc}%
    \pgfmathdivide@{\pgfmathresult}{2}%
    \let\halfcomplementarc\pgfmathresult%
    %
    \addtosavedmacro\arc%
    \addtosavedmacro\quarterarc%
    \addtosavedmacro\halfcomplementarc%
    %
    \pgfmathsec@{\halfcomplementarc}% 1/cos((180-a)/2)
    \let\sechalfcomplementarc\pgfmathresult%
    \pgfmathsin@{\halfcomplementarc}% sin((180-a)/2)
    \let\sinhalfcomplementarc\pgfmathresult%
    %
    \addtosavedmacro\sechalfcomplementarc%
    \addtosavedmacro\sinhalfcomplementarc%
    %
    \pgfmathsin@{\quarterarc}% sin(a/4)
    \let\sinquarterarc\pgfmathresult%
    \pgfmathcos@{\quarterarc}% cos(a/4)
    \let\cosquarterarc\pgfmathresult%
    \pgfmathreciprocal@{\cosquarterarc}%
    \pgfmathmultiply@{\pgfmathresult}{\sinquarterarc}% tan(a/4)
    \let\tanquarterarc\pgfmathresult%
    %
    \addtosavedmacro\sinquarterarc%
    \addtosavedmacro\cosquarterarc%
    \addtosavedmacro\tanquarterarc%
    %
  }
  \savedanchor\centerpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y.5\ht\pgfnodeparttextbox%
    \advance\pgf@y-.5\dp\pgfnodeparttextbox%
  }
  \savedanchor\midpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@y{+.5ex}%
  }
  \savedanchor\basepoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y0pt%
  }
  \anchor{center}{\centerpoint}
  \anchor{mid}{\midpoint}
  \anchor{base}{\basepoint}
  \anchor{north}{%
    \getradii%
    \csname pgf@anchor@cloud@border\endcsname{\pgfqpoint{0pt}{\youterradius}}%
  }%
  \anchor{south}{%
    \getradii%
    \csname pgf@anchor@cloud@border\endcsname{\pgfqpoint{0pt}{-\youterradius}}%
  }%
  \anchor{east}{%
    \getradii%
    \csname pgf@anchor@cloud@border\endcsname{\pgfqpoint{\xouterradius}{0pt}}%
  }%
  \anchor{west}{%
    \getradii%
    \csname pgf@anchor@cloud@border\endcsname{\pgfqpoint{-\xouterradius}{0pt}}%
  }%
  \anchor{north west}{%
    \getradii%
    \pgfextract@process\pgf@sh{%
      \pgf@x\xouterradius\relax%
      \pgf@x-0.707106\pgf@x%
      \pgf@y\youterradius\relax%
      \pgf@y0.707106\pgf@y%
    }%
    \csname pgf@anchor@cloud@border\endcsname{\pgf@sh}%
  }%
  \anchor{north east}{%
    \getradii%
    \pgfextract@process\pgf@sh{%
      \pgf@x\xouterradius\relax%
      \pgf@x0.707106\pgf@x%
      \pgf@y\youterradius\relax%
      \pgf@y0.707106\pgf@y%
    }%
    \csname pgf@anchor@cloud@border\endcsname{\pgf@sh}%
  }%
  \anchor{south west}{%
    \getradii%
    \pgfextract@process\pgf@sh{%
      \pgf@x\xouterradius\relax%
      \pgf@x-0.707106\pgf@x%
      \pgf@y\youterradius\relax%
      \pgf@y-0.707106\pgf@y%
    }%
    \csname pgf@anchor@cloud@border\endcsname{\pgf@sh}%
  }%
  \anchor{south east}{%
    \getradii%
    \pgfextract@process\pgf@sh{%
      \pgf@x\xouterradius\relax%
      \pgf@x0.707106\pgf@x%
      \pgf@y\youterradius\relax%
      \pgf@y-0.707106\pgf@y%
    }%
    \csname pgf@anchor@cloud@border\endcsname{\pgf@sh}%
  }%
  %
  % Each `puff' is a circular arc of length a, drawn using two a/2 
  % arcs (a < 180), approximated by Bezier curves. 
  % Due to TeX rounding errors, it is sometimes necessary to `force' 
  % the arc to end at a specific point. So...
  %
  % @article{riskus2006,
  %   author  = {Aleskus Ri\v{s}kus},
  %   title   = {Approximation of a cubic Bezier curve by circular arcs and vice versa},
  %   journal = {Information Technology and Control},
  %   year    = {2006},
  %   volume  = {35},
  %   number  = {4}
  % }
  %
  \backgroundpath{%
    {%
    \getradii%
    %
    % Get the start angle.
    %
    \pgfmathdivide@{\anglestep}{2}%
    \pgfmathsubtract@{90}{\pgfmathresult}%
    \let\angle\pgfmathresult%
    %
    % Calculate the first arc point.
    %
    \pgfextract@process\arcfirstpoint{%
      \pgfpointadd{\centerpoint}{%
        \pgfpointpolar{+\angle}{+\xinnerradius and +\yinnerradius}%
      }%
    }%
    \pgfpathmoveto{\arcfirstpoint}%
    \let\arcendpoint\arcfirstpoint%
    %
    \pgfmathloop%
    \ifnum\pgfmathcounter>\puffs\relax%
    \else
      \let\arcstartpoint\arcendpoint%
      %
      % Make sure beginning and end of path are exactly the same.
      %
      \ifnum\pgfmathcounter=\puffs\relax%
        \let\arcendpoint\arcfirstpoint%
      \else%
        \pgfmathadd@{\angle}{\anglestep}%
        \let\angle\pgfmathresult%
        \pgfextract@process\arcendpoint{%
          \pgfpointadd{\centerpoint}{%
            \pgfpointpolar{+\angle}{+\xinnerradius and +\yinnerradius}%
          }%
        }%  
      \fi%
      %
      % Get some useful cloud parameters from \arcstartpoint and \arcendpoint.
      %
      \pgf@sh@getcloudpuffparameters%
      %
      % Get the rotation for the Bezier curve.
      %
      \pgfmathsubtract@{90}{\quarterarc}%
      \pgfmathadd@{\pgfmathresult}{\arcslope}%
      \let\arcrotate\pgfmathresult%
      \pgfmathsin@{\arcrotate}%
      \let\sinarcrotate\pgfmathresult%
      \pgfmathcos@{\arcrotate}%
      \let\cosarcrotate\pgfmathresult%
      %
      % Calculate the amount by which to scale the control 
      % points, in order to approximate an a/2 arc with radius x.
      %
      \pgf@x\arcradius\relax%
      \pgf@x\tanquarterarc\pgf@x% tan(a/4)
      \edef\controlscale{\pgfmath@tonumber{\pgf@x}}%
      %
      % Get the first control point for the first arc (length a/2)...
      %
      \pgfextract@process\controlone{%
        %
        % k = 0.552284745 (a `magic' number)...
        %
        \pgf@x0.55228475pt\relax%
        \pgf@x\sinquarterarc\pgf@x% k * sin(a/2)
        \pgf@y0.55228475pt\relax%
        \pgf@y\cosquarterarc\pgf@y% k * cos(a/2)
        %
        % ...scale the control points up...
        %
        \pgf@x\controlscale\pgf@x%
        \pgf@y\controlscale\pgf@y%
        %
        % ...rotate...
        %
        \pgf@xa\cosarcrotate\pgf@x%
        \advance\pgf@xa-\sinarcrotate\pgf@y%
        \pgf@ya\cosarcrotate\pgf@y%
        \advance\pgf@ya\sinarcrotate\pgf@x%
        %
        % ...and shift.
        %
        \arcstartpoint%
        \advance\pgf@x\pgf@xa%
        \advance\pgf@y\pgf@ya%
      }%
      %
      % Get the midpoint of the 150� arc.
      %
      \pgfextract@process\arcmidpoint{%
        \pgfextract@process\arcmidpoint{%
          \pgf@x-\halfchordlength\relax%
          \pgf@y\segmentheight\relax%
        }%
        \pgfpointadd{\arcstartpoint}{%
          \pgfmathrotatepointaround{\arcmidpoint}{\pgfpointorigin}{\arcslope}%
        }%
      }%
      %
      % Get the second control point for the first arc (length a/2)...
      %
      \pgfextract@process\controltwo{%    
        \pgf@x0.55228475pt\relax%
        \pgf@x\sinquarterarc\pgf@x%  k * sin(a/2)
        \pgf@y-0.55228475pt\relax%
        \pgf@y\cosquarterarc\pgf@y% -k * cos(a/2)    
        %
        % ...scale, rotate and shift.
        %
        \pgf@x\controlscale\pgf@x%
        \pgf@y\controlscale\pgf@y%
        %
        \pgf@xa\cosarcrotate\pgf@x%
        \advance\pgf@xa-\sinarcrotate\pgf@y%
        \pgf@ya\cosarcrotate\pgf@y%
        \advance\pgf@ya\sinarcrotate\pgf@x%
        %
        \arcmidpoint%
        \advance\pgf@x\pgf@xa%
        \advance\pgf@y\pgf@ya%
      }%
      {%
        \pgfsetcornersarced{\pgfpointorigin}%
        \pgfpathcurveto{\controlone}{\controltwo}{\arcmidpoint}%
      }%
      %
      % Do the same for the second arc...
      %
      \pgfmathadd@{\quarterarc}{90}%
      \pgfmathadd@{\pgfmathresult}{\arcslope}%
      \let\arcrotate\pgfmathresult%
      \pgfmathsin@{\arcrotate}%
      \let\sinarcrotate\pgfmathresult%
      \pgfmathcos@{\arcrotate}%
      \let\cosarcrotate\pgfmathresult%
      %
      % First control point for the second arc...
      %
      \pgfextract@process\controlone{%        
        \pgf@x0.55228475pt\relax%
        \pgf@x\sinquarterarc\pgf@x% k * sin(a/2)
        \pgf@y0.55228475pt\relax%
        \pgf@y\cosquarterarc\pgf@y% k * cos(a/2)
        %
        % ...scale, rotate and shift.
        %
        \pgf@x\controlscale\pgf@x%
        \pgf@y\controlscale\pgf@y%
        %
        \pgf@xa\cosarcrotate\pgf@x%
        \advance\pgf@xa-\sinarcrotate\pgf@y%
        \pgf@ya\cosarcrotate\pgf@y%
        \advance\pgf@ya\sinarcrotate\pgf@x%
        %
        \arcmidpoint%
        \advance\pgf@x\pgf@xa%
        \advance\pgf@y\pgf@ya%
      }%
      %
      % Second control point for the second arc.
      %
      \pgfextract@process\controltwo{%        
        \pgf@x0.55228475pt\relax%
        \pgf@x\sinquarterarc\pgf@x%  k * sin(a/2)
        \pgf@y-0.55228475pt\relax%
        \pgf@y\cosquarterarc\pgf@y% -k * cos(a/2)    
        %
        % ...scale, rotate and shift.
        %
        \pgf@x\controlscale\pgf@x%
        \pgf@y\controlscale\pgf@y%
        %
        \pgf@xa\cosarcrotate\pgf@x%
        \advance\pgf@xa-\sinarcrotate\pgf@y%
        \pgf@ya\cosarcrotate\pgf@y%
        \advance\pgf@ya\sinarcrotate\pgf@x%
        %
        \arcendpoint%
        \advance\pgf@x\pgf@xa%
        \advance\pgf@y\pgf@ya%
      }%
      \pgfpathcurveto{\controlone}{\controltwo}{\arcendpoint}%
      \repeatpgfmathloop%
    \pgfpathclose% Phew!
    }%
  }%
  %
  % Calculate a point on the border of the cloud. This is a two-stage process:
  %
  % 1. Locate the correct puff.
  % 2. Locate the angle on the circular arc which forms the puff.
  %
  \anchorborder{%
    %
    % Save x and y.
    %
    \edef\externalx{\the\pgf@x}%
    \edef\externaly{\the\pgf@y}%
     %
    % Get the inner radii and trig. constants.
    %
    \getradii%    
    %
    %
    %
    \ifpgfcloudanchorsuseellipse%
      \pgfpointadd{\centerpoint}{%
        \pgfpointborderellipse{%
          \pgfpoint{\externalx}{\externaly}
          }{%
            \pgfpoint{\xouterradius}{\youterradius}
          }%
      }%
    \else%
      \pgfextract@process\externalpoint{%
        \centerpoint%
        \advance\pgf@x\externalx\relax%
        \advance\pgf@y\externaly\relax%
      }%
      \pgfmathanglebetweenpoints{\centerpoint}{\externalpoint}%
      \let\externalangle\pgfmathresult%
      %
      % 1. Locate the correct puff: 
      %
      % Get end angle of the relavent puff arc.
      %
      \pgfmathdivide@{\anglestep}{2}%
      \let\halfanglestep\pgfmathresult%
      \pgfmathsubtract@{90}{\halfanglestep}%
      \let\endangle\pgfmathresult%
      \pgfmathloop%
        \pgfmathsubtract@{\endangle}{\anglestep}%
        \ifdim\pgfmathresult pt<-\anglestep pt\relax%
        \else%
          \let\endangle\pgfmathresult%
      \repeatpgfmathloop%
      \def\angle{0}%
      \let\lastangle\angle%
      \pgfmathloop%
        \pgfmathadd@{\endangle}{\anglestep}%
        \let\endangle\pgfmathresult%
        %
        % Calculate the `miter point'. This is the point between 
        % each puff, and takes into account the outer sep.
        %
        \pgfextract@process\miterpoint{%
          %
          \pgfextract@process\secondpoint{%
            \pgfpointpolar{+\endangle}{+\xinnerradius and +\yinnerradius}%
          }%
          %
          \pgfmathadd@{\endangle}{\anglestep}%
          \let\angletemp\pgfmathresult%
          \pgfextract@process\thirdpoint{%
            \pgfpointpolar{+\angletemp}{+\xinnerradius and +\yinnerradius}%
          }%
          %
          \pgfmathsubtract@{\endangle}{\anglestep}%
          \let\angletemp\pgfmathresult%
          \pgfextract@process\firstpoint{%
            \pgfpointpolar{+\angletemp}{+\xinnerradius and +\yinnerradius}%
          }%
          %
          \pgfmathanglebetweenpoints{\firstpoint}{\secondpoint}%
          \let\anglealpha\pgfmathresult%
          \pgfmathanglebetweenpoints{\secondpoint}{\thirdpoint}%
          \let\anglebeta\pgfmathresult%
          %
          \pgfmathsubtract@{\anglebeta}{\anglealpha}%
          \pgfmathdivide@{\pgfmathresult}{2}%
          \pgfmathadd@{\pgfmathresult}{\halfcomplementarc}%
          \pgfmathcosec@{\pgfmathresult}%
          \pgf@x\outersep\relax%
          \pgf@x\pgfmathresult\pgf@x%
          \edef\miterradius{\the\pgf@x}%
          %
          \pgfmathadd@{\anglealpha}{\anglebeta}%
          \pgfmathsubtract@{\pgfmathresult}{180}%
          \pgfmathdivide@{\pgfmathresult}{2}%
          \let\miterangle\pgfmathresult%
          \pgfpointadd{\secondpoint}{%
            \pgfqpointpolar{\miterangle}{\miterradius}%
          }%
        }%
        %
        % Get the angle of the miter point...
        %
        \pgfmathanglebetweenpoints{\pgfpointorigin}{\miterpoint}%
        \let\angle\pgfmathresult%
        \ifdim\angle pt<\lastangle pt\relax% Guard against 360� = 0�
          \pgfmathadd@{\angle}{360}%
          \let\angle\pgfmathresult%
        \fi%
        \let\lastangle\angle%
        %
        % ...and see if it is greater than the external point.
        %
      \ifdim\externalangle pt>\angle pt\relax%
      \repeatpgfmathloop%
      %
      % Get the start angle of the relevant arc and ensure angles are in the range.
      %
      \pgfmathmod@{\endangle}{360}%
      \let\endangle\pgfmathresult%
      \pgfmathsubtract@{\endangle}{\anglestep}%
      \ifdim\pgfmathresult pt<0pt\relax%
        \pgfmathadd@{\pgfmathresult}{360}%
      \fi%
      \let\startangle\pgfmathresult%
      %
      % Now, get the start and end points of the arc.
      %
      \pgfextract@process\arcstartpoint{%
        \pgfpointadd{\centerpoint}{%
          \pgfpointpolar{+\startangle}{+\xinnerradius and +\yinnerradius}%
        }%
      }%  
      \pgfextract@process\arcendpoint{%
        \pgfpointadd{\centerpoint}{%
          \pgfpointpolar{+\endangle}{+\xinnerradius and +\yinnerradius}%
        }%
      }%  
      %
      % Get some useful cloud parameters from \arcstartpoint and \arcendpoint.
      %
      \pgf@sh@getcloudpuffparameters%
      %
      % Hackery, for when an arc straddles 0�.
      %
      \ifdim\endangle pt<\startangle pt\relax%
        \pgfmathadd@{\externalangle}{180}%
        \pgfmathmod@{\pgfmathresult}{360}%
        \let\x\pgfmathresult%
      \else%
        \let\x\externalangle%
      \fi%
      %
      % 2. Locate the angle on the circular arc which forms the puff.
      % 
      % Essentially a binary search to find the angle on the circular  
      % arc, which provides the nearset estimate to the border point.
      %
      \let\s\halfcomplementarc% The start of the arc.
      \pgfmathadd@{\s}{\arc}%
      \let\e\pgfmathresult% The end of the arc.
      \pgfmathadd@{\e}{\s}%
      \pgfmathdivide@{\pgfmathresult}{2}%
      \let\n\pgfmathresult% The nearest estimate (default to middle of arc).
      \def\m{360}% Measure of `nearness'.
      \pgfmathloop%
        \pgfmathadd@{\e}{\s}%
        \pgfmathdivide@{\pgfmathresult}{2}%
        \let\p\pgfmathresult% The point halfway between \s and \e.
        \ifdim\p pt=\s pt\relax% 
        \else%
          %
          % Get the point on the circular arc.
          %
          \pgfmathadd@{\p}{\arcslope}%
          \let\a\pgfmathresult%
          \pgfextract@process\arcpoint{%
            \pgfpointadd{\circlecenterpoint}{%
              \pgfqpointpolar{\a}{\outerarcradius}%
            }%
          }%
          %
          % Find the angle between the node centre and the point on the arc.
          %
          \pgfmathanglebetweenpoints{\centerpoint}{\arcpoint}%
          %
          % Hackery, for when an arc straddles 0�.
          %
          \ifdim\endangle pt<\startangle pt\relax%
            \pgfmathadd@{\pgfmathresult}{180}%
            \pgfmathmod@{\pgfmathresult}{360}%
          \fi%
          \let\q\pgfmathresult%
          \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%
      %
      % Use the nearest estimate as the anchor angle.
      %
      \pgfmathadd@{\n}{\arcslope}%
      \let\anchorangle\pgfmathresult%
      %
      % Finally, the required point.
      %
      \pgfpointadd{\circlecenterpoint}{%
        \pgfqpointpolar{\anchorangle}{\outerarcradius}%
      }%
    \fi%
  }% Again, Phew!
  %
  % Now, a sneaky hack. This means an arbitrary `puff' anchors 
  % can be used for positiong the cloud shape. This is needed
  % if a cloud is positioned using the `puff <n+1>' anchor, where
  % n is the number of puffs of any previously drawn cloud.
  %
  \pgfutil@g@addto@macro\pgf@sh@s@cloud{%
    \c@pgf@counta\puffs\relax%
    \pgfmathloop%
      \ifnum\c@pgf@counta>0\relax%
        \pgfutil@ifundefined{pgf@anchor@cloud@puff\space\the\c@pgf@counta}{%
        \expandafter\xdef\csname pgf@anchor@cloud@puff\space\the\c@pgf@counta\endcsname{%
          \noexpand\pgf@sh@@cloudpuffanchor{\the\c@pgf@counta}%
        }%
      }{\c@pgf@counta0\relax}%
      \advance\c@pgf@counta-1\relax%
    \repeatpgfmathloop%  
  }%
}

% \pgf@sh@@cloudpuffanchor
% 
% Internal macro for calculating the anchors puff 1, puff 2, ... etc.
%
\def\pgf@sh@@cloudpuffanchor#1{%
    \getradii%
    \pgfmathdivide@{\anglestep}{2}%
    \let\halfanglestep\pgfmathresult%
    \c@pgf@counta#1\relax%
    \advance\c@pgf@counta-1\relax%
    \pgfmathmultiply@{\anglestep}{\the\c@pgf@counta}%
    \pgfmathadd@{\pgfmathresult}{90}%
    \pgfmathsubtract@{\pgfmathresult}{\halfanglestep}%
    \let\angle\pgfmathresult%
    %
    % Calculate the first arc point.
    %
    \pgfextract@process\arcstartpoint{%
      \pgfpointadd{\centerpoint}{%
        \pgfpointpolar{+\angle}{+\xinnerradius and +\yinnerradius}%
      }%
    }%
    %
    \pgfmathadd@{\angle}{\anglestep}%
    \let\angle\pgfmathresult%
    \pgfextract@process\arcendpoint{%
      \pgfpointadd{\centerpoint}{%
        \pgfpointpolar{+\angle}{+\xinnerradius and +\yinnerradius}%
      }%
    }%  
    %
    % Get some useful cloud parameters from \arcstartpoint and \arcendpoint.
    %
    \pgf@sh@getcloudpuffparameters%
    %
    % Calculate the point.
    %
    \pgfmathadd@{\arcslope}{90}%
    \let\anchorangle\pgfmathresult%
    \pgfpointadd{\circlecenterpoint}{%
      \pgfqpointpolar{\anchorangle}{\outerarcradius}%
    }%
}  

% \pgf@sh@cloudpuffparameters
%
% Internal macro to calculate some common arc parameters which 
% are required when calculating radii, drawing the background
% path and calculating border anchors.
%
\def\pgf@sh@getcloudpuffparameters{%
  %
  % Calculate the angle to which the entire arc is sloped.
  %
  \pgfmathanglebetweenpoints{\arcendpoint}{\arcstartpoint}%
  \let\arcslope\pgfmathresult%
  %
  % Calculate the chord length and arc radius.
  %
  \pgfpointdiff{\arcendpoint}{\arcstartpoint}%
  \pgfmathveclen@{\pgfmath@tonumber{\pgf@x}}{\pgfmath@tonumber{\pgf@y}}
  \pgf@x\pgfmathresult pt\relax%
  \pgf@xa.5\pgf@x%
  \edef\halfchordlength{\the\pgf@xa}%
  \pgf@x\arcradiusquotient\pgf@x%
  \edef\arcradius{\the\pgf@x}%
  \pgf@xa\outersep\relax%
  \advance\pgf@xa\pgf@x%
  \edef\outerarcradius{\the\pgf@xa}%
  %
  % Calculate the height of the resulting segment.
  %
  \pgf@y-\sinhalfcomplementarc\pgf@x% sin((180-a)/2)
  \advance\pgf@y\pgf@x%
  \edef\segmentheight{\the\pgf@y}%
  %
  % Calculate the center of the circle of which the arc is a part.
  %
  \pgfextract@process\circlecenterpoint{%
    \pgfextract@process\circlecenterpoint{%
      \pgf@x-\halfchordlength\relax%
      \pgf@y\segmentheight\relax%
      \advance\pgf@y-\arcradius
    }%
    \pgfpointadd{\arcstartpoint}{%
      \pgfmathrotatepointaround{\circlecenterpoint}{\pgfpointorigin}{\arcslope}%
    }%
  }%
}





% Internal macros for signal shape.
%
\def\pgf@lib@sh@signal@nowhere{nowhere}%
\def\pgf@lib@sh@signal@from{from}%
\def\pgf@lib@sh@signal@to{to}%

\def\pgf@lib@sh@signal@parsedirection#1#2{%
  %
  \let\pgf@lib@sh@signal@direction=#2%
  \edef\pgf@lib@sh@temp{#1}%
  \expandafter\pgf@lib@sh@signal@@parsedirection\pgf@lib@sh@temp\pgf@stop}

\def\pgf@lib@sh@signal@@parsedirection#1\pgf@stop{%
  \pgfutil@in@{and}{#1}%
  \ifpgfutil@in@%
    \pgf@lib@sh@signal@@@parsedirection#1\pgf@lib%
  \else%
    \pgf@lib@sh@signal@@@parsedirection#1 and #1\pgf@lib%
  \fi
}
\def\pgf@lib@sh@signal@@@parsedirection#1 and #2\pgf@lib{%
  \pgfutil@in@{nowhere}{#1}%
  \ifpgfutil@in@
  \else%
    \pgf@lib@sh@signal@@@@parsedirection{#1}%
    \pgf@lib@sh@signal@@@@parsedirection{#2}%
  \fi%
}
\def\pgf@lib@sh@signal@@@@parsedirection#1{%
  \pgfutil@in@{ #1 }{ east right }%
  \ifpgfutil@in@%
    \let\pgf@lib@sh@signal@east=\pgf@lib@sh@signal@direction%
    \let\pgf@lib@sh@signal@north=\pgf@lib@sh@signal@nowhere%
    \let\pgf@lib@sh@signal@south=\pgf@lib@sh@signal@nowhere%
  \fi%
  \pgfutil@in@{ #1 }{ left west }%
  \ifpgfutil@in@%
    \let\pgf@lib@sh@signal@west=\pgf@lib@sh@signal@direction%
    \let\pgf@lib@sh@signal@north=\pgf@lib@sh@signal@nowhere%
    \let\pgf@lib@sh@signal@south=\pgf@lib@sh@signal@nowhere%
  \fi%
  \pgfutil@in@{ #1 }{ above up north }%
  \ifpgfutil@in@%
    \let\pgf@lib@sh@signal@north=\pgf@lib@sh@signal@direction%
    \let\pgf@lib@sh@signal@east=\pgf@lib@sh@signal@nowhere%
    \let\pgf@lib@sh@signal@west=\pgf@lib@sh@signal@nowhere%
  \fi%
  \pgfutil@in@{ #1 }{ below down south }%
  \ifpgfutil@in@%
    \let\pgf@lib@sh@signal@south=\pgf@lib@sh@signal@direction%
    \let\pgf@lib@sh@signal@east=\pgf@lib@sh@signal@nowhere%
    \let\pgf@lib@sh@signal@west=\pgf@lib@sh@signal@nowhere%
  \fi%
}


% Keys for signal shape:
%
\pgfkeys{/pgf/.cd,
  signal pointer angle/.initial=90,
  signal to/.initial=east,
  signal from/.initial=nowhere
}

\pgfdeclareshape{signal}{%
  \savedmacro\installsignalparameters{%
    %
    \let\pgf@lib@sh@signal@north=\pgf@lib@sh@signal@nowhere%
    \let\pgf@lib@sh@signal@south=\pgf@lib@sh@signal@nowhere%
    \let\pgf@lib@sh@signal@east=\pgf@lib@sh@signal@nowhere%
    \let\pgf@lib@sh@signal@west=\pgf@lib@sh@signal@nowhere%
    %
    \pgf@lib@sh@signal@parsedirection{\pgfkeysvalueof{/pgf/signal from}}{\pgf@lib@sh@signal@from}%
    \pgf@lib@sh@signal@parsedirection{\pgfkeysvalueof{/pgf/signal to}}{\pgf@lib@sh@signal@to}%    
    %
    % Define a centerpoint.
    %
    \pgfextract@process\centerpoint{%
      \pgf@x.5\wd\pgfnodeparttextbox%
      \pgf@y.5\ht\pgfnodeparttextbox%
      \advance\pgf@y-.5\dp\pgfnodeparttextbox%
    }%
    %
    % Get some useful trig. stuff
    %
    \pgfmathsetmacro\pointerangle{\pgfkeysvalueof{/pgf/signal pointer angle}}%
    %
    \pgfmathdivide@{\pointerangle}{2}%
    \let\halfpointerangle=\pgfmathresult%
    %
    \pgfmathcosec@{\halfpointerangle}%
    \let\cosechalfpointerangle=\pgfmathresult%
    %
    \pgfmathdivide@{\halfpointerangle}{2}%
    \let\quarterpointerangle=\pgfmathresult%
    %
    \pgfmathcosec@{\quarterpointerangle}%
    \let\cosecquarterpointerangle=\pgfmathresult%
    %
    \pgfmathsec@{\quarterpointerangle}%
    \let\secquarterpointerangle=\pgfmathresult%
    %
    \pgfmathsubtract@{90}{\quarterpointerangle}%
    \let\complementquarterpointerangle\pgfmathresult%
    %
    % Get the larger of the outer sep.
    %
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/outer xsep}}%
    \pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/outer ysep}}%
    \ifdim\pgf@x>\pgf@y%
      \pgf@y\pgf@x%
    \fi%
    \pgf@yc=\pgf@y%
    %
    % Calculate the miter due to the line width, at the pointer apex... 
    %
    \pgf@x=\cosechalfpointerangle\pgf@y%
    \edef\pointerapexmiter{\the\pgf@x}%
    %
    % ...at a corner by a `to' pointer (i.e. sticks out)...
    %
    \pgf@x=\secquarterpointerangle\pgf@y%
    \edef\tocornermiter{\the\pgf@x}%
    %
    % ...at a corner by a `from' pointer (i.e. sticks in).
    %
    \pgf@x=\cosecquarterpointerangle\pgf@y
    \edef\fromcornermiter{\the\pgf@x}%
    %
    % Get the (half) dimensions of the node.
    %
    \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/inner xsep}}%
    \advance\pgf@xa.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/inner ysep}}%
    \advance\pgf@ya.5\ht\pgfnodeparttextbox%
    \advance\pgf@ya.5\dp\pgfnodeparttextbox%
    %
    % Get the distance a pointer sticks out to the side...
    %
    \pgfmathsubtract@{90}{\halfpointerangle}%
    \pgfmathtan@{\pgfmathresult}%
    \pgf@xb=\pgfmathresult\pgf@ya%
    % 
    % ...and up.
    %
    \pgf@yb=\pgfmathresult\pgf@xa%
    %
    % Adjust for minimum height.
    %
    \pgfutil@tempdima=2.0\pgf@ya%
    \ifx\pgf@lib@sh@signal@north\pgf@lib@sh@signal@nowhere%
    \else%
      \advance\pgfutil@tempdima by\pgf@yb%
    \fi%
    \ifx\pgf@lib@sh@signal@south\pgf@lib@sh@signal@nowhere%
    \else%
      \advance\pgfutil@tempdima by\pgf@yb%
    \fi%
    \pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/minimum height}}%
    \ifdim\pgfutil@tempdima<\pgf@y%
      \pgfutil@tempdima=\pgf@y%
      %
      \ifx\pgf@lib@sh@signal@north\pgf@lib@sh@signal@nowhere%
      \else%
        \advance\pgfutil@tempdima by-\pgf@yb%
      \fi%
      \ifx\pgf@lib@sh@signal@south\pgf@lib@sh@signal@nowhere%
      \else%
        \advance\pgfutil@tempdima by-\pgf@yb%
      \fi%
      \pgf@ya=0.5\pgfutil@tempdima%
      \pgfmathsubtract@{90}{\halfpointerangle}%
      \pgfmathtan@{\pgfmathresult}%
      \pgf@xb=\pgfmathresult\pgf@ya%
    \fi%
    %
    % Adjust for minimum width.
    %
    \pgfutil@tempdima=2.0\pgf@xa%
    \ifx\pgf@lib@sh@signal@east\pgf@lib@sh@signal@nowhere%
    \else%
      \advance\pgfutil@tempdima by\pgf@xb%
    \fi%
    \ifx\pgf@lib@sh@signal@west\pgf@lib@sh@signal@nowhere%
    \else%
      \advance\pgfutil@tempdima by\pgf@xb%
    \fi%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/minimum width}}%
    \ifdim\pgfutil@tempdima<\pgf@x%
      \pgfutil@tempdima=\pgf@x%
      \ifx\pgf@lib@sh@signal@east\pgf@lib@sh@signal@nowhere%
      \else%
        \advance\pgfutil@tempdima by-\pgf@xb%
      \fi%
      \ifx\pgf@lib@sh@signal@west\pgf@lib@sh@signal@nowhere%
      \else%
        \advance\pgfutil@tempdima by-\pgf@xb%
      \fi%
      \pgf@xa=0.5\pgfutil@tempdima%
      \pgfmathsubtract@{90}{\halfpointerangle}%
      \pgfmathtan@{\pgfmathresult}%
      \pgf@yb=\pgfmathresult\pgf@xa%
    \fi%
    %
    % So, define the points for the background path.
    %
    \pgfextract@process\north{%
      \centerpoint%
      \advance\pgf@y\pgf@ya%
      \ifx\pgf@lib@sh@signal@north\pgf@lib@sh@signal@to%
        \advance\pgf@y\pgf@yb%
      \fi%
    }%
    \pgfextract@process\south{%
      \centerpoint%
      \advance\pgf@y-\pgf@ya%
      \ifx\pgf@lib@sh@signal@south\pgf@lib@sh@signal@to%
        \advance\pgf@y-\pgf@yb%
      \fi%
    }%
    \pgfextract@process\east{%
      \centerpoint%
      \advance\pgf@x\pgf@xa%
      \ifx\pgf@lib@sh@signal@east\pgf@lib@sh@signal@to%
        \advance\pgf@x\pgf@xb%
      \fi%
    }%
    \pgfextract@process\west{%
      \centerpoint%
      \advance\pgf@x-\pgf@xa%
      \ifx\pgf@lib@sh@signal@west\pgf@lib@sh@signal@to%
        \advance\pgf@x-\pgf@xb%
      \fi%
    }%
    \pgfextract@process\northeast{%
      \centerpoint%
      \advance\pgf@y\pgf@ya%
      \advance\pgf@x\pgf@xa%
      \ifx\pgf@lib@sh@signal@north\pgf@lib@sh@signal@from%
        \advance\pgf@y\pgf@yb%
      \fi%
      \ifx\pgf@lib@sh@signal@east\pgf@lib@sh@signal@from%
        \advance\pgf@x\pgf@xb%
      \fi%
    }%
    \pgfextract@process\southeast{%
      \centerpoint%
      \advance\pgf@y-\pgf@ya%
      \advance\pgf@x\pgf@xa%
      \ifx\pgf@lib@sh@signal@south\pgf@lib@sh@signal@from%
        \advance\pgf@y-\pgf@yb%
      \fi%
      \ifx\pgf@lib@sh@signal@east\pgf@lib@sh@signal@from%
        \advance\pgf@x\pgf@xb%
      \fi%
    }%
    \pgfextract@process\southwest{%
      \centerpoint%
      \advance\pgf@y-\pgf@ya%
      \advance\pgf@x-\pgf@xa%
      \ifx\pgf@lib@sh@signal@south\pgf@lib@sh@signal@from%
        \advance\pgf@y-\pgf@yb%
      \fi%
      \ifx\pgf@lib@sh@signal@west\pgf@lib@sh@signal@from%
        \advance\pgf@x-\pgf@xb%
      \fi%
    }%
    \pgfextract@process\northwest{%
      \centerpoint%
      \advance\pgf@y\pgf@ya%
      \advance\pgf@x-\pgf@xa%
      \ifx\pgf@lib@sh@signal@north\pgf@lib@sh@signal@from%
        \advance\pgf@y\pgf@yb%
      \fi%
      \ifx\pgf@lib@sh@signal@west\pgf@lib@sh@signal@from%
        \advance\pgf@x-\pgf@xb%
      \fi%
    }%
    \addtosavedmacro{\north}%
    \addtosavedmacro{\south}%
    \addtosavedmacro{\east}%
    \addtosavedmacro{\west}%
    \addtosavedmacro{\northeast}%
    \addtosavedmacro{\southwest}%
    \addtosavedmacro{\southeast}%
    \addtosavedmacro{\northwest}%
    %
    % Calculate the `miter vectors' (i.e. +outer sep). 
    %
    \pgfextract@process\northmiter{%
      \pgf@x0pt%
      \ifx\pgf@lib@sh@signal@north\pgf@lib@sh@signal@nowhere%
        \pgf@y\pgf@yc%
      \else%
        \pgf@y\pointerapexmiter\relax%
      \fi%
    }%
    \pgfextract@process\southmiter{%
      \pgf@x0pt%
      \ifx\pgf@lib@sh@signal@south\pgf@lib@sh@signal@nowhere%
        \pgf@y-\pgf@yc%
      \else%
        \pgf@y-\pointerapexmiter\relax%
      \fi%
    }%
    \pgfextract@process\eastmiter{%
      \pgf@y0pt%
      \ifx\pgf@lib@sh@signal@east\pgf@lib@sh@signal@nowhere%
        \pgf@x\pgf@yc%
      \else%
        \pgf@x\pointerapexmiter\relax%
      \fi%
    }%
    \pgfextract@process\westmiter{%
      \pgf@y0pt%
      \ifx\pgf@lib@sh@signal@west\pgf@lib@sh@signal@nowhere%
        \pgf@x-\pgf@yc%
      \else%
        \pgf@x-\pointerapexmiter\relax%
      \fi%
    }%
    \pgfextract@process\northeastmiter{%
      \ifx\pgf@lib@sh@signal@east\pgf@lib@sh@signal@nowhere%
        \pgf@x\pgf@yc
        \pgf@y\pgf@yc%
      \else
        \ifx\pgf@lib@sh@signal@east\pgf@lib@sh@signal@from%
          \pgfqpointpolar{\quarterpointerangle}{\fromcornermiter}
        \else%
          \ifx\pgf@lib@sh@signal@east\pgf@lib@sh@signal@to%
            \pgfqpointpolar{\complementquarterpointerangle}{\tocornermiter}%
          \fi%
        \fi%  
      \fi%
      \ifx\pgf@lib@sh@signal@north\pgf@lib@sh@signal@from%
        \pgfqpointpolar{\complementquarterpointerangle}{\fromcornermiter}%
      \else%
        \ifx\pgf@lib@sh@signal@north\pgf@lib@sh@signal@to%
          \pgfqpointpolar{\quarterpointerangle}{\tocornermiter}%
        \fi%
      \fi%  
    }%
    \pgfextract@process\southeastmiter{%
      \ifx\pgf@lib@sh@signal@east\pgf@lib@sh@signal@nowhere%
        \pgf@x\pgf@yc%
        \pgf@y\pgf@yc%
      \else
        \ifx\pgf@lib@sh@signal@east\pgf@lib@sh@signal@from%
          \pgfqpointpolar{-\quarterpointerangle}{\fromcornermiter}
        \else%
          \ifx\pgf@lib@sh@signal@east\pgf@lib@sh@signal@to%
            \pgfqpointpolar{-\complementquarterpointerangle}{\tocornermiter}%
          \fi%
        \fi%  
      \fi%
      \ifx\pgf@lib@sh@signal@south\pgf@lib@sh@signal@from%
        \pgfqpointpolar{-\complementquarterpointerangle}{\fromcornermiter}
      \else%
        \ifx\pgf@lib@sh@signal@south\pgf@lib@sh@signal@to%
          \pgfqpointpolar{-\quarterpointerangle}{\tocornermiter}%
        \fi%
      \fi%  
    }%
    \pgfextract@process\southwestmiter{%
      \ifx\pgf@lib@sh@signal@west\pgf@lib@sh@signal@nowhere%
        \pgf@x-\pgf@yc
        \pgf@y-\pgf@yc%
      \else
        \ifx\pgf@lib@sh@signal@west\pgf@lib@sh@signal@from%
          \pgfmathadd@{\quarterpointerangle}{180}%
          \expandafter\pgfqpointpolar\expandafter{\pgfmathresult}{\fromcornermiter}
        \else%
          \ifx\pgf@lib@sh@signal@west\pgf@lib@sh@signal@to%
            \pgfmathadd@{\complementquarterpointerangle}{180}%
            \expandafter\pgfqpointpolar\expandafter{\pgfmathresult}{\tocornermiter}%
          \fi%
        \fi%  
      \fi%
      \ifx\pgf@lib@sh@signal@south\pgf@lib@sh@signal@from%
        \pgfmathadd@{\complementquarterpointerangle}{180}%
        \expandafter\pgfqpointpolar\expandafter{\pgfmathresult}{\fromcornermiter}%
      \else%
        \ifx\pgf@lib@sh@signal@south\pgf@lib@sh@signal@to%
          \pgfmathadd@{\quarterpointerangle}{180}%
          \expandafter\pgfqpointpolar\expandafter{\pgfmathresult}{\tocornermiter}%
        \fi%
      \fi%  
    }%
    \pgfextract@process\northwestmiter{%
      \ifx\pgf@lib@sh@signal@west\pgf@lib@sh@signal@nowhere%
        \pgf@x-\pgf@yc%
        \pgf@y\pgf@yc%
      \else
        \ifx\pgf@lib@sh@signal@west\pgf@lib@sh@signal@from%
          \pgfmathsubtract@{180}{\quarterpointerangle}%
          \expandafter\pgfqpointpolar\expandafter{\pgfmathresult}{\fromcornermiter}
        \else%
          \ifx\pgf@lib@sh@signal@west\pgf@lib@sh@signal@to%
            \pgfmathsubtract@{180}{\complementquarterpointerangle}%
            \expandafter\pgfqpointpolar\expandafter{\pgfmathresult}{\tocornermiter}%
          \fi%
        \fi%  
      \fi%
      \ifx\pgf@lib@sh@signal@north\pgf@lib@sh@signal@from%
        \pgfmathsubtract@{180}{\complementquarterpointerangle}%
        \expandafter\pgfqpointpolar\expandafter{\pgfmathresult}{\fromcornermiter}%
      \else%
        \ifx\pgf@lib@sh@signal@west\pgf@lib@sh@signal@to%
          \pgfmathsubtract@{180}{\quarterpointerangle}%
          \expandafter\pgfqpointpolar\expandafter{\pgfmathresult}{\tocornermiter}%
        \fi%
      \fi%  
    }%
    \addtosavedmacro{\northmiter}%
    \addtosavedmacro{\southmiter}%
    \addtosavedmacro{\eastmiter}%
    \addtosavedmacro{\westmiter}%
    \addtosavedmacro{\northeastmiter}%
    \addtosavedmacro{\southeastmiter}%
    \addtosavedmacro{\southwestmiter}%
    \addtosavedmacro{\northwestmiter}%
    %
    % Now calculate the anchor points
    %
    \pgfextract@process\anchornorth{%
      \pgfpointadd{\north}{\northmiter}%
    }%
    \pgfextract@process\anchorsouth{%
      \pgfpointadd{\south}{\southmiter}%
    }%
    \pgfextract@process\anchoreast{%
      \pgfpointadd{\east}{\eastmiter}%
    }%
    \pgfextract@process\anchorwest{%
      \pgfpointadd{\west}{\westmiter}%
    }%
    \pgfextract@process\anchornortheast{%
      \pgfpointadd{\northeast}{\northeastmiter}%
    }%
    \pgfextract@process\anchorsoutheast{%
      \pgfpointadd{\southeast}{\southeastmiter}%
    }%
    \pgfextract@process\anchorsouthwest{%
      \pgfpointadd{\southwest}{\southwestmiter}%
    }%
    \pgfextract@process\anchornorthwest{%
      \pgfpointadd{\northwest}{\northwestmiter}%
    }%
    \addtosavedmacro{\anchornorth}%
    \addtosavedmacro{\anchorsouth}%
    \addtosavedmacro{\anchoreast}%
    \addtosavedmacro{\anchorwest}%
    \addtosavedmacro{\anchornortheast}%
    \addtosavedmacro{\anchorsouthwest}%
    \addtosavedmacro{\anchorsoutheast}%
    \addtosavedmacro{\anchornorthwest}%    
  }%
  \savedanchor\centerpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y.5\ht\pgfnodeparttextbox%
    \advance\pgf@y-.5\dp\pgfnodeparttextbox%
  }%
  \savedanchor\basepoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y0pt%
  }%
  \savedanchor\midpoint{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@y{+.5ex}%
  }%
  \anchor{center}{\centerpoint}%
  \anchor{base}{\basepoint}%
  \anchor{base east}{%
    \installsignalparameters%
    \anchoreast%
    \pgf@xa\pgf@x%
    \pgf@ya\pgf@y%
    \anchorsoutheast%
    \ifdim\pgf@xa>\pgf@x%
      \pgfutil@tempdima\pgf@xa%
    \else%
      \pgfutil@tempdima\pgf@x%
    \fi%
    \pgfextract@process\externalpoint{%
      \basepoint%
      \pgf@x\pgfutil@tempdima%
    }
    \basepoint%
    \let\firstpoint\anchoreast%
    \ifdim\pgf@y<\pgf@ya%
      \let\secondpoint\anchorsoutheast%
    \else%
      \let\secondpoint\anchornortheast%
    \fi%
    \pgfpointintersectionoflines{\basepoint}{\externalpoint}%
      {\firstpoint}{\secondpoint}%    
  }%
  \anchor{base west}{%
    \installsignalparameters%
    \anchorwest%
    \pgf@xa\pgf@x%
    \pgf@ya\pgf@y%
    \anchorsouthwest%
    \ifdim\pgf@xa<\pgf@x%
      \pgfutil@tempdima\pgf@xa%
    \else%
      \pgfutil@tempdima\pgf@x%
    \fi%
    \pgfextract@process\externalpoint{%
      \basepoint%
      \pgf@x\pgfutil@tempdima%
    }
    \basepoint%
    \let\firstpoint\anchorwest%
    \ifdim\pgf@y<\pgf@ya%
      \let\secondpoint\anchorsouthwest%
    \else%
      \let\secondpoint\anchornorthwest%
    \fi%
    \pgfpointintersectionoflines{\basepoint}{\externalpoint}%
      {\firstpoint}{\secondpoint}%    
  }%
  \anchor{mid}{\midpoint}%
  \anchor{mid east}{%
    \installsignalparameters%
    \anchoreast%
    \pgf@xa\pgf@x%
    \pgf@ya\pgf@y%
    \anchorsoutheast%
    \ifdim\pgf@xa>\pgf@x%
      \pgfutil@tempdima\pgf@xa%
    \else%
      \pgfutil@tempdima\pgf@x%
    \fi%
    \pgfextract@process\externalpoint{%
      \midpoint%
      \pgf@x\pgfutil@tempdima%
    }
    \midpoint%
    \let\firstpoint\anchoreast%
    \ifdim\pgf@y<\pgf@ya%
      \let\secondpoint\anchorsoutheast%
    \else%
      \let\secondpoint\anchornortheast%
    \fi%
    \pgfpointintersectionoflines{\midpoint}{\externalpoint}%
      {\firstpoint}{\secondpoint}%    
  }%
  \anchor{mid west}{%
    \installsignalparameters%
    \anchorwest%
    \pgf@xa\pgf@x%
    \pgf@ya\pgf@y%
    \anchorsouthwest%
    \ifdim\pgf@xa<\pgf@x%
      \pgfutil@tempdima\pgf@xa%
    \else%
      \pgfutil@tempdima\pgf@x%
    \fi%
    \pgfextract@process\externalpoint{%
      \midpoint%
      \pgf@x\pgfutil@tempdima%
    }
    \midpoint%
    \let\firstpoint\anchorwest%
    \ifdim\pgf@y<\pgf@ya%
      \let\secondpoint\anchorsouthwest%
    \else%
      \let\secondpoint\anchornorthwest%
    \fi%
    \pgfpointintersectionoflines{\midpoint}{\externalpoint}%
      {\firstpoint}{\secondpoint}%    
  }%
  \anchor{north}{\installsignalparameters\anchornorth}%
  \anchor{south}{\installsignalparameters\anchorsouth}%
  \anchor{east}{\installsignalparameters\anchoreast}%
  \anchor{west}{\installsignalparameters\anchorwest}%
  \anchor{north east}{\installsignalparameters\anchornortheast}%
  \anchor{south east}{\installsignalparameters\anchorsoutheast}%
  \anchor{south west}{\installsignalparameters\anchorsouthwest}%
  \anchor{north west}{\installsignalparameters\anchornorthwest}%
  \backgroundpath{%
    \installsignalparameters%
    \pgfpathmoveto{\north}%
    \pgfpathlineto{\northeast}%
    \pgfpathlineto{\east}%
    \pgfpathlineto{\southeast}%
    \pgfpathlineto{\south}%
    \pgfpathlineto{\southwest}%
    \pgfpathlineto{\west}%
    \pgfpathlineto{\northwest}%
    \pgfpathclose%
  }
  \anchorborder{%
    %
    % Save x and y.
    %
    \edef\externalx{\the\pgf@x}%
    \edef\externaly{\the\pgf@y}%
    %
    % Adjust the location of the external 
    % point relative to \centerpoint.
    %
    \centerpoint%
    \pgf@xa\externalx\relax%
    \pgf@ya\externaly\relax%
    \advance\pgf@xa\pgf@x%
    \advance\pgf@ya\pgf@y%
    \edef\externalx{\the\pgf@xa}%
    \edef\externaly{\the\pgf@ya}%
    %
    % Get the shape parameters.
    %
    \installsignalparameters%
    %
    % Get the angle of the external point to the \centerpoint.
    %
    \pgfmathanglebetweenpoints{\centerpoint}{\pgfqpoint{\externalx}{\externaly}}%
    \let\externalangle\pgfmathresult%
    %
    %
    %
    \pgfmathanglebetweenpoints{\centerpoint}{\anchorwest}%
    \ifdim\externalangle pt<\pgfmathresult pt\relax%
      \pgfmathanglebetweenpoints{\centerpoint}{\anchornorth}%
      \ifdim\externalangle pt<\pgfmathresult pt\relax%
        \pgfmathanglebetweenpoints{\centerpoint}{\anchornortheast}%
        \ifdim\externalangle pt<\pgfmathresult pt\relax%
          \let\firstpoint\anchoreast%
          \let\secondpoint\anchornortheast%
        \else%
          \let\secondpoint\anchornortheast%
          \let\firstpoint\anchornorth%
        \fi%
      \else%
        \pgfmathanglebetweenpoints{\centerpoint}{\anchornorthwest}%
        \ifdim\externalangle pt<\pgfmathresult pt\relax%
          \let\firstpoint\anchornorth%
          \let\secondpoint\anchornorthwest%
        \else%
          \let\secondpoint\anchornorthwest%
          \let\firstpoint\anchorwest%
        \fi%
      \fi%
    \else%
      \pgfmathanglebetweenpoints{\centerpoint}{\anchorsouth}%
      \ifdim\externalangle pt<\pgfmathresult pt\relax%
        \pgfmathanglebetweenpoints{\centerpoint}{\anchorsouthwest}%
        \ifdim\externalangle pt<\pgfmathresult pt\relax%
          \let\firstpoint\anchorwest%
          \let\secondpoint\anchorsouthwest%
        \else%
          \let\secondpoint\anchorsouthwest%
          \let\firstpoint\anchorsouth%
        \fi%
      \else%
        \pgfmathanglebetweenpoints{\centerpoint}{\anchorsoutheast}%
        \ifdim\externalangle pt<\pgfmathresult pt\relax%
          \let\firstpoint\anchorsouth%
          \let\secondpoint\anchorsoutheast%
        \else%
          \let\secondpoint\anchorsoutheast%
          \let\firstpoint\anchoreast%
        \fi%
      \fi%
    \fi%
    %
    % Now locate the point.
    %
    \pgfpointintersectionoflines{\centerpoint}{\pgfqpoint{\externalx}{\externaly}}%
      {\firstpoint}{\secondpoint}%
  }%
}%






% Keys for shape tape
%
% /pgf/tape bend top : Type of bend for north side.
% /pgf/tape bend bottom : Type of bend for south side.
% /pgf/tape bend height : The height of the bends.
\pgfkeys{/pgf/.cd,
  tape bend top/.initial=in and out,
  tape bend bottom/.initial=in and out,
  tape bend/.style={/pgf/tape bend top=#1, /pgf/tape bend bottom=#1},
  tape bend height/.initial=5pt
}

\def\pgf@lib@sh@inandouttext{in and out}
\def\pgf@lib@sh@outandintext{out and in}
\def\pgf@lib@sh@nonetext{none}

\pgfdeclareshape{tape}{
  \savedmacro\tapedimensions{%
    \pgfmathsetlength\pgf@x{\pgfkeysvalueof{/pgf/inner xsep}}%
    \advance\pgf@x.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@y{\pgfkeysvalueof{/pgf/inner ysep}}%
    \advance\pgf@y.5\ht\pgfnodeparttextbox%
    \advance\pgf@y.5\dp\pgfnodeparttextbox%
    %
    \pgfmathsetlengthmacro\outerxsep{\pgfkeysvalueof{/pgf/outer xsep}}%
    \pgfmathsetlengthmacro\outerysep{\pgfkeysvalueof{/pgf/outer ysep}}%
    \addtosavedmacro\outerxsep%
    \addtosavedmacro\outerysep%
    %
    \pgfmathsetlength\pgfutil@tempdima{\pgfkeysvalueof{/pgf/tape bend height}}%
    \pgfutil@tempdima.5\pgfutil@tempdima%
    \edef\halfbendheight{\the\pgfutil@tempdima}%
    \addtosavedmacro\halfbendheight%
    %
    \pgfkeysgetvalue{/pgf/tape bend top}{\topbendstyle}%
    \pgfkeysgetvalue{/pgf/tape bend bottom}{\bottombendstyle}%
    \addtosavedmacro\topbendstyle%
    \addtosavedmacro\bottombendstyle%
    %
    \ifx\topbendstyle\pgf@lib@sh@nonetext%
    \else%
      \advance\pgf@y\pgfutil@tempdima%
    \fi%
    \ifx\bottombendstyle\pgf@lib@sh@none%
    \else%
      \advance\pgf@y\pgfutil@tempdima%
    \fi%
    %
    \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/minimum width}}%
    \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/minimum height}}%
    \ifdim\pgf@x<.5\pgf@xa%
      \pgf@x.5\pgf@xa%
    \fi%
    \ifdim\pgf@y<.5\pgf@ya%
      \pgf@y.5\pgf@ya%
    \fi%
    \ifx\topbendstyle\pgf@lib@sh@nonetext%
    \else%
      \advance\pgf@y-\pgfutil@tempdima%
    \fi%
    \ifx\bottombendstyle\pgf@lib@sh@nonetext%
    \else%
      \advance\pgf@y-\pgfutil@tempdima%
    \fi%  
    %
    \pgfutil@tempdima3.414213\pgfutil@tempdima% 1 / (1-sin(45))
    \edef\bendyradius{\the\pgfutil@tempdima}%
    \addtosavedmacro\bendyradius%
    \advance\pgfutil@tempdima\outerysep%
    \edef\outerbendyradius{\the\pgfutil@tempdima}%
    \addtosavedmacro\outerbendyradius%
    \advance\pgfutil@tempdima-\outerysep%
    \advance\pgfutil@tempdima-\outerysep%
    \edef\innerbendyradius{\the\pgfutil@tempdima}%
    \addtosavedmacro\innerbendyradius%
    %
    \pgfutil@tempdima0.707106\pgf@x% cos(45) 
    \edef\bendxradius{\the\pgfutil@tempdima}%
    \addtosavedmacro\bendxradius%
    \advance\pgfutil@tempdima\outerxsep%
    \edef\outerbendxradius{\the\pgfutil@tempdima}%
    \addtosavedmacro\outerbendxradius%
    \advance\pgfutil@tempdima-\outerxsep%
    \advance\pgfutil@tempdima-\outerxsep%
    \edef\innerbendxradius{\the\pgfutil@tempdima}%
    \addtosavedmacro\innerbendxradius%
    %
    \edef\halfwidth{\the\pgf@x}%
    \edef\halfheight{\the\pgf@y}%
    \addtosavedmacro\halfwidth%
    \addtosavedmacro\halfheight%
    %
    \advance\pgf@x\outerxsep%
    \edef\outerhalfwidth{\the\pgf@x}%
    \addtosavedmacro\outerhalfwidth%
    %
    \pgf@xc\bendxradius%
    \pgf@yc\bendyradius%
    \pgfmathdivide@{\pgfmath@tonumber{\pgf@yc}}{\pgfmath@tonumber{\pgf@xc}}%
    \pgfmathatan{\pgfmathresult}%
    \pgf@xc\pgfmathresult pt\relax%
    \pgf@xc.5\pgf@xc%
    \edef\halfangle{\pgfmath@tonumber{\pgf@xc}}%
    \addtosavedmacro\halfangle%
    %
    \pgf@xc45pt\relax%
    \advance\pgf@xc-\halfangle pt%
    \pgfmathcot@{\pgfmath@tonumber{\pgf@xc}}%
    \let\cothalfanglein\pgfmathresult%
    \addtosavedmacro\cothalfanglein%
    %
    \pgf@xc90pt\relax%
    \advance\pgf@xc-\halfangle pt%
    \pgfmathcot@{\pgfmath@tonumber{\pgf@xc}}%
    \let\cothalfangleout\pgfmathresult%
    \addtosavedmacro\cothalfangleout%
    %
  }
  \savedanchor{\centerpoint}{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y.5\ht\pgfnodeparttextbox%
    \advance\pgf@y-.5\dp\pgfnodeparttextbox%  
  }
    \savedanchor{\midpoint}{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@y{+0.5ex}%
  }
  \savedanchor{\basepoint}{%
    \pgf@x.5\wd\pgfnodeparttextbox%
    \pgf@y0pt%
  }
  \anchor{center}{\centerpoint}%
  \anchor{mid}{\midpoint}%
  \anchor{mid east}{\tapedimensions\midpoint\advance\pgf@x\outerhalfwidth}%
  \anchor{mid west}{\tapedimensions\midpoint\advance\pgf@x-\outerhalfwidth}%
  \anchor{base}{\basepoint}%
  \anchor{base east}{\tapedimensions\basepoint\advance\pgf@x\outerhalfwidth}%
  \anchor{base west}{\tapedimensions\basepoint\advance\pgf@x-\outerhalfwidth}%
  \anchor{north}{%
    \csname pgf@anchor@tape@north east\endcsname%
    \pgf@ya\pgf@y%  
    \csname pgf@anchor@tape@north west\endcsname%
    \advance\pgf@ya\pgf@y%  
    \centerpoint%
    \pgf@y.5\pgf@ya%
  }
  \anchor{south}{%
    \csname pgf@anchor@tape@south east\endcsname%
    \pgf@ya\pgf@y%  
    \csname pgf@anchor@tape@south west\endcsname%
    \advance\pgf@ya\pgf@y%  
    \centerpoint%
    \pgf@y.5\pgf@ya%
  }
  \anchor{east}{%
    \tapedimensions%
    \centerpoint%
    \advance\pgf@x\outerhalfwidth%
  }
  \anchor{west}{%
    \tapedimensions%
    \centerpoint%
    \advance\pgf@x-\outerhalfwidth%
  }
  \anchor{north east}{%
    \tapedimensions%
    \centerpoint%
    \advance\pgf@x\outerhalfwidth%
    \advance\pgf@y\halfheight%
    \pgf@yc\outerysep%
    \ifx\topbendstyle\pgf@lib@sh@inandouttext%
      \advance\pgf@y\halfbendheight%
      \advance\pgf@y\cothalfangleout\pgf@yc%  
    \else%
      \ifx\topbendstyle\pgf@lib@sh@outandintext%  
        \advance\pgf@y\halfbendheight%
        \advance\pgf@y\cothalfanglein\pgf@yc%  
      \else%
        \advance\pgf@y\pgf@yc%
      \fi%
    \fi%    
  }%
  \anchor{north west}{%
    \tapedimensions%
    \centerpoint%
    \advance\pgf@x-\outerhalfwidth%
    \advance\pgf@y\halfheight%
    \pgf@yc\outerysep%
    \ifx\topbendstyle\pgf@lib@sh@inandouttext%
      \advance\pgf@y\halfbendheight%
      \advance\pgf@y\cothalfanglein\pgf@yc%  
    \else%
      \ifx\topbendstyle\pgf@lib@sh@outandintext%
        \advance\pgf@y\halfbendheight%
        \advance\pgf@y\cothalfangleout\pgf@yc%  
      \else%
        \advance\pgf@y\pgf@yc%
      \fi%
    \fi%      
  }%
  \anchor{south east}{%
    \tapedimensions%
    \centerpoint%
    \advance\pgf@x\outerhalfwidth%
    \advance\pgf@y-\halfheight%
    \pgf@yc\outerysep%
    \ifx\topbendstyle\pgf@lib@sh@outandintext%
      \advance\pgf@y-\halfbendheight%
      \advance\pgf@y-\cothalfangleout\pgf@yc%  
    \else%
      \ifx\topbendstyle\pgf@lib@sh@inandouttext%  
        \advance\pgf@y-\halfbendheight%
        \advance\pgf@y-\cothalfanglein\pgf@yc%  
      \else%
        \advance\pgf@y-\pgf@yc%
      \fi%
    \fi%      
  }%
  \anchor{south west}{%
    \tapedimensions%
    \centerpoint%
    \advance\pgf@x-\outerhalfwidth%
    \advance\pgf@y-\halfheight%
    \pgf@yc\outerysep%
    \ifx\topbendstyle\pgf@lib@sh@outandintext%
      \advance\pgf@y-\halfbendheight%
      \advance\pgf@y-\cothalfanglein\pgf@yc%  
    \else%
      \ifx\topbendstyle\pgf@lib@sh@inandouttext%
        \advance\pgf@y-\halfbendheight%
        \advance\pgf@y-\cothalfangleout\pgf@yc%  
      \else%
        \advance\pgf@y-\pgf@yc%
      \fi%
    \fi%      
  }%
  \backgroundpath{%
    \tapedimensions%
    %
    \pgf@xc\halfwidth%
    \pgf@yc\halfheight%    
    %
    \pgf@xc\bendxradius%
    \pgf@yc\bendyradius%    
    {%
      \pgftransformshift{\centerpoint}%
      \pgfpathmoveto{\pgfqpoint{-\halfwidth}{0pt}}%
      \pgfpathlineto{\pgfqpoint{-\halfwidth}{\halfheight}}%
      \ifx\topbendstyle\pgf@lib@sh@inandouttext%
        \pgfpathlineto{\pgf@x-\halfwidth\pgf@y\halfheight\advance\pgf@y\halfbendheight}%
        \pgfpatharc{225}{315}{\bendxradius and \bendyradius}%
        \pgfpatharc{135}{45}{\bendxradius and \bendyradius}%
      \else%
        \ifx\topbendstyle\pgf@lib@sh@outandintext%
          \pgfpathlineto{\pgf@x-\halfwidth\pgf@y\halfheight\advance\pgf@y\halfbendheight}%
          \pgfpatharc{135}{45}{\bendxradius and \bendyradius}%
          \pgfpatharc{225}{315}{\bendxradius and \bendyradius}%
        \else%
          \pgfpathlineto{\pgfqpoint{\halfwidth}{\halfheight}}%
        \fi%
      \fi%
      \pgfpathlineto{\pgfqpoint{\halfwidth}{-\halfheight}}%
      \ifx\bottombendstyle\pgf@lib@sh@inandouttext%
        \pgfpathlineto{\pgf@x\halfwidth\pgf@y-\halfheight\advance\pgf@y-\halfbendheight}%
        \pgfpatharc{45}{135}{\bendxradius and \bendyradius}%
        \pgfpatharc{315}{225}{\bendxradius and \bendyradius}%
      \else%
        \ifx\bottombendstyle\pgf@lib@sh@outandintext%
          \pgfpathlineto{\pgf@x\halfwidth\pgf@y-\halfheight\advance\pgf@y-\halfbendheight}%
          \pgfpatharc{315}{225}{\bendxradius and \bendyradius}%
          \pgfpatharc{45}{135}{\bendxradius and \bendyradius}%
        \else%
          \pgfpathlineto{\pgfqpoint{-\halfwidth}{-\halfheight}}%
        \fi%
      \fi%
      \pgfpathclose%
    }%  
  }
  \anchorborder{%
    \pgf@xa\pgf@x%
    \pgf@ya\pgf@y%
    \pgfextract@process\externalpoint{%
      \centerpoint%
      \advance\pgf@x\pgf@xa%
      \advance\pgf@y\pgf@ya%
    }%
    \pgfmathanglebetweenpoints{\centerpoint}{\externalpoint}%
    \let\externalangle\pgfmathresult%
    \tapedimensions%
    %
    \pgfmathanglebetweenpoints{\centerpoint}{\csname pgf@anchor@tape@north west\endcsname}%
    \ifdim\externalangle pt<\pgfmathresult pt%
      \ifdim\externalangle pt<90pt%
        \pgfmathanglebetweenpoints{\centerpoint}{\csname pgf@anchor@tape@north east\endcsname}%
        \ifdim\externalangle pt<\pgfmathresult pt%
          \pgfpointintersectionoflines{\externalpoint}{\centerpoint}%
            {\csname pgf@anchor@tape@north east\endcsname}%
            {\csname pgf@anchor@tape@south east\endcsname}%
        \else%
          % Between north and north east.
          \ifx\topbendstyle\pgf@lib@sh@inandouttext%
            % in and out.
            \pgfmathpointintersectionoflineandarc{\externalpoint}{\centerpoint}%
            {%
              \centerpoint%
              \pgf@xc\halfwidth%
              \advance\pgf@x.5\pgf@xc%
              \advance\pgf@y\halfheight%
              \advance\pgf@y\halfbendheight%
              \pgf@yc\bendyradius%
              \advance\pgf@y-.707106\pgf@yc%
            }%
            {5}{175}{\outerbendxradius and \outerbendyradius}%
          \else%
            \ifx\topbendstyle\pgf@lib@sh@outandintext%
              % out and in.
              \pgfmathpointintersectionoflineandarc{\centerpoint}{\externalpoint}%
              {%
                \centerpoint%
                \pgf@xc\halfwidth%
                \advance\pgf@x.5\pgf@xc%
                \advance\pgf@y\halfheight%
                \advance\pgf@y\halfbendheight%
                \pgf@yc\bendyradius%
                \advance\pgf@y.707106\pgf@yc%
              }%
              {185}{355}{\innerbendxradius and \innerbendyradius}%
            \else%
              \pgfpointintersectionoflines{\externalpoint}{\centerpoint}%
                {\csname pgf@anchor@tape@north east\endcsname}%
                {\csname pgf@anchor@tape@north west\endcsname}%
            \fi%
          \fi%
        \fi%
      \else%
        % Between north and north west.
        \ifx\topbendstyle\pgf@lib@sh@inandouttext%
          % in and out.
          \pgfmathpointintersectionoflineandarc{\centerpoint}{\externalpoint}%
            {%
              \centerpoint%
              \pgf@xc\halfwidth%
              \advance\pgf@x-.5\pgf@xc%
              \advance\pgf@y\halfheight%
              \advance\pgf@y\halfbendheight%
              \pgf@yc\bendyradius%
              \advance\pgf@y.707106\pgf@yc%
            }%
            {185}{355}{\innerbendxradius and \innerbendyradius}%
        \else%
          \ifx\topbendstyle\pgf@lib@sh@outandintext%
            % out and in.
            \pgfmathpointintersectionoflineandarc{\externalpoint}{\centerpoint}%
            {%
              \centerpoint%
              \pgf@xc\halfwidth%
              \advance\pgf@x-.5\pgf@xc%
              \advance\pgf@y\halfheight%
              \advance\pgf@y\halfbendheight%
              \pgf@yc\bendyradius%
              \advance\pgf@y-.707106\pgf@yc%
            }%
            {5}{175}{\outerbendxradius and \outerbendyradius}%
          \else%
            \pgfpointintersectionoflines{\externalpoint}{\centerpoint}%
              {\csname pgf@anchor@tape@north east\endcsname}%
              {\csname pgf@anchor@tape@north west\endcsname}%
          \fi%
        \fi%
      \fi%
    \else%
      \pgfmathanglebetweenpoints{\centerpoint}{\csname pgf@anchor@tape@south west\endcsname}%
        \ifdim\externalangle pt>\pgfmathresult pt%
        \ifdim\externalangle pt>270pt%
          \pgfmathanglebetweenpoints{\centerpoint}{\csname pgf@anchor@tape@south east\endcsname}%
          \ifdim\externalangle pt>\pgfmathresult pt%
            \pgfpointintersectionoflines{\externalpoint}{\centerpoint}%
              {\csname pgf@anchor@tape@north east\endcsname}%
              {\csname pgf@anchor@tape@south east\endcsname}%
          \else%
            % Between south and south east.
            \ifx\bottombendstyle\pgf@lib@sh@inandouttext%
              % in and out.
              \pgfmathpointintersectionoflineandarc{\centerpoint}{\externalpoint}%
              {%
                \centerpoint%
                \pgf@xc\halfwidth%
                \advance\pgf@x.5\pgf@xc%
                \advance\pgf@y-\halfheight%
                \advance\pgf@y-\halfbendheight%
                \pgf@yc\bendyradius%
                \advance\pgf@y-.707106\pgf@yc%
              }%
              {5}{175}{\innerbendxradius and \innerbendyradius}%
            \else%
              \ifx\bottombendstyle\pgf@lib@sh@outandintext%
                % out and in.
                \pgfmathpointintersectionoflineandarc{\externalpoint}{\centerpoint}%
              {%
                \centerpoint%
                \pgf@xc\halfwidth%
                \advance\pgf@x.5\pgf@xc%
                \advance\pgf@y-\halfheight%
                \advance\pgf@y-\halfbendheight%
                \pgf@yc\bendyradius%
                \advance\pgf@y.707106\pgf@yc%
              }%
              {185}{355}{\outerbendxradius and \outerbendyradius}%
              \else%
                \pgfpointintersectionoflines{\externalpoint}{\centerpoint}%
                  {\csname pgf@anchor@tape@south east\endcsname}%
                  {\csname pgf@anchor@tape@south west\endcsname}%
              \fi%
            \fi%
          \fi%
        \else%
          % Between south and south west.
          \ifx\bottombendstyle\pgf@lib@sh@inandouttext%
            % in and out.
            \pgfmathpointintersectionoflineandarc{\externalpoint}{\centerpoint}%
              {%
                \centerpoint%
                \pgf@xc\halfwidth%
                \advance\pgf@x-.5\pgf@xc%
                \advance\pgf@y-\halfheight%
                \advance\pgf@y-\halfbendheight%
                \pgf@yc\bendyradius%
                \advance\pgf@y.707106\pgf@yc%
              }%
              {185}{355}{\outerbendxradius and \outerbendyradius}%
          \else%
            \ifx\bottombendstyle\pgf@lib@sh@outandintext%
              % out and in.
              \pgfmathpointintersectionoflineandarc{\centerpoint}{\externalpoint}%
              {%
                \centerpoint%
                \pgf@xc\halfwidth%
                \advance\pgf@x-.5\pgf@xc%
                \advance\pgf@y-\halfheight%
                \advance\pgf@y-\halfbendheight%
                \pgf@yc\bendyradius%
                \advance\pgf@y-.707106\pgf@yc%
              }%
              {5}{175}{\innerbendxradius and \innerbendyradius}%
            \else%
              \pgfpointintersectionoflines{\externalpoint}{\centerpoint}%
                {\csname pgf@anchor@tape@south east\endcsname}%
                {\csname pgf@anchor@tape@south west\endcsname}%
            \fi%
          \fi%
        \fi%
      \else%
        \pgfpointintersectionoflines{\externalpoint}{\centerpoint}%
          {\csname pgf@anchor@tape@north west\endcsname}%
          {\csname pgf@anchor@tape@south west\endcsname}%
      \fi%
    \fi%
  }%
}




% Keys for magnifying glass shape
%
% /pgf/magnifying glass handle angle  : The angle of handle
% /pgf/magnifying glass handle aspect : The length of the handle as a multiple
%                               of the radius of the circle
%

\pgfkeys{/pgf/.cd,
  magnifying glass handle angle/.initial=-45,
  magnifying glass handle aspect/.initial=1.5
}

\pgfdeclareshape{magnifying glass}
{
  \inheritsavedanchors[from=circle] % this is nearly a circle
  \inheritanchorborder[from=circle]
  \inheritanchor[from=circle]{north}
  \inheritanchor[from=circle]{north west}
  \inheritanchor[from=circle]{north east}
  \inheritanchor[from=circle]{center}
  \inheritanchor[from=circle]{west}
  \inheritanchor[from=circle]{east}
  \inheritanchor[from=circle]{mid}
  \inheritanchor[from=circle]{mid west}
  \inheritanchor[from=circle]{mid east}
  \inheritanchor[from=circle]{base}
  \inheritanchor[from=circle]{base west}
  \inheritanchor[from=circle]{base east}
  \inheritanchor[from=circle]{south}
  \inheritanchor[from=circle]{south west}
  \inheritanchor[from=circle]{south east}
  \inheritbackgroundpath[from=circle]
  \foregroundpath{
    \centerpoint%
    \pgf@xc=\pgf@x%
    \pgf@yc=\pgf@y%
    \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%
    \pgfpathmoveto{\pgfpointadd{\pgfqpoint{\pgf@xc}{\pgf@yc}}
      {\pgfpointpolar{\pgfkeysvalueof{/pgf/magnifying glass handle angle}}{\pgfutil@tempdima}}}
    \pgfpathlineto{\pgfpointadd{\pgfqpoint{\pgf@xc}{\pgf@yc}}
      {\pgfpointpolar{\pgfkeysvalueof{/pgf/magnifying glass handle angle}}{\pgfutil@tempdima+\pgfutil@tempdima*(\pgfkeysvalueof{/pgf/magnifying glass handle aspect})}}}
    \pgfsetarrowsstart{}
    \pgfsetarrowsend{}
  }
}


\pgfkeys{%
  /pgf/magnetic tape tail/.initial=0.15,
  /pgf/magnetic tape tail extend/.initial=0cm,
}
\pgfdeclareshape{magnetic tape}{
  \nodeparts{text}
  \savedmacro\installparameters{%
    %
    \pgf@x=0.5\wd\pgfnodeparttextbox%
    \pgf@y=0.5\ht\pgfnodeparttextbox%
    \advance\pgf@y by-0.5\dp\pgfnodeparttextbox%
    \edef\centerpoint{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
    %
    \pgf@x=\wd\pgfnodeparttextbox%
    \pgf@y=\ht\pgfnodeparttextbox%
    \advance\pgf@y by\dp\pgfnodeparttextbox%
    \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/inner xsep}}%
    \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/inner ysep}}%
    \advance\pgf@x by2.0\pgf@xa%
    \advance\pgf@y by2.0\pgf@ya%
    \ifdim\pgf@y>\pgf@x%
      \pgf@x=\pgf@y%
    \fi%
    \pgf@x=1.414213\pgf@x%
    \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/minimum width}}%
    \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/minimum height}}%
    \ifdim\pgf@x<\pgf@xa%
      \pgf@x=\pgf@xa%
    \fi%
    \ifdim\pgf@x<\pgf@ya%
      \pgf@x=\pgf@ya%
    \fi%
    \pgf@x=0.5\pgf@x%
    \edef\radius{\the\pgf@x}%
    %
    \pgfmathparse{max(\pgfkeysvalueof{/pgf/magnetic tape tail extend},0)}%
    \edef\tailextend{\pgfmathresult pt}%
    %
    \pgfmathparse{min(max(\pgfkeysvalueof{/pgf/magnetic tape tail},0),1)}%    
    \pgf@xa=\pgfmathresult\pgf@x%    
    \edef\tailheight{\the\pgf@xa}%
    %
    \pgfmathsetlength\pgf@xa{\pgfkeysvalueof{/pgf/outer xsep}}%
    \pgfmathsetlength\pgf@ya{\pgfkeysvalueof{/pgf/outer ysep}}%
    \ifdim\pgf@xa<\pgf@ya%
      \pgf@xa=\pgf@ya%
    \fi%
    \edef\outersep{\the\pgf@xa}%
    %
    \pgfmathparse{\outersep+\radius}%
    \edef\outerradius{\pgfmathresult pt}%
    %
    \pgfmathparse{(\radius-\tailheight)/\radius}%
    \pgfmathasin@{\pgfmathresult}%
    \pgfmathadd@{-\pgfmathresult}{360}%
    \let\tailangle=\pgfmathresult%
    %
    \pgfmathparse{\outerradius/(\outerradius+\tailextend)}%
    \pgfmathatan@{\pgfmathresult}%
    \pgfmathadd@{-\pgfmathresult}{360}%
    \let\tailbottomangle=\pgfmathresult%
    %
    \pgfmathparse{(\outerradius-\outersep-\tailheight-\outersep)/(\outerradius+\tailextend)}%
    \pgfmathatan@{\pgfmathresult}%
    \pgfmathadd@{-\pgfmathresult}{360}%
    \let\tailtopangle=\pgfmathresult%
    %
    \addtosavedmacro\radius%
    \addtosavedmacro\outerradius%
    \addtosavedmacro\outersep%
    \addtosavedmacro\tailheight%
    \addtosavedmacro\tailextend
    \addtosavedmacro\tailangle%
    \addtosavedmacro\tailtopangle%
    \addtosavedmacro\tailbottomangle%
    \addtosavedmacro\centerpoint%
  }
  \savedanchor{\base}{\pgfqpoint{0.5\wd\pgfnodeparttextbox}{0pt}}
  \savedanchor{\mid}{\pgfqpoint{0.5\wd\pgfnodeparttextbox}{0pt}\pgfmathsetlength\pgf@y{.5ex}}
  \anchor{center}{\installparameters\centerpoint}%  \addtosavedmacro\outerradius%
  \anchor{base}{\base}
  \anchor{mid}{\mid}
  \anchor{base west}{\installparameters\pgfpointadd{\base}{\pgfqpoint{-\outerradius}{0pt}}}
  \anchor{base east}{\installparameters\pgfpointadd{\base}{\pgfqpoint{\outerradius}{0pt}}}
  \anchor{mid west}{\installparameters\pgfpointadd{\mid}{\pgfqpoint{-\outerradius}{0pt}}}
  \anchor{mid east}{\installparameters\pgfpointadd{\mid}{\pgfqpoint{\outerradius}{0pt}}}
  \anchor{north}{\installparameters%
    \pgfpointadd{\centerpoint}{\pgfqpoint{0pt}{\outerradius}}}
  \anchor{north east}{\installparameters%
    \pgfpointadd{\centerpoint}{\pgfqpointpolar{45}{\outerradius}}}
  \anchor{south}{\installparameters%
    \pgfpointadd{\centerpoint}{\pgfqpoint{0pt}{-\outerradius}}}
  \anchor{south east}{\installparameters%
    \pgfpointadd{\centerpoint}{\pgfqpoint{\outerradius}{-\outerradius}}}
  \anchor{east}{\installparameters%
      \pgfpointadd{\centerpoint}{\pgfqpoint{\outerradius}{0pt}}}
  \anchor{south west}{\installparameters%
    \pgfpointadd{\centerpoint}{\pgfqpointpolar{225}{\outerradius}}}
  \anchor{west}{\installparameters%
    \pgfpointadd{\centerpoint}{\pgfqpoint{-\outerradius}{0pt}}}
  \anchor{north west}{\installparameters%
      \pgfpointadd{\centerpoint}{\pgfqpointpolar{135}{\outerradius}}}    
  \anchor{tail east}{\installparameters%
        \pgfpointadd{\centerpoint}{\pgfpoint{\radius+\tailextend+\outersep}{-\outerradius+\outersep+\tailheight/2}}}  
  \anchor{tail south east}{\installparameters%
          \pgfpointadd{\centerpoint}{\pgfpoint{\radius+\tailextend+\outersep}{-\outerradius}}}    
  \anchor{tail north east}{\installparameters%
            \pgfpointadd{\centerpoint}{\pgfpoint{\radius+\tailextend+\outersep}{-\outerradius+\outersep+\tailheight+\outersep}}}        
  \backgroundpath{
  %
    \installparameters%
    {%
    \pgftransformshift{\centerpoint}%
    \pgfpathmoveto{\pgfpointpolar{\tailangle}{\radius}}%
    \pgfpatharc{\tailangle}{360}{\radius}%
    \pgfpatharc{0}{270}{\radius}%
    \pgfpathlineto{\pgfpoint{\radius+\tailextend}{-\radius}}%
    \pgfpathlineto{\pgfpoint{\radius+\tailextend}{-\radius+\tailheight}}%
    \pgfpathclose%
    }%
  }
  \anchorborder{%
    \pgfextract@process\externalpoint{}%
    \installparameters%
    \pgfmathanglebetweenpoints{\pgfpointorigin}{\externalpoint}
    \ifdim\pgfmathresult pt<270pt\relax%
      \pgfpointadd{\centerpoint}{%
        \pgfpointborderellipse%
          {\externalpoint}%
          {\pgfqpoint{\outerradius}{\outerradius}}%  
      }%
    \else%
      \ifdim\pgfmathresult pt<\tailbottomangle pt\relax%
        \pgfpointadd{\centerpoint}{%
          \pgfpointintersectionoflines%
            {\externalpoint}{\pgfpointorigin}%
            {\pgfqpoint{0pt}{-\outerradius}}{\pgfqpoint{\outerradius}{-\outerradius}}%  
        }%
      \else%
        \ifdim\pgfmathresult pt<\tailtopangle pt\relax%
          \pgfpointadd{\centerpoint}{%
            \pgfpointintersectionoflines%
              {\externalpoint}{\pgfpointorigin}%
              {\pgfqpoint{\outerradius}{\outerradius}}{\pgfqpoint{\outerradius}{-\outerradius}}%  
          }%
        \else%
          \pgfpointadd{\centerpoint}{%
            \pgfpointborderellipse%
              {\externalpoint}%
              {\pgfqpoint{\outerradius}{\outerradius}}%  
            }%
        \fi%
      \fi%
    \fi%
  }
}

% Local Variables:
% tab-width: 2
% End:
pgflibrarysnakes.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/pgflibrarysnakes.code.tex,v 1.25 2013/07/15 12:05:34 tantau Exp $

\pgfwarning{Snakes have been superseded by decorations. Use the decoration libraries instead of the snakes library}

\usepgflibrary{decorations.pathmorphing,decorations.pathreplacing,decorations.shapes}

\endinput

pgflibrarysvg.path.code.tex
% Copyright 2009 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/pgflibrarysvg.path.code.tex,v 1.7 2013/09/23 18:04:36 tantau Exp $


\usepgfmodule{parser}




% Scan an SVG-Path
%
% #1 = the path
%
% Description:
%
% This command takes a path in the compressed SVG-syntax. It then
% issues a sequences of appropriate \pgfpath commands for this
% path. For a description of the compressed svg path syntax, see a
% book on svg.
% 
% The notion of a pixel used by svg makes no sense in pgf (actually
% it does not really make sense in svg either, but never mind), and
% instead of pixels "pt" is used as the basic unit. Use coordinate
% transformation to change this.
%
% Example:
%
% \pgfpathsvg{M10 20 L 30-20 0 1}
% 
% % this has the same effect as
% 
% \pgfpathmoveto{\pgfpoint{10pt}{20pt}}
% \pgfpathlineto{\pgfpint{30pt}{-20pt}}
% \pgfpathlineto{\pgfpint{0pt}{1pt}}
% 

\def\pgfpathsvg#1{%
  \let\pgf@lib@svg@finish@prev\relax%
  {%
    \pgftransforminvert%
    \pgf@process{\pgfpointtransformed{\pgfqpoint{\pgf@path@lastx}{\pgf@path@lasty}}}
  }
  \pgf@lib@svg@last@x\pgf@x%
  \pgf@lib@svg@last@y\pgf@y%
  \let\pgf@lib@svg@num=\pgfutil@empty%
  \pgfparserparse{svgpath}#1"%
}



\newdimen\pgf@lib@svg@last@x
\newdimen\pgf@lib@svg@last@y
\newdimen\pgf@lib@svg@last@c@x
\newdimen\pgf@lib@svg@last@c@y

\newcount\pgf@lib@svg@count
\newcount\pgf@lib@svg@max@num

\newif\pgf@lib@svg@relative



% For the smooth commands (S, s, T, t) we need to keep track of the
% previous control points. This is done in the following two
% variables. If they are empty, there was no previous control point of
% the desired kind, in which case the specification prescribes that
% the start point is used. 

\def\pgf@lib@svg@clear@bezier@quad{
  \let\pgf@lib@svg@bezier@last=\pgfutil@empty
  \let\pgf@lib@svg@quad@last=\pgfutil@empty
}
\pgf@lib@svg@clear@bezier@quad

%
% Here comes the DFA:
%

% Handle a moveto:

\pgfparserdef{svgpath}{all}{the letter M}
{
  \pgf@lib@svg@finish@prev
  \pgf@lib@svg@read@nums{2}{\pgf@lib@svg@moveto}
}

\def\pgf@lib@svg@moveto{%
  \pgf@lib@svg@clear@bezier@quad%
  \pgf@lib@svg@last@x=\pgf@lib@svg@get@num{0}pt%
  \pgf@lib@svg@last@y=\pgf@lib@svg@get@num{1}pt%
  \pgfpathmoveto{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}%
  \pgf@lib@svg@read@nums{2}{\pgf@lib@svg@lineto}
}


% Handle a relative moveto:

\pgfparserdef{svgpath}{all}{the letter m}
{
  \pgf@lib@svg@finish@prev
  \pgf@lib@svg@read@nums{2}{\pgf@lib@svg@moveto@rel}
}

\def\pgf@lib@svg@moveto@rel{%
  \pgf@lib@svg@clear@bezier@quad%
  \advance\pgf@lib@svg@last@x by\pgf@lib@svg@get@num{0}pt%
  \advance\pgf@lib@svg@last@y by\pgf@lib@svg@get@num{1}pt%
  \pgfpathmoveto{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}%
  \pgf@lib@svg@read@nums{2}{\pgf@lib@svg@lineto@rel}
}


% Handle a lineto:

\pgfparserdef{svgpath}{all}{the letter L}
{
  \pgf@lib@svg@finish@prev%
  \pgf@lib@svg@read@nums{2}{\pgf@lib@svg@lineto}
}

\def\pgf@lib@svg@lineto{%
  \ifnum\pgf@lib@svg@count=0\relax% nothing read
  \else%
    \pgf@lib@svg@clear@bezier@quad%
    \pgf@lib@svg@last@x=\pgf@lib@svg@get@num{0}pt%
    \pgf@lib@svg@last@y=\pgf@lib@svg@get@num{1}pt%
    \pgfpathlineto{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}%
    \pgf@lib@svg@read@nums{2}{\pgf@lib@svg@lineto}%
  \fi
}


% Handle a relative lineto:

\pgfparserdef{svgpath}{all}{the letter l}
{
  \pgf@lib@svg@finish@prev
  \pgf@lib@svg@read@nums{2}{\pgf@lib@svg@lineto@rel}
}

\def\pgf@lib@svg@lineto@rel{%
  \ifnum\pgf@lib@svg@count=0\relax% nothing read
  \else%
    \pgf@lib@svg@clear@bezier@quad%
    \advance\pgf@lib@svg@last@x by\pgf@lib@svg@get@num{0}pt%
    \advance\pgf@lib@svg@last@y by\pgf@lib@svg@get@num{1}pt%
    \pgfpathlineto{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}%
    \pgf@lib@svg@read@nums{2}{\pgf@lib@svg@lineto@rel}%
  \fi
}


% Handle a closepath:

\pgfparserdef{svgpath}{all}{the letter Z}
{
  \pgf@lib@svg@closepath
}

\pgfparserdef{svgpath}{all}{the letter z}
{
  \pgf@lib@svg@closepath
}

\def\pgf@lib@svg@closepath{
  \pgf@lib@svg@finish@prev
  \pgfpathclose
  \let\pgf@lib@svg@finish@prev=\relax
  \pgf@lib@svg@clear@bezier@quad%
  \pgfparserswitch{initial}%
}


% Ignore spaces if no other rules says differently:

\pgfparserdef{svgpath}{all}{blank space \space}{}




% Handle a horizontal lineto:

\pgfparserdef{svgpath}{all}{the letter H}
{
  \pgf@lib@svg@finish@prev
  \pgf@lib@svg@read@nums{1}{\pgf@lib@svg@hlineto}
}

\def\pgf@lib@svg@hlineto{%
  \ifnum\pgf@lib@svg@count=0\relax% nothing read
  \else%
    \pgf@lib@svg@clear@bezier@quad%
    \pgf@lib@svg@last@x=\pgf@lib@svg@get@num{0}pt%
    \pgfpathlineto{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}%
    \pgf@lib@svg@read@nums{1}{\pgf@lib@svg@hlineto}
  \fi
}

\pgfparserdef{svgpath}{all}{the letter h}
{
  \pgf@lib@svg@finish@prev
  \pgf@lib@svg@read@nums{1}{\pgf@lib@svg@hlineto@rel}
}

\def\pgf@lib@svg@hlineto@rel{%
  \ifnum\pgf@lib@svg@count=0\relax% nothing read
  \else%
    \pgf@lib@svg@clear@bezier@quad%
    \advance\pgf@lib@svg@last@x by\pgf@lib@svg@get@num{0}pt%
    \pgfpathlineto{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}%
    \pgf@lib@svg@read@nums{1}{\pgf@lib@svg@hlineto@rel}
  \fi
}


% Handle a horizontal lineto:

\pgfparserdef{svgpath}{all}{the letter V}
{
  \pgf@lib@svg@finish@prev
  \pgf@lib@svg@read@nums{1}{\pgf@lib@svg@vlineto}
}

\def\pgf@lib@svg@vlineto{%
  \ifnum\pgf@lib@svg@count=0\relax% nothing read
  \else%
    \pgf@lib@svg@clear@bezier@quad%
    \pgf@lib@svg@last@y=\pgf@lib@svg@get@num{0}pt%
    \pgfpathlineto{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}%
    \pgf@lib@svg@read@nums{1}{\pgf@lib@svg@vlineto}
  \fi
}

\pgfparserdef{svgpath}{all}{the letter v}
{
  \pgf@lib@svg@finish@prev
  \pgf@lib@svg@read@nums{1}{\pgf@lib@svg@vlineto@rel}
}

\def\pgf@lib@svg@vlineto@rel{%
  \ifnum\pgf@lib@svg@count=0\relax% nothing read
  \else%
    \pgf@lib@svg@clear@bezier@quad%
    \advance\pgf@lib@svg@last@y by\pgf@lib@svg@get@num{0}pt%
    \pgfpathlineto{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}%
    \pgf@lib@svg@read@nums{1}{\pgf@lib@svg@vlineto@rel}
  \fi
}




% Handle a Bezier curve:

\pgfparserdef{svgpath}{all}{the letter C}
{
  \pgf@lib@svg@finish@prev
  \pgf@lib@svg@read@nums{6}{\pgf@lib@svg@curveto}
}

\def\pgf@lib@svg@curveto{%
  \ifnum\pgf@lib@svg@count=0\relax% nothing read
  \else%
    % Clear quadratic last point and save new last control point:
    \let\pgf@lib@svg@quad@last=\pgfutil@empty%
    \edef\pgf@lib@svg@bezier@last{%
      \noexpand\pgfqpoint{\pgf@lib@svg@get@num{2}pt}{\pgf@lib@svg@get@num{3}pt}}%
    % Draw curve
    \pgf@lib@svg@last@x=\pgf@lib@svg@get@num{4}pt%
    \pgf@lib@svg@last@y=\pgf@lib@svg@get@num{5}pt%
    \pgfpathcurveto
    {\pgfqpoint{\pgf@lib@svg@get@num{0}pt}{\pgf@lib@svg@get@num{1}pt}}%
    {\pgfqpoint{\pgf@lib@svg@get@num{2}pt}{\pgf@lib@svg@get@num{3}pt}}%
    {\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}%
    % Go on
    \pgf@lib@svg@read@nums{6}{\pgf@lib@svg@curveto}
  \fi
}


\pgfparserdef{svgpath}{all}{the letter c}
{
  \pgf@lib@svg@finish@prev
  \pgf@lib@svg@read@nums{6}{\pgf@lib@svg@curveto@rel}
}

\def\pgf@lib@svg@curveto@rel{%
  \ifnum\pgf@lib@svg@count=0\relax% nothing read
  \else%
    % Clear quadratic last point and save new last control point:
    \let\pgf@lib@svg@quad@last=\pgfutil@empty%
    \pgf@process{\pgfpointadd{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}{\pgfqpoint{\pgf@lib@svg@get@num{2}pt}{\pgf@lib@svg@get@num{3}pt}}}
    \edef\pgf@lib@svg@bezier@last{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
    % Draw curve
    \pgfpathcurveto
    {\pgfpointadd{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}{\pgfqpoint{\pgf@lib@svg@get@num{0}pt}{\pgf@lib@svg@get@num{1}pt}}}%
    {\pgfpointadd{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}{\pgfqpoint{\pgf@lib@svg@get@num{2}pt}{\pgf@lib@svg@get@num{3}pt}}}%
    {\pgfpointadd{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}{\pgfqpoint{\pgf@lib@svg@get@num{4}pt}{\pgf@lib@svg@get@num{5}pt}}}%
    \advance\pgf@lib@svg@last@x by\pgf@lib@svg@get@num{4}pt%
    \advance\pgf@lib@svg@last@y by\pgf@lib@svg@get@num{5}pt%
    \pgf@lib@svg@read@nums{6}{\pgf@lib@svg@curveto@rel}
  \fi
}





\pgfparserdef{svgpath}{all}{the letter S}
{
  \pgf@lib@svg@finish@prev
  \pgf@lib@svg@read@nums{4}{\pgf@lib@svg@curveto@smooth}
}

\def\pgf@lib@svg@curveto@smooth{%
  \ifnum\pgf@lib@svg@count=0\relax% nothing read
  \else%
    % Draw curve
    % Compute first control point
    \ifx\pgf@lib@svg@bezier@last\pgfutil@empty%
      \def\pgf@lib@svg@first@cp{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}
    \else
      \def\pgf@lib@svg@first@cp{
        \pgfpointadd
        {\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}
        {\pgfpointdiff
          {\pgf@lib@svg@bezier@last}
          {\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}
        }
      }
    \fi
    \pgfpathcurveto
    {\pgf@lib@svg@first@cp}
    {\pgfqpoint{\pgf@lib@svg@get@num{0}pt}{\pgf@lib@svg@get@num{1}pt}}%
    {\pgfqpoint{\pgf@lib@svg@get@num{2}pt}{\pgf@lib@svg@get@num{3}pt}}%
    % Clear quadratic last point and save new last control point:
    \let\pgf@lib@svg@quad@last=\pgfutil@empty%
    \edef\pgf@lib@svg@bezier@last{%
      \noexpand\pgfqpoint{\pgf@lib@svg@get@num{0}pt}{\pgf@lib@svg@get@num{1}pt}}%
    % Update
    \pgf@lib@svg@last@x=\pgf@lib@svg@get@num{2}pt%
    \pgf@lib@svg@last@y=\pgf@lib@svg@get@num{3}pt%
    % Go on
    \pgf@lib@svg@read@nums{4}{\pgf@lib@svg@curveto@smooth}
  \fi
}


\pgfparserdef{svgpath}{all}{the letter s}
{
  \pgf@lib@svg@finish@prev
  \pgf@lib@svg@read@nums{4}{\pgf@lib@svg@curveto@rel@smooth}
}

\def\pgf@lib@svg@curveto@rel@smooth{%
  \ifnum\pgf@lib@svg@count=0\relax% nothing read
  \else%
    % Draw curve
    % Compute first control point
    \ifx\pgf@lib@svg@bezier@last\pgfutil@empty%
      \def\pgf@lib@svg@first@cp{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}
    \else
      \def\pgf@lib@svg@first@cp{
        \pgfpointadd
        {\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}
        {\pgfpointdiff
          {\pgf@lib@svg@bezier@last}
          {\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}
        }
      }
    \fi
    \pgfpathcurveto
    {\pgf@lib@svg@first@cp}
    {\pgfpointadd{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}{\pgfqpoint{\pgf@lib@svg@get@num{0}pt}{\pgf@lib@svg@get@num{1}pt}}}%
    {\pgfpointadd{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}{\pgfqpoint{\pgf@lib@svg@get@num{2}pt}{\pgf@lib@svg@get@num{3}pt}}}%
    % Clear quadratic last point and save new last control point:
    \let\pgf@lib@svg@quad@last=\pgfutil@empty%
    \pgf@process{\pgfpointadd{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}{\pgfqpoint{\pgf@lib@svg@get@num{2}pt}{\pgf@lib@svg@get@num{3}pt}}}
    \edef\pgf@lib@svg@bezier@last{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
    % update
    \advance\pgf@lib@svg@last@x by\pgf@lib@svg@get@num{2}pt%
    \advance\pgf@lib@svg@last@y by\pgf@lib@svg@get@num{3}pt%
    % Go on
    \pgf@lib@svg@read@nums{4}{\pgf@lib@svg@curveto@rel@smooth}
  \fi
}




% Handle a quadratic curve:

\pgfparserdef{svgpath}{all}{the letter Q}
{
  \pgf@lib@svg@finish@prev
  \pgf@lib@svg@read@nums{4}{\pgf@lib@svg@quad@curveto}
}

\def\pgf@lib@svg@quad@curveto{%
  \ifnum\pgf@lib@svg@count=0\relax% nothing read
  \else%
    % Clear bezier last point and save new last control point:
    \let\pgf@lib@svg@bezier@last=\pgfutil@empty%
    \edef\pgf@lib@svg@quad@last{%
      \noexpand\pgfqpoint{\pgf@lib@svg@get@num{0}pt}{\pgf@lib@svg@get@num{1}pt}}%
    % Draw curve
    \pgf@lib@svg@last@x=\pgf@lib@svg@get@num{2}pt%
    \pgf@lib@svg@last@y=\pgf@lib@svg@get@num{3}pt%
    \pgfpathquadraticcurveto
    {\pgfqpoint{\pgf@lib@svg@get@num{0}pt}{\pgf@lib@svg@get@num{1}pt}}%
    {\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}%
    % Go on
    \pgf@lib@svg@read@nums{4}{\pgf@lib@svg@quad@curveto}
  \fi
}


\pgfparserdef{svgpath}{all}{the letter q}
{
  \pgf@lib@svg@finish@prev
  \pgf@lib@svg@read@nums{4}{\pgf@lib@svg@quad@curveto@rel}
}

\def\pgf@lib@svg@quad@curveto@rel{%
  \ifnum\pgf@lib@svg@count=0\relax% nothing read
  \else%
    % Clear quadratic last point and save new last control point:
    \let\pgf@lib@svg@bezier@last=\pgfutil@empty%
    \pgf@process{\pgfpointadd{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}{\pgfqpoint{\pgf@lib@svg@get@num{0}pt}{\pgf@lib@svg@get@num{1}pt}}}
    \edef\pgf@lib@svg@quad@last{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
    % Draw curve
    \pgfpathquadraticcurveto
    {\pgfpointadd{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}{\pgfqpoint{\pgf@lib@svg@get@num{0}pt}{\pgf@lib@svg@get@num{1}pt}}}%
    {\pgfpointadd{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}{\pgfqpoint{\pgf@lib@svg@get@num{2}pt}{\pgf@lib@svg@get@num{3}pt}}}%
    \advance\pgf@lib@svg@last@x by\pgf@lib@svg@get@num{2}pt%
    \advance\pgf@lib@svg@last@y by\pgf@lib@svg@get@num{3}pt%
    \pgf@lib@svg@read@nums{4}{\pgf@lib@svg@quad@curveto@rel}
  \fi
}




\pgfparserdef{svgpath}{all}{the letter T}
{
  \pgf@lib@svg@finish@prev
  \pgf@lib@svg@read@nums{2}{\pgf@lib@svg@quad@curveto@smooth}
}

\def\pgf@lib@svg@quad@curveto@smooth{%
  \ifnum\pgf@lib@svg@count=0\relax% nothing read
  \else%
    % Draw curve
    % Compute first control point
    \pgf@process{
      \ifx\pgf@lib@svg@quad@last\pgfutil@empty%
        \pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}
      \else
        \pgfpointadd
        {\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}
        {\pgfpointdiff
          {\pgf@lib@svg@quad@last}
          {\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}
        }
      \fi
    }
    \edef\pgf@lib@svg@first@cp{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
    \pgfpathquadraticcurveto
    {\pgf@lib@svg@first@cp}
    {\pgfqpoint{\pgf@lib@svg@get@num{0}pt}{\pgf@lib@svg@get@num{1}pt}}%
    % Clear quadratic last point and save new last control point:
    \let\pgf@lib@svg@bezier@last=\pgfutil@empty%
    \let\pgf@lib@svg@quad@last=\pgf@lib@svg@first@cp%
    % Update
    \pgf@lib@svg@last@x=\pgf@lib@svg@get@num{0}pt%
    \pgf@lib@svg@last@y=\pgf@lib@svg@get@num{1}pt%
    % Go on
    \pgf@lib@svg@read@nums{2}{\pgf@lib@svg@quad@curveto@smooth}
  \fi
}


\pgfparserdef{svgpath}{all}{the letter t}
{
  \pgf@lib@svg@finish@prev
  \pgf@lib@svg@read@nums{2}{\pgf@lib@svg@quad@curveto@rel@smooth}
}

\def\pgf@lib@svg@quad@curveto@rel@smooth{%
  \ifnum\pgf@lib@svg@count=0\relax% nothing read
  \else%
    % Draw curve
    % Compute first control point
     \pgf@process{
      \ifx\pgf@lib@svg@quad@last\pgfutil@empty%
        \pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}
      \else
        \pgfpointadd
        {\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}
        {\pgfpointdiff
          {\pgf@lib@svg@quad@last}
          {\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}
        }
      \fi
    }
    \edef\pgf@lib@svg@first@cp{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
    \pgfpathquadraticcurveto
    {\pgf@lib@svg@first@cp}
    {\pgfpointadd{\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}{\pgfqpoint{\pgf@lib@svg@get@num{0}pt}{\pgf@lib@svg@get@num{1}pt}}}%
    % Clear quadratic last point and save new last control point:
    \let\pgf@lib@svg@bezier@last=\pgfutil@empty%
    \let\pgf@lib@svg@quad@last=\pgf@lib@svg@first@cp%
    % update
    \advance\pgf@lib@svg@last@x by\pgf@lib@svg@get@num{0}pt%
    \advance\pgf@lib@svg@last@y by\pgf@lib@svg@get@num{1}pt%
    % Go on
    \pgf@lib@svg@read@nums{2}{\pgf@lib@svg@quad@curveto@rel@smooth}
  \fi
}



% Handle an arcto:

\pgfparserdef{svgpath}{all}{the letter A}
{
  \pgf@lib@svg@finish@prev
  \pgf@lib@svg@read@nums{7}{\pgf@lib@svg@arcto}
}

\def\pgf@lib@svg@arcto{%
  \ifnum\pgf@lib@svg@count=0\relax% nothing read
  \else%
    % Clear bezier last point and save new last control point:
    \pgf@lib@svg@clear@bezier@quad%
    % Draw curve
    \pgf@lib@svg@last@x=\pgf@lib@svg@get@num{5}pt%
    \pgf@lib@svg@last@y=\pgf@lib@svg@get@num{6}pt%
    \pgfpatharcto
    {\pgf@lib@svg@get@num{0}pt}{\pgf@lib@svg@get@num{1}pt}
    {\pgf@lib@svg@get@num{2}}
    {\pgf@lib@svg@get@num{3}}
    {\pgf@lib@svg@get@num{4}}
    {\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}%
    % Go on
    \pgf@lib@svg@read@nums{7}{\pgf@lib@svg@arcto}
  \fi
}

\pgfparserdef{svgpath}{all}{the letter a}
{
  \pgf@lib@svg@finish@prev
  \pgf@lib@svg@read@nums{7}{\pgf@lib@svg@arcto@rel}
}

\def\pgf@lib@svg@arcto@rel{%
  \ifnum\pgf@lib@svg@count=0\relax% nothing read
  \else%
    % Clear bezier last point and save new last control point:
    \pgf@lib@svg@clear@bezier@quad%
    % Draw curve
    \advance\pgf@lib@svg@last@x by\pgf@lib@svg@get@num{5}pt%
    \advance\pgf@lib@svg@last@y by\pgf@lib@svg@get@num{6}pt%
    \pgfpatharcto
    {\pgf@lib@svg@get@num{0}pt}{\pgf@lib@svg@get@num{1}pt}
    {\pgf@lib@svg@get@num{2}}
    {\pgf@lib@svg@get@num{3}}
    {\pgf@lib@svg@get@num{4}}
    {\pgfqpoint{\pgf@lib@svg@last@x}{\pgf@lib@svg@last@y}}%
    % Go on
    \pgf@lib@svg@read@nums{7}{\pgf@lib@svg@arcto@rel}
  \fi
}





% Handle to end of the world

\pgfparserdef{svgpath}{all}{the character "}
{
  \pgf@lib@svg@finish@prev
  \pgfparserswitch{final}
}




% Handle spacers for numbers

\def\pgf@lib@svg@read@nums#1#2{% get #1 number symbols, then do #2
  \pgf@lib@svg@count=0\relax
  \pgf@lib@svg@max@num=#1\relax
  \pgfparserswitch{num}
  \def\pgf@lib@svg@finish@prev{
    \ifx\pgf@lib@svg@num\pgfutil@empty%
    \else%
      \expandafter\let\csname pgf@lib@svg@num@\the\pgf@lib@svg@count\endcsname=\pgf@lib@svg@num
      \advance\pgf@lib@svg@count by1\relax%
      \let\pgf@lib@svg@num=\pgfutil@empty%
    \fi
    #2
  }
}

\def\pgf@lib@svg@get@num#1{\csname pgf@lib@svg@num@#1\endcsname}


\pgfparserdef{svgpath}{num}{the character ,}
{
  \pgf@lib@svg@handle@spacer
}

\pgfparserdef{svgpath}{num}{\meaning\pgfutil@sptoken}
{
  \pgf@lib@svg@handle@spacer
}

\pgfparserdef{svgpath}{num}{the character -}
{
  \pgf@lib@svg@handle@spacer
  \def\pgf@lib@svg@num{-}%
}

\def\pgf@lib@svg@handle@spacer{
  \ifx\pgf@lib@svg@num\pgfutil@empty%
    % ignore
  \else
    \expandafter\let\csname pgf@lib@svg@num@\the\pgf@lib@svg@count\endcsname=\pgf@lib@svg@num
    \advance\pgf@lib@svg@count by1\relax%
    \ifnum\pgf@lib@svg@count=\pgf@lib@svg@max@num\relax%
      \pgf@lib@svg@finish@prev%
    \fi
    \let\pgf@lib@svg@num=\pgfutil@empty%
  \fi
}


% Handle digits

\pgfparserdef{svgpath}{all}{the character .}
{\expandafter\def\expandafter\pgf@lib@svg@num\expandafter{\pgf@lib@svg@num.}}

\pgfparserdef{svgpath}{all}{the character 0}
{\expandafter\def\expandafter\pgf@lib@svg@num\expandafter{\pgf@lib@svg@num0}}

\pgfparserdef{svgpath}{all}{the character 1}
{\expandafter\def\expandafter\pgf@lib@svg@num\expandafter{\pgf@lib@svg@num1}}

\pgfparserdef{svgpath}{all}{the character 2}
{\expandafter\def\expandafter\pgf@lib@svg@num\expandafter{\pgf@lib@svg@num2}}

\pgfparserdef{svgpath}{all}{the character 3}
{\expandafter\def\expandafter\pgf@lib@svg@num\expandafter{\pgf@lib@svg@num3}}

\pgfparserdef{svgpath}{all}{the character 4}
{\expandafter\def\expandafter\pgf@lib@svg@num\expandafter{\pgf@lib@svg@num4}}

\pgfparserdef{svgpath}{all}{the character 5}
{\expandafter\def\expandafter\pgf@lib@svg@num\expandafter{\pgf@lib@svg@num5}}

\pgfparserdef{svgpath}{all}{the character 6}
{\expandafter\def\expandafter\pgf@lib@svg@num\expandafter{\pgf@lib@svg@num6}}

\pgfparserdef{svgpath}{all}{the character 7}
{\expandafter\def\expandafter\pgf@lib@svg@num\expandafter{\pgf@lib@svg@num7}}

\pgfparserdef{svgpath}{all}{the character 8}
{\expandafter\def\expandafter\pgf@lib@svg@num\expandafter{\pgf@lib@svg@num8}}

\pgfparserdef{svgpath}{all}{the character 9}
{\expandafter\def\expandafter\pgf@lib@svg@num\expandafter{\pgf@lib@svg@num9}}





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:

pgfmathode.code.tex
% Copyright 2011 by Christophe Jorssen
%
% 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.
\def\pgfmathode@stopadd{\pgfmathode@stopadd}

\def\pgfmathode@addindextofunc[#1]#2{%
  \begingroup
    \gdef\pgfmathode@func{}%
    \pgfmathode@addindextofunc@i[#1]#2\pgfmathode@stopadd}

\def\pgfmathode@addindextofunc@i[#1]#2#3{%
    \ifx#1#2
      \expandafter\gdef\expandafter\pgfmathode@func\expandafter{%
        \pgfmathode@func #2[\pgfmathode@timeindex]}%
    \else
      \expandafter\gdef\expandafter\pgfmathode@func\expandafter{%
        \pgfmathode@func #2}%
    \fi
    \ifx#3\pgfmathode@stopadd
      \expandafter\gdef\expandafter\pgfmathode@func\expandafter{%
        \expandafter{\pgfmathode@func}}%
      \let\next\endgroup
    \else
      \def\next{\pgfmathode@addindextofunc@i[#1]#3}%
    \fi
    \next}

%**********************************************************************
% Know limitation: fk cannot be a time function. Should be possible to
% use \Sol[0] as time in the set of equations.
%**********************************************************************

% Numerically solve a differential system with 1st order Runge-Kutta
% (Euler method) 
% dq1/dt = f1(t,q1,q2,...,qN)
% dq2/dt = f2(t,q1,q2,...,qN)
% ...
% dqN/dt = fN(t,q1,q2,...,qN)
% 
% #1: A pgf array where the solution will be stored.
% At the end:
% #1 -> {{t(0),q1(t(0)),q2(t(0)),...,qN(t(0))},
%        {t(1),q1(t(1)),q2(t(1)),...,qN(t(1))},
%        ...
%        {t(Nstep),q1(t(Nstep)),q2(t(Nstep)),...,qN(t(Nstep))}}
% #2: A pgf array with f1,f2,...,fN
% {f1}
% #3: A pgf array with initial conditions.
% {t(0),q1(t(0)),q2(t(0)),...,qN(t(0))}
% #4: t(Nstep)
% #5: Nstep (number of steps)
%
% * First order example: dq/dt = -q + 5 with IC=(t=0,q(0)=0)
% \pgfmathodeRKI{\Sol}{{-\Sol[1]+5}}{{0,0}}{3.5}{100}
% * Second order example: {dq1/dt=q2, dq2/dt=-q2/2-sin(q1)} (damped
%   pendulum) 
% \pgfmathodeRKI{\Sol}{{\Sol[2],-\Sol[2]/2-sin(deg(\Sol[1]))}}%
%   {{0,-1,5}}{15}{50}

\def\pgfmathode@generic@init@RK{%
  \begingroup
    % Sol array (#1) first element is given by the set of initial
    % conditions (#3). We need to enclose it in brace so that is a now
    % a "matrix" array.
    \gdef#1{{#3}}%
    % The set of rhs {f1(t,q1,q2,...,qN),...,fN(t,q1,q2,...,qN)} is
    % given in terms of #1[0],#1[1],...,#1[N]. We need to transform to
    % #1[\pgfmathode@timeindex][0],...,#1[\pgfmathode@timeindex][N], that is
    % add [\pgfmathode@timeindex] after every occurence of #1 in #2.
    % No need to brace #2 since it is already surounded by braces. The
    % result is stored in \pgfmathode@func
    \pgfmathode@addindextofunc[#1]#2%
    % Set time step. Actually the number of time steps is #5-1, so we
    % divide by (#5-1)+1 = #5.
    \pgfmathsetmacro\pgfmathode@Sol@t{#1[0][0]}%
    \pgfmathsetmacro\pgfmathode@Deltat{(#4-\pgfmathode@Sol@t)/#5}%
    % Compute the order of the system: it is equal to the number of IC
    % minus one (time).
    \pgfmathsetmacro\pgfmathode@dimfunc{dim(#3)-1}%
    \pgfmathsetmacro\pgfmathode@numstep{#5-1}}

\def\pgfmathodeRKI#1#2#3#4#5{%
    \pgfmathode@generic@init@RK
    % Start the time loop for Runge-Kutta 1st order
    \foreach \pgfmathode@timeindex in {0,...,\pgfmathode@numstep} {%
      \message{Step \pgfmathode@timeindex...}%
      % Start the function loop
      \foreach \pgfmathode@funcindex in {1,...,\pgfmathode@dimfunc} {%
        % The RKI algorithm
        % qk[t(i)] = Deltat*fk(t(i-1),q1(t(i-1)),...qN(t(i-1))) +
        %            qk[t(i-1)] 
        % Note: this part can be really slow due to array managment in
        % pgfmath. 
        % TODO: find a better way (at least inside this loop)
        \pgfmathparse{%
          \pgfmathode@Deltat*(\pgfmathode@func[\pgfmathode@funcindex-1])+
          #1[\pgfmathode@timeindex][\pgfmathode@funcindex]}%
        % Store the result in a helper macro
        \expandafter\xdef\csname pgfmathode@Sol@\pgfmathode@funcindex
          \endcsname{\pgfmathresult}%
      }
      % Store step i
      \pgfmathparse{\pgfmathode@Sol@t+\pgfmathode@Deltat}%
      \xdef\pgfmathode@Sol@t{\pgfmathresult}%
      \xdef\pgfmathode@temp{}%
      \foreach \pgfmathode@funcindex in {1,...,\pgfmathode@dimfunc} {%
        \ifx\pgfmathode@temp\pgfutil@empty
          \xdef\pgfmathode@temp{%
            \csname pgfmathode@Sol@\pgfmathode@funcindex\endcsname}%
        \else
          \xdef\pgfmathode@temp{%
            \pgfmathode@temp,
            \csname pgfmathode@Sol@\pgfmathode@funcindex\endcsname}%
        \fi}
      \xdef#1{%
        {\expandafter\pgfutil@firstofone#1,%
          {\pgfmathode@Sol@t,\pgfmathode@temp}}}%
    }
  \endgroup}

% RKIV: far from working yet!
\def\pgfmathodeRKIV#1#2#3#4#5{%
    \pgfmathode@generic@init@RK
    % Start the time loop for Runge-Kutta 4th order
    \foreach \pgfmathode@timeindex in {0,...,\pgfmathode@numstep} {%
      \message{Step \pgfmathode@timeindex...}%
      % Start the function loop
      \foreach \pgfmathode@funcindex in {1,...,\pgfmathode@dimfunc} {%
        % The RKIV algorithm
        % qk[t(i)] = qk[t(i-1)] + 
        %            (1/6) * (j1k + 2j2k + 2j3k + j4k)
        % where j1k = fk(t(i-1),q1(t(i-1)),...qN(t(i-1))) * Deltat
        %       j2k = fk(t(i-1)+.5*Deltat,
        %                q1(t(i-1))+.5*j11,...qN(t(i-1))+.5*j1N) * Deltat
        %       j3k = fk(t(i-1)+.5*Deltat,
        %                q1(t(i-1))+.5*j21,...qN(t(i-1))+.5*j2N) * Deltat
        %       j4k = fk(t(i-1)+Deltat,
        %                q1(t(i-1))+j31,...qN(t(i-1))+j3N) * Deltat
        %
        % Compute j1k
        \pgfmathparse{%
          \pgfmathode@Deltat*(\pgfmathode@func[\pgfmathode@funcindex-1])+
          #1[\pgfmathode@timeindex][\pgfmathode@funcindex]}%
        \expandafter\xdef\csname pgfmathode@RKIV@1@\pgfmathode@funcindex
          \endcsname{\pgfmathresult}%
        % Compute j2k
        \pgfmathparse{%
          \pgfmathode@Deltat*(\pgfmathode@func[\pgfmathode@funcindex-1])+
          #1[\pgfmathode@timeindex][\pgfmathode@funcindex]}%
        \expandafter\xdef\csname pgfmathode@RKIV@1@\pgfmathode@funcindex
          \endcsname{\pgfmathresult}%
      }
      % Store step i
      \pgfmathparse{\pgfmathode@Sol@t+\pgfmathode@Deltat}%
      \xdef\pgfmathode@Sol@t{\pgfmathresult}%
      \xdef\pgfmathode@temp{}%
      \foreach \pgfmathode@funcindex in {1,...,\pgfmathode@dimfunc} {%
        \ifx\pgfmathode@temp\pgfutil@empty
          \xdef\pgfmathode@temp{%
            \csname pgfmathode@Sol@\pgfmathode@funcindex\endcsname}%
        \else
          \xdef\pgfmathode@temp{%
            \pgfmathode@temp,
            \csname pgfmathode@Sol@\pgfmathode@funcindex\endcsname}%
        \fi}
      \xdef#1{%
        {\expandafter\pgfutil@firstofone#1,%
          {\pgfmathode@Sol@t,\pgfmathode@temp}}}%
    }
  \endgroup}


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

pgfmodulebending.code.tex
% Copyright 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[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/modules/pgfmodulebending.code.tex,v 1.18 2013/09/30 18:30:15 tantau Exp $


%
% This file defines commands for drawing bending arrows and lines.
%

\usepgfmodule{nonlineartransformations}
\usepgflibrary{curvilinear}


% Configuration options for arrow tips:

\pgfkeys{
  /pgf/arrow keys/flex/.code=\pgfarrowsaddtooptions{\pgf@arrows@the@rigidity#1pt\let\pgf@arrow@flex@mode\pgf@arrow@mode@is@flex},
  /pgf/arrow keys/flex/.default=1,
  /pgf/arrow keys/flex'/.code=\pgfarrowsaddtooptions{\pgf@arrows@the@rigidity#1pt\let\pgf@arrow@flex@mode\pgf@arrow@mode@is@flex@prime},
  /pgf/arrow keys/flex'/.default=1,
  /pgf/arrow keys/bend/.code=\pgfarrowsaddtooptions{\let\pgf@arrow@flex@mode\pgf@arrow@mode@is@bend}
}


\def\pgf@arrow@mode@is@flex{1}
\def\pgf@arrow@mode@is@flex@prime{2}
\def\pgf@arrow@mode@is@bend{3}

\newdimen\pgf@arrows@the@rigidity

%
%
% Handle the end of a curve
%
% 

% First, the preparation. This is, essenatially, setting up the
% nonlinear transformation

\def\pgf@prep@curveend{
  \pgftransformreset%
  \pgfsetcurvilinearbeziercurve{\pgfpointlastonpath}{\pgfpointsecondlastonpath}{\pgfpointthirdlastonpath}{\pgfpointfourthlastonpath}
}

% Second, the shortening.

\def\pgf@do@shorten@curvedend{%
  \expandafter\expandafter\expandafter\pgf@do@shorten@curvedend@unpack\expandafter\pgfpointfourthlastonpath\pgfpointthirdlastonpath%
}
\def\pgf@do@shorten@curvedend@unpack\pgfqpoint#1#2\pgfqpoint#3#4{%
  \pgf@process{\pgfcurvilineardistancetotime{\pgf@path@shortening@distance}}%
  % Compute new curve:
  \pgfpointcurveattime{\pgf@x}{\pgfpointlastonpath}{\pgfpointsecondlastonpath}{\pgfpointthirdlastonpath}{\pgfpointfourthlastonpath}%
  % \pgfx/y and \pgf xa/xb already correct. Need to setup remaining vector...
  \pgf@xb#3%
  \pgf@yb#4%
  \pgf@xb\pgf@time@t\pgf@xb%
  \pgf@yb\pgf@time@t\pgf@yb%
  \advance\pgf@xb by\pgf@time@s\pgf@xc%
  \advance\pgf@yb by\pgf@time@s\pgf@yc%
  \edef\pgfprocessresultsubpathsuffix{%
    \expandafter\noexpand\pgfsubpathfourthlasttoken{#1}{#2}%
    \noexpand\pgfsyssoftpath@curvetosupportatoken{\the\pgf@xb}{\the\pgf@yb}%
    \noexpand\pgfsyssoftpath@curvetosupportbtoken{\the\pgf@xa}{\the\pgf@ya}%
    \noexpand\pgfsyssoftpath@curvetotoken{\the\pgf@x}{\the\pgf@y}}%
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\pgfprocessresultpathsuffix%
  \expandafter\expandafter\expandafter{\expandafter\pgfprocessresultsubpathprefix\pgfprocessresultsubpathsuffix}%
}

% Third, the drawing

\def\pgf@do@draw@curvedend{%
  \pgf@do@draw@curved\pgf@end@tip@sequence%
}

\def\pgf@do@draw@curved#1{%
  {%
    \pgftransformreset%
    \pgf@xb\pgf@arrow@tip@total@length% xb will keep track of the total length
    \let\pgf@arrow@handle\pgf@draw@curved%
    \let\pgf@arrow@handle@dot\relax%
    #1%
  }%
}

\def\pgf@draw@curved#1#2{%
  % Prepare:
  {%
    \pgfarrows@getid{#1}{#2}%
    % Do shift:
    \expandafter\expandafter\expandafter\pgf@arrow@drawer@rigid@shift\csname pgf@ar@ends@\pgf@arrow@id\endcsname%
    \expandafter\let\expandafter\pgf@arrow@bending@mode\csname pgf@ar@bending@mode@#1\endcsname%
    \ifx\pgf@arrow@bending@mode\pgfutil@empty\let\pgf@arrow@flex@mode\pgf@arrow@mode@is@flex\fi%
    % do swap:
    {%
      \csname pgf@ar@saves@\pgf@arrow@id\endcsname%
      \ifcase\pgf@arrow@flex@mode\relax%
        \expandafter\expandafter\expandafter\pgf@arrow@drawer@rigid\csname pgf@ar@visual@\pgf@arrow@id\endcsname% like flex
      \or%
        \expandafter\expandafter\expandafter\pgf@arrow@drawer@rigid\csname pgf@ar@visual@\pgf@arrow@id\endcsname% 
      \or%
        \expandafter\expandafter\expandafter\pgf@arrow@drawer@rigid\csname pgf@ar@ends@\pgf@arrow@id\endcsname%      
      \or%
        \pgf@arrow@drawer@bend%
      \fi%
      % hull points inside the above
    }%
  \expandafter}%
  % Transform to next tip:
  \expandafter\pgf@xb\the\pgf@xb%
}
\def\pgf@falsetext{false}

\def\pgf@arrow@drawer@rigid@shift#1#2#3{% tip end, back end, line end, sep
  % Let xa be the actual back end of the current arrow plus the back end:
  \advance\pgf@xb by#2%
  \pgf@xa\pgf@xb%
  % Update the xb:
  \pgf@x#1%
  \advance\pgf@x by\pgfarrowsep%
  \advance\pgf@xb by-\pgf@x%
}


\def\pgf@arrow@drawer@bend{%
  \pgftransformnonlinear{\pgf@arrow@bending@mode{\pgf@x}{\pgf@y}}
  \pgftransformscale{-1}%
  \pgftransformxshift{-\pgf@xa}%
  % Do slant:  
  \ifdim\pgfarrows@slant pt=0pt%
  \else%
    \pgftransformxslant{\pgfarrows@slant}%
  \fi%
  \ifpgfarrowswap%
    \pgftransformyscale{-1}%
  \fi%
  {%
    \pgf@relevantforpicturesizefalse%
    \pgfscope%
      \pgf@arrows@color@setup%
      \csname pgf@ar@inst@code@\pgf@arrow@id\endcsname%
    \endpgfscope%
  }%
  \pgf@arrows@bending@hull%
}

\def\pgf@arrow@drawer@rigid#1#2#3{% (rigid) start, (rigid) end, dummy
  % Compute the rigid positions:
  \pgf@x#1% start
  \pgf@y#2% flexibility*(end-start) + start
  \advance\pgf@y by-\pgf@x%
  \pgf@y\pgf@sys@tonumber\pgf@arrows@the@rigidity\pgf@y%
  \advance\pgf@y by\pgf@x%
  % Are they equal?
  \ifdim\pgf@x=\pgf@y%
    % Yes, do tangent:
    \pgf@bending@do@tangent%
  \else%
    \pgf@bending@do@flex%
  \fi%
  \pgf@xc#1%
  \pgf@xc-\pgf@xc%
  \pgftransformxshift{+\pgf@xc}%
  % Do slant:  
  \ifdim\pgfarrows@slant pt=0pt%
  \else%
    \pgftransformxslant{\pgfarrows@slant}%
  \fi%
  % do swap:
  \ifpgfarrowswap%
    \pgftransformyscale{-1}%
  \fi%
  \pgfscope%
    \pgf@arrows@color@setup%
    \pgflowlevelsynccm\csname pgf@ar@cache@\pgf@arrow@id\endcsname%
  \endpgfscope%
  \pgf@arrows@rigid@hull%
}

\def\pgf@bending@do@tangent{%
  \pgf@xb\pgf@xa%
  \advance\pgf@xb by-\pgf@x%
  \pgfcurvilineardistancetotime{\pgf@xb}%
  \pgf@xb\pgf@x%
  % Compute points:
  \ifdim\pgf@xb=0pt%
    \pgf@bending@possible@degenerate%
  \else%
    \pgf@bending@do@tangent@normal%
  \fi%
  \pgf@ya-\pgf@y%
  \pgfsettransformentries%
    {\pgf@sys@tonumber\pgf@x}{\pgf@sys@tonumber\pgf@y}%
    {\pgf@sys@tonumber\pgf@ya}{\pgf@sys@tonumber\pgf@x}{\pgf@xc}{\pgf@yc}%
}%

\def\pgf@bending@do@tangent@normal{%
  \pgfpointcurveattime{\pgf@xb}{\pgf@curvilinear@line@a}{\pgf@curvilinear@line@b}{\pgf@curvilinear@line@c}{\pgf@curvilinear@line@d}%
  \pgf@xc\pgf@x% save
  \pgf@yc\pgf@y% save
  % compute normal:
  \advance\pgf@xb by-\pgf@xa%
  \advance\pgf@yb by-\pgf@ya%
  \pgf@process{\pgfpointnormalised{\pgf@x=\pgf@xb\pgf@y=\pgf@yb}}
}   

\def\pgf@bending@possible@degenerate{%
  \ifx\pgf@curvilinear@line@a\pgf@curvilinear@line@b% degenerate!
    \ifx\pgf@curvilinear@line@a\pgf@curvilinear@line@c% double degenerate!
      \let\pgf@ref\pgf@curvilinear@line@d%
    \else
      \let\pgf@ref\pgf@curvilinear@line@c%
    \fi%
    \pgf@process{\pgf@curvilinear@line@a}%
    \pgf@xc\pgf@x% save
    \pgf@yc\pgf@y% save
    \pgf@process{\pgf@ref}%
    \advance\pgf@x by-\pgf@xc
    \advance\pgf@y by-\pgf@yc
    \pgf@process{\pgfpointnormalised{}}
    \pgf@x-\pgf@x
    \pgf@y-\pgf@y
  \else%
    \pgf@bending@do@tangent@normal%
  \fi%
}

\def\pgf@bending@do@flex{
  \pgf@xb\pgf@xa%
  \pgf@xc\pgf@xa%
  \advance\pgf@xc by-\pgf@x%
  \advance\pgf@xb by-\pgf@y%
  \pgfcurvilineardistancetotime{\pgf@xc}%
  \pgf@xc\pgf@x%
  \pgfcurvilineardistancetotime{\pgf@xb}%
  \pgf@xb\pgf@x%
  % Compute points:
  \pgf@process{\pgfpointcurveattime{\pgf@xc}{\pgf@curvilinear@line@a}{\pgf@curvilinear@line@b}{\pgf@curvilinear@line@c}{\pgf@curvilinear@line@d}}%
  \pgf@xc\pgf@x\pgf@yc\pgf@y%
  \pgf@process{\pgfpointcurveattime{\pgf@xb}{\pgf@curvilinear@line@a}{\pgf@curvilinear@line@b}{\pgf@curvilinear@line@c}{\pgf@curvilinear@line@d}}%
  \pgf@xb\pgf@x\pgf@yb\pgf@y%
  \pgftransformarrow{\pgfqpoint{\pgf@xb}{\pgf@yb}}{\pgfqpoint{\pgf@xc}{\pgf@yc}}%
}






% Convex hull stuff:

\def\pgf@arrows@bending@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@bending@hull@point@first%
      \pgf@temp%
      \pgf@arrow@bending@update@bb%
    \fi%
  \fi%  
}

\def\pgf@arrow@bending@hull@point@first#1#2{%
  \pgfpointtransformednonlinear{\pgfqpoint{#1}{#2}}%
  \pgf@xa\pgf@x\pgf@xb\pgf@x%
  \pgf@ya\pgf@y\pgf@yb\pgf@y%
  \let\pgf@arrow@hull@point\pgf@arrow@bending@hull@point@other%
}
\def\pgf@arrow@bending@hull@point@other#1#2{%
  \pgfpointtransformednonlinear{\pgfqpoint{#1}{#2}}%
  \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@bending@update@bb{%
  \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%
}




%
%
% Handle the start of a curve
%
% 


% First, the preparation. 

\def\pgf@prep@curvedstart{
  \pgftransformreset%
  \pgfsetcurvilinearbeziercurve{\pgfpointfirstonpath}{\pgfpointsecondonpath}{\pgfpointthirdonpath}{\pgfpointfourthonpath}%
}

% Second, the shortening.

\def\pgf@do@shorten@curvedstart{%
  \expandafter\expandafter\expandafter\pgf@do@shorten@curvedstart@unpack\expandafter\pgfpointthirdonpath\pgfpointfourthonpath%
}
\def\pgf@do@shorten@curvedstart@unpack\pgfqpoint#1#2\pgfqpoint#3#4{%
  \pgf@process{\pgfcurvilineardistancetotime{\pgf@path@shortening@distance}}%
  % Compute new curve:
  \pgfpointcurveattime{\pgf@x}{\pgfpointfirstonpath}{\pgfpointsecondonpath}{\pgfpointthirdonpath}{\pgfpointfourthonpath}%
  % \pgfx/y and \pgf xa/xb already correct. Need to setup remaining vector...
  \pgf@xb#1%
  \pgf@yb#2%
  \pgf@xb\pgf@time@t\pgf@xb%
  \pgf@yb\pgf@time@t\pgf@yb%
  \advance\pgf@xb by\pgf@time@s\pgf@xc%
  \advance\pgf@yb by\pgf@time@s\pgf@yc%
  \edef\pgfpointfirstonpath{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
  \edef\pgfpointsecondonpath{\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}%
  \edef\pgfprocessresultpathsuffix{%
    \noexpand\pgfsyssoftpath@movetotoken{\the\pgf@x}{\the\pgf@y}%
    \noexpand\pgfsyssoftpath@curvetosupportatoken{\the\pgf@xa}{\the\pgf@ya}%
    \noexpand\pgfsyssoftpath@curvetosupportbtoken{\the\pgf@xb}{\the\pgf@yb}%
    \noexpand\pgfsyssoftpath@curvetotoken{#3}{#4}%
  }
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\pgfprocessresultpathsuffix%
  \expandafter\expandafter\expandafter{\expandafter\pgfprocessresultpathsuffix\pgfsubpathend}%
}


% Third, the drawing

\def\pgf@do@draw@curvedstart{%
  \pgf@do@draw@curved\pgf@start@tip@sequence%
}





\endinput

pgfmoduledatavisualization.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/pgfmoduledatavisualization.code.tex,v 1.47 2013/07/19 13:16:48 tantau Exp $

\usepgfmodule{oo,shapes}
\usepgflibrary{fpu}


% This module defines the basic framework for data visualization. 

% In order to visualize data, you first need data. The format for this
% data is not specified, indeed, different formats are possible. A
% data point is created each time the command \pgfdatapoint is
% used. The "parameters" of the data point are just the current values
% of the keys or macros in the current scope. 
%
% A set of data points created using the \pgfdata command.
% When a data point is created, a number of signals are emitted, see
% the description of \pgfdatapoint. To actually visualize something,
% objects should be created that listen to these signals and that
% handle them. 
%
% The following class manages a data visualization

\pgfooclass{data visualization}
{
  % Class data visualization
  %
  % This class is used to "manage" a data visualization. It provides
  % methods for hooking into the data visualization process and its
  % constructor initializes the signals that are issued during a data
  % visualization. 
  %
  % When a data visualization object is created, a whole bunch of
  % signal objects. You should then create objects that connect to
  % these signals. They will be emitted when datapoints come
  % available.
  %
  % It is permissible to have several data visualization objects
  % active at the same time.
  %
  % To use a data visualization object, you should (possibly
  % repeatedly) call the method add data() or the macro \pgfdata. You should also
  % create transformation, mapping and visualization objects. Then,
  % you should, first, call the method survey, which will "survey" the
  % data, allowing the mapping and bounding objects to compute the
  % correct ranges. You may then create further objects based on this
  % data. Then, you should call the "visualize" method, which will
  % invoke the visualization signals for the data points.


  % These attribute store code that should be executed at certain
  % points. The order is the following:
  %
  %  1. "before survey" code
  %  2. "begin survey" phase signal
  %  3. "at start survey" code
  %  4. data points are processed
  %  5. "at end survey" code
  %  6. "end survey" phase signal
  %  7. "after survey" code
  %
  % The first seven points will be repeated until the method "do
  % another survey" is no longer called during a survey.
  %
  %  8. "before visualization" code
  %  9. "begin visualization" phase signal
  % 10. "at start visualization" code
  % 11. data points are processed once more
  % 12. "at end visualization" code
  % 13. "end visualization" phase signal
  % 14. "after visualization" code
  \attribute before survey;
  \attribute at start survey;
  \attribute at end survey;
  \attribute after survey;
  \attribute before visualization;
  \attribute at start visualization;
  \attribute at end visualization;
  \attribute after visualization;
  
  %
  % Survey counts and handling
  %
  
  \attribute survey count=1;
  % Each time a survey is done before the visualization is done, this
  % count is incremented. Normally, there is only one survey, but
  % objects may request another survey or even more surveys to be
  % done, giving them a chance to setup further internal values. By
  % accessing this count (via the get survey count method), you can
  % find out which survey is currently being done.

  \attribute number of surveys=1;
  % By increasing this count, you can request additional surveys to be
  % done.

  
  % Stores the to-be-visualized data
  \attribute data;

  
  % Stores the signal objects
  \attribute prepare datapoint signal;
  \attribute map datapoint signal;
  \attribute transform datapoint signal;
  \attribute visualize datapoint signal;
  \attribute finish datapoint signal;
  \attribute survey datapoint signal;
  \attribute phase signal;
  \attribute path signal;
  \attribute direction signal;
  \attribute style signal;

  
  % Constructor
  %
  % Inits the signals
  \method data visualization() {
    \pgfoonew{prepare datapoint signal}=new signal()%
    \pgfoonew{map datapoint signal}=new signal()%
    \pgfoonew{transform datapoint signal}=new signal()%
    \pgfoonew{visualize datapoint signal}=new signal()%
    \pgfoonew{finish datapoint signal}=new signal()%
    \pgfoonew{survey datapoint signal}=new signal()%
    \pgfoonew{phase signal}=new signal()%
    \pgfoonew{path signal}=new signal()%
    \pgfoonew{direction signal}=new signal()%
    \pgfoonew{style signal}=new signal()%
    %
    % Store this object in a key
    %
    \pgfoothis.get handle(\pgf@dv@me)
    \pgfkeyslet{/pgf/data visualization/obj}\pgf@dv@me
  }

  % The phase signal will emit the following constants:
  \def\pgfdvbeforesurvey{1}
  \def\pgfdvbeginsurvey{2}
  \def\pgfdvendsurvey{3}
  \def\pgfdvaftersurvey{4}
  \def\pgfdvbeforevisualization{5}
  \def\pgfdvbeginvisualization{6}
  \def\pgfdvendvisualization{7}
  \def\pgfdvaftervisualization{8}

  % The path signale will meit the following constants:
  \def\pgfdvpathmovetotoken{5}
  \def\pgfdvpathlinetotoken{6}
  \def\pgfdvdirectionfromtoken{7}
  \def\pgfdvdirectiontotoken{8}
  \def\pgfdvdirectionattoken{9}

  % Method
  %
  % Connect the object #1's slot "#2" to the signal named "#3"
  \method connect(#1,#2,#3) {
    \pgfoovalueof{#3}.connect(#1,#2)
  }
  
  % Method
  %
  % Add data that is to be visualized. The code #1 should call the
  % \pgfdatapoint macro for each data point it creates.
  \method add data(#1) {
    \pgf@dv@stripped@add#1\pgf@stop
  }
  \def\pgf@dv@stripped@add#1\pgf@stop{%
    \pgfooappend{data}{#1}%
  }
  

  % Setters
  \method before survey(#1) {
    \pgfooappend{before survey}{#1}
  }
  \method at start survey(#1) {
    \pgfooappend{at start survey}{#1}
  }
  \method before visualization(#1) {
    \pgfooappend{before visualization}{#1}
  }
  \method at start visualization(#1) {
    \pgfooappend{at start visualization}{#1}
  }

  % Method
  \method at end survey(#1) {
    \pgfooprefix{at end survey}{#1}
  }
  \method after survey(#1) {
    \pgfooprefix{after survey}{#1}
  }
  \method at end visualization(#1) {
    \pgfooprefix{at end visualization}{#1}
  }
  \method after visualization(#1) {
    \pgfooprefix{after visualization}{#1}
  }


  % Method
  %
  % Copy the signals to macros. This is just for efficiency (ha!)
  \method prepare signal macros() {
    \pgfooget{prepare datapoint signal}\pgf@signalpreparedatapoint
    \pgfooget{map datapoint signal}\pgf@signalmapdatapoint
    \pgfooget{transform datapoint signal}\pgf@signaltransformdatapoint
    \pgfooget{visualize datapoint signal}\pgf@signalvisualizedatapoint
    \pgfooget{finish datapoint signal}\pgf@signalfinishdatapoint
    \pgfooget{survey datapoint signal}\pgf@signalsurveydatapoint
    \pgfooget{phase signal}\pgf@signalphase
    \pgfooget{path signal}\pgf@signalpath
    \pgfooget{direction signal}\pgf@signaldirection
    \pgfooget{style signal}\pgf@signalstyle
  }

  
  % Survey method
  %
  % Call this method to "survey" the data. This should be done before
  % the "visualize" method is called.
  \method survey() {
    % Survey phase.
    \let\pgfdatapoint=\pgfdatapoint@surveyphase%
    \pgfoothis.prepare signal macros()
    \pgfooset{survey count}{1}
    \pgfutil@loop
      \pgf@signalphase.emit(\pgfdvbeforesurvey)
      \pgfoovalueof{before survey}%
      \pgf@signalphase.emit(\pgfdvbeginsurvey)
      \pgfoovalueof{at start survey}
      \pgfoovalueof{data}%
      \pgfoovalueof{at end survey}
      \pgf@signalphase.emit(\pgfdvendsurvey)%
      \pgfoovalueof{after survey}
      \pgf@signalphase.emit(\pgfdvaftersurvey)
      \c@pgf@counta=\pgfoovalueof{survey count}\relax
      \c@pgf@countb=\pgfoovalueof{number of surveys}\relax
    \ifnum\c@pgf@counta<\c@pgf@countb
      \advance\c@pgf@counta by1\relax
      \pgfooeset{survey count}{\the\c@pgf@counta}
    \pgfutil@repeat  
  }

  % Getter
  \method get survey count(#1) {
    \pgfooget{survey count}{#1}
  }

  % Request another survey to be done
  \method do an additional survey() {
    \c@pgf@counta=\pgfoovalueof{number of surveys}\relax
    \advance\c@pgf@counta by1\relax
    \pgfooeset{number of surveys}{\the\c@pgf@counta}
  }
  
  % Visualize method
  %
  % This method will cause the actual visualization.
  \method visualize() {
    % Visualization phase.
    \let\pgfdatapoint=\pgfdatapoint@visualizationphase%
    \pgfoothis.prepare signal macros()
    \pgf@signalphase.emit(\pgfdvbeforevisualization)%
    \pgfoovalueof{before visualization}
    \pgf@signalphase.emit(\pgfdvbeginvisualization)%
    \pgfoovalueof{at start visualization}
    \pgfoovalueof{data}%
    \pgfoovalueof{at end visualization}
    \pgf@signalphase.emit(\pgfdvendvisualization)%
    \pgfoovalueof{after visualization}
    \pgf@signalphase.emit(\pgfdvaftervisualization)%
  }
}  


%
% The data point keys
%
% Unlike other keys, the subkeys of /data point/ can simply be set
% directly. If the key has not been initialized, it will automatically
% be.
\pgfkeys{/data point/.unknown/.code={%
    \pgfkeyssetvalue{/data point/\pgfkeyscurrentname}{#1}
  }}




% Create and handle a data point
%
% Description:
%
% This command is called by the survey and the visualize methods
% whenever a complete data point has been produced. Depending on the
% current circumstances, different signals will be emitted.
%
% The data that is represented by the data point is not given as a
% parameter. Rather, it is stored in macros and keys, that is, the
% data point is conceptually given by the settings of all the keys and
% macros in the local scope.
%
% There are two phases to data processing: In the survey phase data
% points are produced and handled in order to find out things like
% their number or the minimum and maximum values of attributes, so
% that axes and picture sizes can be prepared correctly. In the
% visualization phase, data point are actually shown. 
%
% During the survey phase, for each data point the signal
% "surveydatapoint" is emitted.
%
% During the visualization phase, more signals are emitted. A prepare
% signal is emitted first, giving all objects a 
% chance to "prepare" for the data point. Note that it is permissible
% for an object to manipulate the data point here (and also
% in later on).
%
% Next, the command \pgfdvmapdatapointtocanvas is called. Mainly,
% the effect of this command is to setup the keys /data point/canvas x
% and /data point/canvas y, see the description of this command for
% more details. 
%
% The next step consists of signaling "visualize data point". Objects
% listening to this will cause some form of visualization of the
% data point to occur. 
%
% Before the visualization is started, it is checked whether the key
% /data point/name is set (to a non-empty value). If so,
% a coordinate is created with the given canvas x and y values and
% this key's value as name.
%
% Finally, finish data point allows objects to do any final processing
% of the data point.

\def\pgfdatapoint@surveyphase{%
  \pgf@signalpreparedatapoint.emit()%
  \pgf@signalmapdatapoint.emit()%
  \pgf@signalsurveydatapoint.emit()%
}

\def\pgfdatapoint@visualizationphase{%
  \pgf@signalpreparedatapoint.emit()%
  \pgfdvmapdatapointtocanvas%
  \pgfkeysifdefined{/data point/name}
  {%
    \pgfcoordinate{\pgfkeysvalueof{/data point/name}}{\pgfpointdvdatapoint}%
  }{}%
  \pgf@signalvisualizedatapoint.emit()%
  \pgf@signalfinishdatapoint.emit()%
}



% Compute a position of a data point
%
% Description:
%
% This command uses a special signal to compute the position where a
% data point should be visualized on the canvas. In detail, the
% following happens:
%
% A local scope is created and the
% transformation matrix is reset. Then, two signals are emitted: First,
% "map data points" and then "transform data point". The first
% lets listening objects "map" the object by setting up
% attributes of the data point. The second asks objects
% listening to this signal to transform  the current transformation
% matrix. After the signals, we compute where 
% the origin lies inside this transformed coordinate system. Then the
% two keys /data point/canvas x and /data point/canvas y are set to
% the values of this position. The local scope ends (but the settings
% of the keys persist by a bit of magic), thus restoring the
% transformation matrix to its original value.

\def\pgfdvmapdatapointtocanvas{%
  {%
    \pgfpointdvlocaldatapoint
    % Smuggle outside group
    \expandafter%
  }%
  \edef\pgf@marshal{%
    \noexpand\pgfkeyssetvalue{/data point/canvas x}{\the\pgf@x}
    \noexpand\pgfkeyssetvalue{/data point/canvas y}{\the\pgf@y}
  }%
  \pgf@marshal%
}

% Help functions for locating a canvas data point
%
% Description:
%
% The first function returns the data point computed by a
% canvasposition... call.

\def\pgfpointdvdatapoint{%
  \pgfqpoint{\pgfkeysvalueof{/data point/canvas x}}{\pgfkeysvalueof{/data point/canvas y}}%
}

\def\pgfpointdvlocaldatapoint{%
  {%
    % only returns the data point in \pgf@x and \pgf@y, does not set
    % canvas x and canvas y
    \pgf@signalmapdatapoint.emit()%
    \pgftransformreset%
    \pgf@signaltransformdatapoint.emit()%
    \pgfpointtransformed{\pgfpointorigin}%
  }%
}



%
% Special path constructions commands
%
%
% The following commands are used to construct paths based on
% datapoints.
%
% Normally, all these methods need to do is to compute the current
% canvas position of the current data point and then do a moveto,
% lineto or some other operation to this position.
%
% However, when the coordinate system is weird, like with polar
% coordinates or spherical or log-polar coordinate or whatever, a
% straight line "along an attribute" is no longer a straight line.
% In this case, two actions can be taken:
%
% 1. The problem can be ignored, resulting in a wrong line.
% 2. Some clever algorithm kicks in an replaces the straight line by
%    the correct replacement.
%
% As always, when a computer tries to be clever, things can go
% wrong... Nevertheless, some support for the second method is
% given. This works as follows: Objects can register to the data
% visualization path signal. This signal is emitted every time the
% lineto or moveto commands are executed. If an object reacts to such
% a command and handles it, it should set
% \pgfdvhandledtrue.

\newif\ifpgfdvhandled

\def\pgfdv@generic#1#2#3{%
  {%
    \pgfdvhandledfalse%
    \pgf@signalmapdatapoint.emit()%
    #1.emit(#2)%
    \ifpgfdvhandled%
    \else%
      \pgf@process{%
        \pgftransformreset%
        \pgf@signaltransformdatapoint.emit()%
        \pgfpointtransformed{\pgfpointorigin}%
      }%
      #3{}%
    \fi%
  }%
}


% Handle a moveto
%
% This command has no parameters since the target of the moveto is
% given by the canvas position of the current local data point.
\def\pgfpathdvmoveto{%
  \pgfdv@generic{\pgf@signalpath}{\pgfdvpathmovetotoken}{\pgfpathmoveto}
}


% Handle a lineto
%
% This command has no parameters since the target of the moveto is
% given by the canvas position of the current local data point.
\def\pgfpathdvlineto{%
  \pgfdv@generic{\pgf@signalpath}{\pgfdvpathlinetotoken}{\pgfpathlineto}
}



% Compute a normalized vector at the current point pointing along a
% line from #1 to #2.
%
% #1 = code for setting the attributes of the first point
% #2 = code for setting the attributes of the second point
%
% The current point should be a point on a line from #1 to
% #2. Both points as well as the current point are 
% localized on the canvas and a vector pointing from the first point
% to the second one is returned. However, for instance in polar 
% coordinates the vector may actually "point along" the angle axis.
%
% Internally, this command first sets up the first data point and then
% emits a "direction" signal with the \pgfdvpathdirectionfromtoken set and
% then sets up the second point and emits the corresponding
% ...totoken. Finally, the \pgfdvpathdirectionattoken is emitted.
%

\def\pgfpointdvdirection#1#2{%
  {
    {
      #1
      \pgfdv@generic{\pgf@signaldirection}{\pgfdvdirectionfromtoken}{\xdef\pgf@dv@from{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}}
    }
    {
      #2
      \pgfdv@generic{\pgf@signaldirection}{\pgfdvdirectiontotoken}{\xdef\pgf@dv@to{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}}
    }
    {\pgfdv@generic{\pgf@signaldirection}{\pgfdvdirectionattoken}{%
        \pgf@process{
          \pgfpointnormalised{%
            \pgfpointdiff{\pgf@dv@from}{\pgf@dv@to}
          }
        }}}
  }
}





%
%
% Data parsing and formatting
%
%



% Run the rendering pipeline on a dataset and/or save the dataset.
% 
% #1 = options with path /pgf/data/
% #2 = optionally data given inline in curly braces.
%
% Description:
%
% This command is used to define a data set. For a single data
% visualization, multiple data sets can be defined, they will
% accumulate. Data can be in different formats, as specified by the
% "format" key, and you can define new formats.  
%
% The settings of the following keys are important:
%
% /pgf/data visualization/obj
%   contains a handle to the dv-object
%
% /pgf/data/format
%   stores the format (see below)
%
% /pgf/data/read from file
%   determines where the data is.
%  
% /pgf/data/store in group
%   when nonempty, the data is stored here instead of being fed to the
%   rendering pipeline
%
% /pgf/data/use group
%   when nonempty, data that has previsouly been stored here using
%   |define group| is read from here and all other keys are ignored
%
% If "read from file" is empty, the data is stored in the argument that
% follows. Otherwise, the data is read from the specified source file.  
% This data is stored in an internal variable, which is local to the
% current group.
%
% After the group, the key "/pgf/data/continue code" will be
% executed.
%
% When the data is actually used later on (during a survey or a
% visualization), independently of what source is used, a format
% handler is started for each data set. This works as follows: first,
% the handler's startup code is executed. Then for each line of the
% data file/the data given inline, the line handler function is
% called. Finally, the data format end handler is called. 
%
% The format handler's job is to call \pgfdatapoint each time a
% complete data point has been produced.
%
% Example:
%
% \pgfoonew \dv=new data visualization()
% \pgfoonew \obj=new attribute mapper(...)
% ...
%
% \pgfkeys{/pgf/data/.cd,
%          column 1=dax/low,
%          column 2=dax/high,
%          column 3=dax/entry,
%          column 4=dax/exit}
%
% \pgfdata[format=space separated columns]
% {
%   % today
%   2000 2300 2100 2200 
%   2000 2350 2200 2500
%   2200 2300 2250 2260 
%   1800 2260 2260 1900 
%   2000 2300 2100 2200
% }
%
% \pgfdata[format=comma separated columns]
% {
%   % yesterday
%   2000, 2350, 2200, 2250 
%   2200, 2300, 2250, 2260 
% }
%
% \pgfdata[read from file=data.csv,format=comma separated columns]
%
% \dv.survey()
% \dv.visualize()

\def\pgfdata{\pgfutil@ifnextchar[{\pgf@datagroup@data@opt}{\pgf@datagroup@data@opt[]}}%}
\def\pgf@datagroup@data@opt[#1]{%
  % Ok, add one data thing...
  \begingroup%
    \pgfkeys{/pgf/data/.cd,/pgf/every data/.try,#1}%
    \pgfkeysgetvalue{/pgf/data/continue code}\pgf@dv@cont@code%
    \global\let\pgf@dv@cont@code\pgf@dv@cont@code%
    \pgfkeysgetvalue{/pgf/data/use group}\pgf@dv@use@group%
    \ifx\pgf@dv@use@group\pgfutil@empty%
      \pgf@dv@do@adddata{\pgfkeysvalueof{/pgf/data visualization/obj}.add data(\pgf@do@data{#1})}%
      \expandafter\pgf@datagroup@data@opt@cont%
    \else%
      \expandafter\ifx\csname pgf@dv@group@@\pgf@dv@use@group\endcsname\relax%
        \pgferror{Undefined data group '\pgf@dv@use@group'}%
      \else%
        {%
          \pgfkeys{/pgf/data/define group/.code=}% no redefinitions during use
          \csname pgf@dv@group@@\pgf@dv@use@group\endcsname%
        }%
      \fi%
  \endgroup%  
  \expandafter\pgf@dv@cont@code%
      \fi%
}
\def\pgf@datagroup@data@opt@cont{%
  \pgfkeysgetvalue{/pgf/data/format}\pgf@dv@format%
  \expandafter\let\expandafter\pgf@dv@format@catcodes\csname pgfdv@format@\pgf@dv@format @catcodes\endcsname%
  \ifx\pgf@dv@format@catcodes\relax
    \pgferror{Unknown data format '\pgf@dv@format'}%
  \else%
    \pgfkeysgetvalue{/pgf/data/read from file}\pgf@dv@source%
    \ifx\pgf@dv@source\pgfutil@empty%
      \let\pgf@next\pgf@datagroup@grab@inline%
    \else%
      \let\pgf@next\pgf@datagroup@grab@external%
    \fi%
    \pgf@next%
}
  
\def\pgf@datagroup@grab@inline{%
  \pgfutil@ifnextchar\bgroup{%
    \begingroup%
    \catcode`\^^M=\active%
    \pgf@dv@format@catcodes%
    \pgf@datagroup@grab@@inline}%
  {\pgferror{Opening brace expected}}%
}
\def\pgf@datagroup@grab@external{%
    \fi%
  \endgroup%
  \pgf@dv@do@adddata{\pgfkeysvalueof{/pgf/data visualization/obj}.add data({{{\pgf@datagroup@do@external}}})}%
  \pgf@dv@cont@code%
}

\def\pgf@dv@do@adddata#1{%
  \pgfkeysgetvalue{/pgf/data/store in group}\pgf@dv@temp%
  \ifx\pgf@dv@temp\pgfutil@empty%
    #1%
  \else%
    \expandafter\pgfutil@g@addto@macro\csname pgf@dv@group@@\pgf@dv@temp\endcsname{#1}%
  \fi%
}

{\catcode`\^^M=\active%
  \gdef\pgf@datagroup@grab@@inline#1{%
    \endgroup%
    \pgf@dv@do@adddata{\pgfkeysvalueof{/pgf/data visualization/obj}.add data({{{\pgf@datagroup@do@inline#1^^M\pgf@@eol}}})}%
    \fi%
  \endgroup%
  \pgf@dv@cont@code%
  }%
}%
\def\pgf@@eol{\pgf@eol}

\def\pgf@do@data#1#2{%
  \begingroup%
    \pgfkeys{/pgf/data/.cd,/pgf/every data/.try,#1}%
    \pgfkeysgetvalue{/pgf/data/format}\pgf@dv@format%
    \expandafter\let\expandafter\pgf@dv@format@line\csname pgfdv@format@\pgf@dv@format @line\endcsname%
    \expandafter\let\expandafter\pgf@dv@format@emptyline\csname pgfdv@format@\pgf@dv@format @empty\endcsname%
    \csname pgfdv@format@\pgfkeysvalueof{/pgf/data/format}@startup\endcsname%
    #2%
    \csname pgfdv@format@\pgfkeysvalueof{/pgf/data/format}@end\endcsname%
  \endgroup%
}


%
% Read external file
%

\def\pgf@datagroup@do@external{%
  \csname pgfdv@format@\pgfkeysvalueof{/pgf/data/format}@catcodes\endcsname%
  \immediate\openin\r@pgf@reada=\pgfkeysvalueof{/pgf/data/read from file} %
  \ifeof\r@pgf@reada\relax
     \pgferror{Data file '\pgfkeysvalueof{/pgf/data/read from file}' not found}%
  \else
    \pgf@datagroup@readline%
  \fi
  \immediate\closein\r@pgf@reada%
}

\def\pgf@partext{\par}%
\def\pgf@datagroup@readline{%
  \immediate\read\r@pgf@reada to \pgf@temp%
  \ifx\pgf@temp\pgf@partext%
    \pgf@dv@format@emptyline%
  \else%
    \ifx\pgf@temp\pgfutil@empty%
      \pgf@dv@format@emptyline%
    \else%
      \expandafter\pgf@dv@format@line\pgf@temp\pgfeol%
    \fi%
  \fi%
  \ifeof\r@pgf@reada\else\expandafter\pgf@datagroup@readline\fi%
}


%
% Read inline data
%

\def\pgf@datagroup@do@inline{%
  \pgf@dv@handle@line%
}

{\catcode`\^^M=\active%
\gdef\pgf@dv@handle@line{%
  \pgfutil@ifnextchar^^M{\pgf@dv@format@emptyline\expandafter\pgf@dv@handle@line\pgfutil@gobble}%
  {\pgfutil@ifnextchar\pgf@@eol{\pgfutil@gobble}{\pgf@dv@handle@nonemptyline}}%
}%
\gdef\pgf@dv@handle@nonemptyline#1^^M{%
  \pgf@dv@format@line#1\pgfeol%
  \pgf@dv@handle@line%
}%
}

\pgfkeys{
  /pgf/data/data visualization obj/.initial=\undefined,
  /pgf/data/format/.initial=table,% the default format
  /pgf/data/read from file/.initial=,
  /pgf/data/inline/.style={read from file=},
  /pgf/data/continue code/.initial=,
  /pgf/data/store in group/.initial=,
  /pgf/data/new group/.code={\expandafter\global\expandafter\let\csname pgf@dv@group@@#1\endcsname\pgfutil@empty},
  /pgf/data/use group/.initial=,
}






% Define a data format
%
% #1 = format name
% #2 = catcode code
% #3 = startup code
% #4 = line arguments
% #5 = line code
% #6 = empty line code
% #7 = end code
%
% Description:
%
% This command defines a new data format for data visualization. When
% a data set is visualized and the format is set to #1, this handler
% is used to parse the data.
%
% In detail, the \pgfdata command will select a source. Before this
% source is read, #2 will be executed to setup the
% catcodes. Additionally, each time the data is parsed, #3 will be
% called. Then, for each nonempty line of the source, the
% command #5 is executed, where the line will be matched against the
% argument pattern given in #4. For empty lines, #6 will be executed
% instead. At the end of the source, #7 will be executed.

\def\pgfdeclaredataformat#1#2#3#4#5#6#7{%
  \expandafter\def\csname pgfdv@format@#1@catcodes\endcsname{#2}%
  \expandafter\def\csname pgfdv@format@#1@startup\endcsname{#3}%
  \expandafter\def\csname pgfdv@format@#1@line\endcsname#4\pgfeol{#5}%
  \expandafter\def\csname pgfdv@format@#1@empty\endcsname{#6}%
  \expandafter\def\csname pgfdv@format@#1@end\endcsname{#7}%
}



%
% Predefined standard formats
%

% TeX code format
%
% Description:
%
% The lines of the data set are assumed to contain executable TeX
% code that will call \pgfdatapoint.
%
% Example:
%
% \pgfdatavisualizationrender[format=TeX code]
% \dataset{
%   \pgfkeyssetvalue{/data point/x}{5}
%   \pgfkeyssetvalue{/data point/y}{5}
%   \pgfdatapoint
%   \pgfkeyssetvalue{/data point/x}{6}
%   \pgfkeyssetvalue{/data point/y}{6}
%   \pgfdatapoint
% }

\pgfdeclaredataformat{TeX code}{}{}{#1}{#1 }{}{}



% Key-value lines format
%
% Description:
%
% The lines of the data set are passed to \pgfkeys with the path set
% to /data point.
%
% Example:
%
% \data[format=named] {
%   x=5, y=6, hi=9
%   x=7, y=6, lo=10
% }

\pgfdeclaredataformat{named}{}{}{#1}{\pgf@dv@parse@named#1,\pgf@stop}{}{}
\def\pgf@dv@parse@named{%
  \pgfutil@ifnextchar\pgf@stop{\pgfdatapoint\pgfutil@gobble}{\pgf@dv@parse@named@}
}
\def\pgf@dv@parse@named@#1=#2,#3\pgf@stop{%
  \foreach \pgf@dv@temp in {#2} {%
    \def\pgf@dv@tempb{/data point/#1=}%
    \expandafter\expandafter\expandafter\pgfkeys%
    \expandafter\expandafter\expandafter{\expandafter\pgf@dv@tempb\pgf@dv@temp}%
    \pgf@dv@parse@named#3\pgf@stop%
  }
}





% Table format
%
% Description:
%
% A table consists of a head line, which contains the attribute names
% of the values that will be found in the following lines. Each line
% (except for the headline) contains one data point.
% 
% Inside each line the data points are separated by a separator like a
% comma or a space or a colon. The separator can be configured using
% the key /pgf/data/separator (leave the separator empty or set it to
% \space for a space as separator). The default separator is a comma.
% 
% Some tables will miss the headline. In this case, using the
% /pgf/data/headline key you can provide a headline yourself.
%
% Example:
%
% \data[format=table] {
%    x  y
%   10  5
%   11  6
%    6  7
%  }
%
% \data[format=table,separator={,}] {
%    x, y
%   10, 5
%   11, 6
%    6, 7
% }
%
% \data[format=table,headline=x y] {
%   10 5
%   11 6
%    6 7
% }

\pgfdeclaredataformat{table}
{} % no catcodes
{
  \pgfkeysgetvalue{/pgf/data/headline}\pgf@dv@headline
  \pgfkeysgetvalue{/pgf/data/separator}\pgf@dv@separator
  \ifx\pgf@dv@separator\pgfutil@empty
    \let\pgf@dv@separator\space
  \fi
  \ifx\pgf@dv@separator\pgf@dv@spacetext
    \let\pgf@dv@separator\space
  \fi
  \expandafter\def\expandafter\pgf@dv@till@separator%
  \expandafter##\expandafter1\pgf@dv@separator{\pgf@dv@table@handle{##1}}  
  \expandafter\def\expandafter\pgf@dv@till@separator@head%
  \expandafter##\expandafter1\pgf@dv@separator{\pgf@dv@head@handle{##1}}  
  \ifx\pgf@dv@headline\pgfutil@empty
    % Ok, read headline from file
    \pgfdv@firstlinetrue
  \else
    % Headline already set  
    \pgfdv@firstlinefalse
    \expandafter\pgf@dv@parse@headline\expandafter{\pgf@dv@headline}
  \fi
}
{#1} % special line pattern, so read everything
{
  \ifpgfdv@firstline
    \pgfdv@firstlinefalse
    \pgf@dv@parse@headline{#1}
  \else
    {
      \c@pgf@counta=0\relax% keep track of attribute number
      \def\pgf@marshal{\pgf@dv@parse@table#1}
      \expandafter\expandafter\expandafter\pgf@marshal%
      \expandafter\pgf@dv@separator\expandafter\pgfeol\pgf@dv@separator  
      \pgfdatapoint
    }
  \fi
}
{} % ignore empty lines
{} % no special end code

\newif\ifpgfdv@firstline

\pgfkeys{
  /pgf/data/separator/.initial={,},
  /pgf/data/headline/.initial=
}
\def\pgf@dv@spacetext{\space}

\def\pgf@dv@parse@table{%
  \pgfutil@ifnextchar"% Special, but ignored right now...
  {\pgferror{csv with quotes not yet implemented}}
  {\pgf@dv@till@separator}
}
\def\pgf@dv@table@handle#1{%
  \def\pgf@temp{#1}%
  \ifx\pgf@temp\pgfeoltext%
    % Bingo! Stop
    \let\pgf@next=\relax%
  \else%
    \advance\c@pgf@counta by1\relax%
    \pgfkeysgetvalue{/pgf/data/table/attribute \the\c@pgf@counta}\pgf@dv@target
    \ifx\pgf@dv@target\relax%
      \edef\pgf@dv@target{attribute \the\c@pgf@counta}
      \pgfkeyslet{/pgf/data/table/attribute \the\c@pgf@counta}\pgf@dv@target
    \fi
    \pgfkeyssetvalue{/data point/\pgf@dv@target}{#1}
    \let\pgf@next=\pgf@dv@parse@table%
  \fi%
  \pgf@next% 
}



\def\pgf@dv@parse@headline#1{
  \c@pgf@counta=0\relax% keep track of attribute number
  \def\pgf@marshal{\pgf@dv@doparse@headline#1}
  \expandafter\expandafter\expandafter\pgf@marshal%
  \expandafter\pgf@dv@separator\expandafter\pgfeol\pgf@dv@separator  
}

\def\pgf@dv@doparse@headline{%
  \pgfutil@ifnextchar"% Special, but ignored right now...
  {\pgferror{csv with quotes not yet implemented}}
  {\pgf@dv@till@separator@head}
}
\def\pgf@dv@head@handle#1{%
  \def\pgf@temp{#1}%
  \ifx\pgf@temp\pgfeoltext%
    % Bingo! Stop
    \let\pgf@next=\relax%
  \else%
    \advance\c@pgf@counta by1\relax%
    \pgfkeyssetvalue{/pgf/data/table/attribute \the\c@pgf@counta}{#1}
    \let\pgf@next=\pgf@dv@doparse@headline%
  \fi%
  \pgf@next% 
}

\def\pgfeoltext{\pgfeol}


%
%
% Micro math kernel for dv
%
%

% The idea behind the following methods is to "abstract away" which
% math engine is used. In the future, something fancy build on luatex
% might be used, so it would we should not rely directly on the
% fpu library code.
% 
% The system works as follows: First, you "enter" a number into the
% engine. When you do so, it is converted into some internal
% representation that cannot be accessed any more and is called a
% "math variable" henceforth. All commands of the
% math system only work on math variables.
% 
% In order to "exit" a value stored in a math variable from the
% engine, some other macros can be used.
% 
% Operations like addition or multiplication take two math variables
% and store the result in another math variable.



% Store a value in a math variable of the math engine
%
% #1 = a math variable (a macro name) that is to store the value
% #2 = an expression describing a number
% 
%
% Description:
% 
% The #2 should be an expression that evaluates to a number. However,
% due to the way the pgf math engine(s) work, currently, there are
% several restrictions/the syntax is not as simple as one might
% hope. Fortunately, the syntax is hopefully compatible with
% easier-to-use future systems.
% 
% The syntax is as follows: #2 may be
% 
% 1. a simple high-precision number. This number is currently directly
%    passed to \pgfmathfloatparsenumber, so typical permissible values
%    are "100" or "10000000000000" or "nan" or "-5.673543345345e9000"
%    
% 2. a mathematical expression, which *must* be surrounded by
%    parantheses. From a "mathematical" point of view these
%    parantheses are superfluous, but the they are used to help pgf
%    distinguish expressions from high-precision numbers. (If, in the
%    future, expressions may contain high precision numbers, the
%    parantheses will simply be ignored.)
%    
%    The expression is evaluated using \pgfmathparse, which means that
%    TeX-precision is used. This means, for instance, that numbers
%    larger than about 16500 will create error messages.
%    
%    The advantage is that you may say write things like "(5+6)" or
%    "(pi/2)".
%    
% 3. In case #2 starts with an exclamation mark (indicating an
%    "escape"), everything following the mark is simply evaluated by
%    TeX. The effect of evaluating #2 should be that the math
%    variable "\pgfdvmathvalue" is set to some value. This value will
%    then be transferred to #1.
%    
% 4. In case #2 is the result of calling \pgfdvmathexitbyserializing, the
%    "serialized" value is restored. The idea is that the serialized
%    will turn its internal representation of a number into something
%    that can be stored as a text somewhere.
%    
%    Currently, "@" at the beginning of #2 is used to indicate that
%    what follows is a serialized version of a math variable.
%    
% In order to determine which of the above cases is to be used for a
% variable, the first symbol #2 is checked, *after* the first symbol
% of #2 has been expanded once (using \expandafter once).    
%
% Example:
%
% \pgfdvmathenter{\mymacro}{20000000000000}
% \pgfdvmathenter{\mymacro}{(5+pi)}
% \pgfdvmathenter{\mymacro}{!\pgfdvmathadd{\pgfdvmathvalue}{\a}{\b}}
% 
% \pgfdvmathenter{\foo}{5}
% \pgfdvmathexitbyserializing{\somevalue}{\foo}
% \pgfdvmathenter{\mymacro}{\somevalue}

\def\pgfdvmathenter#1#2{%
  \expandafter\pgfdvmathenter@check\expandafter#1#2\pgfdvmath@end%
}
\def\pgfdvmathenter@check#1{%
  \pgfutil@ifnextchar @{\pgfdvmath@internal#1}{%
    \pgfutil@ifnextchar ({\pgfdvmath@expression#1}{%)
      \pgfutil@ifnextchar !{\pgfdvmath@execute#1}{\pgfdvmath@normal#1}}}%
}

\def\pgfdvmath@internal#1@#2\pgfdvmath@end{%
  \def#1{#2}%
}
\def\pgfdvmath@expression#1(#2)#3\pgfdvmath@end{%
  \pgfmathparse{#2}%
  \pgfmathfloatparsenumber{\pgfmathresult}%
  \let#1=\pgfmathresult%
}
\def\pgfdvmath@execute#1!#2\pgfdvmath@end{%
  #2%
  \let#1=\pgfdvmathvalue%
}
\def\pgfdvmath@normal#1#2\pgfdvmath@end{%
  \pgfmathfloatparsenumber{#2}%
  \let#1=\pgfmathresult%
}



% Print a math variable in the math engine using \pgfmathprintnumber
%
% #1 = math variable 
%
% Description:
%
% See the description of \pgfmathprintnumber
%
% Example:
%
% \pgfdvmathenter{\mymacro}{20000000000000}
% \pgfdvmathexitbyprinting{\mymacro}

\def\pgfdvmathexitbyprinting#1{%
  \pgfmathprintnumber{#1}%
}



% Exit a math variable as a number in a scientific and portable number
% format in a macro 
%
% #1 = macro in which to store the value
% #2 = math variable 
%
% Description:
%
% You can exit a number using this operation. You can then directly
% reenter the number using \pgfdvmathenter
%
% Example:
%
% \pgfdvmathenter{\mynumber}{20000000000000}
% \pgfdvmathexitbyscientificformat{\mymacro}{\mynumber}

\def\pgfdvmathexitbyscientificformat#1#2{%
  \edef#1{\pgfmathfloatvalueof#2}%
}



% Exit a math variable as a "serialized" (= string-based)
% version. 
%
% #1 = macro in which to store the value
% #2 = math variable 
%
% Description:
% 
% The serialized version can be reentered using
% \pgfmathenter and is similar to \pgfdvmathexitbyscientificformat,
% but exiting and entering are (a bit) faster.
%
% Example:
%
% \pgfdvmathenter{\mynumber}{20000000000000}
% \pgfdvmathexitbyserializing{\mymacro}{\mynumber}

\def\pgfdvmathexitbyserializing#1#2{%
  \edef#1{@#2}%
}





% Operations on two numbers
%
% #1 = macro that should store the result of applying the
%      corresponding operation to the following:
% #2 = entered number
% #3 = entered number
%
% Description:
%
% Sets #1 to the result of applying an operation to #2 and #3
%
% Example:
%
% \pgfdvmathenter{\a}{2000}
% \pgfdvmathenter{\b}{5+6}
% \pgfdvmathadd{\c}{\a}{\b}

\def\pgfdvmathadd#1#2#3{%
  \pgfmathfloatadd{#2}{#3}%
  \let#1=\pgfmathresult%
}
\def\pgfdvmathsub#1#2#3{%
  \pgfmathfloatsubtract{#2}{#3}%
  \let#1=\pgfmathresult%
}
\def\pgfdvmathmul#1#2#3{%
  \pgfmathfloatmultiply{#2}{#3}%
  \let#1=\pgfmathresult%
}
\def\pgfdvmathdiv#1#2#3{%
  \pgfmathfloatdivide{#2}{#3}%
  \let#1=\pgfmathresult%
}

% Multiply by small number
%
% #1 = macro that should store the result of applying the
%      corresponding operation to the following:
% #2 = entered number
% #3 = fixed point number like 2 or 0.5, but not 10000000000
%
% Description:
%
% Sets #1 to the result of applying an operation to #2 and #3
%
% Example:
%
% \pgfdvmathenter{\a}{2000}
% \pgfdvmathadd{\b}{\a}{0.2}
% % \b now stores 400

\def\pgfdvmathmulfixed#1#2#3{% 
  \pgfmathfloatmultiplyfixed{#2}{#3}%
  \let#1=\pgfmathresult%
}



% Log, ln and exponent functions
% 
% #1 = a math variable
% #2 = a math variable
% 
% Description
% 
% \pgfdvmathln will compute #1 = ln(#2)
% \pgfdvmathlog will compute #1 = log_{10}(#2)
% \pgfdvmathexp will compute #1 = exp(#2)
% \pgfdvmathpowten will compute #1 = 10^{#2}

\def\pgfdvmathln#1#2{%
  \pgfmathfloatln{#2}%
  \let#1=\pgfmathresult%
}

\def\pgfdvmathlog#1#2{%
  \pgfmathfloatln{#2}%
  \pgfmathfloatmultiply{\pgfmathresult}{\pgfdvmathalwaysloge}%
  \let#1=\pgfmathresult%
}

\def\pgfdvmathexp#1#2{%
  \pgfmathfloatexp{#2}%
  \let#1=\pgfmathresult%
}

\def\pgfdvmathpowten#1#2{%
  \pgfmathfloattofixed{#2}%
  \let\pgf@dv@temp=\pgfmathresult%
  \pgfmathround{\pgf@dv@temp}%
  \let\pgf@dv@temp@round=\pgfmathresult%
  \pgf@x=\pgf@dv@temp@round pt%
  \pgf@x=-\pgf@x%
  \advance\pgf@x by\pgf@dv@temp pt\relax%
  \ifdim\pgf@x>0.0002pt%
    \pgfmathfloatmultiply{#2}{\pgfdvmathalwayslnten}%
    \pgfmathfloatexp{\pgfmathresult}%
  \else
    \ifdim\pgf@x<-0.0002pt%
      \pgfmathfloatmultiply{#2}{\pgfdvmathalwayslnten}%
      \pgfmathfloatexp{\pgfmathresult}%
    \else
      \pgf@x=\pgf@dv@temp@round sp%
      \c@pgf@counta=\pgf@x%
      \pgfmathfloatcreate{1}{1.0}{\the\c@pgf@counta}%
    \fi
  \fi
  \let#1=\pgfmathresult%
}


% Floor functions
% 
% #1 = a math variable
% #2 = a math variable
% 
% Description
% 
% Sets #1 to the largest integer less or equal to #2

\def\pgfdvmathfloor#1#2{%
  \pgfmathifisint{#2}{%
    \let#1=#2%
  }{%
    \pgfmathfloatgetflags#2\c@pgf@counta%
    \ifcase\c@pgf@counta
      \let#1=\pgfdvmathalwayszero%
    \or
      \pgfmathfloatfloor{#2}%
      \let#1=\pgfmathresult%
    \or
      \pgfmathfloatsubtract{\pgfdvmathalwaysone}{#2}%
      \pgfmathfloatfloor{\pgfmathresult}%
      \pgfmathfloatsubtract{\pgfdvmathalwayszero}{\pgfmathresult}%
      \let#1=\pgfmathresult%
    \or\let#1=#2%
    \or\let#1=#2%
    \or\let#1=#2%
    \fi%
  }%
}


% Advanced unary operations
%
% #1 = macro that should store the result of applying the
%      operation to an entered number
% #2 = the operation (as a string like "ln")
% #3 = entered number
%
% Description:
%
% Sets #1 to the result of applying #2 to #3
%
% Example:
%
% \pgfdvmathenter{\a}{2000}
% \pgfdvmathunaryop{\b}{ln}{\a}

\def\pgfdvmathunaryop#1#2#3{%
  \csname pgfmathfloat#2\endcsname{#3}%
  \let#1=\pgfmathresult%
}


% Advanced binary operations
%
% #1 = macro that should store the result of applying the
%      operation to two entered number
% #2 = the operation (as a string like "veclen")
% #3 = first argument (an entered number)
% #4 = second argument (an entered number)
%
% Description:
%
% Sets #1 to the result of applying #2 to #3
%
% Example:
%
% \pgfdvmathenter{\a}{3}
% \pgfdvmathenter{\b}{4}
% \pgfdvmathbinop{\c}{veclen}{\a}{\b}

\def\pgfdvmathbinop#1#2#3#4{%
  \csname pgfmathfloat#2\endcsname{#3}{#4}%
  \let#1=\pgfmathresult%
}



% Comparing values
%
% #1 = first math variable
% #2 = second math variable
% #3 = code to-be-executed if #1 < #2
% #4 = code to-be-executed if #1 >= #2
%
%
% Example:
%
% \pgfdvmathenter{\a}{3}
% \pgfdvmathenter{\b}{4}
% \pgfdvmathifless{\a}{\b}{yes}{should not happen}

\def\pgfdvmathifless#1#2#3#4{%
  \pgfmathfloatlessthan{#1}{#2}%
  \ifpgfmathfloatcomparison#3\else#4\fi%
}




%
%
% Standard objects for data visualization
% 
%


%
% Transformers
%

\pgfooclass{linear transformer}
{
  % Class linear transformer
  %
  % This class is a transformer class. It reacts to the transform
  % datapoint signal. When this signal is raised, it will shift the
  % coordinate system as follows: If the current value of /data
  % point/this.attribute  is 0, then the system is shifted to the
  % current value of this.origin. If the current value is 1, the
  % system is shifted to this.origin + this.unit vector. For other
  % values of /data point/this.attribuate, the shift is interpolated
  % between these two values. 

  
  \attribute attribute;
  % The attribute (/data point/this.attribute) by which
  % the unit vector is multiplied. If it is empty (which is
  % different from 0), no transformation is done at all.

  \attribute origin = \pgfpointorigin;
  % The shift in case the /data point/this.attribute is 0.

  \attribute unit vector;
  % The coordinate system is additionally shifted by this amount
  % times the current value of /data point/this.attribute.

  
  % Constructor
  %
  % #1 = attribute that is being transformed. Example: x
  % #2 = a vector corresponding to one unit of #1.
  %      Example: \pgfpoint{1cm}{0cm}
  \method linear transformer(#1,#2) {
    \pgfooset{attribute}{#1}
    \pgf@process{#2}
    \edef\pgf@temp{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}
    \pgfoolet{unit vector}\pgf@temp%
  }

  % Method
  \method default connects() {
    \pgfoothis.get handle(\pgf@dv@me)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\pgf@dv@me,transform,transform datapoint signal)
  }
  
  % Setter
  \method set origin(#1) {
    \pgf@process{#1}
    \edef\pgf@temp{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}
    \pgfoolet{origin}\pgf@temp%
  }

  % Slot
  %
  % This slot should be connected to the transform datapoint
  % signal. When this signal is emitted, the coordinate system will be
  % shifted according to the current value of the attribute.
  \method transform() {
    \pgfkeysgetvalue{/data point/\pgfoovalueof{attribute}}\pgf@dv@val%
    \ifx\pgf@dv@val\pgfutil@empty%
    \else%
      \ifx\pgf@dv@val\relax%
      \else%
        \pgfdvmathenter{\pgf@dv@math@var}{\pgf@dv@val}%
        \pgfdvmathexitbyscientificformat{\pgf@dv@val}{\pgf@dv@math@var}%
        \pgftransformshift{\pgfoovalueof{origin}}%
        \pgfmathfloatgetexponent\pgf@dv@math@var\c@pgf@counta%
        \ifnum\c@pgf@counta<-3\relax%
        \else%
          \pgftransformshift{\pgfpointscale{\pgf@dv@val}{\pgfoovalueof{unit vector}}}%
        \fi%
      \fi%
    \fi%
  }

}


%
% Numerical mapping of attributes to other attributes
%

\pgfooclass{interval mapper}
{
  % Class interval mapper
  %
  % This interval mapper reacts to the map datapoint signal. Its purpose is to
  % map one attribute to another attribute. For the first attribute,
  % an intervals is specified.
  %
  % In addition to the in interval [a,b] there is also an outinterval
  % [c,d]. Values in the range [a,b] are linearly mapped to the
  % range [c,d] and the result is stored in the second attribute.
  %
  % For instance, if the first range is [10,20] and the second range
  % is [0,100], then 10 is mapped to 0, 11 is mapped to 10, 20 is
  % mapped to 100 and 30 is mapped to 200.
  %
  % It is permissible to specify an additional non-linear
  % transformation function f. In this case, for an input value x the
  % position of f(x) inside the interval [f(a),f(b)] is determined and
  % this position is linearly mapped to [c,d]. 
  %
  % For example, if f(x) = log_10 (x) and the first range [a,b] =
  % [10,1000] and the second range is [1,2], then 10 is mapped to 1,
  % 100 is mapped to 1.5 (since f(100) = 3 lies in the middle
  % between f(10) = 2 and f(1000) = 4) and 100000 is mapped to 3.
  

  \attribute in;
  % The name of the input attribute. If the value of this attribute
  % is empty or undefined, no mapping is done.
  %
  % The in attribute may have a subkey called .../const. If this key
  % has a value different from \relax, it will always be used instead
  % of the in attribute itself. This can be useful to temporarily
  % set a constant value to a key inside a mapping chain.

%  \attribute clip;
%  % The code for clipping the interval. Will set \pgf@dvcliptrue, if a
%  % clip is necessary.
  
  \attribute out;
  % The name of the output attribute.
  
  \attribute trans;
  % Stores (more or less) the transformation function.

  \attribute out min;
  % Start of the second range (the value of c).

  \attribute out min;
  % End of the second range (the value of d).

  \attribute trans in min;
  % Transformed value of the start of the first range (the value
  % f(a)).

  \attribute scale;
  % The scaling factor, that is, the value of (f(b)-f(a))/(d-c).

  
  % Constructor
  %
  % #1 = input attribute. Example: velocity.
  % #2 = output attribute. Example: x
  % #3 = optional transformation function. The input value for this
  %      function is stored in entered number \pgfvalue.
  %      The output of the function should be stored in the
  %      same entered number.
  %
  % The intervals are set using setter methods later on.
  %
  \method interval mapper(#1,#2,#3) {
    \pgfooset{in}{#1}
    \pgfooset{out}{#2}
    \def\pgf@temp{#3}%
    \ifx\pgf@temp\pgfutil@empty%
    \else%
      \pgfooset{trans}{%
        #3%
      }%
    \fi%
  } 

  % Method
  \method default connects() {
    \pgfoothis.get handle(\pgf@dv@me)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\pgf@dv@me,map,map datapoint signal)
  }

%   % Method
%   \method set clip interval(#1,#2) {
%     \def\pgfdvmin{#1}%
%     \def\pgfdvmax{#2}%
%     \ifx\pgfdvmin\pgfutil@empty%
%     \else%
%       \pgfdvmathenter{\pgf@dv@temp}{\pgfdvmin}%
%       \pgfdvmathexitbyserializing{\pgfdvmin}{\pgf@dv@temp}%
%     \fi
%     \ifx\pgfdvmax\pgfutil@empty%
%     \else%
%       \pgfdvmathenter{\pgf@dv@temp}{\pgfdvmax}%
%       \pgfdvmathexitbyserializing{\pgfdvmax}{\pgf@dv@temp}%
%     \fi
%     \pgfooeset{clip}{%
%       \noexpand\pgf@dvclipfalse%
%       \ifx\pgfdvmin\pgfutil@empty%
%       \else%
%         \noexpand\pgfdvmathenter{\noexpand\pgf@dv@temp}{\pgfdvmin}%
%         \noexpand\pgfdvmathifless{\noexpand\pgfvalue}{\noexpand\pgf@dv@temp}{\noexpand\pgf@dvcliptrue}{}%
%       \fi%
%       \ifx\pgfdvmax\pgfutil@empty%
%       \else%
%         \noexpand\pgfdvmathenter{\noexpand\pgf@dv@temp}{\pgfdvmax}%
%         \noexpand\pgfdvmathifless{\noexpand\pgf@dv@temp}{\noexpand\pgfvalue}{\noexpand\pgf@dvcliptrue}{}%
%       \fi%
%     }
%   }

  % Method
  %
  % #1 = in interval minimum
  % #2 = in interval maximum
  % #3 = out interval minimum
  % #4 = out interval maximum
  %
  % This method will (re)compute the correct mappings for the interval
  % mapper. 
  \method set interval values(#1,#2,#3,#4) {
    {%
      \pgfdvmathenter{\pgf@in@interval@min}{#1}
      \pgfdvmathenter{\pgf@in@interval@max}{#2}
      \pgfdvmathenter{\pgf@out@interval@min}{#3}
      \pgfdvmathenter{\pgf@out@interval@max}{#4}
      % Let's start with the output, it's easier...
      \pgfoolet{out min}{\pgf@out@interval@min}
      \pgfoolet{out max}{\pgf@out@interval@max}
      \pgfdvmathsub{\pgf@out@diff}{\pgf@out@interval@max}{\pgf@out@interval@min}
      \let\pgfvalue=\pgf@in@interval@min
      \pgfoovalueof{trans}
      \let\pgf@in@interval@min@transformed=\pgfvalue
      \pgfoolet{trans in min}{\pgf@in@interval@min@transformed}%
      \let\pgfvalue=\pgf@in@interval@max
      \pgfoovalueof{trans}
      \let\pgf@in@interval@max@transformed=\pgfvalue
      \pgfdvmathsub{\pgf@diff@in@transformed}{\pgf@in@interval@max@transformed}{\pgf@in@interval@min@transformed}
      % 
      % Precompute the scaling
      % 
      \pgfdvmathdiv{\pgf@scale}{\pgf@out@diff}{\pgf@diff@in@transformed}%
      \pgfoolet{scale}{\pgf@scale}%
    }%
  } 

  % Slot
  \method map() {
    \pgfooget{scale}\pgf@temp
    \ifx\pgf@temp\pgfutil@empty%
      % not yet setup
    \else%
      \pgfkeysgetvalue{/data point/\pgfoovalueof{in}/const}\pgf@dv@external@value%
      \ifx\pgf@dv@external@value\relax%
        \pgfkeysgetvalue{/data point/\pgfoovalueof{in}}\pgf@dv@external@value%
      \fi%
      \ifx\pgf@dv@external@value\pgfutil@empty%
        \pgf@dv@mapper@pos@check%
      \else%
        \ifx\pgf@dv@external@value\relax%
          \pgf@dv@mapper@pos@check%
        \else%
%          % Clip?
          \pgfdvmathenter{\pgfvalue}{\pgf@dv@external@value}%
%          \pgfoovalueof{clip}%
%          \ifpgf@dvclip%
%            \pgfkeyslet{/data point/\pgfoovalueof{out}}\pgfutil@empty%
%          \else%
            \pgf@dv@mapper@trans{}
%          \fi%
        \fi%
      \fi%
%       \pgfkeysgetvalue{/data point/\pgfoovalueof{in}/min}\pgf@dv@external@value%
%       \ifx\pgf@dv@external@value\relax\else%
%         \ifx\pgf@dv@external@value\pgfutil@empty\else%
%           \pgfdvmathenter{\pgfvalue}{\pgf@dv@external@value}%
%           \pgf@dv@mapper@trans{/min}
%         \fi
%       \fi
%       \pgfkeysgetvalue{/data point/\pgfoovalueof{in}/max}\pgf@dv@external@value%
%       \ifx\pgf@dv@external@value\relax\else%
%         \ifx\pgf@dv@external@value\pgfutil@empty\else%
%           \pgfdvmathenter{\pgfvalue}{\pgf@dv@external@value}%
%           \pgf@dv@mapper@trans{/max}
%         \fi
%       \fi
    \fi%
  }

  \def\pgf@dv@mapper@trans#1{
    \pgfooget{trans in min}{\pgf@dv@trans@in@min}%
    \pgfooget{scale}{\pgf@dv@scale}%
    \pgfooget{out min}{\pgf@dv@out@min}%
    \pgfoovalueof{trans}%
    \pgfdvmathsub{\pgfvalue}{\pgfvalue}{\pgf@dv@trans@in@min}%
    \pgfdvmathmul{\pgfvalue}{\pgfvalue}{\pgf@dv@scale}%
    \pgfdvmathadd{\pgfvalue}{\pgfvalue}{\pgf@dv@out@min}%
    \pgfkeysgetvalue{/data point/\pgfoovalueof{out}#1/offset}\pgf@dv@external@offset%
    \ifx\pgf@dv@external@offset\relax\else%
      \ifx\pgf@dv@external@offset\pgfutil@empty\else%
        \pgfdvmathenter{\pgf@dv@offset}{\pgf@dv@external@offset}%
        \pgfdvmathadd{\pgfvalue}{\pgfvalue}{\pgf@dv@offset}
      \fi
    \fi
    \pgfdvmathexitbyserializing{\pgf@temp}{\pgfvalue}%
    \pgfkeyslet{/data point/\pgfoovalueof{out}#1}\pgf@temp%
  }

  \def\pgf@dv@mapper@pos@check{%
    \pgfkeysgetvalue{/data point/\pgfoovalueof{in}/out pos}\pgf@dv@pos@value%
    \ifx\pgf@dv@pos@value\relax\else\if\pgf@dv@pos@value\pgfutil@empty\else%
      \pgfmathsetmacro{\pgf@dv@pos@num}{\pgf@dv@pos@value}%
      \pgfmathsetmacro{\pgf@dv@pos@num@prime}{1-\pgf@dv@pos@num}%
      % Ok, compute transformed min position:
      \pgfooget{out min}{\pgf@out@interval@min}
      \pgfooget{out max}{\pgf@out@interval@max}
      \pgfdvmathmulfixed{\pgf@out@interval@min}{\pgf@out@interval@min}{\pgf@dv@pos@num@prime}
      \pgfdvmathmulfixed{\pgf@out@interval@max}{\pgf@out@interval@max}{\pgf@dv@pos@num}
      \pgfdvmathadd{\pgf@out@val}{\pgf@out@interval@min}{\pgf@out@interval@max}%
      \pgfdvmathexitbyserializing{\pgf@temp}{\pgf@out@val}%
      \pgfkeyslet{/data point/\pgfoovalueof{out}}\pgf@temp%
    \fi\fi%
  }
}





%\newif\ifpgf@dvclip
\newif\ifpgf@dvignore

\pgfooclass{scaling mapper}
{
  % Class scaling mapper
  %
  % A scaling mapper is (mainly) used to scale an attribute in such a way
  % that it can be rendered easily on a page. The idea is that you
  % specify some attribute and a desired target interval size (like
  % [0,5]). The scaling mapper will then survey the data and will setup a
  % interval mapper in such a way that the minimum value present in the data is
  % mapped to 0 and the maximum to 5. However, it is also possible to,
  % say, only have the maximum value mapped to 5 and have 0 be mapped
  % to 0. Other, more complicated specifications are also possible.
  %
  % The scaling mapper internally creates several objects: First, a surveyor
  % for determining the minimum and maximum values of the attribute
  % and a interval mapper for then mapping the values to the scaled
  % values. Additionally, interval objects are needed.

  \attribute in;
  % The to-be-scaled attribute;

  \attribute out;
  % The attribute storing the scaled value.

  \attribute in range obj;
  % This interval keep track of the range of the in attribute
  
  \attribute scaling spec;
  % A specification of how the scaling should be performed.
  %
  % The format is the following:
  %
  % #1 at #2 and #3 at #4
  %
  % Here, #2 and #4 must be numbers. #1 and #3 can either be numbers
  % or #1 can be the text "min" and #3 can be the text "max".
  %
  % The effect of such a specification is the following: The value #1
  % is mapped to #2, the value #3 is mapped to #4 and values between
  % #1 and #3 (or outside this range) are mapped linearly to a value
  % between (or outside) #2 and #4. In case #1 is set to "min", the
  % smallest observed value of the in-attribute is mapped to #3 and
  % similarly for a value of "max" for #3.
  %
  % Additionally, as for a interval mapper, a function f might be specified
  % that deforms the linear mapping. In case f is specified,
  % f(#1) is mapped to #2 and f(#3) is mapped to #4.

  \attribute function;
  % Stores the function
  
  \attribute interval mapper;
  % Stores the interval mapper object
  
  \attribute range surveyor;
  % Stores the range surveyor object
  
  
  % Constructor
  %
  % #1 = in attribute
  % #2 = out attribute
  % #3 = scaling specification
  % #4 = optional function
  %
  \method scaling mapper(#1,#2,#3,#4) {
    %
    % Save the parameters in attributes
    %
    \pgfooset{in}{#1}
    \pgfooset{out}{#2}
    \pgfooset{scaling spec}{#3}
    \pgfooset{function}{#4}
    %
    % Now setup the objects for the before survey phase
    %
    %
    % First, the in range interval
    \pgfoonew \pgf@dv@in@range@obj=new interval(,)
    \pgfoolet{in range obj}\pgf@dv@in@range@obj
    % Second, the in range surveyor. We do not need to store this
    % object, it will "do its work in the background"
    \pgfoonew \pgf@dv@range@obj=new range surveyor(#1,\pgf@dv@in@range@obj)
    \pgf@dv@range@obj.default connects()
    \pgfoolet{range surveyor}\pgf@dv@range@obj
    %
    %
    % The interval mapper:
    % 
    \pgfoonew{interval mapper}=new interval mapper(#1,#2,#4)
    \pgfoovalueof{interval mapper}.default connects()
  }

  % Method
  \method default connects() {
    \pgfoothis.get handle(\pgf@dv@me)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\pgf@dv@me,phase,phase signal)
  }


%  % Method
%  %
%  % #1 = a min clip -- everything below this value will be clipped
%  % #2 = a max value -- everything above this value will be clipped
%  % 
%  % Sets a clipping for the underlying interval mapper.
%  %
%  \method set clip interval(#1,#2) {
%    \pgfoovalueof{interval mapper}.set clip interval({#1},{#2})%
%  }

  % Getter
  %
  % Returns an interval object that stores the range of the in
  % attribute. 
  \method get in range interval() {
    \pgfooget{in range obj}\pgfdvinrangeinterval
  }
  
  
  % Getter
  %
  % Returns the out attribute.
  % 
  \method get out() {
    \pgfooget{out}\pgfdvout
  }

  % Getter
  %
  % Returns the function attribute.
  % 
  \method get function(#1) {
    \pgfooget{function}#1
  }

  % Method
  %
  % #1 = a included in value
  % 
  % This method only affects the survey. The value #1 is recorded as
  % if it were encountered for the in attribute at some point.
  % 
  \method include in value(#1) {
    \pgfoovalueof{range surveyor}.include attribute value({#1})
  }

  
  % Method
  %
  % #1 = value for the attribute
  %
  % Sets the attribute to the (evaluated) given value (evaluation
  % using \pgfmathparse). When the value  is evaluated, the values of
  % \pgfdvmin and \pgfdvmax will be set to the minimum and maximum
  % values of the in interval. (See \pgfdvmathenter with the "!"-notation). 
  %
  % In case #1 is set to the special value "min", it evaluates to
  % \pgfdvmin, when set to "max" it evaluates to \pgfdvmax.
  %
  \method set in to(#1) {
    \edef\pgf@temp{#1}
    \ifx\pgf@temp\pgf@min@text
      \pgf@dv@lib@set@mm%
      \let\pgf@dv@value\pgfdvmin
    \else
      \ifx\pgf@temp\pgf@max@text
        \pgf@dv@lib@set@mm%
        \let\pgf@dv@value\pgfdvmax
      \else
        \pgfdvmathenter{\pgf@dv@value}{\pgf@temp}
      \fi
    \fi
    \pgfdvmathexitbyserializing{\pgf@dv@serial}{\pgf@dv@value}
    \pgfkeyslet{/data point/\pgfoovalueof{in}}\pgf@dv@serial
  }
  \def\pgf@dv@lib@set@mm{
    \pgfooget{in range obj}\pgfdvinrangeinterval
    \pgfdvinrangeinterval.get min and max()%
  }

  
  % Slot 
  \method phase(#1) {
    \ifx#1\pgfdvendsurvey
      % Ok, we setup the interval mapper.
      %
      % We start by computing the interval borders:
      \pgfoovalueof{in range obj}.get min and max()
      \ifx\pgfdvmin\pgfutil@empty% undefined, since no data points
      \else%
        \pgfooget{scaling spec}\pgf@temp
        \expandafter\pgf@lib@dv@parse@scaling\pgf@temp\pgf@stop%
        \pgfoovalueof{interval mapper}.set interval values(%
          \pgf@lib@dv@min,\pgf@lib@dv@max,%
          \pgf@lib@dv@min@at,\pgf@lib@dv@max@at)
      \fi
    \fi
  }

  
  % Internal helper
  \def\pgf@lib@dv@parse@scaling#1 at#2and #3 at#4\pgf@stop{%
    \def\pgf@lib@dv@min{#1}%
    \pgfdvmathenter{\pgf@lib@dv@min@at@mv}{#2}
    \def\pgf@lib@dv@max{#3}%
    \pgfdvmathenter{\pgf@lib@dv@max@at@mv}{#4}
    \ifx\pgf@lib@dv@min\pgf@min@text%
      \let\pgf@lib@dv@min@mv\pgfdvmin
    \else
      \pgfdvmathenter{\pgf@lib@dv@min@mv}{\pgf@lib@dv@min}
    \fi
    \ifx\pgf@lib@dv@max\pgf@max@text%
      \let\pgf@lib@dv@max@mv\pgfdvmax
    \else
      \pgfdvmathenter{\pgf@lib@dv@max@mv}{\pgf@lib@dv@max}
    \fi
    \pgfdvmathexitbyserializing{\pgf@lib@dv@min}{\pgf@lib@dv@min@mv}
    \pgfdvmathexitbyserializing{\pgf@lib@dv@min@at}{\pgf@lib@dv@min@at@mv}
    \pgfdvmathexitbyserializing{\pgf@lib@dv@max}{\pgf@lib@dv@max@mv}
    \pgfdvmathexitbyserializing{\pgf@lib@dv@max@at}{\pgf@lib@dv@max@at@mv}
  }
  \def\pgf@min@text{min}
  \def\pgf@max@text{max}
}





%
% Surveyors
%

\pgfooclass{range surveyor}
{
  % Class range surveyor
  %
  % A range surveyor is used only in the survey phase. Its job is to
  % determine the minimum and maximum values of an attribute that are
  % "seen" during the survey phase. Based on this value, the size of,
  % say, an axis can be detemined later on.
  %
  % You can also set the key "sub attributes" of the attribute. In
  % this case, this key should contain -- as the name suggests -- a
  % list of subkeys that should also be taken into account for the
  % computation of the minimum and maximum value. Inside the "sub
  % attributes" key, each subkey should be surrounded by a call of
  % \pgfdvsub. For instance, if there are two sub attributes "/data
  % point/velocity/min" and "/data point/velocity/max" for a key
  % "/data point/velocity", then "/data point/velocity/sub attributes"
  % should be set to "\pgfdvsub{/min}\pgfdvsub{/max}".

  \attribute attribute;
  % The to-be-surveyed attribute

  \attribute interval obj;
  % The interval object that protocols the minimum and maximum
  % values. 


  % Constructor
  %
  % #1 = the attribute
  % #2 = handle to the interval object
  %
  \method range surveyor(#1,#2) {
    \pgfooset{attribute}{#1}
    \pgfoolet{interval obj}#2
  }

  % Method
  \method default connects() {
    \pgfoothis.get handle(\pgf@dv@me)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\pgf@dv@me,survey,survey datapoint signal)
  }

  % Method
  %
  % #1 = a value
  % 
  % Adjust the interval as if during the survey this value were
  % encountered 
  \method include attribute value(#1) {
    \pgf@dv@assign@val@stripped#1\pgf@stop%
    \pgfoovalueof{interval obj}.adjust(\pgf@dv@range@surv)
  }
  \def\pgf@dv@assign@val@stripped#1\pgf@stop{%
    \def\pgf@dv@val{#1}
  }

  % Slot
  %
  % This slot should be connected to the survey datapoint signal. For
  % each datapoint, this method will call the adjust method of the
  % interval.
  %
  \method survey() {
    \let\pgfdvsub\pgf@dv@range@surv@sub
    \pgfdvsub{}%
    \pgfkeysvalueof{/data point/\pgfoovalueof{attribute}/sub attributes}
  }

  \def\pgf@dv@range@surv@sub#1{
    \pgfkeysgetvalue{/data point/\pgfoovalueof{attribute}#1}\pgf@dv@val%
    \ifx\pgf@dv@val\relax%
    \else%
      \edef\pgf@dv@val{\pgf@dv@val}%
      \ifx\pgf@dv@val\pgfutil@empty%
      \else%
        \pgfoovalueof{interval obj}.adjust(\pgf@dv@range@surv)%
      \fi%
    \fi%
  }

  \def\pgf@dv@range@surv{%
    \pgfdvmathenter{\pgf@dv@value}{\pgf@dv@val}%
    % Now, protocol value
    \ifx\pgfdvmin\pgfutil@empty%
      \let\pgfdvmin\pgf@dv@value%
    \else%
      \pgfdvmathifless{\pgf@dv@value}{\pgfdvmin}{\let\pgfdvmin\pgf@dv@value}{}%
    \fi%
    \ifx\pgfdvmax\pgfutil@empty%
      \let\pgfdvmax\pgf@dv@value%
    \else%
      \pgfdvmathifless{\pgfdvmax}{\pgf@dv@value}{\let\pgfdvmax\pgf@dv@value}{}%
    \fi%
  }
}



%
% Visualizers
%

\usepgflibrary{plothandlers}



\pgfooclass{plot handler visualizer}
{
  % Class plot handler visualizer
  %
  % This visualizer uses one or more plot handlers to visualize data points.
  % As the data points are processed, the canvas positions of the data 
  % points are recorded. At the end of a group of data points, the
  % recorded stream of canvas position is visualized (rendered)
  % using plot handlers. For instance, when the lineto plot handler 
  % is used, the data points are connected by straight lines, when the
  % curveto plot handler is used, they are connected by smooth curves
  % and so on.
  %
  % Since plot lines are not drawn immediately, but only at the end,
  % when everything has been collected, multiple plot handlers can
  % coexist peacefully at the same time.
  %
  % You can specify a "filter", which will cause only those data
  % points to be visualized by the visualizer that pass the test. The
  % filter should set \pgfdvfilterpassedfalse for to-be-filtered data
  % point. 
  %
  % You can specify "projection code" that changes the canvas x and
  % canvas y positions. This projection code allows you to draw, say,
  % projected points instead of the actual data point.
  %
  % The keys /data point/<name>/execute at begin and /data
  % point/<name>/execute at end, where <name> is the name of
  % the visualizer, should store code that is to be executed directly
  % before and after the stream of coordinates is created. Typically,
  % these keys will store commands to use the path created by the plot
  % handler. 

  \attribute handlers;
  % The to-be-used handlers
  
  \attribute name;
  % The attribute
  
  \attribute filter=\pgfdvnamedvisualizerfilter;
  % Filter code
    
  \attribute positions;
  % An internal protocol of the positions on the stream
  
  \attribute cache;
  % An internal cache. Positions are first inserted into this
  % cache. Every 100 steps this cache is moved to positions. The idea
  % behind this is that it will avoid the quadratic time increase that
  % is normally caused when a protocol is build in TeX.
  
  \attribute projection code;
  % This code is empty by default. However, you can set it for
  % instance to the following
  % 
  % \pgfkeyssetvalue{/data point/y=0}\pgfdvmapdatapointtocanvas
  % 
  % in order to visualize the data point with its y-coordinate
  % replaced by 0.
  
  % Constructor
  %
  % #1 = A name
  % #2 = A comma-separated list of handlers like
  %      "\pgfplothandlerlineto,\pgfplothandlercurveto"
  %
  \method plot handler visualizer(#1,#2) {
    \pgfooset{name}{#1}
    \pgfooset{handlers}{#2}
  }
  
  % Method
  \method default connects() {
    \pgfoothis.get handle(\pgf@dv@me)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\pgf@dv@me,protocol,visualize datapoint signal)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\pgf@dv@me,phase,phase signal)
  }

  % Setter
  \method set filter(#1) {
    \pgfooset{filter}{#1}
  }

  % Setter
  \method set projection code(#1) {
    \pgfooset{projection code}{#1}
  }

  % Slot
  \method protocol() {
    \pgfdvfilterpassedtrue
    \pgfoovalueof{filter}
    \ifpgfdvfilterpassed%
      \pgf@dv@line@cache@it
    \fi%
  }

  \def\pgf@dv@line@cache@it{
    % Cache it
    \pgfooget{cache}\pgf@dv@cache
    \pgfkeysgetvalue{/data point/outlier}\pgf@temp%
    \ifx\pgf@temp\pgfutil@empty
      {%
        \pgfoovalueof{projection code}
        \xdef\pgf@dv@add{\noexpand\pgf@dv@ph{\pgfkeysvalueof{/data
              point/canvas x}}{\pgfkeysvalueof{/data point/canvas y}}}%
      }
    \else%
      % An outlier!
      \gdef\pgf@dv@add{\pgf@dv@outliner}%
    \fi%
    \expandafter\expandafter\expandafter\def%
    \expandafter\expandafter\expandafter\pgf@dv@cache%
    \expandafter\expandafter\expandafter{\expandafter\pgf@dv@cache\pgf@dv@add}%
    % Possibly flush cache
    \global\advance\pgf@lib@dv@cache@count by1\relax%
    \ifnum\pgf@lib@dv@cache@count=100\relax%
      \global\pgf@lib@dv@cache@count=0\relax%
      % Append cache to positions
      \pgfooget{positions}\pgf@dv@temp
      \expandafter\expandafter\expandafter\def%
      \expandafter\expandafter\expandafter\pgf@dv@temp%
      \expandafter\expandafter\expandafter{\expandafter\pgf@dv@temp\pgf@dv@cache}%
      \pgfoolet{positions}\pgf@dv@temp
      \let\pgf@dv@cache\pgfutil@empty
    \fi
    \pgfoolet{cache}\pgf@dv@cache
  }
 
  % Slot
  \method phase(#1) {%
    \ifx#1\pgfdvendvisualization%
      \pgfoothis.render()%
    \fi%
  }

  % Internal method
  \method render() {
    \pgfscope
      \pgfooget{handlers}\tikz@dv@temp@list
      \foreach\tikz@dv@temp in\tikz@dv@temp@list{
        \ifx\tikz@dv@temp\pgfutil@empty
        \else
          \pgfkeysvalueof{/data point/\pgfoovalueof{name}/execute at begin}
          \tikz@dv@temp
          \pgfdvnewstreamtrue
          \pgfoovalueof{positions}
          \pgfoovalueof{cache}
          \ifpgfdvnewstream\else\pgfplotstreamend\fi
          \pgfkeysvalueof{/data point/\pgfoovalueof{name}/execute at end}
        \fi
      }
    \endpgfscope
    \pgfoolet{positions}\pgfutil@empty
    \pgfoolet{cache}\pgfutil@empty
  }

  \def\pgf@dv@ph#1#2{\ifpgfdvnewstream\pgfplotstreamstart\pgfdvnewstreamfalse\fi\pgfplotstreampoint{\pgfqpoint{#1}{#2}}}
  \def\pgf@dv@outliner{\ifpgfdvnewstream\else\pgfplotstreamend\pgfdvnewstreamtrue\fi}
}

\newif\ifpgfdvnewstream
\newcount\pgf@lib@dv@cache@count

\pgfkeys{%
  /data point/outlier/.initial=,
  /data point/outlier/.default=true
}


% A possible filter for unnamed visualizers
%
% #1 = Text to be compared with key /data point/set
%
% Description:
%
% In a data visualization with multiple visualizers, data points
% typically "belong" only to a single visualizer. It is, thus,
% necessary to filter data points accoring to the current
% visualizer. This current visualizer is assumed to be stored in /data
% point/visualizer.
% 
% When objects allow you to set a filter, you can use this filter to
% test against /data point/set being equal to #1.

\def\pgfdvvisualizerfilter#1{%
  \pgfkeysgetvalue{/data point/set}\pgf@dv@visualizer%
  \def\pgf@temp{#1}%
  \ifx\pgf@temp\pgf@dv@visualizer%
  \else
    \pgfdvfilterpassedfalse
  \fi%
}



% A filter for named visualizer
% 
% Description:
% 
% This filter works like \pgfdvvisualizerfilter, only it assumes the
% the object defines a "name" attribute. In this case, the value of
% /data point/set is tested against this attribute.

\def\pgfdvnamedvisualizerfilter{%
  \pgfkeysgetvalue{/data point/set}\pgf@dv@visualizer%
  \pgfooget{name}\pgf@temp%
  \ifx\pgf@temp\pgf@dv@visualizer%
  \else
    \pgfdvfilterpassedfalse
  \fi%
}



\pgfooclass{rectangle visualizer}
{
  % Class rectangle visualizer
  %
  % This visualizer visualizes a datapoint as a rectangle. It needs
  % a name, so that /data point/<name>/attribute 1 and /data
  % point/<name>/attribute 2 store two attributes names a1 to a2. Then,
  % provided the current value of /data point/set equals name, for
  % each data point a rectangle between (a1/min,a2/min) and
  % (a1/max,a2/max) is created. 
  

  \attribute name;
  % The name
  
  \attribute a1;
  \attribute a2;
  % The attributes, filled from /data point/<name>/attribute 1 and 2

  
  % Constructor
  %
  % #1 = first attribute 
  % #2 = second attribute 
  %
  \method rectangle visualizer(#1) {
    \pgfooset{name}{#1}
  }

  % Method
  \method default connects() {
    \pgfoothis.get handle(\pgf@dv@me)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\pgf@dv@me,visualize,visualize datapoint signal)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\pgf@dv@me,phase,phase signal)
  }
    
  % Slot
  \method phase(#1) {%
    \ifx#1\pgfdvbeginsurvey%
      \pgfooeset{a1}{/data point/\pgfkeysvalueof{/data point/\pgfoovalueof{name}/attribute 1}}
      \pgfooeset{a2}{/data point/\pgfkeysvalueof{/data point/\pgfoovalueof{name}/attribute 2}}
      \pgfkeyssetvalue{\pgfoovalueof{a1}/sub attributes}{\pgfdvsub{/min}\pgfdvsub{/max}}
      \pgfkeyssetvalue{\pgfoovalueof{a2}/sub attributes}{\pgfdvsub{/min}\pgfdvsub{/max}}
    \fi%
  }
  
  % Slot
  \method visualize() {
    {
      \pgfkeysgetvalue{/data point/set}\pgf@dv@visualizer%
      \pgfooget{name}\pgf@temp%
      \ifx\pgf@temp\pgf@dv@visualizer%
        \pgf@dv@rect@do
      \fi
    }
  }

  \def\pgf@dv@rect@do{
      \pgfkeysgetvalue{\pgfoovalueof{a1}/min}\pgf@dv@amin
      \ifx\pgf@dv@amin\relax\else\ifx\pgf@dv@amin\pgfutil@empty\else
      \pgfkeysgetvalue{\pgfoovalueof{a1}/max}\pgf@dv@amax
      \ifx\pgf@dv@amax\relax\else\ifx\pgf@dv@amax\pgfutil@empty\else
      \pgfkeysgetvalue{\pgfoovalueof{a2}/min}\pgf@dv@bmin
      \ifx\pgf@dv@bmin\relax\else\ifx\pgf@dv@bmin\pgfutil@empty\else
      \pgfkeysgetvalue{\pgfoovalueof{a2}/max}\pgf@dv@bmax
      \ifx\pgf@dv@bmax\relax\else\ifx\pgf@dv@bmax\pgfutil@empty\else
      \pgfkeysvalueof{/data point/\pgfoovalueof{name}/execute at begin}
        \pgfkeyssetvalue{\pgfoovalueof{a1}}{\pgf@dv@amin}
        \pgfkeyssetvalue{\pgfoovalueof{a2}}{\pgf@dv@bmin}
        \pgfpathdvmoveto
        \pgfkeyssetvalue{\pgfoovalueof{a2}}{\pgf@dv@bmax}
        \pgfpathdvlineto
        \pgfkeyssetvalue{\pgfoovalueof{a1}}{\pgf@dv@amax}
        \pgfpathdvlineto
        \pgfkeyssetvalue{\pgfoovalueof{a2}}{\pgf@dv@bmin}
        \pgfpathdvlineto
        \pgfkeyssetvalue{\pgfoovalueof{a1}}{\pgf@dv@amin}
        \pgfpathdvlineto
        \pgfpathclose
      \pgfkeysvalueof{/data point/\pgfoovalueof{name}/execute at end}
      \fi\fi
      \fi\fi
      \fi\fi
      \fi\fi
  }
}

\newcount\pgf@lib@dv@cache@count



%
% Label positioning classes
%

\pgfooclass{label visualizer}
{
  % Class label visualizer
  %
  % The job of this class is to visualize a label of a curve or some
  % other object.
  % 
  % The idea is as follows: This class monitors a certain
  % attribute. When this attribute reaches a certain value for the
  % first time, the following happens: A normalized vector of the line
  % connecting the current canvas position to the canvas position of
  % the previous data point is computed and stored in pgf@x/pgf@y. The
  % coordinate system is shifted so that the current data point is at
  % the origin. Then, some drawing code is executed.

  \attribute attribute;
  % The monitored attribute

  \attribute filter;
  % Filter code, see plot handler visualizer doc.
      
  \attribute threshold;
  % When the attribute exceeds this threshold, the drawing code is
  % executed

  \attribute before canvas position=;
  % Stores canvas position of the data point before the interesting one
  
  \attribute canvas position=;
  % Stores canvas position of the data point

  \attribute code;
  % To-be-executed code when the label should be drawn
  
  
  % Constructor
  %
  % #1 = attribute 
  % #2 = a macro, storing the threshold
  % #3 = code
  % #4 = filter code
  %
  \method label visualizer(#1,#2,#3,#4) {
    \pgfooset{attribute}{#1}
    \expandafter\pgfdvmathenter\expandafter{\expandafter\pgf@temp\expandafter}\expandafter{#2}
    \pgfoolet{threshold}\pgf@temp
    \pgfooset{code}{#3}
    \pgfooset{filter}{#4}
  }

  % Method
  \method default connects() {
    \pgfoothis.get handle(\pgf@dv@me)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\pgf@dv@me,test,visualize datapoint signal)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\pgf@dv@me,phase,phase signal)
  }

  % Slot
  \method test() {
    \pgfdvfilterpassedtrue
    \pgfoovalueof{filter}
    \ifpgfdvfilterpassed%
      \pgfooget{attribute}\pgf@dv@attribute
      \ifx\pgf@dv@attribute\pgfutil@empty%
      % nothing to do (anymore)
      \else%
        \pgf@dv@label@vis@record
      \fi%
    \fi%
  }

  \def\pgf@dv@label@vis@record{
    % Record current position
    \edef\pgf@dv@pos{%
      \noexpand\pgfqpoint%
      {\pgfkeysvalueof{/data point/canvas x}}%
      {\pgfkeysvalueof{/data point/canvas y}}}%
    \pgfooget{canvas position}\pgf@dv@temp%
    \pgfoolet{before canvas position}\pgf@dv@temp%
    \pgfoolet{canvas position}\pgf@dv@pos%
    % Now check threshold
    \pgfooget{threshold}\pgf@dv@thres%
    \ifx\pgf@dv@thres\pgfutil@empty%
    \else%
      % Hmm, have to check, whether the value is, indeed, correct
      \pgfkeysgetvalue{/data point/\pgfoovalueof{attribute}}\pgf@dv@val
      \ifx\pgf@dv@val\relax%
      \else\ifx\pgf@dv@val\pgfutil@empty%
      \else%
        \pgfdvmathenter{\pgf@dv@value}{\pgf@dv@val}%
        \pgfooget{threshold}{\pgf@dv@thres}
        % Now, protocol value
        \pgfdvmathifless{\pgf@dv@value}{\pgf@dv@thres}{}{%
          \pgfoolet{attribute}\pgfutil@empty% Stop!
        }%
      \fi\fi%
    \fi%
  }
  
  % Slot
  \method phase(#1) {%
    \ifx#1\pgfdvendvisualization%
      \scope
        \pgfcoordinate{label visualizer coordinate}{\pgfoovalueof{canvas position}}
        \pgfcoordinate{label visualizer coordinate'}{\pgfoovalueof{before canvas position}}
        \pgfoovalueof{code}
      \endscope
    \fi%
  }

}



%
% Style sheets
%
\pgfooclass{style attribute}
{
  % Class style attribute
  % 
  % Instances of this class are used to select a style based on the
  % current value of an attribute.
  % 
  % Instances of this class monitor an attribute. Whenever the "style"
  % signal is raised, the object investigates the current value of the
  % attribute. It then looks up /pgf/data visualization/style
  % sheets/<name of style sheet>/<value of the attribute> and executes
  % this key, provided it is defined. If it not defined, the key
  % /pgf/data visualization/style sheets/<name of style sheet>/default
  % style is executed with the value as a parameter.

  \attribute attribute;
  % The name of the attribute

  \attribute style sheet name;
  % The styling function

  % Constructor
  %
  % #1 = attribute (including, if present, /data point/)
  % #2 = style sheet name 
  %
  \method style attribute(#1,#2) {
    \pgfooset{attribute}{#1}
    \pgfooset{style sheet name}{#2}
  }

  % Method
  \method default connects() {
    \pgfoothis.get handle(\pgf@dv@me)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\pgf@dv@me,invoke style,style signal)
  }

  % Slots
  \method invoke style() {
    \pgfooget{attribute}\pgf@dv@temp
    \pgfkeysgetvalue{\pgf@dv@temp}\pgf@dv@temp@val
    \ifx\pgf@dv@temp@val\pgfutil@empty%do nothing
    \else\ifx\pgf@dv@temp@val\relax%do nothing
    \else%
      \pgfkeysifdefined{\pgf@dv@temp/\pgf@dv@temp@val}{\pgfkeysgetvalue{\pgf@dv@temp/\pgf@dv@temp@val}\pgf@dv@temp@val}{}% redirect
      \edef\pgf@temp{/pgf/data visualization/style sheets/\pgfoovalueof{style sheet name}}
      \pgfkeysifassignable{\pgf@temp/\pgf@dv@temp@val}{%
        \pgfkeysalso{\pgf@temp/\pgf@dv@temp@val}}{%
        \pgfkeysalso{\pgf@temp/default style/.expand once=\pgf@dv@temp@val}
      }
    \fi\fi%
  }
}


% Declares a new style sheet
% 
% #1 = name of style sheet 
% #2 = settings
% 
% Description:
% 
% This is a shortcut for doing a /.cd to /pgf/data visualization/style sheets/#1

\def\pgfdvdeclarestylesheet#1#2{
  \pgfkeys{/pgf/data visualization/style sheets/#1/.cd,#2}
}









%
% Legend container class
%

\pgfooclass{legend}
{
  % Class legend
  % 
  % This class is used to collect entries into a legend. The idea is
  % that, say, for each line of a picture you would like to have an
  % entry in a legend. Then you prepare these entries and send
  % them to a legend container object. It will collect the entries
  % and, at the end, arrange them in rows and columns by 
  % separating them using \pgfdvnextcell and \pgfdvendrow.
  %
  % By surrounding the resulting arrangement by a call to \pgfmatrix or
  % a call to \halign you can then create a legend.
  % 
  % To specify how the entries should be arranged, a size
  % specification and two directions are needed.
  % 
  % For the size specification you specify either the ideal number of
  % columns and the maximum number of rows or you specify the ideal
  % number of rows and the maximum number of columns. In the first
  % case, the class first tries to create as many columns as specified
  % by the "ideal" parameter. If there are less entries than this
  % parameter, you obviously get less columns, namely as many as there
  % are entries, each column containing only one entry. If there are
  % more entries that the ideal number of columns, you get multiple
  % columns, each containing as many entries to make sure that the
  % ideal number is met. However, if a column would get more than the
  % specified maximum number of elements per column, you get more
  % columns that the ideal number -- to ensure that no column contains
  % more than the desired number. The case is symmetric, but with the
  % roles of columns and rows exchanged.
  % 
  % Here is an example: You specify that you want 2 columns, ideally,
  % each having a maximum of 4 entries. Here is what you would get:
  % 
  % Number of entries & Number of resulting columns ... & ... and rows
  % 1                 & 1                               & 1
  % 2                 & 2                               & 1
  % 3                 & 2                               & 2
  % 4                 & 2                               & 2
  % 5                 & 2                               & 3
  % 6                 & 2                               & 3
  % 7                 & 2                               & 4
  % 8                 & 2                               & 4
  % 9                 & 3                               & 4
  % 10                & 3                               & 4
  % 11                & 3                               & 4
  % 12                & 3                               & 4
  % 13                & 4                               & 4
  %
  % 
  % Once the number of columns and rows has been computed, the next
  % step is to "fill" the table. For this, eight strategies may be
  % specified: right then down, right then up, left then down, left
  % then up, up then right, up then left, down then right, down then
  % left. A strategy like "right then up" means the following: Each
  % new entry should placed right of the previous entry in the
  % arrangement. However, once the maximum number of elements in a row
  % has been reached, the a new row should be started that is placed
  % above ("up") then just-assembled row.
  % 
  % 
  %  
  %
  % Example:
  % 
  % You create an object \legend and then call
  % 
  % \pgfoofnew \legend=new legend(columns,2,3,down then right)
  % \legend.add entry(first)
  % \legend.add entry(second)
  % \legend.add entry(third)
  % \legend.add entry(fourth)
  % \legend.add entry(fifth)
  % \legend.add entry(sixth)
  % \legend.add entry(seventh)
  % \legend.get arrangment(\arrangement)
  % 
  % Then \arrangment will expand to
  % 
  %   first  \pgfdvnextcell   fourth  \pgfdvnextcell  seventh  \pgfdvendrow
  %   second \pgfdvnextcell   fifth   \pgfdvnextcell  third    \pgfdvendrow
  %   third  \pgfdvendrow   sixth   \pgfdvnextcell           \pgfdvendrow
  %   
  % By saying \let\pgfdvendrow=\\ and \let\pgfdvnextcell=&, you
  % can use \arrangment inside a table.
  
  
  \attribute entries;
  % Collectes the entries

  \attribute columns or rows;
  % Specifies whether columns or rows are specified

  \attribute ideal;
  % The ideal number of columns/rows

  \attribute max;
  % The maximum number of entries per column/row

  \attribute strategy;
  % Specifies how the matrix should be filled
  
  \attribute number of entries=0;
  % Counts the number of entries that have been stored
  
  
  % Constructor
  %
  % #1 = "columns" or "rows" -> specifies whether the ideal number and
  %      the max entries number refer to columns or the row
  % #2 = the ideal number of #1's
  % #3 = the maximum number of entries in a #1
  % #4 = one of the eight strategies
  %
  \method legend(#1,#2,#3,#4) {
    \pgfooset{columns or rows}{#1}
    \pgfooset{ideal}{#2}
    \pgfooset{max}{#3}
    \pgfooset{strategy}{#4}
  }

  % Method
  \method default connects() {
  }

  % Method
  \method add entry(#1) {
    \pgfooappend{entries}{{#1}}
    \c@pgf@counta=\pgfoovalueof{number of entries}\relax%
    \advance\c@pgf@counta by1\relax%
    \pgfooeset{number of entries}{\the\c@pgf@counta}
  }

  % Method
  \method get arrangement(#1) {
    {
      % 
      % Step 1: Compute the desired number of rows or columns
      % 
      % 
      % Compute the ideal number of entries per row/column (called
      % "target" in the following) and entries per colum/row (called
      % "per target" in the following)
      % 
      % if (number of entries > ideal)
      \ifnum\pgfoovalueof{number of entries}>\pgfoovalueof{ideal}\relax%
      % {
        % if (ideal * max > number of entries)
        \c@pgf@counta=\pgfoovalueof{ideal}\relax%
        \multiply\c@pgf@counta by\pgfoovalueof{max}\relax%
        \ifnum\c@pgf@counta>\pgfoovalueof{number of entries}\relax
        % {
        %   target = ideal;
        %   per target = ceil (number of entries / ideal);
          \c@pgf@counta=\pgfoovalueof{ideal}\relax%
          \c@pgf@countb=\pgfoovalueof{number of entries}\relax
          \advance\c@pgf@countb by-1\relax
          \divide\c@pgf@countb by\c@pgf@counta\relax%
          \advance\c@pgf@countb by1\relax%
        % }
        % else
        % {
        %   target = ceil(number of entries / max);
        %   per target = max;
        \else
          \c@pgf@countb=\pgfoovalueof{max}\relax%
          \c@pgf@counta=\pgfoovalueof{number of entries}\relax
          \advance\c@pgf@counta by-1\relax
          \divide\c@pgf@counta by\c@pgf@countb\relax%
          \advance\c@pgf@counta by1\relax%
        \fi
        % }
      % }
      % else
      % {
      %   target = number of entries;
      %   per target = 1;
      % }
      \else
        \c@pgf@counta=\pgfoovalueof{number of entries}\relax%
        \c@pgf@countb=1\relax%
      \fi%
      % 
      % Ensure that counta = rows, countb = columns 
      % 
      \pgfooget{columns or rows}\pgf@temp
      \ifx\pgf@temp\pgf@dv@columnstext%
        \c@pgf@countc=\c@pgf@counta\relax
        \c@pgf@counta=\c@pgf@countb\relax
        \c@pgf@countb=\c@pgf@countc\relax
      \fi
      \edef\temp{rows: \the\c@pgf@counta, columns: \the\c@pgf@countb}\temp
      % 
      % Now arrange the matrix 
      % 
      \csname pgf@dv@legend@init@\pgfoovalueof{strategy}\endcsname
      \expandafter\let\expandafter\pgf@dv@updater\csname pgf@dv@legend@update@\pgfoovalueof{strategy}\endcsname
      \pgfooget{entries}\pgf@temp
      \expandafter\pgf@dv@legend@arrange\pgf@temp\pgf@stop
      % 
      % Now assemble the matrix
      %
      \edef\pgf@dv@row@list{1,...,\the\c@pgf@counta}
      \edef\pgf@dv@column@list{1,...,\the\c@pgf@countb}
      \global\let\pgf@dv@matrix\pgfutil@empty
      \foreach \pgf@dv@row in \pgf@dv@row@list
      {
        \global\let\pgf@dv@matrix@row\pgf@dv@first@mark
        \foreach \pgf@dv@column in \pgf@dv@column@list
        {
          \expandafter\let\expandafter\pgf@temp\csname pgf@dv@legend@entry@\pgf@dv@row @\pgf@dv@column\endcsname
          \ifx\pgf@temp\relax
            \let\pgf@temp\pgfutil@empty
          \fi
          \ifx\pgf@dv@matrix@row\pgf@dv@first@mark
            \global\let\pgf@dv@matrix@row\pgf@temp
          \else
            \expandafter\pgfutil@g@addto@macro\expandafter\pgf@dv@matrix@row\expandafter{\expandafter\pgfdvnextcell\pgf@temp}
          \fi
        }
        \pgfutil@g@addto@macro\pgf@dv@matrix@row{\pgfdvendrow}
        \expandafter\pgfutil@g@addto@macro\expandafter\pgf@dv@matrix\expandafter{\pgf@dv@matrix@row}
      }
      \global\let\pgf@dv@matrix@row\relax
    }
    \let#1\pgf@dv@matrix
    \global\let\pgf@dv@matrix\relax
  }
  
  \def\pgf@dv@first@mark{\pgf@dv@first@mark}
  
  \def\pgf@dv@legend@arrange{%
    \pgfutil@ifnextchar\pgf@stop{\pgfutil@gobble}{\pgf@dv@legend@handle@entry}
  }

  \def\pgf@dv@legend@handle@entry#1{
    \expandafter\def\csname pgf@dv@legend@entry@\the\c@pgf@countc @\the\c@pgf@countd\endcsname{#1}%
    \pgf@dv@updater%
    \pgf@dv@legend@arrange%
  }

  \expandafter\def\csname pgf@dv@legend@init@down then right\endcsname{%
    \c@pgf@countc=1\relax%
    \c@pgf@countd=1\relax%
  }

  \expandafter\def\csname pgf@dv@legend@update@down then right\endcsname{%
    \advance\c@pgf@countc by1\relax
    \ifnum\c@pgf@countc>\c@pgf@counta\relax%
      \c@pgf@countc=1\relax%
      \advance\c@pgf@countd by1\relax%
    \fi%
  }  

  \expandafter\def\csname pgf@dv@legend@init@right then down\endcsname{%
    \c@pgf@countc=1\relax%
    \c@pgf@countd=1\relax%
  }
  
  \expandafter\def\csname pgf@dv@legend@update@right then down\endcsname{%
    \advance\c@pgf@countd by1\relax
    \ifnum\c@pgf@countd>\c@pgf@countb\relax%
      \c@pgf@countd=1\relax%
      \advance\c@pgf@countc by1\relax%
    \fi%
  }

  \expandafter\def\csname pgf@dv@legend@init@up then right\endcsname{%
    \c@pgf@countc=\c@pgf@counta\relax%
    \c@pgf@countd=1\relax%
  }

  \expandafter\def\csname pgf@dv@legend@update@up then right\endcsname{%
    \advance\c@pgf@countc by-1\relax
    \ifnum\c@pgf@countc=0\relax%
      \c@pgf@countc=\c@pgf@counta\relax%
      \advance\c@pgf@countd by1\relax%
    \fi%
  }  
  
  \expandafter\def\csname pgf@dv@legend@init@right then up\endcsname{%
    \c@pgf@countc=\c@pgf@counta\relax%
    \c@pgf@countd=1\relax%
  }

  \expandafter\def\csname pgf@dv@legend@update@right then up\endcsname{%
    \advance\c@pgf@countd by1\relax
    \ifnum\c@pgf@countd>\c@pgf@countb\relax%
      \c@pgf@countd=1\relax%
      \advance\c@pgf@countc by-1\relax%
    \fi%
  }  
  
  \expandafter\def\csname pgf@dv@legend@init@left then up\endcsname{%
    \c@pgf@countc=\c@pgf@counta\relax%
    \c@pgf@countd=\c@pgf@countb\relax%
  }

  \expandafter\def\csname pgf@dv@legend@update@left then up\endcsname{%
    \advance\c@pgf@countd by-1\relax
    \ifnum\c@pgf@countd=0\relax%
      \c@pgf@countd=\c@pgf@countb\relax%
      \advance\c@pgf@countc by-1\relax%
    \fi%
  }
  
  \expandafter\def\csname pgf@dv@legend@init@up then left\endcsname{%
    \c@pgf@countc=\c@pgf@counta\relax%
    \c@pgf@countd=\c@pgf@countb\relax%
  }

  \expandafter\def\csname pgf@dv@legend@update@up then left\endcsname{%
    \advance\c@pgf@countc by-1\relax
    \ifnum\c@pgf@countc=0\relax%
      \c@pgf@countc=\c@pgf@counta\relax%
      \advance\c@pgf@countd by-1\relax%
    \fi%
  }
  
  \expandafter\def\csname pgf@dv@legend@init@left then down\endcsname{%
    \c@pgf@countc=1\relax%
    \c@pgf@countd=\c@pgf@countb\relax%
  }

  \expandafter\def\csname pgf@dv@legend@update@left then down\endcsname{%
    \advance\c@pgf@countd by-1\relax
    \ifnum\c@pgf@countd=0\relax%
      \c@pgf@countd=\c@pgf@countb\relax%
      \advance\c@pgf@countc by1\relax%
    \fi%
  }
  
  \expandafter\def\csname pgf@dv@legend@init@down then left\endcsname{%
    \c@pgf@countc=1\relax%
    \c@pgf@countd=\c@pgf@countb\relax%
  }

  \expandafter\def\csname pgf@dv@legend@update@down then left\endcsname{%
    \advance\c@pgf@countc by1\relax
    \ifnum\c@pgf@countc>\c@pgf@countb\relax%
      \c@pgf@countc=1\relax%
      \advance\c@pgf@countd by-1\relax%
    \fi%
  }
  
  \def\pgf@dv@columnstext{columns}
}       



%
% Help classes
%

\pgfooclass{interval}
{
  % Class interval
  %
  % Instances of this class store intervals. When either the min or
  % the max value is empty, this corresponds to "not yet set", (not to
  % "infinity). 

  \attribute min;
  % The minimum value of the interval
  
  \attribute max;
  % The maximum value of the interval

  % Constructor
  %
  % #1 = initial minimum value
  % #2 = initial maximum value
  %
  \method interval(#1,#2) {
    \pgfooset{min}{#1}
    \pgfooset{max}{#2}
  }

  % Method
  \method default connects() {
  }

  % Sets the minimum/maximum to a new value
  \method set min(#1) {
    \pgfooset{min}{#1}
  }  
  \method set max(#1) {
    \pgfooset{max}{#1}
  }
  \method let min(#1) {
    \pgfoolet{min}{#1}
  }  
  \method let max(#1) {
    \pgfoolet{max}{#1}
  }

  % Getter
  %
  % Returns the current values of the minimum and maximum in the
  % macros \pgfdvmin and \pgfdvmax.
  \method get min and max() {
    \pgfooget{min}\pgfdvmin
    \pgfooget{max}\pgfdvmax
  }

  % Adjusts the mimum and maximum values
  %
  % #1 = some code. When this code is executed, the values of
  %      \pgfdvmin and \pgfdvmax will be set to the current values of
  %      the minimum/maximum. The code may change these values. The
  %      changed values will then be stored.
  %
  % This method does nothing that cannot be achieved also by calling
  % set/get methods, but it is easier to use and faster.
  \method adjust(#1) {
    {%
      \pgfooget{min}\pgfdvmin
      \pgfooget{max}\pgfdvmax
      #1%
      \pgfoolet{min}\pgfdvmin
      \pgfoolet{max}\pgfdvmax
    }%
  }
}



\pgfooclass{count}
{
  % Class count
  %
  % This class can be used to count the number of data points that are
  % present or that have a certain property. By default, for every
  % data point a counter is incremented and the value of this counter
  % is stored in an attribute. You can also specify an increment for
  % the counter. You can specify that certain data points should
  % not have an effect on the counter.

  
  \attribute attribute;
  % The attribute that will be set to the current value of the counter
  
  \attribute val=0;
  % The current value of the counter
  
  \attribute max=0;
  % The current value of the counter
  
  \attribute step=1;
  % The stepping by which the counter is incremented for each
  % datapoint
  
  \attribute start val=0;
  % The start value of the counter

  \attribute filter=;
  % This attribute stores some code that is executed for each
  % data point. If the data point sets the TeX-if ifpgfdvfilterpassed to
  % true, then the counter is not incremented.

  
  % Constructor
  %
  % #1 = The attribute in which the counter value is stored
  %
  \method count(#1) {
    \pgfooset{attribute}{#1}
  }

  % Method
  \method default connects() {
    \pgfoothis.get handle(\pgf@dv@me)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\pgf@dv@me,apply,prepare datapoint signal)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\pgf@dv@me,phase,phase signal)
  }

  % Getter
  \method get max(#1) {
    \pgfooget{max}{#1}
  }

  % Setter
  \method set value(#1) {
    \pgfooset{val}{#1}
    \pgfkeyssetvalue{/data point/\pgfoovalueof{attribute}}{#1}%
  }

  % Setter
  \method set start value(#1) {
    \pgfooset{start val}{#1}
    \pgfooset{max}{#1}
  }

  % Setter
  \method set filter(#1) {
    \pgfooset{filter}{#1}
  }

  % Setter
  \method set step(#1) {
    \pgfooset{step}{#1}
  }

  % Slot
  \method apply() {
    \pgfdvfilterpassedtrue%
    \pgfoovalueof{filter}%
    \ifpgfdvfilterpassed%
      \pgfmathparse{\pgfoovalueof{val}+\pgfoovalueof{step}}%
      \pgfoolet{val}\pgfmathresult%
      \pgfkeyslet{/data point/\pgfoovalueof{attribute}}\pgfmathresult%
      \ifdim\pgfmathresult pt>\pgfoovalueof{max}pt\relax%
        \pgfoolet{max}\pgfmathresult%
      \fi%
      \pgfooget{max}\pgfmathresult%
      \pgfkeyslet{/data point/\pgfoovalueof{attribute}/max}\pgfmathresult%
    \fi%
  }

  % Slot 
  \method phase(#1) {
    \ifx#1\pgfdvbeginsurvey
      \pgfooeset{val}{\pgfoovalueof{start val}}
    \else \ifx#1\pgfdvbeginvisualization
      \pgfooeset{val}{\pgfoovalueof{start val}}
    \fi\fi
  }
}

\newif\ifpgfdvfilterpassed




\pgfooclass{accumulator}
{
  % Class accumulator
  %
  % This class is used to keep track of the sum of the values of some
  % attribute. When this object is connected to some attribute, the
  % subkey attribute/sum will always contain the sum of all values in
  % all previous data points with respect to this
  % attribute. Furthermore, the subkey attribute/prev key will hold
  % the previous sum, which is sometimes also useful to have access
  % to. 

  \attribute attribute;
  % The attribute to-be-accumulated
  
  \attribute sum;
  % The initial value of the sum

  % Constructor
  %
  % #1 = to-be-accumulated attribute
  \method accumulator(#1) {
    \pgfooset{attribute}{#1}
    \pgfoothis.reset()
  }

  % Method
  \method default connects() {
    \pgfoothis.get handle(\pgf@dv@me)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\pgf@dv@me,apply,prepare datapoint signal)
    \pgfkeysvalueof{/pgf/data visualization/obj}.connect(\pgf@dv@me,phase,phase signal)
  }

  % Slot
  \method apply() {%
    % Save old sum
    \pgfkeysgetvalue{/data point/\pgfoovalueof{attribute}/sum}\pgf@temp%    
    \pgfkeyslet{/data point/\pgfoovalueof{attribute}/prev sum}\pgf@temp%
    % Add new attribute...
    \pgfkeysgetvalue{/data point/\pgfoovalueof{attribute}}{\pgf@temp@b}%
    \pgfdvmathenter{\pgf@dv@new@val}{\pgf@temp@b}%
    % ... to sum
    \pgfooget{sum}\pgf@dv@sum%
    \pgfdvmathadd{\pgf@dv@sum}{\pgf@dv@new@val}{\pgf@dv@sum}%
    \pgfoolet{sum}\pgf@dv@sum
    % Record in attribute
    \pgfdvmathexitbyscientificformat{\pgf@dv@serial@sum}{\pgf@dv@sum}
    \pgfkeyslet{/data point/\pgfoovalueof{attribute}/sum}\pgf@dv@serial@sum
  }

  % Method
  %
  % Use this method to reset the sum at any point.
  %
  \method reset() {
    \pgfdvmathenter{\pgf@dv@temp}{0}
    \pgfoolet{sum}{\pgf@dv@temp}
    \pgfdvmathexitbyserializing{\pgf@dv@zero}{\pgf@dv@temp}
    \pgfkeyslet{/data point/\pgfoovalueof{attribute}/prev sum}{\pgf@dv@zero}
    \pgfkeyslet{/data point/\pgfoovalueof{attribute}/sum}{\pgf@dv@zero}
  }

  % Slot
  \method phase(#1) {
    \ifx#1\pgfdvbeginsurvey
      \pgfoothis.reset()
    \else \ifx#1\pgfdvbeginvisualization
      \pgfoothis.reset()
    \fi\fi
  }
}







%
%
% Help keys and, attributes
%
%

\pgfkeys{% do not even think of changing the values of the following:
  /data point/always true/.initial=true,
  /data point/always false/.initial=false,
  /data point/always 0/.initial=0,
  /data point/always 1/.initial=1,
  /data point/always empty/.initial=,
  /data point/always pgfusepath stroke/.initial=\pgfusepath{stroke}
}

\pgfdvmathenter{\pgfdvmathalwaysloge}{0.434294481903252}
\pgfdvmathenter{\pgfdvmathalwayslnten}{2.302585092994046}
\pgfdvmathenter{\pgfdvmathalwayszero}{0}
\pgfdvmathenter{\pgfdvmathalwaysone}{1}


\endinput







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

pgfmodulenonlineartransformations.code.tex
% Copyright 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[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/modules/pgfmodulenonlineartransformations.code.tex,v 1.4 2013/10/09 18:30:27 tantau Exp $


%
% This file defines commands for nonlinear coordinate systems. This is
% needed, for instance, for bend arrow heads.
%
%
% Non-linear coordinate systems transform coordinates, in addition to
% the normal linear transformations, in a, well, non-linear way. An
% example are polar coordinates.
%
% Like the linear transformations, non-linear transformations are
% applied on a low level and they are integrated into the whole path
% construction mechanism. So, while \pgfpointpolar also "does
% something nonlinear", it just provides a way of computing a
% coordinate. In contrast, installing a polar transformation will
% transform everything being drawn using the \pgfpath... commands an
% will even turn a straight line into a circle. 
%
% Since computing non-linear transformations is expensive, they are
% only applied "if really necessary".




% Return a transformed point
%
% #1 = a point
%
% Description:
%
% Applies the current transformation and the current nonlinear
% transformation to the given point and returns the result in \pgf@x/y.

\def\pgfpointtransformednonlinear#1{%
  \pgf@process{%
    #1%
    \pgf@pos@transform{\pgf@x}{\pgf@y}%
    \pgf@nlt@list%
  }
}




% Approximate the nonlinear translation locally
%
% Description:
%
% Does a "local syncronization" of the nonlinear transformation with
% the linear transformation regarding the translation part of the
% current nonlinear transformatoin. The *linear* transformation will be
% updated so that it translates things to the point to which the
% nonlinear transformation transforms the origin. The nonlinear
% transformation will be reset.
% 
% The net effect is that you can now draw things near the origin as
% before, but with just a linear transformation in force. Note that
% the coordinate system will not be rotated, only a shift is done (use
% the "real" local sync for a full sync).

\def\pgfapproximatenonlineartranslation{%
  \ifx\pgf@nlt@list\pgfutil@empty%
  \else%
    \pgfpointtransformednonlinear{\pgfpointorigin}%
    \pgf@pt@x=\pgf@x%
    \pgf@pt@y=\pgf@y%
    \let\pgf@nlt@list\pgfutil@empty%
    \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%
  \fi%
}



% Local sync translation
%
% Description:
%
% Does a "complete local syncronization" of the nonlinear
% transformation with the linear transformation. The *linear*
% transformation will be updated so that it transforms things to the
% point to which the nonlinear transformation transforms the
% origin. The nonlinear transformation will be reset.
% 
% The net effect is that you can now draw things near the origin as
% before, but with just a linear transformation in force. 

\def\pgfapproximatenonlineartransformation{%
  \ifx\pgf@nlt@list\pgfutil@empty%
  \else%
    \pgfpointtransformednonlinear{\pgfpoint{1pt}{0pt}}%
    \pgf@xa\pgf@x
    \pgf@ya\pgf@y
    \pgfpointtransformednonlinear{\pgfpoint{0pt}{1pt}}%
    \pgf@xb\pgf@x
    \pgf@yb\pgf@y
    \pgfpointtransformednonlinear{\pgfpointorigin}%
    \advance\pgf@xa by-\pgf@x
    \advance\pgf@xb by-\pgf@x
    \advance\pgf@ya by-\pgf@y
    \advance\pgf@yb by-\pgf@y
    \pgfsettransformentries{\pgf@sys@tonumber\pgf@xa}{\pgf@sys@tonumber\pgf@ya}{\pgf@sys@tonumber\pgf@xb}{\pgf@sys@tonumber\pgf@yb}{\pgf@x}{\pgf@y}%
    \let\pgf@nlt@list\pgfutil@empty%
    \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%
  \fi%
}



% Adds a non-linear transformation to the current list of
% transformations. 
%
% #1 = code
%
% Description:
%
% When the code #1 is called, \pgf@x and \pgf@y will be set to some 
% values, let us call this the point p. The nonlinear transformation
% will now map this point to a new point f(p). The coordinates of this
% point shoudl be returned in \pgf@x and \pgf@y. Furthermore, consider
% the two "unit tangents" (going in $x$-direction and in
% $y$-direction) at point p. The nonlinear transformaiton will map
% these to new tangents, t_x and t_y. The (not necessarily normalized)
% vectors t_x and t_y should be returned in pgf@xa and -ya and pgf@xb
% and pgf@yb. The macro should not do any global assignments except to
% \pgf@x and \pgf@y, but may do arbitrary local assignments.
% 
% The effect of installing a new transformation is the following: As
% long as there is at least one nonlinear transformation installed,
% whenever the path construction commands add a curve or line to the
% softpath, the line or curve will be "bend" by applying all of the
% nonlinear transformation installed. In particular, straight lines
% will be replaced by curves.
% 
% Note that the normal linear transformation are always applied before
% any nonlinear transformations are applied.

\def\pgftransformnonlinear#1{%
  \expandafter\def\expandafter\pgf@nlt@list\expandafter{\pgf@nlt@list#1}%
  \let\pgf@nlt@moveto\pgf@nlt@moveto@nlt
  \let\pgf@nlt@lineto\pgf@nlt@lineto@nlt
  \let\pgf@nlt@curveto\pgf@nlt@curveto@nlt
  \let\pgf@nlt@closepath\pgf@nlt@closepath@nlt
}

\def\pgf@nlt@moveto@nlt#1#2{%
  {%
    \pgfutil@tempdima#1%
    \pgfutil@tempdimb#2%
    \pgf@x\pgfutil@tempdima%
    \pgf@y\pgfutil@tempdimb%
    \xdef\pgf@nlt@last@moveto@orig{{\the\pgf@x}{\the\pgf@y}}%
    \pgf@nlt@list%
    \xdef\pgf@nlt@last@moveto@trans{{\the\pgf@x}{\the\pgf@y}}%
    \xdef\pgf@nlt@last@moveto@xaxis{{\the\pgf@xa}{\the\pgf@ya}}%
    \xdef\pgf@nlt@last@moveto@yaxis{{\the\pgf@xb}{\the\pgf@yb}}%
    \pgf@protocolsizes{\pgf@x}{\pgf@y}%
    \pgfsyssoftpath@moveto{\the\pgf@x}{\the\pgf@y}%
    \global\let\pgf@nlt@last@coord@orig\pgf@nlt@last@moveto@orig%
    \global\let\pgf@nlt@last@coord@trans\pgf@nlt@last@moveto@trans%
    \global\let\pgf@nlt@last@coord@xaxis\pgf@nlt@last@moveto@xaxis%
    \global\let\pgf@nlt@last@coord@yaxis\pgf@nlt@last@moveto@yaxis%
  }%
}


\def\pgf@nlt@lineto@nlt#1#2{%
  {%
    \edef\pgf@temp{\pgf@xc\the#1\pgf@yc\the#2}%
    \pgf@temp%
    \expandafter\pgfqpoint\pgf@nlt@last@coord@orig%
    \expandafter\pgf@nlt@set@temps\pgf@nlt@last@coord@trans%
    % Test, whether the points are quite near:
    \pgf@xa\pgf@x\advance\pgf@xa by-\pgf@xc%
    \pgf@ya\pgf@y\advance\pgf@ya by-\pgf@yc%
    \pgfutil@tempswafalse%
    \ifdim\pgf@xa<0.1pt\relax\ifdim\pgf@xa>-0.1pt\relax\ifdim\pgf@ya<0.1pt\relax\ifdim\pgf@ya>-0.1pt\relax\pgfutil@tempswatrue\fi\fi\fi\fi%
    \ifpgfutil@tempswa%
      \pgf@x\pgf@xc\pgf@y\pgf@yc%
      \xdef\pgf@nlt@last@coord@orig{{\the\pgf@x}{\the\pgf@y}}%
      \pgf@process{\pgf@nlt@list}%
      \xdef\pgf@nlt@last@coord@trans{{\the\pgf@x}{\the\pgf@y}}%
      \xdef\pgf@nlt@last@coord@xaxis{{\the\pgf@xa}{\the\pgf@ya}}%
      \xdef\pgf@nlt@last@coord@yaxis{{\the\pgf@xb}{\the\pgf@yb}}%
      \pgf@protocolsizes{\pgf@x}{\pgf@y}%
      \pgfsyssoftpath@lineto{\the\pgf@x}{\the\pgf@y}%
    \else%
      % Compute support points
      \pgf@xb=.333333\pgf@x%
      \advance\pgf@xb by.666666\pgf@xc%
      \pgf@yb=.333333\pgf@y%
      \advance\pgf@yb by.666666\pgf@yc%
      \pgf@xa=.333333\pgf@xc%
      \advance\pgf@xa by.666666\pgf@x%
      \pgf@ya=.333333\pgf@yc%
      \advance\pgf@ya by.666666\pgf@y%
      \pgf@nlt@inner@curve%
    \fi%
  }%
}

\def\pgf@nlt@set@temps#1#2{%
  \pgfutil@tempdima#1\pgfutil@tempdimb#2%
}

\def\pgf@nlt@curveto@nlt#1#2#3#4#5#6{%
  {%
    \edef\pgf@temp{\pgf@xa\the#1\pgf@ya\the#2\pgf@xb\the#3\pgf@yb\the#4\pgf@xc\the#5\pgf@yc\the#6}%
    \pgf@temp%
    \pgf@nlt@inner@curve%
  }%
}

\newdimen\pgftransformnonlinearflatness
\pgftransformnonlinearflatness=5pt
\def\pgfsettransformnonlinearflatness#1{\pgfmathsetlength\pgftransformnonlinearflatness{#1}}



% Compute a curve from \pgf@nlt@last@coord@orig to \pgf@xc/\pgf@yc via the
% controls \pgf@xa/\pgf@ya and \pgf@xb/\pgf@yb.
\def\pgf@nlt@inner@curve{%
  \expandafter\pgfqpoint\pgf@nlt@last@coord@orig%
  % Save delta of supports:
  \pgfutil@tempdima\pgf@xa\advance\pgfutil@tempdima by-\pgf@xb
  \pgfutil@tempdimb\pgf@ya\advance\pgfutil@tempdimb by-\pgf@yb
  \begingroup
    % Replace supports by relative supports
    \advance\pgf@xa by-\pgf@x%
    \advance\pgf@ya by-\pgf@y%
    \advance\pgf@xb by-\pgf@xc%
    \advance\pgf@yb by-\pgf@yc%
    % 
    % Now, test whether the flatness is satisfied:
    % 
    \pgfutil@tempswafalse
    \ifdim\pgfutil@tempdima>\pgftransformnonlinearflatness\pgfutil@tempswatrue\fi%
    \ifdim\pgfutil@tempdima<-\pgftransformnonlinearflatness\pgfutil@tempswatrue\fi%
    \ifdim\pgfutil@tempdimb>\pgftransformnonlinearflatness\pgfutil@tempswatrue\fi%
    \ifdim\pgfutil@tempdimb<-\pgftransformnonlinearflatness\pgfutil@tempswatrue\fi%
    \ifdim\pgf@xa>\pgftransformnonlinearflatness\pgfutil@tempswatrue\fi%
    \ifdim\pgf@xa<-\pgftransformnonlinearflatness\pgfutil@tempswatrue\fi%
    \ifdim\pgf@ya>\pgftransformnonlinearflatness\pgfutil@tempswatrue\fi%
    \ifdim\pgf@ya<-\pgftransformnonlinearflatness\pgfutil@tempswatrue\fi%
    \ifdim\pgf@xb>\pgftransformnonlinearflatness\pgfutil@tempswatrue\fi%
    \ifdim\pgf@xb<-\pgftransformnonlinearflatness\pgfutil@tempswatrue\fi%
    \ifdim\pgf@yb>\pgftransformnonlinearflatness\pgfutil@tempswatrue\fi%
    \ifdim\pgf@yb<-\pgftransformnonlinearflatness\pgfutil@tempswatrue\fi%
  \ifpgfutil@tempswa%
    \endgroup% Undo the adjustmenst...
    {%
      \edef\pgf@orig@xya{\pgf@xa\the\pgf@xa\pgf@ya\the\pgf@ya}
      \edef\pgf@orig@xyb{\pgf@xb\the\pgf@xb\pgf@yb\the\pgf@yb}
      \edef\pgf@orig@xyc{\pgf@xc\the\pgf@xc\pgf@yc\the\pgf@yc}
      \pgfpointcurveattime{.5}%
        {\expandafter\pgfqpoint\pgf@nlt@last@coord@orig}%
        {\pgf@x\pgf@xa\pgf@y\pgf@ya}%
        {\pgf@x\pgf@xb\pgf@y\pgf@yb}%
        {\pgf@x\pgf@xc\pgf@y\pgf@yc}%
      % First new curve:
      % Start is at last@coord@orig,
      % first support is at last@coord@orig*t + s*(original xa/ya)
      % second support is at xb/yb
      % target is at x/y
      {%
        % Target:
        \pgf@xc\pgf@x\pgf@yc\pgf@y
        % First support:
        \expandafter\pgfqpoint\pgf@nlt@last@coord@orig%
        \pgf@orig@xya%
        \pgf@xa\pgf@time@s\pgf@xa\advance\pgf@xa by\pgf@time@t\pgf@x%
        \pgf@ya\pgf@time@s\pgf@ya\advance\pgf@ya by\pgf@time@t\pgf@y%
        \pgf@nlt@inner@curve%
      }%
      % Second new curve:
      % Start is at (new) last@coord@orig
      % first support is at xa/ya
      % second support is at t*(original xb/yb) + s*(original xc/yc)
      % target is at original xc/yc
      {%
        \pgf@orig@xyb%
        \pgf@orig@xyc%
        \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%
        \pgf@nlt@inner@curve%
      }%
    }%
  \else%
    \endgroup% Snap back...
    \pgf@nlt@do@inner@curve%
  \fi%
}

\def\pgf@nlt@do@inner@curve{%
  \pgf@process{\pgf@x\pgf@xa\pgf@y\pgf@ya\pgf@nlt@list}%
  \pgf@xa\pgf@x\pgf@ya\pgf@y%
  \pgf@process{\pgf@x\pgf@xb\pgf@y\pgf@yb\pgf@nlt@list}%
  \pgf@xb\pgf@x\pgf@yb\pgf@y%
  \xdef\pgf@nlt@last@coord@orig{{\the\pgf@xc}{\the\pgf@yc}}%
  \pgf@process{\pgf@x\pgf@xc\pgf@y\pgf@yc\pgf@nlt@list}%
  \pgf@xc\pgf@x\pgf@yc\pgf@y%
  \xdef\pgf@nlt@last@coord@trans{{\the\pgf@xc}{\the\pgf@yc}}%
  \pgf@protocolsizes{\pgf@xa}{\pgf@ya}%
  \pgf@protocolsizes{\pgf@xb}{\pgf@yb}%
  \pgf@protocolsizes{\pgf@xc}{\pgf@yc}%
  \pgfsyssoftpath@curveto{\the\pgf@xa}{\the\pgf@ya}{\the\pgf@xb}{\the\pgf@yb}{\the\pgf@xc}{\the\pgf@yc}%
}


\def\pgf@nlt@closepath@nlt{%
  {%
    \expandafter\pgfqpoint\pgf@nlt@last@moveto@orig%
    \expandafter\pgf@nlt@set@temps\pgf@nlt@last@coord@orig%
    \advance\pgfutil@tempdima by-\pgf@x%
    \advance\pgfutil@tempdimb by-\pgf@y%
    \pgfutil@tempswatrue%
    \ifdim\pgfutil@tempdima<0.01pt\relax\ifdim\pgfutil@tempdima>-0.01pt\relax\ifdim\pgfutil@tempdimb<0.01pt\relax\ifdim\pgfutil@tempdimb>-0.01pt\relax\pgfutil@tempswafalse\fi\fi\fi\fi%
    \ifpgfutil@tempswa%
      \pgf@nlt@lineto@nlt{\pgf@x}{\pgf@y}%
    \fi%
    \pgfsyssoftpath@closepath%
  }%
}


\endinput

pgfmoduleoo.code.tex
% Copyright 2006 by Till Tantau
% Copyright 2011 by Saso Zivanovic
%
% 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.
%
% Based on pgfmoduleoo.code.tex v1.8 by Till Tantau.  This version adds inheritance. 



% Support of object-oriented programming in TeX, with inheritance.


% The oo support works as follows:
%
% The main supported concepts are classes, objects, methods,
% attributes and signal/slots. A class defines a set of methods, which are,
% in the end, just normal TeX macros. Once a class has been created,
% it can be instantiated by calling the \pgfoonew command, resulting
% in a new object. Objects are local to their group. Given an object,
% you can send it a message, resulting in the method code of the
% object's method to be executed. While an object exists, it has a set
% of attributes whose values can change over time. Attributes values
% are not local to TeX groups, rather their life-cycle is the same as
% the object's (which, however, is local to the group in which the
% object was declared).
%
% The implementation is as follows: There is an ID counter that is
% increased each time an object is created. This counter is local to
% the group, which means that when a group ends the counter will
% revert to the previous value, allowing objects to the reused in
% subsequent groups.
%
% A method is just a normal \TeX macro, but to call it you write
% \objecthandle.methodname(parameters). The \objecthandle is a macro
% that is created when you say \pgfoonew. The special object
% \pgfoothis is the current object.
%
% Attributes are stored globally in internal TeX macros whose name is
% composed of the object number and the attribute name.




% Declares a class
%
% #1 = class name
% #2 = methods
%
% Description:
%
% This command declares a class for future use. Inside #2, the macro
% \method can be used to declare a method. The \method macro takes a
% method name, parameters (methods are normal TeX macros, after all)
% and body.

% base classes are put in parenthesis before the new class name, but
% are optional.
\def\pgfooclass{%
  \pgfutil@ifnextchar ({%
    \pgfooclass@
  }{%
    \pgfooclass@()
  }%
}
\long\def\pgfooclass@(#1)#2#3{%
  \def\pgfoo@classname{#2}%
  \expandafter\ifx\csname pgfooY\pgfoo@classname.@pgfooinit\endcsname\relax\else
    \pgferror{class #2 is already defined}%
  \fi
  \pgfoo@ciii{#2}{#1}%
  \expandafter\let\csname pgfooY#2@pgfoo@mro\endcsname\pgfoo@mro
  \let\pgfoo@origmethod=\method%
  \let\pgfoo@origattribute=\attribute%
  \let\method=\pgfoo@declaremethod%
  \let\attribute=\pgfoo@declareattribute%
  \let\pgfoo@attributes=\pgfutil@empty%
  \let\pgfoo@methods=\pgfutil@empty%
  #3%
  % inherit
  \def\pgfoo@temp@baseclasses{#1}%
  \pgfoo@inherit@methods
  \pgfoo@inherit@attributes
  % Always present (and never inherited) methods:
  \expandafter\let\csname pgfooY\pgfoo@classname.get handle\endcsname\pgfoo@obj%
  \expandafter\let\csname pgfooY\pgfoo@classname.get id\endcsname\pgfoo@id%
  % for compatibility with previous versions of pgfoo, define method
  % with the same name as the class as a synonym for init
  \expandafter\let\expandafter\pgfoo@init\csname pgfooY\pgfoo@classname.init\endcsname
  \expandafter\let\csname pgfooY\pgfoo@classname.\pgfoo@classname\endcsname\pgfoo@init
  % Cleanup
  \let\method=\pgfoo@origmethod%
  \let\attribute=\pgfoo@origattribute%
}

\def\pgfoo@emptyinit(){}
\def\pgfoo@escapeif#1#2\fi{\fi#1}% a little helper


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Compute MRO using C3 algorithm
% The sequences are enclosed in brackets; elements of sequences and
% the big list are terminated by a comma and a dot, respectively. (Why
% comma *and* a dot: TeX's parset---brackets don't form groups! Soooo,
% why not braces? Because I don't know how do delete excess "{},"s...)

% #1 = current class, #2 = list of base classes
\def\pgfoo@ciii#1#2{%
  % \pgfoo@seq will hold a list of sequences.
  % (i) the first sequence has just one element: the current class
  \def\pgfoo@seq{[#1,].}%
  % (ii) every subclass has a sequence (in the order as they were
  % given): the class' sequence is its mro.
  \pgfutil@for\pgfoo@baseclass:={#2}\do{%
    \edef\pgfoo@baseclass@mro{\csname pgfooY\pgfoo@baseclass @pgfoo@mro\endcsname}%
    \expandafter\ifx\expandafter\relax\pgfoo@baseclass@mro\relax\else
      \edef\pgfoo@seq{\pgfoo@seq[\pgfoo@baseclass@mro,].}%
    \fi
  }%
  % The final sequence is a sequence of base classes, in the order as
  % they were given. 
  \ifx\relax#2\relax\else
    \edef\pgfoo@seq{\pgfoo@seq[#2,].}%
  \fi
  \edef\pgfoo@temp{()(\pgfoo@seq)}%
  \expandafter\pgfoo@ciii@merge\pgfoo@temp
}

% #1 = MRO so far
% #2 = remaining sequences
% no empty sequences [] should arrive here: they should be removed
% before calling this macro
\def\pgfoo@ciii@merge(#1)(#2){%
  \ifx\relax#2\relax
    \pgfoo@ciii@done(#1)%
  \else\pgfoo@escapeif{% split #2
    \pgfoo@ciii@merge@A(#1)(#2)%
  }\fi%
}
% a splitter: to be only called from \pgfoo@ciii@merge
\def\pgfoo@ciii@merge@A(#1)(#2.#3){%
  \ifx\relax#3\relax % if #3 is empty, we can take the shortcut
    \pgfoo@ciii@mergeA@done(#1)(#2)%
  \else\pgfoo@escapeif{% 
    \pgfoo@ciii@merge@checkHead(#1)()(#2)()(#3)%
  }\fi
}

\def\pgfoo@ciii@mergeA@done(#1)([#2]){%
  \pgfoo@ciii@done(#1#2)%
}

% #1 = MRO so far
% #2 = sequences with bad heads (dot after each sequence)
% [#3,#4] = the sequence whose head we're testing right
%           now---obviously, it should not be empty! (#3 has no comma,
%           #4 has a comma after each class name)
% #5 = #3 does not occur in the tail of these sequences (dot after
%      each sequence)
% #6 = the remaining sequences (dot after each sequence)
\def\pgfoo@ciii@merge@checkHead(#1)(#2)([#3,#4])(#5)(#6){%
  \pgfutil@in@{[#3,}{#2}%
  \ifpgfutil@in@\pgfoo@escapeif{% #3 is already blacklisted
    \pgfoo@ciii@clean\pgfoo@ciii@merge@checkHead@P{(#1)(#2[#3,#4].)(#5#6)}%    
  }\else\pgfoo@escapeif{%
    \ifx\relax#6\relax\pgfoo@escapeif{% no more sequences to test the head against! 
                                 % so, #3 is a good head, and we can recurse
      \pgfoo@ciii@goodHeadFound(#1)(#3)(#2[#4].#5)%
    }\else\pgfoo@escapeif{% split #6 and get to work
      \pgfoo@ciii@merge@checkHead@A(#1)(#2)([#3,#4])(#5)(#6)%
    }\fi
  }\fi
}
% splitter: to be only called from \pgfoo@ciii@merge@checkHead
% we will check if #3 occurs in the tail of #6
\def\pgfoo@ciii@merge@checkHead@A(#1)(#2)([#3,#4])(#5)(#6.#7){%
  \pgfoo@ciii@merge@checkHead@B(#1)(#2)([#3,#4])(#5)(#6)(#7)%
}
% splitter: to be only called from \pgfoo@ciii@merge@checkHead@A
% &worker: we will check if #3 occurs in #7. If it does, #3 is a bad head.
\def\pgfoo@ciii@merge@checkHead@B(#1)(#2)([#3,#4])(#5)([#6,#7])(#8){%
%  \def\pgfoo@ciii@tempA{#3}\def\pgfoo@ciii@tempB{#5}%
%  \ifx\pgfoo@ciii@tempA\pgfoo@ciii@tempB
%    \pgferror{An attempt to derive from the same class twice}%
%  \else\pgfoo@escapeif{%
    \pgfutil@in@{,#3,}{,#7}%
    \ifpgfutil@in@\pgfoo@escapeif{% bad head! get next head and restart
                             % but: need to clean up first!
      \pgfoo@ciii@clean\pgfoo@ciii@merge@checkHead@P{(#1)(#2[#3,#4].)(#5[#6,#7].#8)}%
    }\else\pgfoo@escapeif{% so far, so good
      \ifx\relax#8\relax\pgfoo@escapeif{% if #8 is empty, we won:
        % #3 is a good head! we will move it to MRO
        % but clean-up first!
        \pgfoo@ciii@goodHeadFound(#1)(#3)(#2[#4].#5[#6,#7].)%
      }\else\pgfoo@escapeif{% proceed to the first seq in #8
        \pgfoo@ciii@clean\pgfoo@ciii@merge@checkHead{(#1)(#2)([#3,#4])(#5[#6,#7].)(#8)}%
      }\fi
    }\fi
%  }\fi
}

% #1 = MRO
% #2 = good head
% #3 = the remaining sequences (in need of removing the good head from
% them, and then also some general cleanup)
\def\pgfoo@ciii@goodHeadFound(#1)(#2)(#3){%
  \pgfutil@in@{,#2,}{#3}%
  \ifpgfutil@in@\pgfoo@escapeif{%
    \def\pgfoo@ciii@removeGoodHead(##1)(##2)(##3,#2,##4){%
      \pgfoo@ciii@goodHeadFound(##1)(##2)(##3,##4)}%
    \pgfoo@ciii@removeGoodHead(#1)(#2)(#3)%
  }\else\pgfoo@escapeif{%
    \pgfutil@in@{[#2,}{#3}%
    \ifpgfutil@in@\pgfoo@escapeif{%
      \def\pgfoo@ciii@removeGoodHead(##1)(##2)(##3[#2,##4){%
        \pgfoo@ciii@goodHeadFound(##1)(##2)(##3[##4)}%
      \pgfoo@ciii@removeGoodHead(#1)(#2)(#3)%
    }\else\pgfoo@escapeif{%
      \pgfoo@ciii@clean\pgfoo@ciii@merge{(#1#2,)(#3)}%
    }\fi
  }\fi
}

% mediates between the bad head exit of \pgfoo@ciii@merge@checkHead@B
% and \pgfoo@ciii@merge@checkHead; we need the mediator because #3
% below might have been affected by cleaning.
\def\pgfoo@ciii@merge@checkHead@P(#1)(#2)(#3){%
  \if\relax#3\relax % no more good head candidates!
    \pgferror{Bad MRO: There is no good (monotonic etc.)
      Method Resolution Order for your class hierarchy}%
  \else\pgfoo@escapeif{%
    \pgfoo@ciii@merge@checkHead@Q(#1)(#2)(#3)%
  }\fi
}
% splitter for \pgfoo@ciii@merge@checkHead@P
% #3 = the sequence containing the newest good head candidate
\def\pgfoo@ciii@merge@checkHead@Q(#1)(#2)(#3.#4){%
  \pgfoo@ciii@merge@checkHead(#1)(#2)(#3)()(#4)%
}

% cyclically removes all occurrences of "[]," and "[]." (i.e., empty
% sequences) in #2. When done, calls #1 with whatever remains.
\def\pgfoo@ciii@clean#1#2{% clean commas
  \pgfutil@in@{[].}{#2}% clean dots
  \ifpgfutil@in@\pgfoo@escapeif{%
    \pgfoo@ciii@clean@dot#1#2\pgfoo@ciii@clean@END
  }\else\pgfoo@escapeif{%
    #1#2%
  }\fi
}
\def\pgfoo@ciii@clean@dot#1#2[].#3\pgfoo@ciii@clean@END{%
  \pgfoo@ciii@clean#1{#2#3}%
}

\def\pgfoo@ciii@done(#1,){%
  \def\pgfoo@mro{#1}%
}

% end of C3
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


% Declare a method
%
% Description:
%
% Defines a method. To use/invoke this method for an object \object,
% you write \object.methodname(parameters). This will cause the method
% body to be invoked with the argument "(parameters)".
%
% To define the method \method should be directly followed by the
% method name and, then, by (, followed by a parameter pattern,
% followed by ), followed by the message body. Spaces are allowed only
% after "\method" and after the closing ).
%
% Example:
%
% \pgfooclass{MyPlot}{
%
%   \attribute x=0;
%   \attribute y=0;
%
%   \method MyPlot() {
%   }
%
%   \method getX(#1) {
%     \pgfooget{x}{#1}
%   }
%
%   \method setPoint(#1,#2) {
%     \pgfooset{x}{#1}
%     \pgfooset{y}{#2}
%   }
% }

%   define the method macro and append the method to the method collection
\def\pgfoo@declaremethod#1(#2)#3{%
  \def\pgfoo@method{#1}%
  \ifx\pgfoo@classname\pgfoo@method
    \def\pgfoo@method{init}%
  \fi
  \expandafter\long\expandafter\def\csname pgfooY\pgfoo@classname.\pgfoo@method\endcsname(#2){#3}%
  \edef\pgfoo@methods{\pgfoo@methods,\pgfoo@method}%
}

\def\pgfoo@inherit@methods{%
  % for non-derived classes:
  \expandafter\ifx\expandafter\relax\pgfoo@temp@baseclasses\relax
    % if init is not defined, define an empty one 
    \expandafter\ifx\csname pgfooY\pgfoo@classname.init\endcsname\relax
      \expandafter\let\csname pgfooY\pgfoo@classname.init\endcsname\pgfoo@emptyinit%
      \edef\pgfoo@methods{,init\pgfoo@methods}%
    \fi
  \fi
  \if\relax\pgfoo@methods\relax\else
    % gobble the initial comma
    \edef\pgfoo@methods{\expandafter\pgfutil@gobble\pgfoo@methods}%
  \fi
  % remember the list of collected methods
  \expandafter\let\csname pgfooY\pgfoo@classname @pgfoo@methods\endcsname\pgfoo@methods
  % get MRO
  \expandafter\let\expandafter\pgfoo@mro\csname pgfooY\pgfoo@classname @pgfoo@mro\endcsname  
  % loop throough base classes in MRO
  \pgfutil@for\pgfoo@baseclass:=\pgfoo@mro\do{%
    \ifx\pgfoo@baseclass\pgfoo@classname % skip self
    \else\pgfoo@escapeif{%
      % get methods defined in this base class
      \expandafter\let\expandafter\pgfoo@methods\csname pgfooY\pgfoo@baseclass @pgfoo@methods\endcsname
      \pgfutil@for\pgfoo@method:=\pgfoo@methods\do{% for each method
        % check if it is already defined in our class
        \expandafter\ifx\csname pgfooY\pgfoo@classname.\pgfoo@method\endcsname\relax 
          % if not, link the method name from our class to base class
          \edef\pgfoo@temp{\noexpand\let
            \expandafter\noexpand\csname pgfooY\pgfoo@classname.\pgfoo@method\endcsname
            \expandafter\noexpand\csname pgfooY\pgfoo@baseclass.\pgfoo@method\endcsname}%
          \pgfoo@temp
        \fi
      }%
    }\fi
  }%
}

\def\pgfoosuper(#1,#2).#3({%
  #2.get id(\pgfoo@temp@id)%
  \edef\pgfoo@classname{\csname pgfooX\pgfoo@temp@id @class\endcsname}%
  \def\pgfoo@super@A##1,#1,##2.##3({%
    \pgfoo@super@B##2.##3(%
  }%
  \expandafter\let\expandafter\pgfoo@mro\csname pgfooY\pgfoo@classname @pgfoo@mro\endcsname
  \expandafter\pgfoo@super@A\expandafter,\pgfoo@mro,.#3(%
}
\def\pgfoo@super@B#1,#2.#3({%
  \expandafter\ifx\csname pgfooY#1.#3\endcsname\relax
    \pgfoo@escapeif{\pgfoo@super@B#2.#3(}%
  \else
    \pgfoo@escapeif{\expandafter\pgfoo@caller\pgfoo@temp@id.#1.#3(}%
  \fi
}



% Declare an attribute
%
% #1 = attribute name
% #2 = optional default value
%
% Description:
%
% Declares the attribute #1 for the current class. If the attribute
% name is followed by =, the text following the equal sign is the
% default value.

\def\pgfoo@declareattribute#1;{%
  \pgfutil@in@{ =}{#1}%
  \ifpgfutil@in@%
    \pgfoo@declareunpackspace#1;%
  \else%
    \pgfutil@in@={#1}%
    \ifpgfutil@in@%
      \pgfoo@declareunpack#1;%
    \else%
      \pgfoo@declareattribute@\let{#1}\pgfutil@empty
    \fi%  
  \fi%  
}
\def\pgfoo@declareunpack#1=#2;{\pgfoo@declareattribute@\def{#1}{{#2}}}
\def\pgfoo@declareunpackspace#1 =#2;{\pgfoo@declareattribute@\def{#1}{{#2}}}

% put the initial value in the class's namespace
% put the attr name in a list
\def\pgfoo@declareattribute@#1#2#3{%
  \expandafter#1\csname pgfooY\pgfoo@classname @#2\endcsname#3%
  \expandafter\def\expandafter\pgfoo@attributes\expandafter{\pgfoo@attributes,#2}%
}

% for each base class:
%   for each attribute declared in that class:
%       add the attr on a list if it's not there yet
% convert the list of (attr,class which it comes from) into an
% efficient sequence of triples \op{attrname}\pointer-to-initial-value
% (\op is then set differently in init and garbage collection)
\def\pgfoo@inherit@attributes{%
  % store the list of attributes declared in this class for use in
  % derived classes
  \if\relax\pgfoo@attributes\relax\else
    \edef\pgfoo@attributes{\expandafter\pgfutil@gobble\pgfoo@attributes}% gobble comma
  \fi
  \expandafter\let\csname pgfooY\pgfoo@classname.@pgfoo@attributes\endcsname\pgfoo@attributes%
  % get MRO
  \expandafter\let\expandafter\pgfoo@mro\csname pgfooY\pgfoo@classname @pgfoo@mro\endcsname  
  \def\pgfoo@allattributes{}% here we will store the attrs declared in base classes
  \pgfutil@for\pgfoo@baseclass:=\pgfoo@mro\do{% for each base class in MRO order
    % the attributes declared in this base class
    \expandafter\let\expandafter\pgfoo@attributes\csname pgfooY\pgfoo@baseclass.@pgfoo@attributes\endcsname
    \pgfutil@for\pgfoo@attribute:=\pgfoo@attributes\do{% for each attribute
      % check if we have already found it in some previous base class
      \edef\pgfoo@temp{{,\pgfoo@attribute=}{\pgfoo@allattributes,}}
      \expandafter\pgfutil@in@\pgfoo@temp
      \ifpgfutil@in@\else % don't overwrite
        % append to the list
        \edef\pgfoo@allattributes{\pgfoo@allattributes,\pgfoo@attribute=\pgfoo@baseclass}%
      \fi
    }%
  }%
  \if\relax\pgfoo@allattributes\relax\else
    \edef\pgfoo@allattributes{\expandafter\pgfutil@gobble\pgfoo@allattributes}% gobble comma
  \fi
  % this macro will hold a list of attributes from all base classes
  % we run this macro at init and gc 
  \def\pgfoo@process@attributes{}  
  \pgfutil@for\pgfoo@attributeclass:=\pgfoo@allattributes\do{% for each (attribute, class) pair
    % append to the attribute processor
    \expandafter\pgfoo@inherit@attributes@appendattribute\pgfoo@attributeclass.%
  }%
  \expandafter\let\csname pgfooY\pgfoo@classname .@pgfoo@process@attributes\endcsname\pgfoo@process@attributes
}


% #1=attr, #2=class which the attr comes from
\def\pgfoo@inherit@attributes@appendattribute#1=#2.{%
  \def\pgfoo@tempA{\pgfoo@attribute@op{#1}}%
  \expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter\pgfoo@tempB\expandafter\expandafter\expandafter{\expandafter\pgfoo@tempA\csname pgfooY#2@#1\endcsname}%
  \expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter\pgfoo@process@attributes\expandafter\expandafter\expandafter{\expandafter\pgfoo@process@attributes\pgfoo@tempB}%
  % above is just this:
  %     \def\pgfoo@process@attributes{\pgfoo@process@attributes\pgfoo@attribute@op{#1}%
  %     \csname pgfooY#2@#1\endcsname}
  %  with \pgfoo@process@attributes and \csname expanded exactly once:
}

% \pgfoo@attribute@op for garbace collection
\def\pgfoo@gc@attribute#1#2{\pgfoolet{#1}\relax}


\newcount\pgfoo@objectcount
\newcount\pgfoothis@count

% The attribute value method
%
% #1 = attr
%
% This method inserts the current value of the given attribute for the
% current object.

\def\pgfoovalueof#1{%
  \csname pgfooX\the\pgfoothis@count @#1\endcsname%
}


% The attribute get method
%
% #1 = attr
% #2 = macro
%
% This method makes the macro equal to the current value of the
% attribute for the current object.

\def\pgfooget#1#2{%
  \expandafter\let\expandafter#2\csname pgfooX\the\pgfoothis@count @#1\endcsname%
}


% The attribute set method
%
% #1 = attr
% #2 = value
%
% This method sets the given attribute for the current object to the
% given value.

\long\def\pgfooset#1#2{%
  \expandafter\gdef\csname pgfooX\the\pgfoothis@count @#1\endcsname{#2}%
}


% The attribute set method (expanded version)
%
% #1 = attr
% #2 = value
%
% This method sets the given attribute for the current object to the
% expanded version of the given value.

\long\def\pgfooeset#1#2{%
  \expandafter\xdef\csname pgfooX\the\pgfoothis@count @#1\endcsname{#2}%
}


% The attribute let method
%
% #1 = attr
% #2 = value
%
% This method sets the given attribute for the current object to the
% given value using \let.

\def\pgfoolet#1#2{%
  \expandafter\global\expandafter\let\csname pgfooX\the\pgfoothis@count @#1\endcsname#2%
}


% Add something to an attribute at the end
%
% #1 = attr
% #2 = code
%
% This method adds the give code to the attr at the end.

\def\pgfooappend#1#2{%
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\pgf@oo@temp\expandafter\expandafter\expandafter{\csname pgfooX\the\pgfoothis@count @#1\endcsname#2}%
  \expandafter\global\expandafter\let\csname pgfooX\the\pgfoothis@count @#1\endcsname\pgf@oo@temp%
}


% Add something to an attribute at the beginning
%
% #1 = attr
% #2 = code
%
% This method adds the give code to the attr at the beginning.

\def\pgfooprefix#1#2{%
  \pgfooget{#1}\pgf@oo@temp%
  \def\pgf@oo@@temp{#2}%
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\pgf@oo@temp%
  \expandafter\expandafter\expandafter{\expandafter\pgf@oo@@temp\pgf@oo@temp}%
  \pgfoolet{#1}\pgf@oo@temp%
}



% Help macro for scanning arguments
\newtoks\pgfoo@toks

\def\pgfoo@collect@args{%
  \pgfutil@ifnextchar\bgroup\pgfoo@collect@args@group\pgfoo@collect@args@nogroup%
}
\def\pgfoo@collect@args@nogroup#1){%
  \pgfoo@toks{#1}%
  \pgfoo@continue%
}
\def\pgfoo@collect@args@group#1{%
  \pgfutil@ifnextchar){\pgfoo@toks{{#1}}\expandafter\pgfoo@continue\pgfutil@gobble}{\pgfoo@collect@args@nogroup{#1}}%
}


% Instantiate an object
%
% Possible syntax:
%
% 1) \pgfoonew new <class name>(<constructor parameters)
% 2) \pgfoonew \<objectname>=new <class name>(<constructor parameters)
% 3) \pgfoonew{attribute}=new <class name>(<constructor parameters)
%
% Description:
%
% Creates an object. After the object has been created, the method
% called <class name> (the constructor) is invoked. If the
% \<objectname>= part is present, the macro is assigned to the newly
% created object.

\def\pgfoonew{%
  \pgfutil@ifnextchar n{%
    \pgfoo@new\pgfoo@dummy=%
  }{%
    \pgfutil@ifnextchar\bgroup{%
      \pgfoo@new@attribute%
    }{%
      \pgfoo@new%
    }%
  }%
}
\def\pgfoo@new#1=new #2({%
  \expandafter\ifx\csname pgfooY#2.get id\endcsname\relax%
    \pgferror{Unknown class '#2'}%
  \else%
    \pgfoo@new@create#1{#2}%
    {%
      \pgfoothis@count\pgfoo@objectcount%
      \let\pgfoo@attribute@op\pgfoolet
      \csname pgfooY#2.@pgfoo@process@attributes\endcsname%
    }%
    \let\pgfoo@continue=\pgf@oo@new@cont%
    \expandafter\pgfoo@collect@args%
  \fi%
}

\def\pgf@oo@new@cont{%
  \expandafter\pgfoolastobj\expandafter.\expandafter i\expandafter n\expandafter i\expandafter t\expandafter(\the\pgfoo@toks)%
  \aftergroup\pgfoogc% cleanup after group
}

\def\pgfoo@new@attribute#1=new #2({%
  \expandafter\ifx\csname pgfooY#2.get id\endcsname\relax%
    \pgferror{Unknown class '#2'}%
  \else%
    \pgfoo@new@create\pgfoo@temp{#2}%
    {%
      \pgfoothis@count\pgfoo@objectcount%
      \let\pgfoo@attribute@op\pgfoolet%
      \csname pgfooY#2.@pgfoo@process@attributes\endcsname%
    }%
    \pgfoolet{#1}\pgfoo@temp%
    \let\pgfoo@continue=\pgf@oo@new@cont%
    \expandafter\pgfoo@collect@args%
  \fi%
}

\def\pgf@oo@new@cont{%
  \expandafter\pgfoolastobj\expandafter.\expandafter i\expandafter n\expandafter i\expandafter t\expandafter(\the\pgfoo@toks)%
  \aftergroup\pgfoogc% cleanup after group
}

\def\pgfoo@new@create#1#2{%
  \advance\pgfoo@objectcount by 1\relax%
  \edef\pgfoolastobj{\noexpand\pgfoo@caller{\the\pgfoo@objectcount}}%
  \expandafter\gdef\csname pgfooX\the\pgfoo@objectcount @class\endcsname{#2}%
  \let#1\pgfoolastobj%
}

\def\pgfoo@caller#1.#2({%
  \expandafter\let\expandafter\pgfoo@caller@temp\csname pgfooY\csname pgfooX#1@class\endcsname.#2\endcsname%
  \ifx\pgfoo@caller@temp\relax%
    % assume that #2 is of form "superclass.method"
    \expandafter\let\expandafter\pgfoo@caller@temp\csname pgfooY#2\endcsname%
    \ifx\pgfoo@caller@temp\relax%
      \pgferror{Object #1 has no method '#2'}%
    \fi%
  \fi%    
  \def\pgf@marshal{%
    \pgfoothis@count=#1\relax%
  }%
  \let\pgfoo@continue\pgfoo@caller@cont%
  \pgfoo@collect@args%
}
\def\pgfoo@caller@cont{%
  \edef\pgf@marshal{%
    \pgf@marshal%
    \noexpand\pgfoo@caller@temp(\the\pgfoo@toks)%
  }%
  \expandafter\pgf@marshal\expandafter\pgfoothis@count\the\pgfoothis@count\relax%
}
\let\pgfoo@orig@caller=\pgfoo@caller

% The special "this" object

\def\pgfoothis.#1({%
  \expandafter\let\expandafter\pgfoo@caller@temp\csname pgfooY\csname pgfooX\the\pgfoothis@count @class\endcsname.#1\endcsname%
  \ifx\pgfoo@caller@temp\relax%
    % assume that #1 is of form "superclass.method"
    \expandafter\let\expandafter\pgfoo@caller@temp\csname pgfooY#1\endcsname%
  \fi%
  \let\pgfoo@continue\pgfoothis@cont%
  \pgfoo@collect@args%
}
\def\pgfoothis@cont{%
  \expandafter\pgfoo@caller@temp\expandafter(\the\pgfoo@toks)%
}



% Get the object id
%
% #1 = macro to store the id
%
% Description:
%
% This special method allows you to access the object id. You can then
% use \pgfoocall to call a method using this id. This is mainly useful
% when you wish to store the id for a longer time.

\def\pgfoo@id(#1){%
  \edef#1{\the\pgfoothis@count}%
}

% Yields the object with the given id
%
% #1 = id
%
% Description:
%
% Given an object id, \pgfooobj{<id>} will yield the object having
% this id.

\def\pgfooobj#1{%
  \pgfoo@caller{#1}%
}


% Get the object
%
% #1 = macro to store the object
%
% Description:
%
% This special method allows you to get a new handle to a given
% object. If \obj is an object, you could normally just say
% \let#1=\obj. However, if \obj happens to be \pgfoothis, then you may
% wish to get a handle to the object itself, not to the special macro
% \pgfoothis. In this case you can say \obj.get handle(#1).

\def\pgfoo@obj(#1){%
  \edef#1{\noexpand\pgfoo@caller{\the\pgfoothis@count}}%
}



% The garbage collector
%
% Description:
%
% This method frees space ocupied by unused objects. Garbage are
% objects that have been destroyed because of the end of the scope in
% which they were created. In this case, however, the memory used by
% this object is not immediately reused because the attributes of the 
% object are actually stored in global variables. When the garbage
% collector is called, it will set all these global variables to
% \relax, thereby ensuring that no memory is needed for them.

\def\pgfoogc{%
  {%
    % We do this in a group...
    \pgfoothis@count\pgfoo@objectcount% this is temporary...
    \let\pgfoo@next=\pgfoo@dogc%
    \pgfoo@next%
  }%
}
\def\pgfoo@dogc{%
  \advance\pgfoothis@count by 1\relax%
  \expandafter\ifx\csname pgfooX\the\pgfoothis@count @class\endcsname\relax%
    \let\pgfoo@next=\relax%
  \else%
    % Cleanup this object:
    % The following is the fast version of \pgfooobj{\the\pgfoo@objectcount}.@pgfoogc:
    \let\pgfoo@attribute@op\pgfoo@gc@attribute
    \csname pgfooY\csname pgfooX\the\pgfoothis@count @class\endcsname.@pgfoo@process@attributes\endcsname%
    \expandafter\global\expandafter\let\csname pgfooX\the\pgfoothis@count @class\endcsname\relax%
  \fi%
  \pgfoo@next%
}
  


%
%
% Object class
% defines method "copy"
%
%

\pgfooclass{object}{%
  \method copy(#1) {%
    % create a new object
    \edef\pgfoo@temp@classname{\csname pgfooX\the\pgfoothis@count @class\endcsname}%
    \expandafter\pgfoo@new@create\expandafter#1\expandafter{\pgfoo@temp@classname}%
    \def\pgfoo@copy@attributes##1##2{%
      \pgfooget{##1}\pgfoo@attrvalue
      \expandafter\let\csname pgfooX\the\pgfoo@objectcount @##1\endcsname\pgfoo@attrvalue
    }%
    \let\pgfoo@attribute@op\pgfoo@copy@attributes
    \csname pgfooY\pgfoo@temp@classname .@pgfoo@process@attributes\endcsname  
    \aftergroup\pgfoogc% cleanup after group
  }
}


%
%
% Signal class
%
%

\pgfooclass{signal}
{
  %
  % This class implements signals.
  %
  % After you have created a signal object, you can call
  % connect to connect a slot. Then, whenever the emit method is
  % called, all connected methods get called.

  % Attribute
  \attribute emitter;
  % Collects the objects that should be called.
  
  % Constructor
  \method signal() {}

  % Connect a slot (method) #2 of object #1
  \method connect(#1,#2) {%
    {%
      #1.get id(\pgf@tempid)%
      % Save in emmiter
      \pgfooget{emitter}\pgf@temp%
      \let\pgfoo@signal@call=\relax% avoid expansion
      \edef\pgf@temp{\pgf@temp\pgfoo@signal@call{\pgf@tempid}{#2}}%
      \pgfoolet{emitter}\pgf@temp%
    }%
  }

  \def\pgfoo@signal@call#1#2{%
    \def\pgf@temp{\pgfooobj{#1}.#2}%
    \expandafter\pgf@temp\expandafter(\pgfoo@signal@args)%
  }
  
  % Emit a signal
  \method emit(#1) {%
    \def\pgfoo@signal@args{#1}%
    \pgfoovalueof{emitter}
  }
}




\endinput

pgfmoduleparser.code.tex
% Copyright 2009 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/modules/pgfmoduleparser.code.tex,v 1.2 2013/07/15 12:05:34 tantau Exp $

%
% This file defines commands for defining a letter-by-letter parser
% based on a dfa.
%




% Parse the following text
%
% #1 = parser
%
% Description:
%
% This command starts the parser #1 in the initial state "initial". It
% will parse the following text, stopping when the state "final" has
% been reached.

\def\pgfparserparse#1{%
  \def\pgf@parser{#1}%
  \def\pgf@parser@state{initial}%
  \pgf@parser@parse%
}
\def\pgf@parser@parse{%
  \futurelet\pgf@parser@symbol\pgf@parser@cont%
}
\def\pgf@parser@cont{%
  % Ok, defined?
  \expandafter\let\expandafter\pgf@parser@action%
  \csname pgf@parser@a@\pgf@parser @\pgf@parser@state @\meaning\pgf@parser@symbol\endcsname%
  \ifx\pgf@parser@action\relax%
    \expandafter\let\expandafter\pgf@parser@action%
    \csname pgf@parser@a@\pgf@parser @all@\meaning\pgf@parser@symbol\endcsname%
    \ifx\pgf@parser@action\relax%
      \pgferror{Unexpected character
        '\meaning\pgf@parser@symbol' in parser '\pgf@parser' in state
        '\pgf@parser@state'}%
    \fi%
  \fi%
  \pgf@parser@action%
  \ifx\pgf@parser@symbol\pgfutil@sptoken%
    \expandafter\pgf@parser@rid@space%
  \else%
    \expandafter\pgf@parser@rid@other%  
  \fi%
}

\def\pgf@parser@ridded{%
  \ifx\pgf@parser@state\pgf@parser@final@text%
    % done
  \else%
    \expandafter\pgf@parser@parse%
  \fi%
}

\def\pgf@parser@final@text{final}

{%
  \def\:{\pgf@parser@rid@space} \expandafter\gdef\: {\futurelet\pgf@parser@ignore\pgf@parser@ridded}
  \gdef\pgf@parser@rid@other{\afterassignment\pgf@parser@ridded\let\pgf@parser@ignore=}  
}



% Switches the state
% 
% #1 = new state
% 
% Description:
% 
% This command can be used inside a state action to switch to a
% different state.

\def\pgfparserswitch#1{\def\pgf@parser@state{#1}}




% Defines an action to be taken in a state for some symbol
% 
% #1 = parser
% #2 = state
% #3 = symbol text (result of saying \meaning on the symbol)
% #4 = action
% 
% Description:
% 
% When the parser encounters #3 while being in state #2, then code #4
% is executed.
% 
% When #2 is set to the special text "all", then the symbol is handled
% in all states by #4, except when a state defines something special
% for this symbol

\def\pgfparserdef#1#2#3#4{%
  \expandafter\def\csname pgf@parser@a@#1@#2@#3\endcsname{#4}
}


\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

pgfmodulesnakes.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/pgfmodulesnakes.code.tex,v 1.3 2013/07/15 12:05:34 tantau Exp $

\pgfwarning{Snakes have been superseded by decorations. Use the module decorations instead of snakes}

\usepgfmodule{decorations}

\endinput



\newdimen\pgfsnakeremainingdistance
\newdimen\pgfsnakecompleteddistance


% Creates a new pgf snake
%
% #1 = snake name
% #1 = initial state
% #3 = states of the snake
%
%
% This command declares a new snake for later use. The second
% parameter specifies the states of the snake, see also the
% description of pgfpathsnake.
%
% Inside the code of #3 the command \state may be used. This command
% will only be defined while #3 is executed.
%
% Example:
%
% \pgfdeclaresnake{zig zag}{one zig zag}
% {
%   \state{one zig zag}[width=10pt]
%   {
%     \pgfpathlineto{\pgfpoint{2.5pt}{2.5pt}}
%     \pgfpathlineto{\pgfpoint{7.5pt}{-2.5pt}}
%     \pgfpathlineto{\pgfpoint{10pt}{0pt}}
%   }
%   \state{final}
%   {
%     \pgfpathlineto{\pgfpoint{\pgfsnakeremainingdistance}{0pt}}
%   }
% }

\long\def\pgfdeclaresnake#1#2#3{%
  \def\pgf@snake@name{#1}%
  \pgfutil@namedef{pgf@snake@@#1@initial}{#2}%
  \let\pgf@orig@state=\state%
  \let\state=\pgf@snake@state
  #3
  \let\state=\pgf@orig@state%
}


% Sets the additional transformation applied to every segment of a snake
%
% #1 = transformation
%
% Example:
%
% \pgfsetsnakesegmenttransformation{\pgftransformyshift{5pt}}

\def\pgfsetsnakesegmenttransformation#1{\def\pgf@snakeadditionaltransform{#1}}
\pgfsetsnakesegmenttransformation{}


% Declares a new state
%
% #1 = state name
% #2 = options
% #3 = path element
%
% Description:
%
% When a snake is drawn and the current state is #1, the following
% happens. First, the options are executed, which will possible change
% the state. If that does not happen, the path element is added to the
% path and the coordinate system is translated by the path element's
% width (which is specified using the width option).
%
% Example:
%
% \state{initial}[width=10pt]
% {
%   \pgfpathlineto{\pgfpoint{2.5pt}{2.5pt}}
%   \pgfpathlineto{\pgfpoint{7.5pt}{-2.5pt}}
%   \pgfpathlineto{\pgfpoint{10pt}{0pt}}
% }

\def\pgf@snake@state#1{\pgfutil@ifnextchar[{\pgf@@snake@start#1}{\pgf@@snake@start#1[]}}%}
\def\pgf@@snake@start#1[#2]#3{%
  \pgfutil@namedef{pgf@snake@@\pgf@snake@name @#1@options}{#2}%
  \pgfutil@namedef{pgf@snake@@\pgf@snake@name @#1@code}{#3}%
}



% Use multiple snakes
%
% #1 = list of snake names/length pairs
% #2 = point to which the snake leads
%
% This operation uses the snakes in parameter #1 to get to the point
% #4. The parameter #1 should contain pairs consisting of a snake name
% and a length for which this snake should be used. When the length is
% computed, the dimensions \pgfsnakeremainingdistance and
% \pgfsnakecompleteddistance will have been set to the length of the
% total distance to #2 that has already been covered/that still needs
% to be covered.
%
% Example:
%
% \pgfpathsnakesto{{lineto}{1cm},{zig zag}{\pgfsnakeremainingdistance}}{\pgfpoint{2cm}{3cm}}

\def\pgfpathsnakesto#1#2{%
  \begingroup%
    % compute target vector
    \pgfpointtransformed{#2}%
    \advance\pgf@x by-\pgf@path@lastx%
    \advance\pgf@y by-\pgf@path@lasty%
    %
    % MW: Calculate the angle of the snake.
    %
    \edef\pgf@marshal{%
    	\noexpand\pgfmathanglebetweenpoints{\noexpand\pgfpointorigin}{%
    		\noexpand\pgf@x\the\pgf@x\noexpand\pgf@y\the\pgf@y}%
    }%
    \pgf@marshal%
    \let\pgfsnakeangle\pgfmathresult%
    %
    % MW: Use this instead for length (?). More accurate and only a few operations slower.
    %
    \pgfmathveclen@{\pgfmath@tonumber{\pgf@x}}{\pgfmath@tonumber{\pgf@y}}%
    \pgfsnakeremainingdistance\pgfmathresult pt\relax%
    %
    % Ok, now normalize the vector...
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgf@process{\pgfpointnormalised{}}%
    % ok, now computer length (arghh...)
    % In theory that's easy: divide the larger of the values x or y by
    % the normalized x or y. Well...
    %
    % First, make xa and ya positive:
   % \ifdim\pgf@xa<0pt%
%      \pgf@xa=-\pgf@xa%
%    \fi%
%    \ifdim\pgf@ya<0pt%
%      \pgf@ya=-\pgf@ya%
%    \fi%
%    % Now do division:
%    \ifdim\pgf@xa>\pgf@ya%
%      \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%
%    % Make positive:
%    \ifdim\pgf@xa<0pt%
%      \pgf@xa=-\pgf@xa%
%    \fi%
%    % Ok, now we draw things...
    \edef\pgf@list{#1}%
%   \pgfsnakeremainingdistance=\pgf@xa%
    \pgfsnakecompleteddistance=0pt%
    \pgf@xb=\pgf@x%
    \pgf@yb=\pgf@y%
    \pgfutil@for\pgf@temp:=\pgf@list\do{%
      \ifx\pgf@temp\pgfutil@empty%
      \else%
        \expandafter\pgf@snake@invoke\pgf@temp%
      \fi%
    }%
  \endgroup%
}

\def\pgf@snake@invoke#1#2{%
  \pgfmathsetlength\pgf@xa{#2}%
  {%
    \edef\pgf@marshal{\noexpand\pgfpathsnakealongvector{#1}{\the\pgf@xa}{\noexpand\pgfqpoint{\the\pgf@xb}{\the\pgf@yb}}}%
    \pgf@marshal%
  }%
  \advance\pgfsnakecompleteddistance by\pgf@xa%
  \advance\pgfsnakeremainingdistance by-\pgf@xa%
}

% Use a snake
%
% #1 = snake name
% #2 = point to which the snake leads
%
% This operation mainly computes \pgfpathsnakealongvector for a vector
% appropriately choosen. See \pgfpathsnakealongvector for details.
%
% Example:
%
% \pgfpathsnaketo{zig zag}{\pgfpoint{2cm}{3cm}}

\def\pgfpathsnaketo#1#2{\pgfpathsnakesto{{#1}{\pgfsnakeremainingdistance}}{#2}}



% Use a snake
%
% #1 = snake name
% #2 = length of the snake
% #3 = vector along which the snake grows, should have unit length.
%
% This command draws a snake (more precisely, it adds a snake to the
% path). This works as follows:
%
% First, the coordinate system is transformed such that the vector #3
% points to the right.
%
% Next, the state `initial' of the snake is entered. Unless the
% options of this state cause it to switch to another state, the path
% element is added to the path. Then, the coordinate system is
% translated by the width of the path element as specified in the
% width option of the path element. The dimensions
% \pgfsnakeremainingdistance and \pgfsnakecompleteddistance are
% updated. 
%
% The process ends when the state `final' is entered. The code of the
% final state is executed and the process stops.
%
% Example:
%
% \pgfpathsnakealongvector{zig zag}{100pt}{\pgfpolar{30}{1pt}}

\def\pgfpathsnakealongvector#1#2#3{%
  \pgfutil@ifundefined{pgf@snake@@#1@initial}{\pgferror{Undefined snake ``#1''}}
  { 
  \begingroup% keep things local
    \pgftransformreset%
    \pgf@pt@x=\pgf@path@lastx% evil trickery to transform to the last point
    \pgf@pt@y=\pgf@path@lasty%
    \pgf@process{#3}%
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
    \pgf@xb=-\pgf@y%
    \pgf@yb=\pgf@x%
    \pgftransformcm
      {\pgf@sys@tonumber{\pgf@xa}}{\pgf@sys@tonumber{\pgf@ya}}
      {\pgf@sys@tonumber{\pgf@xb}}{\pgf@sys@tonumber{\pgf@yb}}
      {\pgfpointorigin}%
    % Now, setup the automaton
    \expandafter\let\expandafter\pgf@snake@current@state\expandafter=\csname pgf@snake@@#1@initial\endcsname%
    \def\pgf@snake@name{#1}%  
    \pgfsnakecompleteddistance=0pt%  
    \pgfmathsetlength\pgfsnakeremainingdistance{#2}%
    \pgf@snake@run%
    % Last step:
    {%
      \pgftransformxshift{\pgfsnakecompleteddistance}%
      \pgf@snakeadditionaltransform%
      \csname pgf@snake@@#1@final@code\endcsname%
    }%
  \endgroup%
  }%
}

\def\pgf@final@text{final}

\def\pgf@snake@run{%
  \let\pgf@snake@next=\pgf@snake@do@state%
  \ifx\pgf@snake@current@state\pgf@final@text%
    \let\pgf@snake@next=\relax%
  \fi%
  \pgf@snake@next%  
}

\def\pgf@snake@do@state{%
  \let\pgf@snake@next=\relax%
  \let\pgf@snake@next@state=\pgf@snake@current@state%
  % execute options
  \expandafter\expandafter\expandafter\pgf@snakes@setter
  \expandafter\expandafter\expandafter{\csname pgf@snake@@\pgf@snake@name @\pgf@snake@current@state @options\endcsname}%
  \ifx\pgf@snake@next\relax%
    \let\pgf@snake@next=\pgf@snake@do@code%
  \fi%
  \pgf@snake@next%
}
\def\pgf@snakes@setter{%
  \pgfqkeys{/pgf/snakes}%
}

\def\pgf@snake@do@code{%
  % Ok, execute code:
  {%
    \pgftransformxshift{\pgfsnakecompleteddistance}%
    \pgf@snakeadditionaltransform%
    \csname pgf@snake@@\pgf@snake@name @\pgf@snake@current@state @code\endcsname%
  }%
  % next, do transformation and update
  \pgfmathsetlength{\pgf@xa}{\pgf@snake@width}%
  \advance\pgfsnakeremainingdistance by-\pgf@xa%
  \advance\pgfsnakecompleteddistance by\pgf@xa%
  % Next iteration:
  \let\pgf@snake@current@state=\pgf@snake@next@state%
  \pgf@snake@run%
}

\pgfkeys{
  /pgf/snakes/width/.code=\def\pgf@snake@width{#1}\pgf@snake@switch@if#1 to final\pgf@stop,%
  /pgf/snakes/switch if less than/.code=\pgf@snake@switch@if#1\pgf@stop,%
  /pgf/snakes/next state/.store in=\pgf@snake@next@state%
}

\def\pgf@snake@switch@if#1to #2\pgf@stop{%
  \ifx\pgf@snake@next\relax%
    \pgfmathsetlength\pgf@x{#1}%
    \ifdim\pgfsnakeremainingdistance<\pgf@x%
      \def\pgf@snake@current@state{#2}%
      \let\pgf@snake@next=\pgf@snake@run%
    \fi%
  \fi%
}



% lineto snake
%
% This snake simply adds a straight line. This snake is mainly useful
% in conjunction with other snakes.

\pgfdeclaresnake{lineto}{final}
{
  \state{final}
  { \pgfpathlineto{\pgfqpoint{\pgfsnakeremainingdistance}{0pt}} }
}



% moveto snake
%
% This snake simply jumps to the end. This snake, too, is mainly
% useful in conjunction with other snakes.

\pgfdeclaresnake{moveto}{final}
{
  \state{final}
  { \pgfpathmoveto{\pgfqpoint{\pgfsnakeremainingdistance}{0pt}} }
}



\endinput

pgfmodulesorting.code.tex
% Copyright 2008 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/modules/pgfmodulesorting.code.tex,v 1.1 2008/11/12 23:39:37 tantau Exp $

%
% This file defines commands for sorting data. This is useful for 3d plots,
% but also for drawing things in the correct order.
%


\newcount\pgfsortingbuckets


% Init the sorting
%
% #1 = number of buckets
%
% Description:
%
% This macro inits a sorting. At any time there can be only one active
% sorting. When you init the sorting, #1 should be a number of
% buckets. You can then call \pgfsortinginsert to insert code into the
% buckets. Once you are done, calling \pgfsortingexecute will execute
% first the code in buckets 0, then the code in bucket 1, and so on to
% bucket number #1-1.
%
\def\pgfsortinginit#1{
  \pgfsortingbuckets#1\relax%
  \c@pgf@counta=0\relax
  \pgfutil@loop
  \ifnum\c@pgf@counta<\c@pgf@countb\relax%
    \expandafter\global\expandafter\let\csname pgf@sort@\the\c@pgf@counta\endcsname\pgfutil@empty%
    \advance\c@pgf@counta by1\relax%
  \pgfutil@repeat
}

% Insert code into some bucket
% 
% #1 = the bucket
% #2 = the code
% 
\def\pgfsortinginsert#1#1{
  \expandafter\let\expandafter\pgf@temp\csname pgf@lib@sort@#1\endcsname%
  \expandafter\def\expandafter\pgf@temp\expandafter{\pgf@temp#2}%
  \expandafter\global\expandafter\let\csname pgf@lib@sort@\the\c@pgf@counta\endcsname\pgf@temp%
}


% After all code has been inserted into the buckets, you can call
% this method to execute the code in the order of the buckets.
\def\pgfsortingexecute{
  \c@pgf@countb=\pgfoovalueof{buckets}\relax
  \c@pgf@counta=0\relax
  \pgfutil@loop
  \ifnum\c@pgf@counta<\c@pgf@countb\relax%
    \csname pgf@lib@sort@\the\c@pgf@counta\endcsname%
    \advance\c@pgf@counta by1\relax%
  \pgfutil@repeat
}


\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

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

tikzexternalshared.code.tex
% Copyright 2008-2010 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 here is the shared implementation of TeX-dialect specific files
%   tikzlibraryexternal.code.tex
% ******************************
%
% 
% This file provides a high-level automatic export feature for tikz pictures.
% It allows to export EACH SINGLE FIGURE into a separate PDF.
%
% The simplest way is to use the 'convert with system call' option; it simply converts every figure using the write18 method. If that is not possible, a list of figure file names is generated and you need to generate these figures manually (or with a script).
%
%
% It replaces \tikzpicture/ \endtikzpicture and \tikz and invokes \beginpgfgraphicnamed ... \endpgfgraphicnamed
% commands if necessary.

% handle with extreme care and only in small, local groups:
\toksdef\t@tikzexternal@tmpa=0
\toksdef\t@tikzexternal@tmpb=1

\newif\iftikzexternal@nestedflag
\newif\iftikzexternal@verboseuptodate
\newif\iftikzexternal@verboseio
\newif\iftikzexternal@genfigurelist
\newif\iftikzexternal@onlynamed
\newif\iftikzexternal@file@isuptodate
\newif\iftikzexternal@force@remake
\newif\iftikzexternal@optimize
\newif\iftikzexternal@export@enabled
\tikzexternal@export@enabledtrue

% This 'if' can be used as part of the public user interface.
%
% It is set by the 'remake next' key.
%
% It disables any up-to-date checks for the *next* picture, forcing a
% remake of it.
%
% It applies only to *one* picture.
\newif\iftikzexternalremakenext
\newif\iftikzexternal@verbose@optimize
\tikzexternal@verbose@optimizetrue

% A global boolean which can be used to skip single figures.
\newif\iftikzexternalexportnext
\tikzexternalexportnexttrue

% Invokes '#1' if the external lib is currently externalizing
% something and '#2' if not.
%
% This command must be called *after* \tikzexternalize.
\def\tikzifexternalizing#1#2{%
	\ifpgf@external@grabshipout #1\else #2\fi
}%
% Invokes '#1' if the external lib is currently externalizing the NEXT FOLLOWING
% tikzpicture. It invokes '#2' if that is not the case.
\def\tikzifexternalizingnext#1#2{%
	\ifpgf@external@grabshipout 
		\tikzexternalgetnextfilename\tikzexternal@temp
		\tikzifexternaljobnamematches\tikzexternal@temp{#1}{#2}%
	\else 
		#2%
	\fi
}%
% Invokes '#1' if the external lib is currently externalizing the
% current picture. It invokes '#2' if that is not the case.
%
% If the command is invoked outside of a picture, '#2' will be
% invoked.
\def\tikzifexternalizingcurrent#1#2{%
	\ifpgf@external@grabshipout 
		\tikzexternalgetcurrentfilename\tikzexternal@temp
		\ifx\tikzexternal@temp\pgfutil@empty
			#2%
		\else
			\tikzifexternaljobnamematches\tikzexternal@temp{#1}{#2}%
		\fi
	\else 
		#2%
	\fi
}%

% Invokes '#2' if \jobname equals '#1' and '#3' if not.
% I suppose that '#1' is a macro containing the file name.
%
\def\tikzifexternaljobnamematches#1#2#3{%
	\edef\pgf@tempa{\expandafter\string\csname#1\endcsname}%
	\edef\pgf@tempb{\expandafter\string\csname\pgfactualjobname\endcsname}%
	\ifx\pgf@tempa\pgf@tempb #2\else#3 \fi%
}%


\pgfutil@ifundefined{pdfshellescape}{%
	\def\tikzexternalcheckshellescape{}%
}{%
	\ifnum\pdfshellescape=1
		\def\tikzexternalcheckshellescape{\pgfkeysvalueof{/tikz/external/shell escape}\space}%
	\else
		\def\tikzexternalcheckshellescape{}%
	\fi
}%
\newif\iftikzexternal@auto@detect@jobname

\pgfqkeys{/tikz/external}{
	figure list/.is if=tikzexternal@genfigurelist,
	aux in dpth/.style={/pgf/images/aux in dpth=#1},%
	disable dependency files/.code={%
		\let\tikzexternalfiledependsonfile@ACTIVE=\tikzexternalfiledependsonfile
	},
	% 'mode' applies only if \jobname==real job name.
	mode/.is choice,
	mode/only graphics/.code	= {%
		\def\tikzexternal@opmode{0}%
		\pgfkeysalso{/pgf/images/aux in dpth=true}%
	},
	mode/no graphics/.code		= {\def\tikzexternal@opmode{1}},
	% an alias for 'no graphics:'
	mode/only pictures/.code	= {\def\tikzexternal@opmode{1}},
	mode/graphics if exists/.code= {%
		\def\tikzexternal@opmode{2}%
		\pgfkeysalso{/pgf/images/aux in dpth=true}%
	},
	mode/list only/.code		= {\def\tikzexternal@opmode{3}\tikzexternal@genfigurelisttrue},
	mode/convert with system call/.code={%
		\def\tikzexternal@opmode{4}%
		\pgfkeysalso{/tikz/external/figure list=false,/pgf/images/aux in dpth=true}% ATTENTION: this *can't* work if \label{} contains pictures!
	},
	mode/list and make/.code	= {%
		\def\tikzexternal@opmode{5}%
		\pgfkeysalso{/tikz/external/figure list=true,/pgf/images/aux in dpth=true}%
	},
	mode=convert with system call,
	system call/.initial={pdflatex \tikzexternalcheckshellescape -halt-on-error -interaction=batchmode -jobname "\image" "\texsource"},
%	system call/.initial={pdflatex -interaction=batchmode -jobname '\image' '\texsource'; pdftops -eps \image.pdf},
	force remake/.is if=tikzexternal@force@remake,
	force remake/.default=true,
	failed ref warnings for/.initial={\ref,\cite,\pageref},
	export next/.is if=tikzexternalexportnext,
	export/.is if=tikzexternal@export@enabled,
	remake next/.is if=tikzexternalremakenext,
	remake next/.default=true,
	verbose IO/.is if=tikzexternal@verboseio,
	verbose IO/.default=true,
	verbose IO=true,
	verbose optimize/.is if=tikzexternal@verbose@optimize,
	verbose up to date/.is if=tikzexternal@verboseuptodate,
	verbose/.style={
		verbose IO=#1,
		verbose optimize=#1,
		verbose up to date=#1,
	},
	shell escape/.initial=-shell-escape,
	read main aux/.is if=pgfexternalreadmainaux,
	image discarded text/.initial={%
		[[ \textsc{Image Discarded Due To} \texttt{`/tikz/external/%
				\ifcase\tikzexternal@opmode\relax
					mode=only graphics%
				\or
					mode=no graphics%
				\or
					mode=graphics if exists%
				\or
					mode=list only%
				\or
					mode=convert with system call%
				\or
					mode=list and make%
				\fi
		'}~]]%
		\pgfutil@ifundefined{tikzexternal@warning@at@end}{%
			\pgfutil@ifundefined{AtEndDocument}{}{%
				\AtEndDocument{%
					\message{! Package tikz Warning: Some images are not up-to-date and need to be generated. }%
				}%
			}%
			\gdef\tikzexternal@warning@at@end{1}%
		}{}%
	},
	optimize/.is choice,
	optimize/true/.code={%
		\tikzexternal@optimizetrue
		\iftikzexternal@optimize
			\ifpgf@external@grabshipout
				% we have already started the externalization! Install
				% optimization commands to activate the new one:
				\tikzexternal@optimize@REPLACE
			\fi
		\fi
	},
	optimize/false/.code={%
		\tikzexternal@optimizefalse%
		\tikzexternal@optimize@RESTORE
	},%
	optimize=true,
	optimize away text/.code={[ \textsc{\string#1\ optimized away because it does not contribute to exported PDF}]},
	optimize/install/.code={},%
	optimize/restore/.code={},%
	% Expects two arguments, the command name and (optionally) a count
	% of expected arguments.
	% Example: 
	% 	'optimize command away=\includegraphics'
	% 	'optimize command away={\mycommand}{3}'
	%
	% It accepts commands which have '[]' arguments and whose first
	% argument always begins with '{'.
	%
	% #1: the command name
	% #2: either empty or a number of EXPECTED arguments. It will be checked
	% for one optional argument in square brackets as well.
	optimize command away/.code 2 args={%
		\expandafter\global\expandafter\let\csname\string#1@ORIG\endcsname=#1%
		\pgfkeysalso{%
			/tikz/external/optimize/install/.append code={%
				\def#1{\tikzexternal@optimize@away@cmd{#1}{#2}}%
			},
			/tikz/external/optimize/restore/.append code={%
				\expandafter\let\expandafter#1\csname\string#1@ORIG\endcsname
			}
		}%
		\iftikzexternal@optimize
			\ifpgf@external@grabshipout
				% we have already started the externalization! Install
				% optimization commands to activate the new one:
				\tikzexternal@optimize@REPLACE
			\fi
		\fi
	},
	optimize command away=\includegraphics,
	% EXPERIMENTAL (UNTESTED):
	optimize latex env away/.code={%
		\expandafter\let\expandafter\pgf@tempa\csname #1\endcsname
		\expandafter\global\expandafter\let\csname #1@ORIG\endcsname=\pgf@tempa%
		\pgfkeysalso{%
			/tikz/external/optimize/install/.append code={%
				\pgfutil@namedef{#1}{\tikzexternal@optimize@away@latex@env{#1}}%
			},
			/tikz/external/optimize/restore/.append code={%
				\pgfutil@namelet{#1}{#1@ORIG}%
			}%
		}%
	},
	only named/.is if=tikzexternal@onlynamed,
	only named/.default=true,
	figure name/.initial=\tikzexternal@realjob-figure,
	reset counter/.code={%
		\expandafter\gdef\csname c@tikzext@no@#1\endcsname{0}%
	},%
	prefix/.code={\tikzsetexternalprefix{#1}},
	up to date check/.is choice,
	up to date check/simple/.code={\def\tikzexternal@uptodate@mode{0}},
	% md5 relies on \pdfmdfivesum of pdftex. It uses 'diff' as fallback if we do not have that command.
	up to date check/md5/.code={\def\tikzexternal@uptodate@mode{1}},
	up to date check/diff/.code={\def\tikzexternal@uptodate@mode{2}},
	up to date check=md5,
}

\def\tikzsetfigurename#1{\pgfkeyssetvalue{/tikz/external/figure name}{#1}}%
\def\tikzappendtofigurename#1{\pgfkeys{/tikz/external/figure name/.add={}{#1}}}

% This method sets the file name prefix used for every import/export.
%
% It is invoked by the '/tikz/external/prefix' key.
\def\tikzsetexternalprefix#1{\def\tikzexternal@filenameprefix{#1}}
\tikzsetexternalprefix{}

% This method initialises automatic externalization.
% 
% The command does need any argument, but it has two optional ones:
%
% 1. \tikzexternalize[<options>]
%
% 2. \tikzexternalize{<real job's name>}
%
% 3. \tikzexternalize[<options>]{<real job's name>}
%
% The <real job's name> is the job's file name, without the suffix
% .tex .
% If the <real job's name> is omitted, it will be deduced
% automatically.
%
% The effect is:
% 1. automatically surround EVERY tikzpicture by \beginpgfgraphicnamed % sections.
% 2. in case that the job's real name and the current \jobname differ,
% it will process ONLY the matching tikzpicture.
\def\tikzexternalize{%
	\pgfutil@ifnextchar[{%
		\tikzexternalize@opt
	}{%
		\tikzexternalize@opt[]%
	}%
}%
\def\tikzexternalize@opt[#1]{%
	\pgfutil@ifnextchar\bgroup{%
		\tikzexternal@auto@detect@jobnamefalse
		\tikzexternalize@opt@withname[#1]%
	}{%
		\tikzexternal@auto@detect@jobnametrue
		\pgfutil@ifundefined{tikzexternalrealjob}{%
			% ok, \tikzexternalrealjob is not known. 
			% Assume we are currently *not* externalizing.
			\let\tikzexternalrealjob=\jobname
		}{}%
		\def\pgf@tempa{\tikzexternalize@opt@withname[#1]}%
		\expandafter\pgf@tempa\expandafter{\tikzexternalrealjob}%
	}%
}%
\def\tikzexternalize@opt@withname[#1]#2{%
	\gdef\tikzexternalrealjob{#2}%
	\if1\tikzexternalize@hasbeencalled
	\else
		\pgfqkeys{/tikz/external}{#1}%
		\def\tikzexternal@realjob{#2}%
		\tikzexternalauxlock@init
		\pgfrealjobname{#2}%
		\def\tikzexternalize@hasbeencalled{1}%
		\tikzexternalenable
		\def\tikzexternal@determineimgextension##1:##2\relax{\gdef\tikzexternalimgextension{##1}}%
		\xdef\pgf@tempa{\pgfsys@imagesuffixlist}%
		\expandafter\tikzexternal@determineimgextension\pgf@tempa:\relax
		\pgfutil@ifundefined{includegraphics}{%
			\let\tikzexternal@orig@includegraphics=\relax
		}{%
			\let\tikzexternal@orig@includegraphics=\includegraphics
		}%
		\let\tikzexternalfiledependsonfile=\tikzexternalfiledependsonfile@ACTIVE
		\let\tikzpicturedependsonfile=\tikzpicturedependsonfile@ACTIVE
	\fi
}
\def\tikzexternalize@hasbeencalled{0}%

\def\tikzifexternalizehasbeencalled#1#2{%
	\if1\tikzexternalize@hasbeencalled
		#1%
	\else
		#2%
	\fi
}%

% If mode=`convert with system call', the boolean \ifpgfexternalreadmainaux 
% will be set depending on the current lock file.
%
% The idea is as follows: Suppose
% pdflatex -shell-escape mainjob.tex 
% is running.
% 
% While it runs, 
% a) it modifies its mainjob.aux file,
% b) it issues pdflatex -jobname mainjob-figure0 mainjob.tex .
%
% The call (b) will try to read mainjob.aux in order to resolve \ref
% commands. This may fail since the aux
% file is not complete; it may be subject to output buffering. To
% avoid such failure, a locking mechanism is established.
%
% The locking mechanisms causes (a) to write a lock command into
% mainjob.auxlock 
% just before (b) is called. Then, (b) will check it. After (b) has
% completed, the lock will be reset.
%
% Thus: mode=convert with system call does NOT support \ref commands
% inside of images. You will need to call the externalization command
% manually. In this case, it should work.
%
% The lock file allows to detect automatically whether an image is created by
% 'convert with system call' or if the user issued the required command manually.
%
% @PRECONDITION : this command must be invoked AFTER
% \tikzexternal@realjob has been defined but BEFORE \pgfrealjobname is
% called.
%
% @POSTCONDITION : If \ifpgfexternalreadmainaux=\iffalse, we won't do
% anything. Otherwise, it will be changed depending for 'mode=convert
% with system call' if necessary.
\def\tikzexternalauxlock@init{%
	\if4\tikzexternal@opmode
		% mode=convert with system call
		\ifpgfexternalreadmainaux
			% ohoh. This case needs care because the main.aux might
			% not be ready at this time!
			% check.
			%
			\edef\pgf@tempa{\expandafter\string\csname\tikzexternal@realjob\endcsname}%
			\edef\pgf@tempb{\expandafter\string\csname\jobname\endcsname}%
			\ifx\pgf@tempa\pgf@tempb
				% we are *not* externalizing. Set lock into its
				% initial "unlocked" state.
				\tikzexternalauxlock@setlock{0}%
			\else
				% we are externalizing. Query the lock's value:
				\tikzexternalauxlock@getlockvalue
				\if1\tikzexternallocked
					\pgfexternalreadmainauxfalse
					% the main .aux file won't be read. Handle \ref commands:
					\tikzexternalauxlock@handleref
				\else
					\pgfexternalreadmainauxtrue
				\fi
			\fi
		\else
			% NO-OP. We won't read the main aux file anyway.
			\def\tikzexternalauxlock@setlock##1{}%
		\fi
	\fi
}
% defines \tikzexternallocked to be either 0 or 1, depending on the
% lock file.
\def\tikzexternalauxlock@getlockvalue{%
	\openin\r@pgf@reada=\tikzexternal@realjob.auxlock
	\ifeof\r@pgf@reada
		% no lock file. Unlock.
		\def\tikzexternallocked{0}%
	\else
		% read first line...
		\read\r@pgf@reada to\pgf@tempa
		% ... and execute it.
		\pgf@tempa
		% it should contain a definition of \tikzexternallocked. If
		% not, lock it anyway.
		\pgfutil@ifundefined
			{tikzexternallocked}
			{\def\tikzexternallocked{1}}%
			{}%
	\fi
	\closein\r@pgf@reada
}%
\def\tikzexternalauxlock@setlock#1{%
	\immediate\openout\w@pgf@writea=\tikzexternal@realjob.auxlock
	\immediate\write\w@pgf@writea{\noexpand\def\noexpand\tikzexternallocked{#1}}%
	\immediate\closeout\w@pgf@writea
}


% Installs a special \ref{} command such that externalized pictures
% can use \ref and the user gets a warning if something fails.
%
% The special \ref handling is installed for every reference command
% in the list '/tikz/external/failed ref warnings for' which contains
% '\ref,\pageref,\cite'.
%
% For use in the aux lock handling only.
\def\tikzexternalauxlock@handleref{%
	\let\pgf@external@grab@refundefinedtrue=\pgf@external@grab@refundefinedtrue@orig
	%
	\pgfkeysgetvalue{/tikz/external/failed ref warnings for}\tikzexternal@temp
	\expandafter\tikzexternalauxlock@handleref@loop\tikzexternal@temp,\@EOI,%
}
\def\tikzexternalauxlock@handleref@loop#1,{%
	\def\tikzexternal@temp{#1}%
	\ifx\tikzexternal@temp\pgfutil@empty
		\expandafter\tikzexternalauxlock@handleref@loop
	\else
		\ifx#1\@EOI
		\else
			{%
				% strip the leading '\'
				% this allows proper \protect ion when you write
				% \caption{...\cite{..}} and #1=\cite
				\escapechar=-1
				\xdef\pgf@temp{\string#1}%
			}%
			\expandafter\let\csname tikzexternalauxlock@handleref@orig@\pgf@temp\endcsname=#1%
			\edef#1{\noexpand\pgf@texdist@protect\noexpand\tikzexternalauxlock@handleref@repl{\pgf@temp}}%
			\expandafter\expandafter\expandafter\tikzexternalauxlock@handleref@loop
		\fi
	\fi
}%
\def\tikzexternalauxlock@handleref@repl#1{\pgfutil@ifnextchar[{\tikzexternalauxlock@handleref@repl@{#1}}{\tikzexternalauxlock@handleref@repl@{#1}[]}}%
\def\tikzexternalauxlock@handleref@repl@#1[#2]#3{%
	\tikzifexternalizingcurrent{%
		% note that '#1' is NO control sequence! it is a protected string
		\csname tikzexternalauxlock@handleref@orig@#1\endcsname{#3}%
		\begingroup
		\def\n{\pgfexternal@hat\pgfexternal@hat J}%
		\tikzexternal@assemble@systemcall{\pgfactualjobname}{\pgf@tempa}%
		\def\space{\noexpand\space}%
		\pgfexternalstorecommand{%
			\noexpand\begingroup
			\noexpand\toks0={\pgf@tempa}%
			\noexpand\immediate\noexpand\write16{\tikzexternalauxlock@handleref@warning{#3}{\noexpand\the\noexpand\toks0}}%
			\noexpand\G@refundefinedtrue
			\noexpand\endgroup
		}%
		\endgroup
	}{%
		% ok. We are not externalizing this part of the document. 
		% Throw the citation away without further notice.
	}%
}%
\def\tikzexternalauxlock@handleref@warning#1#2{%
	\n
	LaTeX Warning: Reference `#1' in external picture `\pgfactualjobname' could not be resolved\noexpand\on@line.\n
	This is because the \tikzexternal@realjob.aux file is not accessable in this context, you will need to issue the externalize command\n
	\space\space\space#2\n
	manually.\n%
}

% Expands to the default image extension (it is set by
% \tikzexternalize).
%
% This image extension may not resemble the correct one; you may need
% to overwrite this macro *after* \tikzexternalize in this case.
%
% The default setting uses the first registered image extension.
\def\tikzexternalimgextension{}%

% can be used to (temporarily) disable the externalization.
\def\tikzexternaldisable{%
	\let\tikz=\tikzexternal@origtikz
	\tikzexternal@TEXDIALECT@restore@picture
	\pgfutil@ifundefined{tikzexternal@orig@tikzfadingfrompicture}
	{}% NOP
	{%
		\let\tikzfadingfrompicture=\tikzexternal@orig@tikzfadingfrompicture
		\let\endtikzfadingfrompicture=\tikzexternal@orig@endtikzfadingfrompicture
		\let\tikzfading=\tikzexternal@orig@tikzfading
	}%
	\iftikzexternal@optimize
		\ifpgf@external@grabshipout
			\tikzexternal@optimize@RESTORE
		\fi
	\fi
}%
% re-enables externalization after a \tikzexternalizedisable.
\def\tikzexternalenable{%
	\if\tikzexternalize@hasbeencalled1%
		\let\tikz=\tikzexternal@tikz@replacement
		\tikzexternal@TEXDIALECT@installreplacement@picture
		\pgfutil@ifundefined{tikzfadingfrompicture}%
		{}% no special handling for 'fading lib'
		{%
			% oh, ok -- patch fading lib!
			\pgfutil@ifundefined{tikzexternal@orig@tikzfadingfrompicture}{%
				\let\tikzexternal@orig@tikzfadingfrompicture=\tikzfadingfrompicture
				\let\tikzexternal@orig@endtikzfadingfrompicture=\endtikzfadingfrompicture
				\let\tikzexternal@orig@tikzfading=\tikzfading
			}{}%
			\def\tikzfadingfrompicture{%
				\begingroup
				\tikzexternaldisable
				\tikzexternal@orig@tikzfadingfrompicture}%
			\def\endtikzfadingfrompicture{%
				\tikzexternal@orig@endtikzfadingfrompicture
				\endgroup}%
			\def\tikzfading[##1]{%
				\begingroup
				\tikzexternaldisable
				\tikzexternal@orig@tikzfading[##1]%
				\endgroup}%
		}%
		\iftikzexternal@optimize
			\ifpgf@external@grabshipout
				\tikzexternal@optimize@REPLACE
			\fi
		\fi
	\fi
}%

% Sets the filename for the next tikzpicture or \tikz shortcommand.
%
% It will *only* be used for the next picture.
%
% If you don't call \tikzsetnextfilename for a picture, a file name
% will be assembled automatically.
%
% Please note that the global file prefix will be prepended anyway.
\def\tikzsetnextfilename#1{\gdef\tikzexternal@nextfile{#1}}
\tikzsetnextfilename{}


% These are few TeX dialect-specific commands which need to be overriden when used with
% something different than plain TeX:
%
% 1. this command collects a complete image into a macro, up to (but not including) the
%    final TeX-dialect specific end-image command.
%    This is really difficult for LaTeX because \end{tikzpicture} either involves dirty
%    catcode-hacks to parse the braces or an ugly loop which loops until it
%	finds \end followed by {tikzpicture}. 
% 
% #1: a macro which will be called with the collected environment contents.
% all following tokens: the environment contents.
\long\gdef\tikzexternal@TEXDIALECT@collectpicture#1#2\endtikzpicture{#1{#2}}
%
% 2. the following commands should expand to the TeX-dialect specific begin and end image command, i.e.
%	\tikzpicture / \endtikzpicture
%    or 
%	\begin{tikzpicture} / \end{tikzpicture}
%	or
%	\starttikzpicture / \stoptikzpicture
\def\tikzexternal@TEXDIALECT@begpicture{\tikzpicture}
\def\tikzexternal@TEXDIALECT@endpicture{\endtikzpicture}%
%
% 3. This installs the replacement macros:
\def\tikzexternal@TEXDIALECT@installreplacement@picture{%
	\let\tikzpicture=\tikzexternal@tikzpicture@replacement
}%
\def\tikzexternal@TEXDIALECT@restore@picture{%
	\let\tikzpicture=\tikzexternal@origpicture
}%




\let\tikzexternal@origtikz=\tikz
\let\tikzexternal@origpicture=\tikzpicture
\let\tikzexternal@origendpicture=\endtikzpicture
\let\tikzexternal@curfilename=\relax

% Replacement for '\tikzpicture'.
%
% There are two different states in which this method is applied:
% - normal typesetting. Then, the 'mode' key controls its behavior.
% - externalize mode (i.e. jobname != real job name). Then, it will
%   externalize the picture selected by 'jobname' (and only this picture).
\def\tikzexternal@tikzpicture@replacement{%
	\leavevmode
	\global\tikzexternal@file@isuptodatetrue% may be set to false during checks.
	\tikzexternal@getnextfilename\tikzexternal@curfilename
	\ifx\tikzexternal@curfilename\pgfutil@empty
		\ifpgf@external@grabshipout
			% This picture won't be externalized.
			% But maybe we can optimize it away:
			\iftikzexternal@optimize
				% -> it won't be shipped out anyway, so save typesetting time!
				\let\tikzexternal@next=\tikzexternal@skipfigure
			\else
				% include this graphics into the output (even if
				% it will be discarded anyway).
				\let\tikzexternal@next=\tikzexternal@normalpicture@nographics
			\fi
		\else
			\let\tikzexternal@next=\tikzexternal@normalpicture@nographics
		\fi
	\else
		\ifpgf@external@grabshipout
			\tikzifexternaljobnamematches\tikzexternal@curfilename{%
				% ok, this here IS the picture for which
				% pdflatex --jobname <my name>
				% has been invoked.
				\let\tikzexternal@next=\tikzexternal@externalizefig
			}{%
				\iftikzexternal@optimize
					% No, another picture should be exported. Simply skip this one
					% -> it won't be shipped out anyway, so save typesetting time!
					\let\tikzexternal@next=\tikzexternal@skipfigure
				\else
					% include this graphics into the output (even it
					% it will be discarded anyway).
					\let\tikzexternal@next=\tikzexternal@normalpicture@nographics
				\fi
			}%
		\else
			\ifcase\tikzexternal@opmode\relax
				% 'mode=only graphics'
				\let\tikzexternal@next=\tikzexternal@forcegraphics
			\or
				% 'mode=no graphics'
				\let\tikzexternal@next=\tikzexternal@normalpicture@nographics
			\or
				% 'mode=graphics if exists'
				\let\tikzexternal@next=\tikzexternal@externalizefig
			\or
				% 'mode=list only'
				\let\tikzexternal@next=\tikzexternal@listmodepicture
			\or
				% 'mode=convert with system call'
				\let\tikzexternal@next=\tikzexternal@externalizefig@systemcall
			\or
				% 'mode=list and make'
				\let\tikzexternal@next=\tikzexternal@list@and@makefile@mode@picture
			\fi
		\fi
	\fi
	\tikzexternal@next
}%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Replacement for \tikz short command:
\def\tikzexternal@tikz@replacement{%
	\pgfutil@ifnextchar[{\tikzexternal@tikz@replacement@opt}{\tikzexternal@tikz@replacement@opt[]}%
}%
\def\tikzexternal@tikz@replacement@opt[#1]{%
	\pgfutil@ifnextchar\bgroup{\tikzexternal@tikz@replacement@opt@{#1}}{\tikzexternal@tikz@replacement@opt@@{#1}}%
}
\long\def\tikzexternal@tikz@replacement@opt@#1#2{%
	\tikzexternal@tikz@replacement@opt@process{#1}{#2}%
}%
\def\tikzexternal@tikz@replacement@opt@@#1{%
  \def\tikz@next{\tikzexternal@tikz@replacement@collectnormalsemicolon{#1}}%
  \ifnum\the\catcode`\;=\active\relax%
    \def\tikz@next{\tikzexternal@tikz@replacement@collectactivesemicolon{#1}}%
  \fi%
  \tikz@next}
\long\def\tikzexternal@tikz@replacement@collectnormalsemicolon#1#2;{%
	\tikzexternal@tikz@replacement@opt@process{#1}{#2;}%
}%
{
  \catcode`\;=\active
  \long\gdef\tikzexternal@tikz@replacement@collectactivesemicolon#1#2;{%
	\tikzexternal@tikz@replacement@opt@process{#1}{#2;}%
  }
}
\long\def\tikzexternal@tikz@replacement@opt@process#1#2{%
	\begingroup
	\t@tikzexternal@tmpa=\expandafter{\tikzexternal@TEXDIALECT@begpicture[#1]#2}%
	\t@tikzexternal@tmpb=\expandafter{\tikzexternal@TEXDIALECT@endpicture}%
	\xdef\pgf@tempa{\the\t@tikzexternal@tmpa\the\t@tikzexternal@tmpb}%
	\endgroup
	\pgf@tempa
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\def\tikzexternal@getnextfilename@advancecount{%
	\begingroup
	\c@pgf@counta=\csname c@tikzext@no@\tikzexternal@figurename\endcsname\relax
	\advance\c@pgf@counta by1 
	\expandafter\xdef\csname c@tikzext@no@\tikzexternal@figurename\endcsname{\the\c@pgf@counta}%
	\endgroup
}%

% Returns the file name which will be used for the next tikzpicture (based on the currently available information only, of course).
\def\tikzexternalgetnextfilename#1{%
	\begingroup
	\let\tikzexternal@getnextfilename@advancecount\relax% NOP
	\let\tikzexternal@getnextfilename@resetglobals=\relax% NOP
	\def\tikzexternal@protocol@to@file##1{}% NOP
	\tikzexternal@getnextfilename#1%
	\pgfmath@smuggleone#1%
	\endgroup
}%

% Returns the file name of the current picture.
%
% It returns the empty string in case the command is invoked outside
% of a picture.
% #1 the macro which will contain the file name.
% @see \tikzexternalgetnextfilename
\def\tikzexternalgetcurrentfilename#1{%
	\ifx\tikzexternal@curfilename\relax
		% we are outside of a picture.
		\let#1=\pgfutil@empty
	\else
		% we are inside of a picture.
		\let#1=\tikzexternal@curfilename
	\fi
}

% Fills #1 with a filename for the current picture.
%
% The filename will be generated automatically by appending '-figure<number>' to the real jobname.
%
% This method deals with
% - \tikzsetnextfilename
% - \tikzexternalexportnextfalse
%
% It returns #1={} if the current figure shall NOT be exported.
%
% Please note that both, \tikzsetnextfilename and \tikzexternalexportnextfalse
% affect only ONE picture. They will be reset afterwards.
\def\tikzexternal@getnextfilename#1{%
	\let#1=\pgfutil@empty
	% determine next file name:
	\iftikzexternal@export@enabled
		\iftikzexternalexportnext
			\begingroup
			\t@tikzexternal@tmpa=\expandafter{\tikzexternal@filenameprefix}%
			\ifx\tikzexternal@nextfile\pgfutil@empty
				\iftikzexternal@onlynamed
					\xdef\pgf@tempa{}%
				\else
					\pgfkeysgetvalue{/tikz/external/figure name}\tikzexternal@figurename
					\pgfutil@ifundefined{c@tikzext@no@\tikzexternal@figurename}{%
						% initialise on first usage:
						\expandafter\gdef\csname c@tikzext@no@\tikzexternal@figurename\endcsname{0}%
					}{}%
					\t@tikzexternal@tmpb=\expandafter{\tikzexternal@figurename}%
					\xdef\pgf@tempa{\the\t@tikzexternal@tmpa\the\t@tikzexternal@tmpb\csname c@tikzext@no@\tikzexternal@figurename\endcsname}%
					% advance the counter for 'figure name':
					\tikzexternal@getnextfilename@advancecount
				\fi
			\else
				\t@tikzexternal@tmpb=\expandafter{\tikzexternal@nextfile}%
				\xdef\pgf@tempa{\the\t@tikzexternal@tmpa\the\t@tikzexternal@tmpb}%
			\fi
			\endgroup
			\let#1=\pgf@tempa
		\fi
	\fi
	% 
	\tikzexternal@getnextfilename@resetglobals%
	%
	\tikzexternal@protocol@to@file#1%
}%

\def\tikzexternal@getnextfilename@resetglobals{%
	% Reset global flags:
	\global\let\tikzexternal@nextfile=\pgfutil@empty
	\global\tikzexternalexportnexttrue
}%

% #1: the image file name which should be protocolled. (can be a
% macro)
\def\tikzexternal@protocol@to@file#1{%
	\ifpgf@external@grabshipout%
	\else
		\iftikzexternal@genfigurelist
			\edef\tikzexternal@temp{#1}%
			\ifx\tikzexternal@temp\pgfutil@empty
			\else
				\pgfutil@ifundefined{tikzexternal@listmode@openedfile}{%
					\message{Opening '\tikzexternal@realjob.figlist' for writing.}%
					\begingroup
						\globaldefs=1
						% this gets round '\outer\newwrite' in plain TeX:
						\csname newwrite\endcsname\tikzexternal@outfile
					\endgroup
					\immediate\openout\tikzexternal@outfile=\tikzexternal@realjob.figlist\relax
					\gdef\tikzexternal@listmode@openedfile{1}%
					\if\tikzexternal@opmode5% mode='list and make'
						\tikzexternal@list@and@make@prepare
					\fi
				}{}%
				\iftikzexternal@verboseio
					\immediate\write16{Writing '#1' to '\tikzexternal@realjob.figlist'.}%
				\fi
				\immediate\write\tikzexternal@outfile{#1}%
				\if\tikzexternal@opmode5% mode='list and make'
					\tikzexternal@list@and@make@gentarget{#1}%
				\fi
			\fi
		\fi
	\fi
}%

\def\tikzexternal@list@and@make@gentarget#1{%
	\tikzexternal@assemble@systemcall{#1}{\pgf@tempa}%
	\def\tikzexternal@tempb{\pgfutilstrreplace{^^J}{^^J\tikzexternal@TABchar}}%
	\expandafter\tikzexternal@tempb\expandafter{\pgf@tempa}%
	\let\pgf@tempa=\pgfretval
	\iftikzexternal@verboseio
		\immediate\write16{Writing '#1' to '\tikzexternal@realjob.makefile'.}%
	\fi
	\global\tikzexternal@file@isuptodatetrue% only check for force remake:
	\tikzexternal@checkforceremake%
	\immediate\write\tikzexternal@outmakefile{#1\tikzexternalimgextension: \iftikzexternal@file@isuptodate\else FORCEREMAKE\fi}%
	\immediate\write\tikzexternal@outmakefile{\tikzexternal@TABchar\pgf@tempa}%
	\immediate\write\tikzexternal@outmakefile{}%
}

\def\tikzexternal@list@and@make@prepare{%
	\iftikzexternal@verboseio
		\immediate\write16{Opening '\tikzexternal@realjob.makefile' for writing.}%
	\fi
	\begingroup
		% this makes \tikzexternal@outmakefile global:
		\globaldefs=1
		% this gets round '\outer\newwrite' in plain TeX:
		\csname newwrite\endcsname\tikzexternal@outmakefile
	\endgroup
	\immediate\openout\tikzexternal@outmakefile=\tikzexternal@realjob.makefile\relax
	\immediate\write\tikzexternal@outmakefile{ALL_FIGURE_NAMES=\tikzexternal@DOLLARchar(shell cat \tikzexternal@realjob.figlist)}%
	\immediate\write\tikzexternal@outmakefile{ALL_FIGURES=\tikzexternal@DOLLARchar(ALL_FIGURE_NAMES:\tikzexternal@PERCENTchar=\tikzexternal@PERCENTchar\tikzexternalimgextension)}%
	\immediate\write\tikzexternal@outmakefile{}%
	\immediate\write\tikzexternal@outmakefile{allimages: \tikzexternal@DOLLARchar(ALL_FIGURES)}%
	\immediate\write\tikzexternal@outmakefile{\tikzexternal@TABchar @echo All images exist now. Use make -B to re-generate them.}%
	\immediate\write\tikzexternal@outmakefile{}%
	\immediate\write\tikzexternal@outmakefile{FORCEREMAKE:}%
	\immediate\write\tikzexternal@outmakefile{}%
	%
	% support for .dep files and auto-dependencies:
	\immediate\write\tikzexternal@outmakefile{include $(ALL_FIGURE_NAMES:\tikzexternal@PERCENTchar=\tikzexternal@PERCENTchar.\tikzexternaldepext)}%
	\immediate\write\tikzexternal@outmakefile{}%
	\tikzexternalmakefiledefaultdeprule
	\immediate\write\tikzexternal@outmakefile{}%
	\tikzexternal@outmakefile@pendingcommands
	\pgfutil@ifundefined{AtEndDocument}{}{%
		\AtEndDocument{\immediate\write16{===== mode=`list and make': Use 'make -f \tikzexternal@realjob.makefile' to generate all images. Then, re-run (pdf)latex \tikzexternal@realjob. =====}}%
	}%
}%
\def\tikzexternaldepext{dep}

\def\tikzexternalmakefiledefaultdeprule{%
	\immediate\write\tikzexternal@outmakefile{\tikzexternal@PERCENTchar.\tikzexternaldepext:}%
	\immediate\write\tikzexternal@outmakefile{\tikzexternal@TABchar mkdir -p $(dir $@)}%
	\immediate\write\tikzexternal@outmakefile{\tikzexternal@TABchar touch $@ \tikzexternal@HASHchar\space will be filled later.}%
}%

% Invokes '#1' if a makefile is to be written and '#2' if not.
\def\tikzexternalifwritesmakefile#1#2{%
	\if5\tikzexternal@opmode #1\else #2\fi
}%
\def\tikzexternal@outmakefile@pendingcommands{}%

% Will write something to the make file. If the makefile is not yet
% opened, #1 will be written as soon as it *is* opened.
\def\tikzexternalwritetomakefile#1{%
	\if\tikzexternal@opmode5% mode='list and make'
		\pgfutil@ifundefined{tikzexternal@outmakefile}{%
			\expandafter\gdef\expandafter\tikzexternal@outmakefile@pendingcommands\expandafter{%
				\tikzexternal@outmakefile@pendingcommands
				\immediate\write\tikzexternal@outmakefile{#1}%
			}%
		}{%
			\immediate\write\tikzexternal@outmakefile{#1}%
		}%
	\fi
}%

\def\tikzexternal@dep@file@name{}

% Adds a dependency for the externalized picture file name `#1',
% namely another file `#2'.
%
% #1: the fully qualified path name (without image extension) of the
% external graphics for which we are adding a dependency.
% #2: a file name. If this file gets changed, #1 shall be remade.
%
% This command will be actived as soons as \tikzexternalize has been
% called.
\def\tikzexternalfiledependsonfile@ACTIVE#1#2{%
	\begingroup
	\def\tikzpicturedependsonfile@name{#1}%
	\ifx\tikzpicturedependsonfile@name\pgfutil@empty
		% could be auto-generated: empty file name means "picture
		% won't be externalized". Skip it.
	\else
		% if we encounter any dependencies while we externalize a
		% picture, we have to write these things into the image's .dep
		% file.
		\tikzifexternalizingcurrent
			{\tikzexternalfiledependsonfile@append@to@dep@file{#1}{#2}}%
			{\tikzexternalfiledependsonfile@append@to@makefile{#1}{#2}}%
	\fi
	\endgroup
}%
\def\tikzexternalfiledependsonfile#1#2{}% NO-OP until \tikzexternalize has been called.

% sub-routine of \tikzexternalfiledependsonfile which appends stuff to
% the pictures .dep file.
%
% The file #1.dep is generated during the externalization of #1. If
% you change and/or overwrite it in any other context, its information
% might get lost (because #1 won't be regenerated).
%
% Consequently, this here has to be called if and only if #1 is about
% to be externalized.
\def\tikzexternalfiledependsonfile@append@to@dep@file#1#2{%
	% write every dependency which is defined *INSIDE* of the current
	% picture into the .dep file of the current picture:
	\tikzexternalgetcurrentfilename\tikzpicturedependsonfile@name
	\edef\tikzpicturedependsonfile@name{\tikzpicturedependsonfile@name.\tikzexternaldepext}%
	%\edef\tikzpicturedependsonfile@name{#1.\tikzexternaldepext}%
	\ifx\tikzexternal@dep@file@name\tikzpicturedependsonfile@name
		% file is open and ready.
	\else
		% create new output file.
		\pgfutil@ifundefined{tikzexternal@dep@file}{%
			\begingroup
				% this makes \tikzexternal@dep@file global:
				\globaldefs=1
				% this gets round '\outer\newwrite' in plain TeX:
				\csname newwrite\endcsname\tikzexternal@dep@file
			\endgroup
		}{}%
		\ifx\tikzexternal@dep@file@name\pgfutil@empty
		\else
			% it is already open. Close it.
			\immediate\closeout\tikzexternal@dep@file
		\fi
		\global\let\tikzexternal@dep@file@name=\tikzpicturedependsonfile@name
		\immediate\openout\tikzexternal@dep@file=\tikzexternal@dep@file@name\relax
	\fi
	\immediate\write\tikzexternal@dep@file{#1\tikzexternalimgextension: #2}%
}

% sub-routine of \tikzexternalfiledependsonfile which appends stuff to
% the makefile of the current \jobname .
%
% This is used for dependencies which are recomputed by every run of
% tex; we must not write them into #1.dep (for reasons explained in
% the documentation of
% \tikzexternalfiledependsonfile@append@to@dep@file)
\def\tikzexternalfiledependsonfile@append@to@makefile#1#2{%
	\edef\tikzexternal@temp{#1\tikzexternalimgextension: #2}%
	\expandafter\tikzexternalwritetomakefile\expandafter{\tikzexternal@temp}%
}

% Adds a dependency for the NEXT picture which is about to be
% externalized. If we are currently inside of a picture, the
% dependency is added for this current picture.
%
% #1: a file name. If this file gets changed, the tikzpicture's
% externalized graphics shall be remade.
%
% This command will be actived as soons as \tikzexternalize has been
% called.
\def\tikzpicturedependsonfile@ACTIVE#1{%
	\begingroup
	\tikzexternalgetcurrentfilename\tikzpicturedependsonfile@name
	\ifx\tikzpicturedependsonfile@name\pgfutil@empty
		\tikzexternalgetnextfilename\tikzpicturedependsonfile@name
	\fi
	\expandafter\tikzexternalfiledependsonfile\expandafter{\tikzpicturedependsonfile@name}{#1}%
	\endgroup
}%
\def\tikzpicturedependsonfile#1{}% NO-OP until \tikzexternalize has been called.


% This command is invoked 
%  if and only if ( (grab mode && --jobname matches) || 'mode=graphics if exists' )
%
% It converts the current tikzpicture into an image in grab mode
% or processes the 'graphics if exist' mode.
\def\tikzexternal@externalizefig{%
	\ifpgf@external@grabshipout%
		% In this case, we already KNOW that the filename matches.
		\expandafter\tikzexternal@externalizefig@GRAB%
	\else
		\expandafter\tikzexternal@externalizefig@mode@graphics@if@exists
	\fi%
}
\def\tikzexternal@externalizefig@mode@graphics@if@exists{%
	% check if there is already a file.
	% In that case, use it. If not, typeset the picture normally.
	\gdef\pgf@filename{}%
	\xdef\pgf@tempa{\noexpand\pgf@findfile\pgfsys@imagesuffixlist:+{\tikzexternal@curfilename}}%
	\pgf@tempa
	\ifx\pgf@filename\pgfutil@empty%
		% Note: since we have no 'GRAB' mode, we do not have to deal with optimization.
		% there is no graphics.
		\expandafter\tikzexternal@normalpicture@nographics
	\else
		\expandafter\tikzexternal@forcegraphics
	\fi
}%


% Used by the optimization code.
% It will be called if GRAB mode is on.
% See the 'optimize command away' key.
\def\tikzexternal@optimize@away@cmd#1#2{%
	\pgfutil@ifnextchar[{%
		\tikzexternal@optimize@away@cmd@{#1}{#2}%
	}{%
		\tikzexternal@optimize@away@cmd@{#1}{#2}[]%
	}%
}%
\def\tikzexternal@optimize@away@cmd@#1#2[#3]{%
	\def\tikz@temp{#2}%
	\ifx\tikz@temp\pgfutil@empty
		\def\tikz@temp{\tikzexternal@optimize@away@cmd@auto{#1}{#3}}%
	\else
		\ifcase#2\relax
			\def\tikzexternal@optimize@away@cmd@manual{%
				\tikzexternal@optimize@away@cmd@@@{#1}{#3}{}%
			}%
		\or
			\def\tikzexternal@optimize@away@cmd@manual##1{%
				\tikzexternal@optimize@away@cmd@@@{#1}{#3}{{##1}}%
			}%
		\or
			\def\tikzexternal@optimize@away@cmd@manual##1##2{%
				\tikzexternal@optimize@away@cmd@@@{#1}{#3}{{##1}{##2}}%
			}%
		\or
			\def\tikzexternal@optimize@away@cmd@manual##1##2##3{%
				\tikzexternal@optimize@away@cmd@@@{#1}{#3}{{##1}{##2}{##3}}%
			}%
		\or
			\def\tikzexternal@optimize@away@cmd@manual##1##2##3##4{%
				\tikzexternal@optimize@away@cmd@@@{#1}{#3}{{##1}{##2}{##3}{##4}}%
			}%
		\or
			\def\tikzexternal@optimize@away@cmd@manual##1##2##3##4##5{%
				\tikzexternal@optimize@away@cmd@@@{#1}{#3}{{##1}{##2}{##3}{##4}{##5}}%
			}%
		\or
			\def\tikzexternal@optimize@away@cmd@manual##1##2##3##4##5##6{%
				\tikzexternal@optimize@away@cmd@@@{#1}{#3}{{##1}{##2}{##3}{##4}{##5}{##6}}%
			}%
		\or
			\def\tikzexternal@optimize@away@cmd@manual##1##2##3##4##5##6##7{%
				\tikzexternal@optimize@away@cmd@@@{#1}{#3}{{##1}{##2}{##3}{##4}{##5}{##6}{##7}}%
			}%
		\or
			\def\tikzexternal@optimize@away@cmd@manual##1##2##3##4##5##6##7##8{%
				\tikzexternal@optimize@away@cmd@@@{#1}{#3}{{##1}{##2}{##3}{##4}{##5}{##6}{##7}{##8}}%
			}%
		\or
			\def\tikzexternal@optimize@away@cmd@manual##1##2##3##4##5##6##7##8##9{%
				\tikzexternal@optimize@away@cmd@@@{#1}{#3}{{##1}{##2}{##3}{##4}{##5}{##6}{##7}{##8}{##9}}%
			}%
		\fi
		\def\tikz@temp{\tikzexternal@optimize@away@cmd@manual}%
	\fi
	\tikz@temp
}%
\def\tikzexternal@optimize@away@cmd@auto#1#2{%
	\pgfutil@ifnextchar\bgroup{%
		\tikzexternal@optimize@away@cmd@auto@{#1}{#2}%
	}{%
		\tikzexternal@optimize@away@cmd@auto@{#1}{#2}{<no argument in curly braces>}% give empty argument.
	}
}%

\def\tikzexternal@optimize@away@cmd@auto@#1#2#3{%
	\tikzexternal@optimize@away@cmd@@@{#1}{#2}{{#3}}% <-- provide braces
}%
\def\tikzexternal@optimize@away@cmd@@@#1#2#3{%
	\begingroup
	\toks0={#1[#2]#3}%
	\iftikzexternal@verbose@optimize
		\immediate\write16{The command '\the\toks0' has been optimized away. Use '/tikz/external/optimize=false' to disable this.}%
	\fi
	\endgroup
	\begingroup
	\pgfkeysvalueof{/tikz/external/optimize away text/.@cmd}#1\pgfeov%
	\endgroup
}%

\def\tikzexternal@optimize@away@latex@env#1{%
	\def\tikzexternal@optimize@away@latex@env@{#1}%
	\begingroup
		\def\tikzexternal@laTeX@collect@until@end@tikzpicturetikzpicturestring{#1}%
		\tikzexternal@TEXDIALECT@collectpicture\tikzexternal@optimize@away@latex@env@close
}%
\long\def\tikzexternal@optimize@away@latex@env@close#1{%
	\iftikzexternal@verbose@optimize
		\immediate\write16{The complete contents of \string\begin{tikzexternal@optimize@away@latex@env@} up to the next \end{tikzexternal@optimize@away@latex@env@} has been optimized away because it does not contribute to the exported PDF. Use '/tikz/external/optimize=false' to disable this.}%
	\fi
	\endgroup
	% we still need to invoke \end{<name>} in latex because \begin{<name>}
	% starts a local group - that must be closed properly. Make sure then \end<name> does nothing:
	\expandafter\let\csname end\tikzexternal@optimize@away@latex@env@\endcsname=\relax
	\expandafter\end\expandafter{\tikzexternal@optimize@away@latex@env@}%
}%

\def\tikzexternal@optimize@REPLACE{%
	\pgfkeysvalueof{/tikz/external/optimize/install/.@cmd}\pgfeov
}%

\def\tikzexternal@optimize@RESTORE{%
	\pgfkeysvalueof{/tikz/external/optimize/restore/.@cmd}\pgfeov
}%

% Closes one 'tikzpicture' environment. This is only used for LaTeX,
% because the '\end{tikzpicture}' command would raise an exception otherwise.
% It does *not* call \endtikzpicture.
\def\tikzexternal@closeenvironments{%
	\let\endtikzpicture=\relax
	\tikzexternal@TEXDIALECT@endpicture
	\let\endtikzpicture=\tikzexternal@origendpicture
	\let\tikzexternal@curfilename=\relax
}

% Throws a tikzpicture away - without further notice.
% Used if we are currently converting *another* picture. No need to waste time
% with expensive pictures if they are not shipped out anyway.
%
% See the 'optimize' key to disable this.
\def\tikzexternal@skipfigure{%
	\tikzexternal@TEXDIALECT@collectpicture\tikzexternal@skipfigure@@
}
\long\def\tikzexternal@skipfigure@@#1{%
	\iftikzexternal@verbose@optimize
		\immediate\write16{A tikzpicture has been optimized away. Use '/tikz/external/optimize=false' to disable this.}%
	\fi
	\tikzexternal@closeenvironments
	\pgfkeysvalueof{/tikz/external/optimize away text/.@cmd}tikzpicture\pgfeov%
}

% Processes tikzpicture normally; without any externalization.
%
% We need to do further work here to deal with NESTED tikzpicture environments 
% because all of them shall also be typeset normally.
%
% Idea:
% 1. restore the original \tikzpicture macro
% 2. install the replacement \tikzpicture in \end{tikzpicture}.
% and keep track of nesting.
%
% FIXME: could it be possible that nested tikzpictures use other code anyway?
\def\tikzexternal@normalpicture@nographics{%
	\tikzexternal@nestedflagfalse
	\let\tikzpicture=\tikzexternal@normalpicture@begreplace
	\let\endtikzpicture=\tikzexternal@normalpicture@endreplace
	\tikzpicture
}
\def\tikzexternal@normalpicture@begreplace{%
	\begingroup
	\tikzexternal@nestedflagtrue
	\tikzexternal@origpicture
}
\def\tikzexternal@normalpicture@endreplace{%
	\tikzexternal@origendpicture
	\endgroup
	\iftikzexternal@nestedflag
	\else
		\let\tikzpicture=\tikzexternal@tikzpicture@replacement
		\let\endtikzpicture=\tikzexternal@origendpicture
	\fi
}%

% Assumes there is an image on disk and reads it. The tikzpicture is thrown away.
\def\tikzexternal@forcegraphics{%
	\tikzexternal@TEXDIALECT@collectpicture\tikzexternal@forcegraphics@@
}
\long\def\tikzexternal@forcegraphics@@#1{\tikzexternal@forcegraphics@@@}%
\def\tikzexternal@forcegraphics@@@{%
	\if5\tikzexternal@opmode
		\let\tikz@refundefinedtrue@@=\G@refundefinedtrue
		\gdef\G@refundefinedtrue{%
			\tikz@refundefinedtrue@@ 
			\tikzexternal@forceremake@undefined@reference@handler
		}%
	\fi
	\expandafter\pgfincludeexternalgraphics\expandafter{\tikzexternal@curfilename}%
	\global\let\G@refundefinedtrue=\tikz@refundefinedtrue@@
	\tikzexternal@closeenvironments
}

\def\tikzexternal@forceremake@undefined@reference@handler{%
	\immediate\write16{===== 'mode=list and make': encountered undefined reference in current picture. Adding dependency to FORCEREMAKE. Rerun make to update the picture.' ========^^J}%
	\tikzpicturedependsonfile{FORCEREMAKE}%
}%

% Simply replaces the complete picture by some placeholder text.
% It is used by 'mode=list only' to reduce runtime.
\def\tikzexternal@listmodepicture{%
	\tikzexternal@TEXDIALECT@collectpicture\tikzexternal@listmodepicture@@
}
\long\def\tikzexternal@listmodepicture@@#1{\tikzexternal@listmodepicture@@@}
\def\tikzexternal@listmodepicture@@@{%
	\pgfkeysvalueof{/tikz/external/image discarded text}%
	\tikzexternal@closeenvironments
}

% check if there is already a file.
% In that case, use it. If not, skip it.
\def\tikzexternal@list@and@makefile@mode@picture{%
	\tikzexternal@TEXDIALECT@collectpicture\tikzexternal@list@and@makefile@mode@picture@
}%
\long\def\tikzexternal@list@and@makefile@mode@picture@#1{%
	%
	\tikzexternal@check@uptodate@mode{#1}%
	%
	\gdef\pgf@filename{}%
	\xdef\pgf@tempa{\noexpand\pgf@findfile\pgfsys@imagesuffixlist:+{\tikzexternal@curfilename}}%
	\pgf@tempa
	\ifx\pgf@filename\pgfutil@empty%
		% Note: since we have no 'GRAB' mode, we do not have to deal with optimization.
		% there is no graphics.
		\expandafter\tikzexternal@listmodepicture@@@
	\else
		\expandafter\tikzexternal@forcegraphics@@@
	\fi
}%

\def\tikzexternal@externalizefig@GRAB{%
	\iftikzexternal@optimize
		\ifpgf@external@grabshipout
			\tikzexternal@optimize@RESTORE
		\fi
	\fi
	\def\tikzpicture{%
		\def\tikzpicture{% make sure that nested \tikzpicture are processed normally.
			\begingroup
			\def\endtikzpicture{%
				\tikzexternal@origendpicture
				\endgroup
			}%
			\tikzexternal@origpicture
		}%
		\pgf@external@grab{\tikzexternal@curfilename}%
		\tikzexternal@origpicture
	}%
	\def\endtikzpicture{%
		\tikzexternal@origendpicture
		\pgf@externalend
		%
		\tikzexternal@ensure@nonempty@floats
		%
		\let\tikzpicture=\tikzexternal@tikzpicture@replacement
		\let\endtikzpicture=\tikzexternal@origendpicture
		\iftikzexternal@optimize
			\ifpgf@external@grabshipout
				\tikzexternal@optimize@REPLACE
			\fi
		\fi
	}%
	\tikzpicture
}%

% If a sequence of floats containing JUST tikzpictures is
% externalized, this results in EMPTY floats. Empty floats, in turn,
% can confuse latex; it thinks it did something wrong.
%
% Solution: Avoid empty floats by writing junk into it.
%
% Note that this method is only invoked if \ifpgf@external@grabshipout
% is true and if the text is OUTSIDE of the original shipout routine.
% In other words: this text is being thrown away.
%
% see
% http://tex.stackexchange.com/questions/54625/why-is-fixltx2e-incompatible-with-tikzexternalize
\def\tikzexternal@ensure@nonempty@floats{%
	tikzexternal: picture has been externalized. This text is required to avoid empty floats.
}%

% 1. Discards the current picture in this document.
% 2. Checks whether an image exists already. If that is the case: acquire it.
% 3. If no image exists: call '/tikz/external/system call'. This will
%    process \tikzexternal@externalizefig.
% 4. Assert that finally an image exists and use it.
\def\tikzexternal@externalizefig@systemcall{%
	\tikzexternal@TEXDIALECT@collectpicture\tikzexternal@externalizefig@systemcall@@
}

{
\catcode`\"=12
\catcode`\'=12
\catcode`\;=12
\catcode`\&=12
\catcode`\-=12
\xdef\tikzexternal@normal@dq{"}
\xdef\tikzexternal@normal@sq{'}
\xdef\tikzexternal@normal@semic{;}
\xdef\tikzexternal@normal@and{&}
\xdef\tikzexternal@normal@dash{-}
\catcode`\"=13
\catcode`\'=13
\catcode`\;=13
\catcode`\&=13
\catcode`\-=13
\gdef\tikzexternal@activate@normal@dq{\let"=\tikzexternal@normal@dq}
\gdef\tikzexternal@activate@normal@sq{\let'=\tikzexternal@normal@sq}
\gdef\tikzexternal@activate@normal@semic{\let;=\tikzexternal@normal@semic}
\gdef\tikzexternal@activate@normal@and{\let&=\tikzexternal@normal@and}
\gdef\tikzexternal@activate@normal@dash{\let-=\tikzexternal@normal@dash}
\catcode`\|=0
\catcode`\\=12
|xdef|tikzexternal@normal@backslash{\}%
}
{
\catcode`\^^I=12 
\catcode`\$=12
\catcode`\%=12
\catcode`\#=12 
\gdef\tikzexternal@HASHchar{#}
\gdef\tikzexternal@TABchar{^^I}\gdef\tikzexternal@PERCENTchar{%}\xdef\tikzexternal@DOLLARchar{$}}

% Creates the '/tikz/external/system call' command as string and
% returns it into the (global!) macro #2.
% #1: the image file name (as returned by
% \tikzexternalgetnextfilename)
% #2: the global return value macro
%
\def\tikzexternal@assemble@systemcall#1#2{%
	\begingroup
		\def\image{#1}%
		\iftikzexternal@auto@detect@jobname
			\edef\texsource{\string\def\string\tikzexternalrealjob{\tikzexternal@realjob}\string\input{\tikzexternal@realjob}}%
		\else
			\let\texsource=\tikzexternal@realjob
		\fi
		\ifnum\the\catcode`\"=13 \tikzexternal@activate@normal@dq\fi
		\ifnum\the\catcode`\'=13 \tikzexternal@activate@normal@sq\fi
		\ifnum\the\catcode`\;=13 \tikzexternal@activate@normal@semic\fi
		\ifnum\the\catcode`\-=13 \tikzexternal@activate@normal@dash\fi
		\let\\=\tikzexternal@normal@backslash
		\xdef#2{\pgfkeysvalueof{/tikz/external/system call}}%
	\endgroup
}%
\long\def\tikzexternal@externalizefig@systemcall@@#1{%
	\tikzexternal@externalizefig@systemcall@uptodatecheck{#1}%
	\iftikzexternal@file@isuptodate
		\iftikzexternal@verboseio
			\immediate\write16{===== Image '\tikzexternal@curfilename' is up-to-date. ======}%
		\fi
		\let\pgf@filename=\tikzexternal@curfilename
	\else
		\begingroup
		% no such image. Generate it!
		\tikzexternal@assemble@systemcall{\tikzexternal@curfilename}{\pgf@tempa}%
		\iftikzexternal@verboseio
			\immediate\write16{===== 'mode=convert with system call': Invoking '\pgf@tempa' ========}%
		\fi
		%
		\tikzexternalauxlock@setlock1%
		\immediate\write18{\pgf@tempa}%
		\tikzexternalauxlock@setlock0%
		\expandafter\tikzexternal@externalizefig@systemcall@assertsuccess\expandafter{\pgf@tempa}%
		\pgfmath@smuggleone\pgf@filename
		\endgroup
	\fi
	\ifx\pgf@filename\pgfutil@empty
		% error recovery: something did not work! Try to load it
		% anyway. Perhaps it was just that shell-escape wasn't
		% enabled.
		\begingroup
		\toks0={%
			\tikzexternaldisable
			\pgfutil@ifundefined{scantokens}{\long\def\scantokens##1{##1}}{}%
		}%
		% FIXME : THIS WILL FAIL IF THERE IS '##' INSIDE OF '#1'!
		% for example something like /.style={#1} in the picture environment *will* fail.
		\toks1={%
			\tikzpicture#1%
		}%
		\toks2={%
			\tikzexternal@TEXDIALECT@endpicture
			\tikzexternalenable
		}%
		\xdef\tikzexternal@externalizefig@systemcall@next{%
			\the\toks0
			%  try reading them again as if they were in the input file.
			\noexpand\scantokens{\the\toks1 }%
			\the\toks2
		}%
		\endgroup
	\else
		% ok, take the image!
		\expandafter\pgfincludeexternalgraphics\expandafter{\tikzexternal@curfilename}%
		\gdef\tikzexternal@externalizefig@systemcall@next{\tikzexternal@closeenvironments}%
	\fi
	\tikzexternal@externalizefig@systemcall@next
}%

% Sets \iftikzexternal@file@isuptodate to false if one of the "force
% remake" things is active.
\def\tikzexternal@checkforceremake{%
	\iftikzexternal@force@remake
		\global\tikzexternal@file@isuptodatefalse
	\else
		\iftikzexternalremakenext
			\global\tikzexternal@file@isuptodatefalse
			\global\tikzexternalremakenextfalse
		\fi
	\fi
}

\pgfutil@IfUndefined{pdfmdfivesum}{%
}{%
	% predefine to this value. This does only make sense for pdftex.
	% note that the latex library for 'external' loads \usepackage{pdftexcmds} which \let's this to \pdf@mdfivesum:
	\let\tikzexternal@mdfivesum=\pdfmdfivesum
}%

\long\def\tikzexternal@computemdfivesum#1{%
	\t@tikzexternal@tmpb={#1}%
	\edef\tikzexternal@temp{\the\t@tikzexternal@tmpb}%
	% \meaning results in a string of catcode 12 - which is expandable.
	\edef\pgfretval{\tikzexternal@mdfivesum{\meaning\tikzexternal@temp}}%
}
\long\def\tikzexternal@computemdfivesum@diff@fallback#1{%
	\t@tikzexternal@tmpb={#1}%
	\edef\tikzexternal@temp{\the\t@tikzexternal@tmpb}%
	% \meaning results in a string of catcode 12 - which is expandable.
	\edef\pgfretval{\meaning\tikzexternal@temp}%
}

% Will be set dynamically, depending on 'up to date check'.
%
% It expands to code such that \tikzexternallastkey contains the
% serialized version of '#1'.
%
% It is used as argument for \write{..}
%
% #1 the hash key to serialize.
% \def\tikzexternal@hashfct@serialize 
\long\def\tikzexternal@hashfct@serialize@std#1{%
	\noexpand\def\noexpand\tikzexternallastkey{#1}%
}%

% serializes using temporary token registers. Necessary if #1 contains
% executable code.
\long\def\tikzexternal@hashfct@serialize@tok#1{%
	\noexpand\begingroup
		% in order to allow '#' inside of the body, we have to use token registers:
		\noexpand\toks0={#1}%
		\noexpand\xdef\noexpand\tikzexternallastkey{\noexpand\the\noexpand\toks0 }%
	\noexpand\endgroup
}%

\def\tikzexternal@check@uptodate@ext{.md5}

\def\tikzexternal@check@uptodate@mode@warn@fallback{%	
	\message{! Package tikz Warning: The key 'up to date check=md5' is impossible, there is no macro to compute MD5. Falling back to 'up to date check=diff'.}%
	%
	% warn only once:
	\global\let\tikzexternal@check@uptodate@mode@warn@fallback=\relax
}%

% assigns the boolean \iftikzexternal@file@isuptodate
\long\def\tikzexternal@check@uptodate@mode#1{%
	\if1\tikzexternal@uptodate@mode
		% up to date check=md5:
		% check if we CAN compute MD5 sums:
		\pgfutil@IfUndefined{tikzexternal@mdfivesum}{%
			% we cannot compute md5 sums - fallback to diff.
			\tikzexternal@check@uptodate@mode@warn@fallback
			\def\tikzexternal@uptodate@mode{2}%
		}{}%
	\fi
	%
	\ifcase\tikzexternal@uptodate@mode
		% up to date check=simple
		% nothing to do -- file existance is checked anyway.
		\let\tikzexternal@hashfct=\pgfutil@empty
		\let\tikzexternal@hashfct@serialize=\pgfutil@empty
	\or
		% up to date check=md5
		\let\tikzexternal@hashfct=\tikzexternal@computemdfivesum
		\let\tikzexternal@hashfct@serialize=\tikzexternal@hashfct@serialize@std
	\or
		\let\tikzexternal@hashfct=\tikzexternal@computemdfivesum@diff@fallback
		\let\tikzexternal@hashfct@serialize=\tikzexternal@hashfct@serialize@tok
	\fi
	\ifx\tikzexternal@hashfct\pgfutil@empty
	\else
		\tikzpicturedependsonfile{\tikzexternal@curfilename\tikzexternal@check@uptodate@ext}%
		\tikzexternal@hashfct{#1}%
		\let\tikzexternal@lastkey@new=\pgfretval
		\begingroup
		% no '@' token in this macro: avoid messing up the catcodes in input files:
		\global\let\tikzexternallastkey=\pgfutil@empty
		\openin\r@pgf@reada=\tikzexternal@curfilename\tikzexternal@check@uptodate@ext\relax %
		\ifeof\r@pgf@reada
		\else
			% read first line...
			\endlinechar=-1 % older versions did not have a '%' at the end-of-line. Avoid spurious spaces.
			\read\r@pgf@reada to\pgf@tempa
			% ... and execute it.
			\pgf@tempa
			% it should contain a definition of \tikzexternallastkey.
		\fi
		\closein\r@pgf@reada
		%
		\let\tikzexternal@lastkey=\tikzexternallastkey
		\pgfmath@smuggleone\tikzexternal@lastkey
		\endgroup
		% normalize catcodes. Unfortunately, they cannot be expected to be the same.
		% \meaning will use catcode 12 for each token:
		\edef\tikzexternal@lastkey@normalized{\meaning\tikzexternal@lastkey}%
		\edef\tikzexternal@lastkey@new@normalized{\meaning\tikzexternal@lastkey@new}%
		\iftikzexternal@verboseuptodate
			\immediate\write16{Up-to-date check of \tikzexternal@curfilename: new \tikzexternal@lastkey@new@normalized; old \tikzexternal@lastkey@normalized.^^J}%
		\fi
		\ifx\tikzexternal@lastkey@normalized\tikzexternal@lastkey@new@normalized
			\tikzexternal@file@isuptodatetrue
		\else
			\tikzexternal@file@isuptodatefalse
			\immediate\openout\w@pgf@writea=\tikzexternal@curfilename\tikzexternal@check@uptodate@ext\relax%
			\immediate\write\w@pgf@writea{\tikzexternal@hashfct@serialize{\tikzexternal@lastkey@new}\tikzexternal@PERCENTchar}%
			\immediate\closeout\w@pgf@writea
		\fi
	\fi
}

% Checks whether the current picture needs to be externalized.
% 
% This is the case if 
% a) there is no external image yet,
% b) the picture has been invalidated manually.
%
% It returns \iftikzexternal@file@isuptodate accordingly.
% #1: the picture-content
\long\def\tikzexternal@externalizefig@systemcall@uptodatecheck#1{%
	\tikzexternal@checkforceremake
	\iftikzexternal@file@isuptodate
		\tikzexternal@check@uptodate@mode{#1}%
	\fi
	\iftikzexternal@file@isuptodate
		% check if there is already a file.
		% In that case, use it. If that is not the case, generate it and include it afterwards.
		\gdef\pgf@filename{}%
		\xdef\pgf@tempa{\noexpand\pgf@findfile\pgfsys@imagesuffixlist:+{\tikzexternal@curfilename}}%
		\pgf@tempa
		\ifx\pgf@filename\pgfutil@empty%
			\global\tikzexternal@file@isuptodatefalse
		\fi
	\fi
}%

% \pgf@filename will be empty if the assertion failed.
\def\tikzexternal@externalizefig@systemcall@assertsuccess#1{%
	% check if there is a file now and raise an error message if not.
	\gdef\pgf@filename{}%
	\xdef\pgf@tempa{\noexpand\pgf@findfile\pgfsys@imagesuffixlist:+{\tikzexternal@curfilename}}%
	\pgf@tempa
	\ifx\pgf@filename\pgfutil@empty%
		\tikzerror{Sorry, the system call '#1' did NOT result in a usable output file '\tikzexternal@curfilename' (expected one of \pgfsys@imagesuffixlist). Please verify that you have enabled system calls. For pdflatex, this is 'pdflatex -shell-escape'. Sometimes it is also named 'write 18' or something like that. Or maybe the command simply failed? Error messages can be found in '\tikzexternal@curfilename.log'. If you continue now, I'll try to typeset the picture}{}%
	\fi
}%

% Overwrite error message of pgf.
% This happens if the generated image was empty, i.e. if there was no \shipout.
\def\pgfexternal@error@no@shipout{%
	\begingroup
	\tikzexternal@assemble@systemcall{\pgfactualjobname}{\pgf@tempa}%
	\toks0=\expandafter{\pgf@tempa}%
	\tikzerror{Sorry, image externalization failed: the resulting image was EMPTY. I tried to externalize '\pgfactualjobname', but it seems there is no such image in the document!?
 \if\tikzexternal@opmode4 ^^J
\space\space You are currently using 'mode=convert with system call'. This problem can happen if the image (or one of the images preceeding it) was declared inside of a \string\label{} (i.e. in the .aux file): 'convert with system call' has no access to the main aux file.^^J
\space\space Possible solutions in this case:^^J
\space\space (a) Try using 'mode=list and make',^^J
\space\space (b) Issue the externalization command '\the\toks0' *manually* (also check the preceeding externalized images, perhaps the file name sequence is not correct).^^J
\space\space Repeat: the resulting image was EMPTY, your attention is required
\else
	\if\tikzexternal@opmode5 ^^J
\space\space You are currently using 'mode=list and make'. Possible solutions:^^J
\space\space (a) Try to delete `\tikzexternal@realjob.makefile'. Perhaps it is not up-to-date.^^J
\space\space (b) Perhaps pictures are declared inside of \string\label{} and the .aux file is not up-to-date. Re-run latex, perhaps re-generate the graphics as well.^^J
\space\space Repeat: the resulting image was EMPTY, your attention is required
	\fi
\fi}%
	\endgroup
}%

tikzlibrary3d.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/tikzlibrary3d.code.tex,v 1.2 2013/07/17 10:36:34 tantau Exp $



% New coordinate systems:

\tikzdeclarecoordinatesystem{xyz cylindrical}
{%
  \pgfset{/tikz/cs/.cd,angle=0,radius=0,z=0,#1}%
  \pgfpointcylindrical{\tikz@cs@angle}{\tikz@cs@xradius}{\tikz@cs@z}%
}

\tikzdeclarecoordinatesystem{xyz spherical}
{%
  \pgfset{/tikz/cs/.cd,angle=0,radius=0,latitude=0,longitude=0,#1}%
  \pgfpointspherical{\tikz@cs@angle}{\tikz@cs@latitude}{\tikz@cs@xradius}%
}

\pgfset{/tikz/cs/longitude/.store in=\tikz@cs@angle}
\pgfset{/tikz/cs/latitude/.store in=\tikz@cs@latitude}


% Options for transforming into a plane:

\tikzoption{plane origin}{\def\tikz@plane@origin{\tikz@scan@one@point\pgfutil@firstofone#1}}
\tikzoption{plane x}{\def\tikz@plane@x{\tikz@scan@one@point\pgfutil@firstofone#1}}
\tikzoption{plane y}{\def\tikz@plane@y{\tikz@scan@one@point\pgfutil@firstofone#1}}

\let\tikz@plane@origin=\pgfpointorigin
\def\tikz@plain@x{\pgfpointxy{1}{0}}
\def\tikz@plain@y{\pgfpointxy{0}{1}}

\tikzoption{canvas is plane}[]{
  \tikz@canvas@is@plane
}
\tikzoption{canvas is xy plane at z}{%
  \tikz@addtransform{\pgftransformshift{\pgfpointxyz{0}{0}{#1}}}%
}
\tikzoption{canvas is yx plane at z}[]{%
  \def\tikz@plane@origin{\pgfpointxyz{0}{0}{#1}}%
  \def\tikz@plane@x{\pgfpointxyz{0}{1}{#1}}%
  \def\tikz@plane@y{\pgfpointxyz{1}{0}{#1}}%
  \tikz@canvas@is@plane
}
\tikzoption{canvas is xz plane at y}[]{%
  \def\tikz@plane@origin{\pgfpointxyz{0}{#1}{0}}%
  \def\tikz@plane@x{\pgfpointxyz{1}{#1}{0}}%
  \def\tikz@plane@y{\pgfpointxyz{0}{#1}{1}}%
  \tikz@canvas@is@plane
}
\tikzoption{canvas is zx plane at y}[]{%
  \def\tikz@plane@origin{\pgfpointxyz{0}{#1}{0}}%
  \def\tikz@plane@x{\pgfpointxyz{0}{#1}{1}}%
  \def\tikz@plane@y{\pgfpointxyz{1}{#1}{0}}%
  \tikz@canvas@is@plane
}
\tikzoption{canvas is yz plane at x}[]{%
  \def\tikz@plane@origin{\pgfpointxyz{#1}{0}{0}}%
  \def\tikz@plane@x{\pgfpointxyz{#1}{1}{0}}%
  \def\tikz@plane@y{\pgfpointxyz{#1}{0}{1}}%
  \tikz@canvas@is@plane
}
\tikzoption{canvas is zy plane at x}[]{%
  \def\tikz@plane@origin{\pgfpointxyz{#1}{0}{0}}%
  \def\tikz@plane@x{\pgfpointxyz{#1}{0}{1}}%
  \def\tikz@plane@y{\pgfpointxyz{#1}{1}{0}}%
  \tikz@canvas@is@plane
}



% Transformation code

\def\tikz@canvas@is@plane{
  \pgf@process{\tikz@plane@x}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \pgf@process{\tikz@plane@y}%
  \pgf@xb=\pgf@x%
  \pgf@yb=\pgf@y%
  \pgf@process{\tikz@plane@origin}%
  \edef\pgf@marshal{\noexpand\tikz@addtransform{%
      \noexpand\pgftransformtriangle
      {\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\pgftransformscale{0.035146}%
      \noexpand\pgfsetxvec{\noexpand\pgfpoint{1cm}{0cm}}%
      \noexpand\pgfsetyvec{\noexpand\pgfpoint{0cm}{1cm}}%
      \noexpand\pgfsetzvec{\noexpand\pgfpoint{0cm}{0cm}}%
    }}%
  \pgf@marshal%
}

                                    
\endinput

tikzlibraryangles.code.tex
% Copyright 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[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/frontendlayer/tikz/libraries/tikzlibraryangles.code.tex,v 1.1 2013/08/28 15:24:27 tantau Exp $


\tikzset{
  pics/angle/.style = {
    setup code  = \tikz@lib@angle@parse#1\pgf@stop,
    background code = \tikz@lib@angle@background#1\pgf@stop,
    foreground code = \tikz@lib@angle@foreground#1\pgf@stop,  
  },
  pics/angle/.default=A--B--C,
  angle eccentricity/.initial=.6,
  angle radius/.initial=5mm
}

\def\tikz@lib@angle@background#1--#2--#3\pgf@stop{%
  \path [name prefix ..] [pic actions, draw=none] (#2.center)
    -- ++(\tikz@start@angle@temp:\tikz@lib@angle@rad pt)
    arc [start angle=\tikz@start@angle@temp, end
    angle=\tikz@end@angle@temp, radius=\tikz@lib@angle@rad pt] -- cycle;
}

\def\tikz@lib@angle@foreground#1--#2--#3\pgf@stop{%
  \path [name prefix ..] [pic actions, fill=none, shade=none]
  ([shift={(\tikz@start@angle@temp:\tikz@lib@angle@rad pt)}]#2.center)
    arc [start angle=\tikz@start@angle@temp, end
    angle=\tikz@end@angle@temp, radius=\tikz@lib@angle@rad pt];
  \ifx\tikzpictext\relax\else%
    \def\pgf@temp{\node()[name prefix
      ..,at={([shift={({.5*\tikz@start@angle@temp+.5*\tikz@end@angle@temp}:\pgfkeysvalueof{/tikz/angle
            eccentricity}*\tikz@lib@angle@rad pt)}]#2.center)}]}
    \expandafter\pgf@temp\expandafter[\tikzpictextoptions]{\tikzpictext};%
  \fi
}


\def\tikz@lib@angle@parse#1--#2--#3\pgf@stop{%
  % Compute radius:
  \pgfmathsetmacro\tikz@lib@angle@rad{\pgfkeysvalueof{/tikz/angle radius}}
  \ifdim\tikz@lib@angle@rad pt>0pt\else\def\tikz@lib@angle@rad{12}\fi%
  % Compute first coordinate:
  \pgf@process{\pgfpointanchor{#2}{center}}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \pgf@process{\pgfpointanchor{#1}{center}}%
  \pgf@xb=\pgf@x%
  \pgf@yb=\pgf@y%
  \pgf@process{\pgfpointanchor{#3}{center}}%
  \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%
  \pgfmathsetmacro{\tikz@start@angle@temp}{atan2(\the\pgf@yb,\the\pgf@xb)}
  \pgfmathsetmacro{\tikz@end@angle@temp}{atan2(\the\pgf@yc,\the\pgf@xc)}
  \ifdim\tikz@end@angle@temp pt<\tikz@start@angle@temp pt%
    \pgfmathsetmacro{\tikz@start@angle@temp}{\tikz@start@angle@temp-360}%
  \fi%  
}



\endinput

tikzlibraryarrows.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/tikzlibraryarrows.code.tex,v 1.1 2008/01/09 17:57:15 tantau Exp $

\usepgflibrary{arrows}

\endinput

tikzlibraryautomata.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/tikzlibraryautomata.code.tex,v 1.3 2008/07/14 10:30:36 tantau Exp $

\usetikzlibrary{shapes.multipart}

% Styles for states:

\tikzstyle{every state}=           []

\tikzstyle{state without output}=  [circle,draw,minimum size=2.5em,every state]
\tikzstyle{state with output}=     [circle split,draw,minimum size=2.5em,every state]

\tikzstyle{accepting by arrow}=    [after node path=
{
  {
    [to path=
    {
      [->,double=none,every accepting by arrow]
      --
      ([shift=(\tikz@accepting@angle:\tikz@accepting@distance)]\tikztostart.\tikz@accepting@angle)
          node [shape=rectangle,anchor=\tikz@accepting@anchor] {\tikz@accepting@text}
      }]
    edge ()
  }
}]
\tikzstyle{every accepting by arrow}=[]
\tikzstyle{accepting by double}= [double,outer sep=.5\pgflinewidth+.3pt] % .3pt is half double width distance

\tikzstyle{initial by arrow}=   [after node path=
{
  {
    [to path=
    {
      [->,double=none,every initial by arrow]
      ([shift=(\tikz@initial@angle:\tikz@initial@distance)]\tikztostart.\tikz@initial@angle)
          node [shape=rectangle,anchor=\tikz@initial@anchor] {\tikz@initial@text}
        -- (\tikztostart)}]
    edge ()
  }
}]
\tikzstyle{every initial by arrow}=[]

\tikzstyle{initial by diamond}=[shape=diamond]


\tikzoption{initial text}{\tikzaddafternodepathoption{\def\tikz@initial@text{#1}}}
\tikzoption{accepting text}{\tikzaddafternodepathoption{\def\tikz@accepting@text{#1}}}

\tikzoption{initial where}{\tikzaddafternodepathoption{\csname tikz@initial@compute@#1\endcsname}}
\tikzoption{accepting where}{\tikzaddafternodepathoption{\csname tikz@accepting@compute@#1\endcsname}}

\tikzoption{initial distance}{\tikzaddafternodepathoption{\def\tikz@initial@distance{#1}}}
\tikzoption{accepting distance}{\tikzaddafternodepathoption{\def\tikz@accepting@distance{#1}}}

\def\tikz@initial@text{start}
\def\tikz@accepting@text{}

\def\tikz@initial@distance{3ex}
\def\tikz@accepting@distance{3ex}

\def\tikz@initial@compute@above{\def\tikz@initial@angle{90}\def\tikz@initial@anchor{south}}
\def\tikz@initial@compute@below{\def\tikz@initial@angle{270}\def\tikz@initial@anchor{north}}
\def\tikz@initial@compute@left{\def\tikz@initial@angle{180}\def\tikz@initial@anchor{east}}
\def\tikz@initial@compute@right{\def\tikz@initial@angle{0}\def\tikz@initial@anchor{west}}

\def\tikz@initial@angle{180}
\def\tikz@initial@anchor{east}

\def\tikz@accepting@compute@above{\def\tikz@accepting@angle{90}\def\tikz@accepting@anchor{south}}
\def\tikz@accepting@compute@below{\def\tikz@accepting@angle{270}\def\tikz@accepting@anchor{north}}
\def\tikz@accepting@compute@left{\def\tikz@accepting@angle{180}\def\tikz@accepting@anchor{east}}
\def\tikz@accepting@compute@right{\def\tikz@accepting@angle{0}\def\tikz@accepting@anchor{west}}

\def\tikz@accepting@angle{0}
\def\tikz@accepting@anchor{west}


\tikzstyle{initial above}=        [initial by arrow,initial where=above]
\tikzstyle{initial below}=        [initial by arrow,initial where=below]
\tikzstyle{initial left}=         [initial by arrow,initial where=left]
\tikzstyle{initial right}=        [initial by arrow,initial where=right]

\tikzstyle{accepting above}=      [accepting by arrow,accepting where=above]
\tikzstyle{accepting below}=      [accepting by arrow,accepting where=below]
\tikzstyle{accepting left}=       [accepting by arrow,accepting where=left]
\tikzstyle{accepting right}=      [accepting by arrow,accepting where=right]


% Defaults:

\tikzstyle{state}=                [state without output]
\tikzstyle{accepting}=            [accepting by double]
\tikzstyle{initial}=              [initial by arrow]



\endinput

tikzlibrarybabel.code.tex
% Copyright 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[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/frontendlayer/tikz/libraries/tikzlibrarybabel.code.tex,v 1.1 2013/06/24 11:49:06 tantau Exp $

\tikzset{
  handle active characters in code,
  handle active characters in nodes
}

\endinput

tikzlibrarybackgrounds.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/tikzlibrarybackgrounds.code.tex,v 1.3 2013/07/18 17:07:38 tantau Exp $


% Layers

\pgfdeclarelayer{background}
\pgfsetlayers{background,main}


% Switch command
\tikzset{on background layer/.style={
    execute at begin scope={%
      \pgfonlayer{background}%
      \let\tikz@options=\pgfutil@empty%
      \tikzset{every on background layer/.try,#1}%
      \tikz@options},
    execute at end scope={\endpgfonlayer}
  }
}


% Main style

\tikzstyle{background rectangle}= [draw]
\tikzstyle{background top}=       [draw]
\tikzstyle{background bottom}=    [draw]
\tikzstyle{background left}=      [draw]
\tikzstyle{background right}=     [draw]
\tikzstyle{background grid}=      [help lines,draw]

\tikzoption{inner frame sep}{\def\tikz@framexsep{#1}\def\tikz@frameysep{#1}}
\tikzoption{inner frame xsep}{\def\tikz@framexsep{#1}}
\tikzoption{inner frame ysep}{\def\tikz@frameysep{#1}}
\def\tikz@framexsep{1ex}
\def\tikz@frameysep{1ex}

\tikzoption{outer frame sep}{\def\tikz@outerframexsep{#1}\def\tikz@outerframeysep{#1}}
\tikzoption{outer frame xsep}{\def\tikz@outerframexsep{#1}}
\tikzoption{outer frame ysep}{\def\tikz@outerframeysep{#1}}
\def\tikz@outerframexsep{0ex}
\def\tikz@outerframeysep{0ex}


% Looseness

\tikzstyle{loose background}=     [inner frame sep=2ex]
\tikzstyle{tight background}=     [inner frame sep=0ex]



% Showing background styles

\tikzstyle{framed}=                   [style=show background rectangle]
\tikzstyle{gridded}=                  [style=show background grid]

\tikzstyle{show background rectangle}=[execute at end picture=\tikz@background@framed]
\tikzstyle{show background top}=      [execute at end picture=\tikz@background@top]
\tikzstyle{show background bottom}=   [execute at end picture=\tikz@background@bottom]
\tikzstyle{show background left}=     [execute at end picture=\tikz@background@left]
\tikzstyle{show background right}=    [execute at end picture=\tikz@background@right]
\tikzstyle{show background grid}=     [execute at end picture=\tikz@background@grid]


% Implementation

\def\tikz@background@save{%
  \pgftransformreset%
  \ifx\tikz@bg@minx\@undefined%
    \pgf@xb=\pgf@picminx%
    \pgf@yb=\pgf@picminy%
    \pgf@xc=\pgf@picmaxx%
    \pgf@yc=\pgf@picmaxy%
    \pgfmathsetlength{\pgf@x}{\tikz@framexsep}%
    \pgfmathsetlength{\pgf@y}{\tikz@frameysep}%
    \advance\pgf@xb by-\pgf@x%
    \advance\pgf@yb by-\pgf@y%
    \advance\pgf@xc by\pgf@x%
    \advance\pgf@yc by\pgf@y%
    \edef\tikz@bg@minx{\the\pgf@xb}%
    \edef\tikz@bg@miny{\the\pgf@yb}%
    \edef\tikz@bg@maxx{\the\pgf@xc}%
    \edef\tikz@bg@maxy{\the\pgf@yc}%
    \pgfmathsetlength{\pgf@x}{\tikz@outerframexsep}%
    \pgfmathsetlength{\pgf@y}{\tikz@outerframeysep}%
    \advance\pgf@xb by-\pgf@x%
    \advance\pgf@yb by-\pgf@y%
    \advance\pgf@xc by\pgf@x%
    \advance\pgf@yc by\pgf@y%
    \edef\tikz@bg@outerminx{\the\pgf@xb}%
    \edef\tikz@bg@outerminy{\the\pgf@yb}%
    \edef\tikz@bg@outermaxx{\the\pgf@xc}%
    \edef\tikz@bg@outermaxy{\the\pgf@yc}%
  \fi%
}

\def\tikz@background@framed{%
  \tikz@background@save%
  \pgfonlayer{background}
    \path[style=background rectangle] (\tikz@bg@minx,\tikz@bg@miny) rectangle (\tikz@bg@maxx,\tikz@bg@maxy);
  \endpgfonlayer
}

\def\tikz@background@top{%
  \tikz@background@save%
  \pgfonlayer{background}
    \path[style=background top] (\tikz@bg@outerminx,\tikz@bg@maxy) -- (\tikz@bg@outermaxx,\tikz@bg@maxy);
  \endpgfonlayer
}

\def\tikz@background@bottom{%
  \tikz@background@save%
  \pgfonlayer{background}
    \path[style=background bottom] (\tikz@bg@outerminx,\tikz@bg@miny) -- (\tikz@bg@outermaxx,\tikz@bg@miny);
  \endpgfonlayer
}

\def\tikz@background@left{%
  \tikz@background@save%
  \pgfonlayer{background}
    \path[style=background left] (\tikz@bg@minx,\tikz@bg@outerminy) -- (\tikz@bg@minx,\tikz@bg@outermaxy);
  \endpgfonlayer
}

\def\tikz@background@right{%
  \tikz@background@save%
  \pgfonlayer{background}
    \path[style=background right] (\tikz@bg@maxx,\tikz@bg@outerminy) -- (\tikz@bg@maxx,\tikz@bg@outermaxy);
  \endpgfonlayer
}

\def\tikz@background@grid{%
  \tikz@background@save%
  \pgfonlayer{background}
    \path[style=background grid] (\tikz@bg@minx,\tikz@bg@miny) grid (\tikz@bg@maxx,\tikz@bg@maxy);
  \endpgfonlayer
}

                                    
\endinput

tikzlibrarybending.code.tex
% Copyright 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[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/frontendlayer/tikz/libraries/tikzlibrarybending.code.tex,v 1.2 2013/09/17 22:00:21 tantau Exp $

\usepgfmodule{bending}
\tikzset{arrows=[flex]}

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


tikzlibrarycalendar.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/tikzlibrarycalendar.code.tex,v 1.3 2013/07/15 12:05:31 tantau Exp $


\pgfutil@usemodule{pgfcalendar}


%
% General options (these options affect all calendars typeset unsind \calendar):
%
% Start, end, and code executed for each current date
%

\tikzoption{dates}{\tikz@lib@cal@parse#1\relax}
\def\tikz@lib@cal@parse#1to#2\relax{%
  \def\tikz@lib@cal@start{#1}
  \def\tikz@lib@cal@end{#2}%
}
\tikzoption{execute at begin day scope}{\expandafter\def\expandafter\tikz@atbegin@day\expandafter{\tikz@atbegin@day#1}}
\tikzoption{execute at end day scope}{%
  \def\pgf@temp{#1}%
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\tikz@atend@day%
  \expandafter\expandafter\expandafter{\expandafter\pgf@temp\tikz@atend@day}}
\tikzoption{execute before day scope}{\expandafter\def\expandafter\tikz@before@day\expandafter{\tikz@before@day#1}}
\tikzoption{execute after day scope}{\expandafter\def\expandafter\tikz@after@day\expandafter{\tikz@after@day#1}}

\let\tikz@atbegin@day=\pgfutil@empty
\let\tikz@atend@day=\pgfutil@empty
\let\tikz@before@day=\pgfutil@empty
\let\tikz@after@day=\pgfutil@empty



% 
% Options affecting some calendars:
%

%
% Shifts and skips
%

% Shift between days 

\tikzoption{day xshift}{\def\tikz@lib@cal@xshift{#1}}
\tikzoption{day yshift}{\def\tikz@lib@cal@yshift{#1}}

\def\tikz@lib@cal@yshift{3ex}
\def\tikz@lib@cal@xshift{3.5ex}


% Shift between months

\tikzoption{month xshift}{\def\tikz@lib@cal@month@xshift{#1}}
\tikzoption{month yshift}{\def\tikz@lib@cal@month@yshift{#1}}

\def\tikz@lib@cal@month@yshift{9ex}
\def\tikz@lib@cal@month@xshift{9ex}




% Templates for typesetting days, month, years

\tikzoption{day code}{\def\tikzdaycode{#1}}
\tikzoption{day text}{\def\tikzdaytext{#1}}
\tikzoption{days}{\tikzstyle{every day}+=[#1]}
\tikzstyle{every day}=[anchor=base east]

\tikzoption{month code}{\def\tikzmonthcode{#1}}
\tikzoption{month text}{\def\tikzmonthtext{#1}}
\tikzstyle{every month}=[]

\tikzoption{year code}{\def\tikzyearcode{#1}}
\tikzoption{year text}{\def\tikzyeartext{#1}}
\tikzstyle{every year}=[]

\def\tikzdaycode{\node[name=\pgfcalendarsuggestedname,every day]{\tikzdaytext};}
\def\tikzmonthcode{\node[every month]{\tikzmonthtext};}
\def\tikzyearcode{\node[every year]{\tikzyeartext};}

\def\tikzdaytext{\%d-}
\def\tikzmonthtext{\%mt}
\def\tikzyeartext{\%y0}


% Internal option for storing the "width" of a calendar as a number of
% days 

\tikzoption{tikz@lib@cal@width}{\def\tikz@lib@cal@width{#1}}

\def\tikz@lib@cal@width{1}

%
% Days on a line
%

\tikzstyle{day list downward}=[%
  execute before day scope={
    \ifdate{day of month=1}{\ifdate{equals=\pgfcalendarbeginiso}{}
      {%
        % On first of month, except when first date in calendar.
        \pgfmathsetlength{\pgf@y}{\tikz@lib@cal@month@yshift}%
        \pgftransformyshift{-\pgf@y}
      }%
    }{}%
  },  
  execute after day scope={\pgfmathsetlength{\pgf@y}{\tikz@lib@cal@yshift}\pgftransformyshift{-\pgf@y}},
  tikz@lib@cal@width=1
]
\tikzstyle{day list upward}=[%
  execute before day scope={
    \ifdate{day of month=1}{\ifdate{equals=\pgfcalendarbeginiso}{}
      {%
        % On first of month, except when first date in calendar.
        \pgftransformyshift{\tikz@lib@cal@month@yshift}%
      }%
    }{}%
  },  
  execute after day scope={\pgftransformyshift\tikz@lib@cal@yshift},
  tikz@lib@cal@width=1
]
\tikzstyle{day list right}=[%
  execute before day scope={
    \ifdate{day of month=1}{\ifdate{equals=\pgfcalendarbeginiso}{}
      {%
        % On first of month, except when first date in calendar.
        \pgftransformxshift{\tikz@lib@cal@month@xshift}%
      }%
    }{}%
  },  
  execute after day scope={\pgftransformxshift\tikz@lib@cal@xshift},
  tikz@lib@cal@width=30% not quite right, but close enough in most cases...
]

\tikzstyle{day list left}=[%
  execute before day scope={
    \ifdate{day of month=1}{\ifdate{equals=\pgfcalendarbeginiso}{}
      {%
        % On first of month, except when first date in calendar.
        \pgfmathsetlength{\pgf@x}{\tikz@lib@cal@month@xshift}
        \pgftransformxshift{-\pgf@x}%
      }%
    }{}%
  },  
  execute after day scope={
    \pgfmathsetlength{\pgf@x}{\tikz@lib@cal@xshift}
    \pgftransformxshift{-\pgf@x}%
  },
  tikz@lib@cal@width=30% not quite right, but close enough in most cases...
]



%
% Week list
%

\tikzstyle{week list}=[%
  execute before day scope={%
    \ifdate{day of month=1}{\ifdate{equals=\pgfcalendarbeginiso}{}
      {%
        % On first of month, except when first date in calendar.
        \pgfmathsetlength{\pgf@y}{\tikz@lib@cal@month@yshift}%
        \pgftransformyshift{-\pgf@y}
      }%
    }{}%
  }, 
  execute at begin day scope={%
    \pgfmathsetlength\pgf@x{\tikz@lib@cal@xshift}%
    \pgf@x=\pgfcalendarcurrentweekday\pgf@x%
    \pgftransformxshift{\pgf@x}%
  },
  execute after day scope={%
    \ifdate{Sunday}{%
      \pgfmathsetlength{\pgf@y}{\tikz@lib@cal@yshift}%
      \pgftransformyshift{-\pgf@y}
    }{}%
  },
  tikz@lib@cal@width=7
]



%
% Month list
%

\tikzstyle{month list}=[%
  execute before day scope={%
    \ifdate{day of month=1}{\ifdate{equals=\pgfcalendarbeginiso}{}
      {%
        % On first of month, except when first date in calendar.
        \pgfmathsetlength{\pgf@y}{\tikz@lib@cal@month@yshift}%
        \pgftransformyshift{-\pgf@y}
      }%
    }{}%
    \ifdate{day of month=1}
    {%
      \edef\tikz@lib@cal@month@list@start{\pgfcalendarcurrentweekday}%
    }{}%
    \ifdate{equals=\pgfcalendarbeginiso}%
    {%
      % Computer day of week for start of month
      {%
        \c@pgf@counta=\pgfcalendarcurrentjulian%
        \advance\c@pgf@counta by-\pgfcalendarcurrentday%
        \advance\c@pgf@counta by1\relax%
        \pgfcalendarjuliantoweekday{\c@pgf@counta}{\c@pgf@countb}%
        \xdef\pgf@temp{\the\c@pgf@countb}%
      }%
      \let\tikz@lib@cal@month@list@start=\pgf@temp%
    }{}%
  }, 
  execute at begin day scope={%
    \pgfmathsetlength\pgf@xa{\tikz@lib@cal@xshift}%
    \pgf@xb=\pgfcalendarcurrentday\pgf@xa%
    \advance\pgf@xb by\tikz@lib@cal@month@list@start\pgf@xa%
    \advance\pgf@xb by-\pgf@xa\relax%
    \pgftransformxshift{\pgf@xb}%
  },
  tikz@lib@cal@width=37
]




%
% Month labels
%

\tikzstyle{month label left}=[%
  execute before day scope={\ifdate{day of month=1}{\tikzmonthcode}{}},
  every month/.append style={anchor=base east,xshift=-3.5ex}
]

\tikzstyle{month label left vertical}=[%
  execute before day scope={\ifdate{day of month=1}{\tikzmonthcode}{}},
  every month/.append style={anchor=base east,xshift=-4.5ex,yshift=2.25ex,rotate=90}
]
  
\tikzstyle{month label right}=[%
execute before day scope={\ifdate{day of month=1}{%
    {%
      \pgfmathsetlength{\pgf@xa}{\tikz@lib@cal@xshift}%
      \pgftransformxshift{\tikz@lib@cal@width\pgf@xa}%
      \pgftransformxshift{-\pgf@xa}%
      \tikzmonthcode%
    }}{}},
  every month/.append style={anchor=base west,xshift=1ex}
]

\tikzstyle{month label right vertical}=[%
  execute before day scope={\ifdate{day of month=1}{%
    {%
      \pgfmathsetlength{\pgf@xa}{\tikz@lib@cal@xshift}%
      \pgftransformxshift{\tikz@lib@cal@width\pgf@xa}%
      \pgftransformxshift{-\pgf@xa}%
      \tikzmonthcode%
    }}{}},
  every month/.append style={anchor=base west,xshift=2ex,yshift=2.25ex,rotate=-90}
]

\tikzstyle{month label above centered}=[%
  execute before day scope={%
    \ifdate{day of month=1}{%
      {
        \pgfmathsetlength{\pgf@xa}{\tikz@lib@cal@xshift}%
        \pgf@xb=\tikz@lib@cal@width\pgf@xa%
        \advance\pgf@xb by-\pgf@xa%
        \pgf@xb=.5\pgf@xb%
        \pgftransformxshift{\pgf@xb}%
        \pgftransformxshift{-1.5ex}%
        \pgfmathsetlength{\pgf@y}{\tikz@lib@cal@yshift}%
        \pgftransformyshift{1.25\pgf@y}
        \tikzmonthcode%
      }
    }{}},
  every month/.append style={anchor=base}
]
  
\tikzstyle{month label above left}=[%
  execute before day scope={%
    \ifdate{day of month=1}{%
      {
        \pgftransformxshift{-3.25ex}%
        \pgfmathsetlength{\pgf@y}{\tikz@lib@cal@yshift}%
        \pgftransformyshift{1.25\pgf@y}
        \tikzmonthcode%
      }
    }{}},
  every month/.append style={anchor=base west}
]



\tikzstyle{month label above right}=[%
  execute before day scope={%
    \ifdate{day of month=1}{%
      {
        \pgfmathsetlength{\pgf@xa}{\tikz@lib@cal@xshift}%
        \pgf@xb=\tikz@lib@cal@width\pgf@xa%
        \advance\pgf@xb by-\pgf@xa%
        \pgftransformxshift{\pgf@xb}%
        \pgfmathsetlength{\pgf@y}{\tikz@lib@cal@yshift}%
        \pgftransformyshift{1.25\pgf@y}
        \tikzmonthcode%
      }
    }{}},
  every month/.append style={anchor=base east}
]
  
\tikzstyle{month label below centered}=[%
  execute before day scope={%
    \ifdate{day of month=1}{%
      {
        \pgfmathsetlength{\pgf@xa}{\tikz@lib@cal@xshift}%
        \pgf@xb=\tikz@lib@cal@width\pgf@xa%
        \advance\pgf@xb by-\pgf@xa%
        \pgf@xb=.5\pgf@xb%
        \pgftransformxshift{\pgf@xb}%
        \pgftransformxshift{-1.5ex}%
        \pgfmathsetlength{\pgf@y}{\tikz@lib@cal@yshift}%
        \pgftransformyshift{-1.25\pgf@y}
        \tikzmonthcode%
      }
    }{}},
  every month/.append style={anchor=base}
]
  
\tikzstyle{month label below left}=[%
  execute before day scope={%
    \ifdate{day of month=1}{%
      {
        \pgftransformxshift{-3.25ex}%
        \pgfmathsetlength{\pgf@y}{\tikz@lib@cal@yshift}%
        \pgftransformyshift{-1.25\pgf@y}
        \tikzmonthcode%
      }
    }{}},
  every month/.append style={anchor=base west}
]



%
% Code of the actual \calendar command (tikz.code.tex contains \let\calendar=\tikz@lib@cal@calendar):
%

\def\tikz@lib@cal@calendar{%
  \begingroup%
    \let\tikz@lib@cal@ifs=\pgfutil@empty%
    \tikz@expandcount=1000\relax%
    \tikzset{name=,at={(0,0)}}%
    \let\%=\pgfcalendarshorthand%
    \tikzset{every calendar/.try}%
    \tikz@lib@cal@scanner%
}

\def\tikz@lib@cal@scanner{%
  \afterassignment\tikz@lib@cal@handle\let\pgf@let@token=%
}

\def\tikz@lib@cal@handle{%
  \let\@next=\tikz@lib@cal@expand%
  \ifx\pgf@let@token;%
    \let\@next=\tikz@lib@cal@stop%
  \else%
    \ifx\pgf@let@token(%)
      \let\@next=\tikz@lib@cal@name%
    \else%
      \ifx\pgf@let@token a%
        \let\@next=\tikz@lib@cal@at%
      \else%
        \ifx\pgf@let@token[%
          \let\@next=\tikz@lib@cal@option%
        \else%
          \ifx\pgf@let@token i%
            \let\@next=\tikz@lib@cal@if%
          \fi%
        \fi%
      \fi%
    \fi%
  \fi%
  \@next%
}
\def\tikz@lib@cal@expand{%
  \advance\tikz@expandcount by -1%
  \ifnum\tikz@expandcount<0\relax%
    \tikzerror{Giving up on this calendar}%
    \let\@next=\tikz@lib@cal@end%
  \else%
    \let\@next=\tikz@lib@cal@@expand
  \fi%
  \@next}

\def\tikz@lib@cal@@expand{\expandafter\tikz@lib@cal@scanner\pgf@let@token}


\def\tikz@lib@cal@name#1){%
  \tikzset{name=#1}%
  \tikz@lib@cal@scanner%
}
\def\tikz@lib@cal@at t#1(#2){%
  \tikzset{at={(#2)}}%
  \tikz@lib@cal@scanner%
}
\def\tikz@lib@cal@option#1]{%
  \tikzset{#1}%
  \tikz@lib@cal@scanner%
}
\def\tikz@lib@cal@if f#1(#2){%
  \pgfutil@ifnextchar[{\tikz@lib@cal@if@opt{#2}}{\tikz@lib@cal@if@code{#2}}}%}

\def\tikz@lib@cal@if@opt#1[#2]{\tikz@lib@cal@if@code{#1}{\tikzset{#2}}}
\def\tikz@lib@cal@if@code#1#2{%
  \pgfutil@ifnextchar e{\tikz@lib@cal@if@else{#1}{#2}}{\tikz@lib@cal@if@else{#1}{#2}else{}}}

\def\tikz@lib@cal@if@else#1#2else{%
  \pgfutil@ifnextchar[{\tikz@lib@cal@if@else@opt{#1}{#2}}{\tikz@lib@cal@if@else@code{#1}{#2}}}%}
\def\tikz@lib@cal@if@else@opt#1#2[#3]{\tikz@lib@cal@if@else@code{#1}{#2}{\tikzset{#3}}}
\def\tikz@lib@cal@if@else@code#1#2#3{%
  \expandafter\def\expandafter\tikz@lib@cal@ifs\expandafter{\tikz@lib@cal@ifs\ifdate{#1}{#2}{#3}}%
  \tikz@lib@cal@scanner%
}
\def\tikz@lib@cal@stop{%
    \pgftransformshift{\tikz@node@at}%
    \expandafter\pgfcalendar\expandafter{\tikz@fig@name}{\tikz@lib@cal@start}{\tikz@lib@cal@end}%
    {%
      \tikz@before@day%  
      \scope%
        \tikz@atbegin@day%
        \tikz@lib@cal@ifs%
        \tikzdaycode%
        \tikz@atend@day%
      \endscope%
      \tikz@after@day%  
    }%
  \endgroup%
}

\tikzoption{if}{%
  \let\tikz@lib@cal@scanner@orig=\tikz@lib@cal@scanner%
  \let\tikz@lib@cal@scanner=\relax%
  \tikz@lib@cal@if f#1\relax%
  \let\tikz@lib@cal@scanner=\tikz@lib@cal@scanner@orig}



\endinput

tikzlibrarychains.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/tikzlibrarychains.code.tex,v 1.6 2013/07/15 12:05:31 tantau Exp $

\usetikzlibrary{positioning}

\tikzset{start chain/.default=,
         start chain/.code={%
    \tikz@lib@chain@parse{#1}%
    \ifx\tikz@lib@chain@name\pgfutil@empty%
      \def\tikz@lib@chain@name{chain}%
    \fi%
    \ifx\tikz@lib@chain@direction\relax%
      \let\tikz@lib@chain@direction=\tikz@lib@chain@default@direction%
    \fi%
    \expandafter\ifx\csname tikz@lib@chain@active@\tikz@lib@chain@name\endcsname\relax%
      \expandafter\let\csname tikz@lib@chain@active@\tikz@lib@chain@name\endcsname=\pgfutil@empty% does not matter
      \expandafter\global\expandafter\let\csname tikz@lib@chain@exists@\tikz@lib@chain@name\endcsname=\pgfutil@empty% does not matter
      % Setup chain parameters
      \expandafter\gdef\csname tikz@lib@chain@count@\tikz@lib@chain@name\endcsname{0}%
      \expandafter\global\expandafter\let\csname tikz@lib@chain@dir@\tikz@lib@chain@name\endcsname\tikz@lib@chain@direction%
      \let\tikz@lib@current@chain=\tikz@lib@chain@name%
      \let\chainin=\tikz@lib@chainin%
    \else%
      \tikzerror{Chain ``\tikz@lib@chain@name'' is already active}%
    \fi%
  },
  continue chain/.default=,
  continue chain/.code={%
    \tikz@lib@chain@parse{#1}%
    \ifx\tikz@lib@chain@name\pgfutil@empty%
      \let\tikz@lib@chain@name\tikz@lib@current@chain%
    \fi%
    \expandafter\ifx\csname tikz@lib@chain@exists@\tikz@lib@chain@name\endcsname\relax%
      \tikzerror{Unknown chain ``#1''}%
    \else%
      \let\tikz@lib@current@chain=\tikz@lib@chain@name%
      \expandafter\let\csname tikz@lib@chain@active@\tikz@lib@chain@name\endcsname=\pgfutil@empty% does not matter
      \ifx\tikz@lib@chain@direction\relax%
        % Just restart...
      \else%
        % Setup chain parameters
        \expandafter\global\expandafter\let\csname tikz@lib@chain@dir@\tikz@lib@chain@name\endcsname\tikz@lib@chain@direction%
      \fi%
    \fi%
  },
  join/.code=\tikz@lib@parse@join{#1},
  join/.default={}% 
}

\def\tikz@lib@chain@parse#1{%
  \pgfutil@in@{going }{#1}%
  \ifpgfutil@in@%
    \tikz@lib@chain@going#1\pgf@stop%
  \else%
    \pgfutil@in@{placed }{#1}%
    \ifpgfutil@in@%
      \tikz@lib@chain@positioning#1\pgf@stop%
    \else%
      \def\tikz@lib@chain@name{#1}%
      \let\tikz@lib@chain@direction\relax%
    \fi%
  \fi%
}

\def\tikz@lib@chain@going#1going #2\pgf@stop{%
  \def\tikz@lib@chain@name{#1}%
  \ifx\tikz@lib@chain@name\pgfutil@empty%
  \else%
    \tikz@lib@chain@strip#1\pgf@stop%%
  \fi%
  \tikz@lib@chain@is@goingtrue%
  \def\tikz@lib@chain@direction{%
    \ifx\tikzchainprevious\pgfutil@empty%
    \else%
      \tikz@lib@chain@place{#2}%
    \fi%
  }%  
}

\def\tikz@lib@chain@positioning#1placed #2\pgf@stop{%
  \def\tikz@lib@chain@name{#1}%
  \ifx\tikz@lib@chain@name\pgfutil@empty%
  \else%
    \tikz@lib@chain@strip#1\pgf@stop%%
  \fi%
  \tikz@lib@chain@is@goingfalse%
  \def\tikz@lib@chain@direction{\tikz@lib@chain@place{#2}}%
}
\newif\iftikz@lib@chain@is@going


\tikzset{/tikz/chain default direction/.code=%
  {%
    \tikz@lib@chain@parse{#1}%
    \let\tikz@lib@chain@default@direction=\tikz@lib@chain@direction%
  },%
  /tikz/chain default direction=going right
}

\def\tikz@lib@current@chain{chain}

\pgfutil@g@addto@macro\tikz@node@reset@hook{\let\tikz@lib@chain@caller=\relax}
\pgfutil@g@addto@macro\tikz@node@begin@hook{\tikz@lib@chain@caller}

\tikzset{
  on chain/.default=,
  on chain/.code=\tikz@lib@on@chain{#1}%
}
\def\tikz@lib@on@chain#1{%    
  \tikz@lib@chain@parse{#1}%
  \ifx\tikz@lib@chain@name\pgfutil@empty%
    \let\tikz@lib@chain@name\tikz@lib@current@chain%
  \fi%
  \expandafter\ifx\csname tikz@lib@chain@exists@\tikz@lib@chain@name\endcsname\relax%
    \tikzerror{Unknown chain ``\tikz@lib@chain@name''}%
  \else%
    \c@pgf@counta\csname tikz@lib@chain@count@\tikz@lib@chain@name\endcsname\relax%
    \ifnum\c@pgf@counta=0\relax%
      \global\let\tikzchainprevious=\pgfutil@empty%
    \else
      \xdef\tikzchainprevious{\tikz@lib@chain@name-\the\c@pgf@counta}%
    \fi%
    \advance\c@pgf@counta by1\relax%
    \xdef\tikzchaincount{\the\c@pgf@counta}%
    \ifx\tikz@lib@chain@direction\relax%
      \csname tikz@lib@chain@dir@\tikz@lib@chain@name\endcsname% use default
    \else%
      \tikz@lib@chain@direction%
    \fi%
    \edef\tikz@lib@chain@caller{\noexpand\tikz@lib@chain@last@found{\tikz@lib@chain@name}}%
  \fi%
}
\def\tikz@lib@chain@last@found#1{%
  % Increase the count and set name, if necessary.
  \c@pgf@counta\csname tikz@lib@chain@count@#1\endcsname\relax%
  \advance\c@pgf@counta by1\relax%
  \xdef\tikzchaincurrent{#1-\the\c@pgf@counta}%
  \expandafter\xdef\csname tikz@lib@chain@count@#1\endcsname{\the\c@pgf@counta}%
  \ifnum\c@pgf@counta=1\relax%
    \tikzset{alias/.expanded=#1-begin} % Define pseudostart
  \fi%    
  \tikzset{alias/.expanded=#1-end} % Define pseudostart
  \tikzset{alias/.expanded=#1-\the\c@pgf@counta} % Define pseudostart
  \tikz@lib@chain@direction%
  \tikzset{every on chain/.try}%
}


\def\tikz@lib@chain@place#1{%
  \pgfutil@in@{=}{#1}%
  \ifpgfutil@in@%
    \tikzset{#1}%
  \else%
    \tikzset{#1=of \tikzchainprevious}%
  \fi%
}

\def\tikz@lib@chain@strip#1 \pgf@stop{%
  \def\tikz@lib@chain@name{#1}%
}

\def\tikz@lib@parse@join#1{%
  \def\tikz@temp{#1}%
  \ifx\tikz@temp\pgfutil@empty%
    \tikz@lib@parse@join@by by \pgf@stop%
  \else%
    \pgfutil@in@{with }{#1}%
    \ifpgfutil@in@%
      \pgfutil@in@{by }{#1}%
      \ifpgfutil@in@%
        \tikz@lib@parse@join@with@by#1\pgf@stop%
      \else%
        \tikz@lib@parse@join@with@by#1 by \pgf@stop%
      \fi%
    \else%
      \tikz@lib@parse@join@by#1\pgf@stop%
    \fi%
  \fi%
}
\def\tikz@lib@parse@join@with@by with #1 by #2\pgf@stop{%
  \tikzset{after node path={(#1)edge[every join,#2](\tikzchaincurrent)}}%
}
\def\tikz@lib@parse@join@by by #1\pgf@stop{%
  \tikzset{after node path={\ifx\tikzchainprevious\pgfutil@empty\else (\tikzchainprevious)edge[every join,#1](\tikzchaincurrent)\fi}}%
}
\tikzset{every join/.style=}


\def\tikz@lib@chainin#1(#2){\pgfutil@ifnextchar[{\tikz@lib@chainin@{#2}}{\tikz@lib@chainin@{#2}[]}}%]
\def\tikz@lib@chainin@#1[#2]{\path[late options={name=#1,on chain,every chain in/.try,#2}]}


%
% Branches
%

\tikzset{start branch/.code={%
    % save last node on current chain:
    \let\tikz@lib@save@current\tikz@lib@current@chain%
    \pgfkeysalso{/tikz/start chain/.expand once=\tikz@lib@current@chain/#1}%
    \path[late options={name=\tikz@lib@save@current-end,on chain}];%
  }%
}
\tikzset{continue branch/.style={continue chain/.expand once=\tikz@lib@current@chain/#1}}

\endinput

tikzlibrarycircuits.code.tex
% Copyright 2008 by Till Tantau and others 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.markings,calc}


%
% Indicate that the picture contains a circuit
%
\tikzset{
  circuit/.style={
    every circuit/.try,
    /utils/exec=\tikz@lib@circ@on@tofalse,
    execute at begin to={
      \tikz@lib@circ@on@totrue
      \let\tikz@lib@circ@start@node\pgfutil@empty
      \def\tikz@lib@circ@end{-- (\tikztotarget) \tikztonodes}
    }
  }
}

\newif\iftikz@lib@circ@on@to


%
% General management
%

\tikzset{
  circuit handle symbol/.code={%
    \global\advance\tikz@lib@circ@count by1\relax%
    \iftikz@lib@circ@on@to
      {%
        % Compute the tikz@time...
        \pgfkeys{
          /pgf/key filters/active families or no family/.install key filter={/pgf/key filters/false}{/pgf/key filters/false},
          /tikz/circuits/pos grabber/.activate family}
        \pgfqkeysfiltered{/tikz}{pos=.5,#1}%
        \expandafter%
      }%
      \expandafter\def\expandafter\tikz@lib@circ@pos\expandafter{\tikz@time}%
      \pgfkeysalso{to path={
         \pgfextra{\tikz@lib@circ@on@tofalse}
         decorate [decoration={markings,mark connection node=mark node}]
          {
            \tikz@lib@circ@start@node
            \tikz@lib@circ@end
          }
        }}
      \ifx\tikz@lib@circ@pos\tikz@zero@text%
        \def\tikz@lib@circ@start@node{%
          {\pgfextra{\tikz@lib@circ@compute@direction{\tikz@lib@circ@start}}%
          node[alias=tikz@lib@circ@node@start,at={(0,0)},#1,pos=]{}}(tikz@lib@circ@node@start)}%
      \else%
        \ifx\tikz@lib@circ@pos\tikz@one@text%
          \def\tikz@lib@circ@end{
            {\pgfextra{\tikz@lib@circ@compute@direction{\tikz@lib@circ@target}}%
              node[alias=tikz@lib@circ@node\the\tikz@lib@circ@count,at={(0,0)},#1,pos=]{}}
            --(tikz@lib@circ@node\the\tikz@lib@circ@count)\tikztonodes
          }%
        \else%
          \edef\tikz@marshal{mark=at position \tikz@lib@circ@pos\space with}%
          \def\tikz@marshala{decoration=}%
          \expandafter\expandafter\expandafter\tikzset%
          \expandafter\expandafter\expandafter{\expandafter\tikz@marshala\expandafter{\tikz@marshal{\node[alias=mark node,#1,pos=]{};}}}
        \fi%
      \fi%
    \else
      \pgfkeysalso{#1}
    \fi
  }
}
\newcount\tikz@lib@circ@count
\def\tikz@zero@text{0.0}
\def\tikz@one@text{1.0}

\def\tikz@lib@circ@compute@direction#1{%
  \tikz@scan@one@point\tikz@lib@circ@save@start(\tikztostart)%
  \tikz@scan@one@point\tikz@lib@circ@save@target(\tikztotarget)%
  \pgf@process{\pgfpointnormalised{\pgfpointdiff{\tikz@lib@circ@start}{\tikz@lib@circ@target}}}%
  \pgf@ya=-\pgf@y%
  \pgftransformcm{\the\pgf@x}{\the\pgf@y}{\the\pgf@ya}{\the\pgf@x}{#1}%
}
\def\tikz@lib@circ@save@start#1{\def\tikz@lib@circ@start{#1}}
\def\tikz@lib@circ@save@target#1{\def\tikz@lib@circ@target{#1}}

\tikzset{
  circuits/pos grabber/.is family,
  pos/.belongs to family=/tikz/circuits/pos grabber,
  at start/.belongs to family=/tikz/circuits/pos grabber,
  very near start/.belongs to family=/tikz/circuits/pos grabber,
  near start/.belongs to family=/tikz/circuits/pos grabber,
  midway/.belongs to family=/tikz/circuits/pos grabber,
  near end/.belongs to family=/tikz/circuits/pos grabber,
  very near end/.belongs to family=/tikz/circuits/pos grabber,
  at end/.belongs to family=/tikz/circuits/pos grabber
}


%
% Declaring a new symbol
%
\tikzset{
  circuit declare symbol/.style args={#1}{
    % Declares a new circuit symbol.
    %
    % #1 = name
    % #2 = factor for default minimum width
    % #3 = factor for default minimum height
    %
    % The following styles are defined:
    %
    % #1
    % Can be given as an option to a "node" command or to a "to"
    % command. It takes a set of options as parameter that will be
    % passed to the option.
    %
    % set #1 graphic
    % This keys can be set to the necessary options to make a normal
    % node look like the symbol. For instance, for a resistor that is
    % rendered as a rectangle, this keys can be set, basically, to
    % "rectangle,draw". Set this key to use a different appearance for
    % symbols of kind #1. 
    %
    % every #1
    % This style will be included with every symbols of this kind and
    % can be used to configure them further.
    %
    % every circuit symbol
    % This style is also included with every symbol.
    #1/.style={circuit handle symbol={
        inner sep=0.5pt,
        every circuit symbol,
        #1/graphic,
        every #1/.try,
        ##1}
    },
    #1/graphic/.style={},
    set #1 graphic/.style={#1/graphic/.style={##1}}
  },
  circuit symbol unit/.code=\pgfmathsetlength\tikzcircuitssizeunit{#1},
  circuit symbol size/.style args={width #1 height #2}{
    minimum width=#1*\tikzcircuitssizeunit,
    minimum height=#2*\tikzcircuitssizeunit
  },
  huge circuit symbols/.style={circuit symbol unit=10pt},
  large circuit symbols/.style={circuit symbol unit=8pt},
  medium circuit symbols/.style={circuit symbol unit=7pt},
  small circuit symbols/.style={circuit symbol unit=6pt},
  tiny circuit symbols/.style={circuit symbol unit=5pt},
}

\newdimen\tikzcircuitssizeunit
\tikzcircuitssizeunit=7pt


%
% Annotations
%

\tikzset{
  circuit declare annotation/.style args={#1#2#3}{%
    #1/.style={
      append after command={%
        \bgroup
          [current point is local=true]
          [every circuit annotation/.try]
          [every #1/.try]
          [shift={(\tikzlastnode.north)}]
          [annotation arrow,->]
          [label distance=#2,##1]
          #3
          \tikz@after@path%
        \egroup%
      }
    },
    #1'/.style={
      append after command={%
        \bgroup
          [current point is local=true]
          [every circuit annotation/.try]
          [every #1/.try]
          [shift={(\tikzlastnode.south)},yscale=-1]
          [annotation arrow,->]
          [label distance=#2,##1]
          #3
          \tikz@after@path%
        \egroup%
      }
    }
  },
  annotation arrow/.style = {
    /utils/exec={\pgfsetarrowoptions{direction ee}{.4*\the\tikzcircuitssizeunit+.3*\the\pgflinewidth}},
    >=direction ee
  }
}



%
% Rotating symbols
%
\tikzset{
  point up/.style={rotate=90},
  point down/.style={rotate=-90},
  point left/.style={rotate=180},
  point right/.style={}
}      



%
% Basic theming
%

\tikzset{
  every circuit symbol/.style={},
  circuit symbol open/.style={draw},
  circuit symbol filled/.style={draw,fill=black},
  circuit symbol lines/.style={draw},
  circuit symbol wires/.style={draw},
}





%
% Labels
%

\tikzset{
  info/.code={\pgfutil@ifnextchar[\tikz@lib@circ@lab@plain{\tikz@lib@circ@lab@plain[]}#1\pgf@stop},%}
  info'/.code={\pgfutil@ifnextchar[\tikz@lib@circ@labp@plain{\tikz@lib@circ@labp@plain[]}#1\pgf@stop},%}
  info sloped/.code={\pgfutil@ifnextchar[\tikz@lib@circ@lab@sloped@plain{\tikz@lib@circ@lab@sloped@plain[]}#1\pgf@stop},%}
  info' sloped/.code={\pgfutil@ifnextchar[\tikz@lib@circ@lab@slopedp@plain{\tikz@lib@circ@lab@slopedp@plain[]}#1\pgf@stop},%}
  circuit declare unit/.style 2 args={
    %
    % Defines four styles that can be used to add labels to a node. 
    %
    #1/.code={\pgfutil@ifnextchar[\tikz@lib@circ@lab{\tikz@lib@circ@lab[]}##1\pgf@stop{#2}{#1}},%}
    #1 sloped/.code={\pgfutil@ifnextchar[\tikz@lib@circ@lab@sloped{\tikz@lib@circ@lab@sloped[]}##1\pgf@stop{#2}{#1}},%}
    #1'/.code={\pgfutil@ifnextchar[\tikz@lib@circ@labp{\tikz@lib@circ@labp[]}##1\pgf@stop{#2}{#1}},%} 
    #1' sloped/.code={\pgfutil@ifnextchar[\tikz@lib@circ@lab@slopedp{\tikz@lib@circ@lab@slopedp[]}##1\pgf@stop{#2}{#1}}%}
  }
}

\def\tikz@lib@circ@lab[#1]#2\pgf@stop#3#4{\tikzset{label={[every info/.try,every #4/.try,#1]$\mathrm{#2#3}$}}}
\def\tikz@lib@circ@lab@sloped[#1]#2\pgf@stop#3#4{\tikzset{label={[every info/.try,every #4/.try,transform shape,#1]$\mathrm{#2#3}$}}}
\def\tikz@lib@circ@labp[#1]#2\pgf@stop#3#4{\tikzset{label={[label position=below,every info/.try,every #4/.try,#1]$\mathrm{#2#3}$}}}
\def\tikz@lib@circ@lab@slopedp[#1]#2\pgf@stop#3#4{\tikzset{label={[label
position=below,every info/.try,every #4/.try,transform shape,#1]$\mathrm{#2#3}$}}}

\def\tikz@lib@circ@lab@plain[#1]#2\pgf@stop{\tikzset{label={[every info/.try,#1]#2}}}
\def\tikz@lib@circ@lab@sloped@plain[#1]#2\pgf@stop{\tikzset{label={[every info/.try,transform shape,#1]#2}}}
\def\tikz@lib@circ@labp@plain[#1]#2\pgf@stop{\tikzset{label={[label position=below,every info/.try,#1]#2}}}
\def\tikz@lib@circ@lab@slopedp@plain[#1]#2\pgf@stop{\tikzset{label={[label
position=below,every info/.try,transform shape,#1]#2}}}



\endinput


tikzlibrarycircuits.ee.code.tex

% Copyright 2008 by Till Tantau and others 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{circuits}
\usepgflibrary{shapes.gates.ee}


%
% Setting up an ee circuit
%
\tikzset{
  circuit ee/.style={
    circuit,
    every circuit ee/.try
  }
}       


%
% The default symbols (you need to load a sublib to install the actual rendering).
%

\tikzset{
  circuit declare symbol = resistor,
  circuit declare symbol = inductor,
  circuit declare symbol = capacitor,
  circuit declare symbol = contact,
  circuit declare symbol = ground,
  circuit declare symbol = battery,
  circuit declare symbol = diode,
  circuit declare symbol = Zener diode,
  circuit declare symbol = Schottky diode,
  circuit declare symbol = tunnel diode,
  circuit declare symbol = backward diode,
  circuit declare symbol = breakdown diode,
  circuit declare symbol = bulb,
  circuit declare symbol = current source,
  circuit declare symbol = voltage source,
  circuit declare symbol = current direction,
  circuit declare symbol = current direction',
  circuit declare symbol = make contact,
  circuit declare symbol = break contact,
  %
  set current direction graphic  = current direction ee graphic,
  set current direction' graphic = current direction' ee graphic,
}


%
% The default labels
%

\tikzset{
  circuit declare unit={ampere}{A},
  circuit declare unit={volt}{V},
  circuit declare unit={ohm}{\Omega},
  circuit declare unit={siemens}{S},
  circuit declare unit={henry}{H},
  circuit declare unit={farad}{F},
  circuit declare unit={coulomb}{C},
  circuit declare unit={voltampere}{VA},
  circuit declare unit={watt}{W},
  circuit declare unit={hertz}{Hz},
}



%
% The direction and arrow settings
%

\tikzset{
  % These styles should set the end-arrow.
  %
  % This arrow will generally be used to indicate current directions in a circuit:
  current direction arrow/.style = {
    /utils/exec={\pgfsetarrowoptions{direction ee}{1.3065*.5*\the\tikzcircuitssizeunit+1.3065*.3*\the\pgflinewidth}},
    >=direction ee,
    direction ee arrow = direction ee,
  }
}




\tikzset{
  current direction ee graphic/.style = {
    shape=direction ee,
    circuit symbol filled,
    current direction arrow,
    minimum width  = .5*\the\tikzcircuitssizeunit+.3*\the\pgflinewidth,
    minimum height = .5*\the\tikzcircuitssizeunit+.3*\the\pgflinewidth,
    transform shape
  },
  current direction' ee graphic/.style = {
    current direction ee graphic,
    rotate=180
  }
}



%
% Annotations
%

\tikzset{
  circuit declare annotation={direction info}{.5\tikzcircuitssizeunit}
  {
    (-1.25\tikzcircuitssizeunit,.3333\tikzcircuitssizeunit) edge[line to] (1.25\tikzcircuitssizeunit,.3333\tikzcircuitssizeunit)
  },
  circuit declare annotation={light emitting}{1.75\tikzcircuitssizeunit}
  {
    (-.2\tikzcircuitssizeunit,.65\tikzcircuitssizeunit) edge[line to] ++(45:1.25\tikzcircuitssizeunit)
    (.2\tikzcircuitssizeunit,.25\tikzcircuitssizeunit) edge[line to] ++(45:1.25\tikzcircuitssizeunit)
  },
  circuit declare annotation={light dependent}{1.75\tikzcircuitssizeunit}
  {
    [shift=(135:1.25\tikzcircuitssizeunit)]
    (.2\tikzcircuitssizeunit,.65\tikzcircuitssizeunit) edge[line to] ++(-45:1.25\tikzcircuitssizeunit)
    (-.2\tikzcircuitssizeunit,.25\tikzcircuitssizeunit) edge[line to] ++(-45:1.25\tikzcircuitssizeunit)
  },
  circuit declare annotation={adjustable}{1.5\tikzcircuitssizeunit}
  {
    [shift=(\tikzlastnode.center)]
    (-1.5\tikzcircuitssizeunit,-1.5\tikzcircuitssizeunit) edge[line to] (1.5\tikzcircuitssizeunit,1.5\tikzcircuitssizeunit)
  },
  circuit declare annotation={adjustable'}{1.5\tikzcircuitssizeunit}
  {
    [shift=(\tikzlastnode.center)]
    (-1.5\tikzcircuitssizeunit,1.5\tikzcircuitssizeunit) edge[line to] (1.5\tikzcircuitssizeunit,-1.5\tikzcircuitssizeunit)
  }
}


\endinput


tikzlibrarycircuits.ee.IEC.code.tex
% Copyright 2008 by Till Tantau and others 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{circuits.ee}
\usetikzlibrary{arrows}

\usepgflibrary{shapes.gates.ee.IEC}


%
% When this lib is loaded, all symbols default to IEC
%

\tikzset{
  circuit ee IEC/.style=
  {
    circuit ee,
    set resistor graphic              = resistor IEC graphic,
    set inductor graphic              = inductor IEC graphic,
    set capacitor graphic             = capacitor IEC graphic,
    set contact graphic               = contact IEC graphic,
    set ground graphic                = ground IEC graphic,
    set battery graphic               = battery IEC graphic,
    set diode graphic                 = diode IEC graphic,
    set Zener diode graphic           = Zener diode IEC graphic,
    set tunnel diode graphic          = tunnel diode IEC graphic,
    set backward diode graphic        = backward diode IEC graphic,
    set Schottky diode graphic        = Schottky diode IEC graphic,
    set breakdown diode graphic       = breakdown diode IEC graphic,
    set bulb graphic                  = bulb IEC graphic,
    set voltage source graphic        = voltage source IEC graphic,
    set current source graphic        = current source IEC graphic,
    set make contact graphic          = make contact IEC graphic,
    set break contact graphic         = break contact IEC graphic,
  }
}


%
% Resistors
%

\tikzset{
  resistor IEC graphic/.style={
    circuit symbol open,
    circuit symbol size=width 4 height 1,
    shape=rectangle ee,
    transform shape
  },
  var resistor IEC graphic/.style={
    circuit symbol lines,
    circuit symbol size=width 4.8 height 0.8,
    shape=var resistor IEC,
    transform shape,
    outer sep=0pt,
    cap=round
  }
}



%
% Inductors
%

\tikzset{
  inductor IEC graphic/.style={
    circuit symbol lines,
    circuit symbol size=width 4 height .5,
    transform shape,
    shape=inductor IEC,
    outer sep=0pt,
    cap=round
  },
  var inductor IEC graphic/.style={
    circuit symbol filled,
    circuit symbol size=width 4 height 1,
    transform shape,
    shape=rectangle ee
  }
}



%
% Capacitors
%

\tikzset{
  capacitor IEC graphic/.style={
    circuit symbol lines,
    circuit symbol size=width .5 height 2,
    transform shape,
    shape=capacitor IEC
  }
}



%
% Ground
%

\tikzset{
  ground IEC graphic/.style={
    circuit symbol lines,
    circuit symbol size=width .75 height 2,
    transform shape,
    shape=ground IEC
  }
}




%
% Battery
%

\tikzset{
  battery IEC graphic/.style={
    circuit symbol lines,
    circuit symbol size=width .5 height 2.5,
    transform shape,
    shape=battery IEC,
    transform shape
  }
}



%
% Diodes
%

\tikzset{
  %
  % normal diode
  %
  diode IEC graphic/.style={
    circuit symbol open,
    circuit symbol size=width 1.25 height 1.25,
    transform shape,
    shape=generic diode IEC,
    /pgf/generic diode IEC/before background={
      \pgfpathmoveto{\pgfqpoint{0pt}{-1pt}}
      \pgfpathlineto{\pgfqpoint{0pt}{1pt}}
      \pgfusepathqstroke
    },
  },
  var diode IEC graphic/.style={
    diode IEC graphic,
    circuit symbol filled
  }
}

\tikzset{
  %
  % Zener diode
  %
  Zener diode IEC graphic/.style={
    diode IEC graphic,
    /pgf/generic diode IEC/before background={
      \pgfpathmoveto{\pgfqpoint{-.5pt}{-1pt}}
      \pgfpathlineto{\pgfqpoint{0pt}{-1pt}}
      \pgfpathlineto{\pgfqpoint{0pt}{1pt}}
      \pgfusepathqstroke
    },
  },
  var Zener diode IEC graphic/.style={
    Zener diode IEC graphic,
    circuit symbol filled
  }
}

\tikzset{
  %
  % Schottky diode
  %
  Schottky diode IEC graphic/.style={
    diode IEC graphic,
    /pgf/generic diode IEC/before background={
      \pgfpathmoveto{\pgfqpoint{-.4pt}{-.6pt}}
      \pgfpathlineto{\pgfqpoint{-.4pt}{-1pt}}
      \pgfpathlineto{\pgfqpoint{0pt}{-1pt}}
      \pgfpathlineto{\pgfqpoint{0pt}{1pt}}
      \pgfpathlineto{\pgfqpoint{.4pt}{1pt}}
      \pgfpathlineto{\pgfqpoint{.4pt}{.6pt}}
      \pgfusepathqstroke
    },
  },
  var Schottky diode IEC graphic/.style={
    Schottky diode IEC graphic,
    circuit symbol filled
  }
}

\tikzset{
  %
  % tunnel diode
  %
  tunnel diode IEC graphic/.style={
    diode IEC graphic,
    /pgf/generic diode IEC/before background={
      \pgfpathmoveto{\pgfqpoint{-.5pt}{-1pt}}
      \pgfpathlineto{\pgfqpoint{0pt}{-1pt}}
      \pgfpathlineto{\pgfqpoint{0pt}{1pt}}
      \pgfpathlineto{\pgfqpoint{-.5pt}{1pt}}
      \pgfusepathqstroke
    },
  },
  var tunnel diode IEC graphic/.style={
    tunnel diode IEC graphic,
    circuit symbol filled
  }
}

\tikzset{
  % 
  % backward diode
  %
  backward diode IEC graphic/.style={
    diode IEC graphic,
    /pgf/generic diode IEC/before background={
      \pgfpathmoveto{\pgfqpoint{-.5pt}{-1pt}}
      \pgfpathlineto{\pgfqpoint{.5pt}{-1pt}}
      \pgfpathmoveto{\pgfqpoint{0pt}{-1pt}}
      \pgfpathlineto{\pgfqpoint{0pt}{1pt}}
      \pgfpathmoveto{\pgfqpoint{-.5pt}{1pt}}
      \pgfpathlineto{\pgfqpoint{.5pt}{1pt}}
      \pgfusepathqstroke
    },
  },
  var backward diode IEC graphic/.style={
    backward diode IEC graphic,
    circuit symbol filled
  }
}


\tikzset{
  %
  % breakdown diode
  %
  breakdown diode IEC graphic/.style={
    circuit symbol open,
    circuit symbol size=width 2.5 height 1.25,
    transform shape,
    shape=breakdown diode IEC,
  },
  var breakdown diode IEC graphic/.style={
    breakdown diode IEC graphic,
    circuit symbol filled
  }
}



%
% Contacts
%

\tikzset{
  contact IEC graphic/.style={
    circuit symbol filled,
    circuit symbol size=width .5 height .5,
    shape=circle ee,
    outer sep=.25\pgflinewidth
  },
%  connection IEC graphic/.style={
%    circuit symbol open,
%    circuit symbol size=width 1 height 1,
%    shape=circle ee,
%    outer sep=.25\pgflinewidth
%  }
}


%
% Bulbs
%

\tikzset{
  bulb IEC graphic/.style={
    circuit symbol lines,
    circuit symbol size=width 1.5 height 1.5,
    shape=generic circle IEC,
    /pgf/generic circle IEC/before background={
      \pgfpathmoveto{\pgfpointpolar{-135}{1pt}}
      \pgfpathlineto{\pgfpointpolar{45}{1pt}}
      \pgfpathmoveto{\pgfpointpolar{-45}{1pt}}
      \pgfpathlineto{\pgfpointpolar{135}{1pt}}
      \pgfusepathqstroke
    },
    transform shape
  }
}


%
% Current and voltage sources
%

\tikzset{
  current source IEC graphic/.style={
    circuit symbol lines,
    circuit symbol size=width 2 height 2,
    shape=generic circle IEC,
    /pgf/generic circle IEC/before background={
      \pgfpathmoveto{\pgfqpoint{0pt}{-1pt}}
      \pgfpathlineto{\pgfqpoint{0pt}{1pt}}
      \pgfusepathqstroke
    },
    transform shape
  },
  voltage source IEC graphic/.style={
    circuit symbol lines,
    circuit symbol size=width 2 height 2,
    shape=generic circle IEC,
    /pgf/generic circle IEC/before background={
      \pgfpathmoveto{\pgfqpoint{-1pt}{0pt}}
      \pgfpathlineto{\pgfqpoint{1pt}{0pt}}
      \pgfusepathqstroke
    },
    transform shape
  }
}



%
% Contacts
%

\tikzset{
  make contact IEC graphic/.style={
    circuit symbol wires,
    circuit symbol size=width 2 height 1,
    transform shape,
    shape=make contact IEC,
    outer sep=0pt,
    cap=round
  },
  var make contact IEC graphic/.style={
    circuit symbol wires,
    circuit symbol size=width 2.4 height 1,
    transform shape,
    shape=var make contact IEC,
    outer sep=0pt,
    cap=round
  }
}


\tikzset{
  break contact IEC graphic/.style={
    circuit symbol wires,
    circuit symbol size=width 2 height 1,
    transform shape,
    shape=break contact IEC,
    outer sep=0pt,
    cap=round
  },
}




\endinput


tikzlibrarycircuits.logic.CDH.code.tex
% Copyright 2008 by Till Tantau and others 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{circuits.logic.US}

\tikzset{
  circuit logic CDH/.style =
  {
    circuit logic US,
    set and gate graphic    = and gate CDH graphic,
    set nand gate graphic   = nand gate CDH graphic,
  }
}

\tikzset{
  circuit logic US make graphic=and gate CDH,
  circuit logic US make graphic=nand gate CDH,
}



\endinput


tikzlibrarycircuits.logic.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.

\usetikzlibrary{circuits}



%
% Provides a shortcut to the "logic gates inputs" key.
%

\tikzset{
  circuit logic/.style={
    circuit,
    inputs/.style={logic gate inputs={##1}},
    logic gate inverted radius=.25\tikzcircuitssizeunit,
    every circuit logic/.try,
  }
}       



%
% The default symbols (you need to load a sublib to install the actual rendering).
%

\tikzset{
  circuit declare symbol = and gate,
  circuit declare symbol = nand gate,
  circuit declare symbol = or gate,
  circuit declare symbol = nor gate,
  circuit declare symbol = xor gate,
  circuit declare symbol = xnor gate,
  circuit declare symbol = not gate,
  circuit declare symbol = buffer gate
}


\endinput


tikzlibrarycircuits.logic.IEC.code.tex
% Copyright 2008 by Till Tantau and others 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{circuits.logic}
\usepgflibrary{shapes.gates.logic.IEC}


%
% When this lib is loaded, all symbols default to IEC
%

\tikzset{
  circuit logic IEC/.style=
  {
    circuit logic,
    set and gate graphic    = and gate IEC graphic,
    set nand gate graphic   = nand gate IEC graphic,
    set or gate graphic     = or gate IEC graphic,
    set nor gate graphic    = nor gate IEC graphic,
    set xor gate graphic    = xor gate IEC graphic,
    set xnor gate graphic   = xnor gate IEC graphic,
    set not gate graphic    = not gate IEC graphic,
    set buffer gate graphic = buffer gate IEC graphic,
    %
    and gate IEC symbol    = {$\scriptstyle\char`\&$},
    nand gate IEC symbol   = {$\scriptstyle\char`\&$},
    or gate IEC symbol     = {$\scriptstyle\geq1$},
    nor gate IEC symbol    = {$\scriptstyle\geq1$},
    xor gate IEC symbol    = {$\scriptstyle=1$},
    xnor gate IEC symbol   = {$\scriptstyle=1$},
    not gate IEC symbol    = {$\scriptstyle1$},
    buffer gate IEC symbol = {$\scriptstyle1$},
  },
}


%
% The logical gate graphics are all nearly identical, so we provide a
% simple style for creating them:
%
\tikzset{
  circuit logic IEC make graphic/.style=
  {
    #1 graphic/.style={
      circuit symbol open,
      circuit symbol size=width 2.5 height 4,
      shape=#1,
      inner sep=.5ex
    }
  }
}


\tikzset{
  circuit logic IEC make graphic=and gate IEC,
  circuit logic IEC make graphic=nand gate IEC,
  circuit logic IEC make graphic=or gate IEC,
  circuit logic IEC make graphic=nor gate IEC,
  circuit logic IEC make graphic=xor gate IEC,
  circuit logic IEC make graphic=xnor gate IEC,
  circuit logic IEC make graphic=not gate IEC,
  circuit logic IEC make graphic=buffer gate IEC,
  circuit logic IEC make graphic=and gate CDH,
  circuit logic IEC make graphic=nand gate CDH,
}



\endinput


tikzlibrarycircuits.logic.US.code.tex
% Copyright 2008 by Till Tantau and others 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{circuits.logic}
\usepgflibrary{shapes.gates.logic.US}


%
% When this lib is loaded, all symbols default to IEC
%

\tikzset{
  circuit logic US/.style=
  {
    circuit logic,
    set and gate graphic    = and gate US graphic,
    set nand gate graphic   = nand gate US graphic,
    set or gate graphic     = or gate US graphic,
    set nor gate graphic    = nor gate US graphic,
    set xor gate graphic    = xor gate US graphic,
    set xnor gate graphic   = xnor gate US graphic,
    set not gate graphic    = not gate US graphic,
    set buffer gate graphic = buffer gate US graphic
  }
}


%
% The logical gate graphics are all nearly identical, so we provide a
% simple style for creating them:
%
\tikzset{
  circuit logic US make graphic/.style=
  {
    #1 graphic/.style={
      circuit symbol open,
      circuit symbol size=width 0 height 2.5,
      shape=#1,
      transform shape
    }
  }
}


\tikzset{
  circuit logic US make graphic=and gate US,
  circuit logic US make graphic=nand gate US,
  circuit logic US make graphic=or gate US,
  circuit logic US make graphic=nor gate US,
  circuit logic US make graphic=xor gate US,
  circuit logic US make graphic=xnor gate US,
  circuit logic US make graphic=not gate US,
  circuit logic US make graphic=buffer gate US,
}



\endinput


tikzlibrarydatavisualization.3d.code.tex
% Copyright 2008 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/datavisualization/tikzlibrarydatavisualization.3d.code.tex,v 1.1 2008/12/17 22:48:46 tantau Exp $

\usetikzlibrary{datavisualization}



% The following is not yet really implement. But you might get the idea...



% A 3d version of the school book plot

\tikzdatavisualizationset{
  school book 3d plot/.style={
    xyz Cartesian,
    x axis={
      visualize axis={y axis={goto=0},z axis={goto=0},styling/.style=->},
      visualize ticks={common={y axis={goto=0},z axis={goto=0},direction axis=y axis},only ticks={tick text at min extend}},
%      visualize ticks={common={y axis={goto=0},z axis={goto=0},direction axis=z axis}},
    },
    y axis={
      visualize axis={x axis={goto=0},z axis={goto=0},styling/.style=->},
      visualize ticks={common={x axis={goto=0},z axis={goto=0},direction axis=x axis},only ticks={tick text at min extend}},
%      visualize ticks={common={x axis={goto=0},z axis={goto=0},direction axis=z axis}},
    },
    z axis={
      visualize axis={x axis={goto=0},y axis={goto=0},styling/.style=->},
      visualize ticks={common={x axis={goto=0},y axis={goto=0},direction axis=x axis},only ticks={tick text at min extend}},
%      visualize ticks={common={x axis={goto=0},y axis={goto=0},direction axis=y axis}}
    },
    new line plot,
    every school book plot/.try
  }
}


% A 3d version of the scientific plot
%
% Here, a "length" is used for the length of the three
% axes, rather than a predetermined rectangle (this does not really
% make sense for the z-axis. You overrule these settings easily.

\tikzdatavisualizationset{
  scientific 3d plot/length/.initial=100pt,
  scientific 3d plot/.style={
    xyz Cartesian,
    x axis={
      length=\pgfkeysvalueof{/tikz/data visualization/scientific 3d plot/length},
      visualize axis={y axis={goto=min},z axis={goto=min}},
      visualize axis={y axis={goto=max},z axis={goto=min}},
      visualize axis={y axis={goto=min},z axis={goto=max}},
      visualize axis={y axis={goto=max},z axis={goto=max}}
    },
    y axis={
      length=\pgfkeysvalueof{/tikz/data visualization/scientific 3d plot/length},
      visualize axis={x axis={goto=min},z axis={goto=min}},
      visualize axis={x axis={goto=max},z axis={goto=min}},
      visualize axis={x axis={goto=min},z axis={goto=max}},
      visualize axis={x axis={goto=max},z axis={goto=max}}
    },
    z axis={
      length=\pgfkeysvalueof{/tikz/data visualization/scientific 3d plot/length},
      visualize axis={x axis={goto=min},y axis={goto=min}},
      visualize axis={x axis={goto=max},y axis={goto=min}},
      visualize axis={x axis={goto=min},y axis={goto=max}},
      visualize axis={x axis={goto=max},y axis={goto=max}}
    },
    new line plot
  }
}


tikzlibrarydatavisualization.barcharts.code.tex
% Copyright 2008 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/datavisualization/tikzlibrarydatavisualization.barcharts.code.tex,v 1.2 2008/07/21 06:22:22 tantau Exp $

\usetikzlibrary{datavisualization}
\usepgflibrary{datavisualization.barcharts}


\tikzdatavisualizationset{%
  candle stick plot/.style={
    new object={
      store=/tikz/data visualization/count,
      class=count,
      arg1=day
    },
    new axis=y axis,
    y axis/source=dax,
    y axis/source max=100,
    y axis/vec=\pgfqpoint{0cm}{1cm},
    new object={
      store=/tikz/data visualization/x line trans,
      class=line transformer,
      arg1=day,
      arg2=\pgfqpoint{3mm}{0mm}
    },
    new object={
      store=/tikz/data visualization/index,
      class=candle stick visualizer,
      arg1 from key=index/source
    },
  },
  index/source/.initial=index,
}


\endinput

tikzlibrarydatavisualization.code.tex
% Copyright 2008 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/datavisualization/tikzlibrarydatavisualization.code.tex,v 1.44 2013/07/19 13:16:48 tantau Exp $

\usepgfmodule{datavisualization}
\usetikzlibrary{backgrounds}


\tikzset{/tikz/data visualization/.is family,
  /tikz/data visualization/.unknown/.code={
    \let\tikz@dv@key\pgfkeyscurrentname% 
    \pgfkeys{/tikz/\tikz@dv@key/.try={#1}}%
    \ifpgfkeyssuccess%
    \else%
      \pgfkeys{/errors/unknown key={/tikz/data visualization/\tikz@dv@key}{#1}}%
    \fi%
  },
  /tikz/data visualization/data/.unknown/.code={%
    % Redirect to /pgf/data
    \let\tikz@dv@key\pgfkeyscurrentname% 
    \pgfkeys{/pgf/data/\tikz@dv@key/.try={#1}}%
    \ifpgfkeyssuccess%
    \else%
      \pgfkeys{/errors/unknown key={/pgf/data/\tikz@dv@key}{#1}}%
    \fi%
  }
}

\def\tikzdatavisualizationset{\pgfqkeys{/tikz/data visualization}}




% The main \datavisualization command
%
% This command must, as always, be given inside a tikz picture. It
% will add a data visualization to the picture; use "shift" option and
% friends to place the data visualization somewhere other than at the
% origin.
%
% The \datavisualization is followed by a sequence of blocks and ended
% with a semicolon. Each block may be one of the following:
%
% "data" blocks.
%
%   Syntax: data [options]                  % options specify an external source
%   Syntax: data [options] { inline data }  
%
%   The optional arguments may either specify an
%   external data source or the data may follow inline.
%
%   The options are executed for the path /pgf/data. The style
%   /tikz/every data is executed for each data, which can be useful to
%   generally set, say, a certain data format.
%
%
% "data set" blocks.
%
%   Syntax: data set [options] {name} = { ... }
%   Syntax: data set [options] {name} += { ... }
%   Syntax: data set [options] {name} 
%
%   The first syntax allows you to define a data set. The data block
%   inside {...} will be stored inside the data set
%   "name". Subsequently, the data set can be referenced by using the
%   third syntax. The second syntax allows you to extend the
%   definition of an already defined data set.
%
%
% "info" and "info'" blocks.
%
%   Syntax: info  [options] {code}
%   Syntax: info' [options] {code}
%
%   A block starting with "info" or "info'" may contain any code. It
%   will be executed after the visualization (info) or before the
%   visualization (info'). 
%
%
% Options blocks.
%
%   Syntax: [options]
%
%   The options will be executed immediately.
%
% Scope blocks.
%
%   Syntax: scope[options] { blocks }
%
%   The blocks are executed inside a scope for which the options are
%   set. This can be used to group data blocks.
%
% Examples:
%
% \datavisualization[schoolbook plot]
%   data [source=my_data_file.csv]
% ;
%
%  \datavisualization[schoolbook plot]
%    data [format=key value pairs]
%    {
%      x=0, y=0
%      x=1, y=1
%      x=2, y=4
%      x=3, y=9
%    };
%
%  \datavisualization[schoolbook plot]
%    data [format=function]
%    {
%      var x: interval [0:3];
%      func y = \value x*\value x;
%    }
%    [at begin visualization={
%      \fill [black!10] (visualization cs:x=0,y=0) -- (visualization cs:x=3,y=9);
%    }]
%    info[red]
%    {
%      \draw (visualization cs:x=0,y=0) -- (visualization cs:x=3,y=9);
%    };
%
%  \datavisualization[schoolbook plot]
%    data [/data point/label=first experiment,source=file_1]
%    data [/data point/label=second experiment,source=file_2]
%    data [/data point/label=third experiment,source=file_3]
%    data [/data point/label=prediction,format=function]
%      { var x: interval [0,1]; func y = rand(\value x); }
%    ;

\def\tikz@lib@datavisualization{
  \begingroup%
    \let\tikz@path@do@at@end=\relax%
    % Ok, first, start a new data visualization
    \pgfoonew \tikz@main@dv=new data visualization()%
    % Next, create a scope for the dv
    \pgfset{local bounding box=data visualization bounding box}%
    % Clear the axis list
    \pgfkeyslet{/tikz/data visualization/axes list}\pgfutil@empty%
    \pgfkeyslet{/tikz/data visualization/axes actions}\pgfutil@empty%
    \pgfkeyslet{/tikz/data visualization/label actions}\pgfutil@empty%
    \pgfkeyslet{/tikz/data visualization/legend actions}\pgfutil@empty%
    \pgfkeyslet{/tikz/data visualization/grid actions}\pgfutil@empty%
    \pgfkeyslet{/tikz/data visualization/major grid actions}\pgfutil@empty%
    \pgfkeyslet{/tikz/data visualization/minor grid actions}\pgfutil@empty%
    \pgfkeyslet{/tikz/data visualization/subminor grid actions}\pgfutil@empty%
    \pgfkeyslet{/tikz/data visualization/ticks actions}\pgfutil@empty%
    \pgfkeyslet{/tikz/data visualization/major ticks actions}\pgfutil@empty%
    \pgfkeyslet{/tikz/data visualization/minor ticks actions}\pgfutil@empty%
    \pgfkeyslet{/tikz/data visualization/subminor ticks actions}\pgfutil@empty%
    \tikz@main@dv.before visualization(%
    )%
    \tikz@main@dv.after visualization(%
      \tikz@lib@dv@alias@dv@bb
      \pgfkeysvalueof{/tikz/data visualization/grid actions}
      \pgfkeysvalueof{/tikz/data visualization/subminor grid actions}
      \pgfkeysvalueof{/tikz/data visualization/minor grid actions}
      \pgfkeysvalueof{/tikz/data visualization/major grid actions}
      \pgfkeysvalueof{/tikz/data visualization/ticks actions}
      \pgfkeysvalueof{/tikz/data visualization/subminor ticks actions}
      \pgfkeysvalueof{/tikz/data visualization/minor ticks actions}
      \pgfkeysvalueof{/tikz/data visualization/major ticks actions}
      \pgfkeysvalueof{/tikz/data visualization/axes actions}
      \pgfkeysvalueof{/tikz/data visualization/label actions}
      \pgfkeysvalueof{/tikz/data visualization/legend actions}
    )%
    %
    \pgfset{/pgf/data/continue code=\tikz@lib@dv@parse@loop}%
    % Now enter parse loop
    \tikz@lib@dv@parse@loop
}

\def\tikz@lib@dv@parse@loop{%  
  \pgfutil@ifnextchar d\tikz@lib@dv@handle@data{%
    \pgfutil@ifnextchar ;\tikz@lib@dv@parse@end{%
      \pgfutil@ifnextchar \par\tikz@lib@dv@handle@par{%
        \pgfutil@ifnextchar s\tikz@lib@dv@handle@beginscope{%
          \pgfutil@ifnextchar i\tikz@lib@dv@handle@info{%
            \pgfutil@ifnextchar [\tikz@lib@dv@handle@options{%
              \pgfutil@ifnextchar \egroup\tikz@lib@dv@handle@endscope{%
                \tikzerror{Semicolon expected}%
                \endgroup%
              }%
            }%
          }%
        }%
      }%
    }%
  }%
}
\def\tikz@lib@dv@parse@end;{%
    % Go!
    \tikz@main@dv.survey()%
    \tikz@main@dv.visualize()%
  \endgroup%
  \tikz@path@do@at@end%
}
\def\tikz@lib@dv@handle@par\par{\tikz@lib@dv@parse@loop}

\def\tikz@lib@dv@handle@options[#1]{%
  \tikzdatavisualizationset{#1}%
  \tikz@lib@dv@parse@loop%
}

\def\tikz@lib@dv@handle@beginscope scope{%
  \begingroup%
    \pgfutil@ifnextchar[\tikz@lib@dv@beg@opt{\tikz@lib@dv@beg@opt[]}%}
}
\def\tikz@lib@dv@beg@opt[#1]{%
  \pgfkeys{/pgf/data/.cd,/pgf/every data/.try,#1}%
  \pgf@dv@do@adddata{\pgfkeysvalueof{/pgf/data visualization/obj}.add data({{\begingroup\pgfkeys{/pgf/data/.cd,/pgf/every data/.try,#1}}})}%
  \pgfutil@ifnextchar\bgroup{
    \afterassignment\tikz@lib@dv@parse@loop%
    \let\tikz@dummy=%get rid of \bgroup
  }{%
    \tikzerror{Opening brace expected}%
    \tikz@lib@dv@parse@loop%
  }%
}
\def\tikz@lib@dv@handle@endscope{%
    \pgf@dv@do@adddata{\pgfkeysvalueof{/pgf/data visualization/obj}.add data(\endgroup)}%
  \endgroup%
  \afterassignment\tikz@lib@dv@parse@loop%
  \let\tikz@dummy=%get rid of \egroup
}

\def\tikz@lib@dv@handle@data data{%
  \pgfutil@ifnextchar g{\tikz@lib@dv@handle@data@group}{%
    \pgfutil@ifnextchar p{\tikz@lib@dv@handle@data@point}{%
      \pgfdata}}}

\def\tikz@lib@dv@handle@data@group group{\pgfutil@ifnextchar[{\tikz@lib@dv@handle@data@group@opt}{\tikz@lib@dv@handle@data@group@opt[]}}%}

\def\tikz@lib@dv@handle@data@group@opt[#1]#2{%
  \pgfutil@ifnextchar={\tikz@lib@dv@handle@data@group@def{#1}{#2}}{%
    \pgfutil@ifnextchar+{\tikz@lib@dv@handle@data@group@extend{#1}{#2}}{%
      \tikz@lib@dv@handle@data@group@use{#1}{#2}}}}

\def\tikz@lib@dv@handle@data@group@def#1#2={%
  \pgfkeys{/pgf/data/new group=#2}%
  \tikz@lib@dv@handle@data@group@extend{#1}{#2}+=%
}

\def\tikz@lib@dv@handle@data@group@extend#1#2+={%
  \pgfutil@ifnextchar\bgroup{
    \begingroup%
      \pgfkeys{/pgf/data/store in group=#2}%
      \pgf@dv@do@adddata{\pgfkeysvalueof{/pgf/data visualization/obj}.add data({{\begingroup\pgfkeys{/pgf/data/.cd,/pgf/every data/.try,#1}}})}%
      \afterassignment\tikz@lib@dv@parse@loop%
      \let\tikz@dummy=%get rid of \bgroup
  }{%
    \tikzerror{Opening brace expected}%
    \tikz@lib@dv@parse@loop%
  }%
}

\def\tikz@lib@dv@handle@data@group@use#1#2{%
  \pgfdata[#1,use group=#2]%
}

\def\tikz@lib@dv@handle@data@point point{\pgfutil@ifnextchar[{\tikz@lib@dv@handle@data@point@opt}{\tikz@lib@dv@handle@data@point@opt[]}}%]
\def\tikz@lib@dv@handle@data@point@opt[#1]{%
  \pgf@dv@do@adddata{\pgfkeysvalueof{/pgf/data visualization/obj}.add data({{\bgroup\pgfkeys{/data point/.cd,#1}\pgfdatapoint\egroup}})}%  
  \tikz@lib@dv@parse@loop%  
}

\def\tikz@lib@dv@handle@info info{%
  \pgfutil@ifnextchar'{\tikz@lib@dv@handle@info@prime}{\tikz@lib@dv@handle@info@noprime}}
\def\tikz@lib@dv@handle@info@noprime{%
  \pgfutil@ifnextchar[{\tikz@lib@dv@handle@info@block@opt}{\tikz@lib@dv@handle@info@block@opt[]}}%}
\def\tikz@lib@dv@handle@info@block@opt[#1]#2{%
  \tikz@main@dv.after visualization({\scope[#1]#2\endscope})%
  \tikz@lib@dv@parse@loop
}
\def\tikz@lib@dv@handle@info@prime'{%
  \pgfutil@ifnextchar[{\tikz@lib@dv@handle@info@block@opt@prime}{\tikz@lib@dv@handle@info@block@opt@prime[]}}%}
\def\tikz@lib@dv@handle@info@block@opt@prime[#1]#2{%
  \tikz@main@dv.before visualization({\scope[#1]#2\endscope})%
  \tikz@lib@dv@parse@loop
}


\pgfset{/pgf/every data/.style={/tikz/every data/.try,/tikz/data visualization/every data/.try}}


%
% Performing before/after stuff via keys
% 

\tikzdatavisualizationset{
  before survey/.code=\tikz@main@dv.before survey({#1}),
  after survey/.code=\tikz@main@dv.after survey({#1}),
  before visualization/.code=\tikz@main@dv.before visualization({#1}),
  after visualization/.code=\tikz@main@dv.after visualization({#1}),
  at start survey/.code=\tikz@main@dv.at start survey({#1}),
  at end survey/.code=\tikz@main@dv.at end survey({#1}),
  at start visualization/.code=\tikz@main@dv.at start visualization({#1}),
  at end visualization/.code=\tikz@main@dv.at end visualization({#1}),
}


\def\tikz@lib@dv@alias@dv@bb{
  \pgfnodealias{data bounding box}{data visualization bounding box}%
  \pgfkeys{/pgf/freeze local bounding box=data bounding box}%
} 

%
% The data point key
%
\tikzdatavisualizationset{
  data point/.code={
    \pgf@dv@do@adddata{\pgfkeysvalueof{/pgf/data visualization/obj}.add data({{\bgroup\pgfkeys{/data point/.cd,#1}\pgfdatapoint\egroup}})}%  
  }
}


%
% Object setup 
%

% The following key is used to create objects for the rendering
% pipeline. They cannot be created "directly" because when it is known
% that the objects needs to be created, in principle, many keys may
% not yet be known.
%
% The following options are used:
%
% store           = key that will store the object (handle)
% class           = class of the object
% arg1            = argument1 of the constructor
% ...
% arg8            = argument8 of the constructor
% when            = specifies when the object will be created. Defaults to
%                   "before survey", other possible values are "after survey" and
%                   "before/after visualization"
% before creation = code to be executed just before the object is
%                   created
% after creation  = code to be executed just after the object has been created
%
% The following styles may be useful:
%
% arg1 from key        = use the contents of the given key as arg1. Similar
%                        for other args          
% arg1 handle from key = the contents of the given key should contain
%                        an object. Then arg1 will be a handle to this
%                        object. Similar for other args          

\tikzdatavisualizationset{%
  new object/.code={%
    \def\tikz@dv@grabbed@when{before survey}%
    \let\tikz@dv@grabbed@store\pgfutil@empty
    \pgfkeys{/tikz/data visualization/new object/grab/.cd,#1}%
    \ifx\tikz@dv@grabbed@store\pgfutil@empty
    \else
      \pgfkeyslet{\tikz@dv@grabbed@store}\pgfutil@empty%
    \fi
    \edef\tikz@marshal{\noexpand\tikz@main@dv.\tikz@dv@grabbed@when(\noexpand\tikz@dv@newobject{\tikz@dv@grabbed@store}}%
    \tikz@marshal{#1})%
  },
  new object/grab/store/.store in=\tikz@dv@grabbed@store,
  new object/grab/when/.store in=\tikz@dv@grabbed@when,
  new object/grab/.unknown/.code={},%ignore
}

\def\tikz@dv@newobject#1#2{%
  \def\tikz@dv@new@obj@store{#1}%
  \ifx\tikz@dv@new@obj@store\pgfutil@empty%
    \let\tikz@dv@new@obj=\pgfutil@empty%
  \else%
    \pgfkeysgetvalue\tikz@dv@new@obj@store\tikz@dv@new@obj%
  \fi%
  \ifx\tikz@dv@new@obj\pgfutil@empty
    \let\tikz@dv@arg@a=\tikz@lib@notused%
    \let\tikz@dv@arg@b=\tikz@lib@notused%
    \let\tikz@dv@arg@c=\tikz@lib@notused%
    \let\tikz@dv@arg@d=\tikz@lib@notused%
    \let\tikz@dv@arg@e=\tikz@lib@notused%
    \let\tikz@dv@arg@f=\tikz@lib@notused%
    \let\tikz@dv@arg@g=\tikz@lib@notused%
    \let\tikz@dv@arg@h=\tikz@lib@notused%
    \let\tikz@dv@new@after=\relax%
    \pgfkeys{/tikz/data visualization/new object/parse/.cd,#2}
    \edef\pgf@marshal{\noexpand\pgfoonew\noexpand\tikzdvobj=new \tikz@dv@new@class(}%
    \tikz@dv@add@arg{}\tikz@dv@arg@a%
    \tikz@dv@add@arg{\expandafter,}\tikz@dv@arg@b%
    \tikz@dv@add@arg{\expandafter,}\tikz@dv@arg@c%
    \tikz@dv@add@arg{\expandafter,}\tikz@dv@arg@d%
    \tikz@dv@add@arg{\expandafter,}\tikz@dv@arg@e%
    \tikz@dv@add@arg{\expandafter,}\tikz@dv@arg@f%
    \tikz@dv@add@arg{\expandafter,}\tikz@dv@arg@g%
    \tikz@dv@add@arg{\expandafter,}\tikz@dv@arg@h%
    \expandafter\def\expandafter\pgf@marshal\expandafter{\pgf@marshal)}%
    \pgf@marshal%
    \tikzdvobj.default connects()%
    \ifx\tikz@dv@new@obj@store\pgfutil@empty%
    \else%
      \pgfkeyslet\tikz@dv@new@obj@store\tikzdvobj%
    \fi%
    \tikz@dv@new@after%
  \fi
}       
\def\tikz@lib@notused{\tikz@lib@notused}

\def\tikz@dv@add@arg#1#2{%
  \ifx#2\tikz@lib@notused%
  \else%
    \expandafter\expandafter\expandafter\def%
    \expandafter\expandafter\expandafter\pgf@marshal%
    \expandafter\expandafter\expandafter{\expandafter\pgf@marshal#1#2}%
  \fi%
}

\tikzdatavisualizationset{%
  new object/parse/.cd,
  store/.code=,% ignore
  when/.code=,% ignore
  class/.store in=\tikz@dv@new@class,
  before creation/.code=#1,
  after creation/.store in=\tikz@dv@new@after,
  arg1/.store in=\tikz@dv@arg@a,
  arg2/.store in=\tikz@dv@arg@b,
  arg3/.store in=\tikz@dv@arg@c,
  arg4/.store in=\tikz@dv@arg@d,
  arg5/.store in=\tikz@dv@arg@e,
  arg6/.store in=\tikz@dv@arg@f,
  arg7/.store in=\tikz@dv@arg@g,
  arg8/.store in=\tikz@dv@arg@h,
  arg1 from key/.code=\pgfkeysgetvalue{#1}{\tikz@dv@arg@a},
  arg2 from key/.code=\pgfkeysgetvalue{#1}{\tikz@dv@arg@b},
  arg3 from key/.code=\pgfkeysgetvalue{#1}{\tikz@dv@arg@c},
  arg4 from key/.code=\pgfkeysgetvalue{#1}{\tikz@dv@arg@d},
  arg5 from key/.code=\pgfkeysgetvalue{#1}{\tikz@dv@arg@e},
  arg6 from key/.code=\pgfkeysgetvalue{#1}{\tikz@dv@arg@f},
  arg7 from key/.code=\pgfkeysgetvalue{#1}{\tikz@dv@arg@g},
  arg8 from key/.code=\pgfkeysgetvalue{#1}{\tikz@dv@arg@h}
  arg1 handle from key/.code=\tikz@dv@handle@from@key{#1}{\tikz@dv@handle@a}{\tikz@dv@arg@a},
  arg2 handle from key/.code=\tikz@dv@handle@from@key{#1}{\tikz@dv@handle@b}{\tikz@dv@arg@b},
  arg3 handle from key/.code=\tikz@dv@handle@from@key{#1}{\tikz@dv@handle@c}{\tikz@dv@arg@c},
  arg4 handle from key/.code=\tikz@dv@handle@from@key{#1}{\tikz@dv@handle@d}{\tikz@dv@arg@d},
  arg5 handle from key/.code=\tikz@dv@handle@from@key{#1}{\tikz@dv@handle@e}{\tikz@dv@arg@e},
  arg6 handle from key/.code=\tikz@dv@handle@from@key{#1}{\tikz@dv@handle@f}{\tikz@dv@arg@f},
  arg7 handle from key/.code=\tikz@dv@handle@from@key{#1}{\tikz@dv@handle@g}{\tikz@dv@arg@g},
  arg8 handle from key/.code=\tikz@dv@handle@from@key{#1}{\tikz@dv@handle@h}{\tikz@dv@arg@h}
}

\def\tikz@dv@handle@from@key#1#2#3{%
  \pgfkeysvalueof{#1}.get handle(#2)%
  \def#3{#2}%
}




%
% Data visualization coordinate system
%
%
% This cs is used to refer to points in a datavisualization. The
% parameters are keys that are set in the /data point key
% directory. Then, a (virtual) data point is created and the
% calculated position is returned

\tikzdeclarecoordinatesystem{visualization}
{%
  \tikzset{/data point/.cd,#1}%
  \pgfpointdvlocaldatapoint%
}




%
%
% Axes
%
%



%
% Axis base
%

\tikzdatavisualizationset{%
  new axis base/.style={
    new object={
      class=scaling mapper,
      store=/tikz/data visualization/#1/scaling mapper,
      before creation={
        \pgfkeysgetvalue{/tikz/data visualization/#1/scaling}\tikz@temp
        \ifx\tikz@temp\pgfutil@empty%
          \pgfkeysgetvalue{/tikz/data visualization/#1/scaling/default}\tikz@temp
        \fi
        \expandafter\tikz@dv@lib@parse@scaling\tikz@temp\pgf@stop%
        \pgfkeyslet{/tikz/data visualization/#1/scaling}\tikz@temp
      },
      arg1 from key=/tikz/data visualization/#1/attribute,
      arg2/.expanded=\pgfkeysvalueof{/tikz/data visualization/#1/attribute}/scaled,
      arg3 from key=/tikz/data visualization/#1/scaling,
      arg4 from key=/tikz/data visualization/#1/function
    },
    #1/attribute/.initial=#1,
    #1/function/.initial=,
    #1/scaling/.initial=,
    #1/scaling/default/.initial=0 at 0 and 1 at 1,
    #1/ticks at/.initial=,
    #1/default ticks at/.initial=,
    #1/major ticks/.initial=,
    #1/minor ticks/.initial=,
    #1/subminor ticks/.initial=,
    #1/grid at/.initial=,
    #1/default grid at/.initial=,
    #1/major grid/.initial=,
    #1/minor grid/.initial=,
    #1/subminor grid/.initial=,
    #1/label/.initial=,
    #1/padding min/.initial=,
    #1/padding max/.initial=,
    #1/.code={
      \let\tikz@temp\tikz@dv@axis%
      \def\tikz@dv@axis{/tikz/data visualization/#1}%
      \expandafter\tikz@do@axis@options\expandafter{\tikz@temp}{##1}%
    },
    #1/@compute at positions/.initial=\tikz@lib@dv@compute@at@linear,
    axes list/.append={\tikz@lib@dv@do@axis{#1}}
  },
  all axes/.code={
    \def\tikz@lib@dv@args{#1}%
    \pgfkeysvalueof{/tikz/data visualization/axes list}%
  },
  % General styling
  styling/.style=,
  style/.style={styling/.append style={#1}},
  @node styling/.initial=,
  node styling/.style={%
    /utils/exec={\pgfkeysgetvalue{/tikz/data visualization/@node styling}\tikz@temp\expandafter\tikzset\expandafter{\tikz@temp}}},
  node style/.style={/tikz/data visualization/@node styling/.append={,#1}},
  % General extends (both axes, grid and ticks)
  low/.initial=0,
  high/.initial=0,
  padded/.style={low=padded min,high=padded max},
  tick length/.style={low={-#1},high={#1}},
  % General tick and grid keys:
  common/.initial=,
  major/.initial=,
  minor/.initial=,
  subminor/.initial=,
  @setup at setters/.style={
    common/.code=\tikz@lib@dv@add@{common}{##1},
    major/.code=\tikz@lib@dv@add@{major}{##1},
    minor/.code=\tikz@lib@dv@add@{minor}{##1},
    subminor/.code=\tikz@lib@dv@add@{subminor}{##1}
  },
  @setup at setters,
  % Tick keys
  direction axis/.initial=,
  % Tick text modifiers
  tick text low even padding/.initial=0pt,
  tick text high even padding/.initial=0pt,
  tick text low odd padding/.initial=0pt,
  tick text high odd padding/.initial=0pt,
  tick text odd padding/.style={tick text low odd padding={-#1},tick text high odd padding={#1}},
  tick text even padding/.style={tick text low even padding={-#1},tick text high even padding={#1}},
  tick text padding/.style={tick text odd padding={#1},tick text even padding={#1}},
  stack/.style={tick text even padding={#1}},
  stack'/.style={tick text odd padding={#1}},
  stack/.default=1em,
  stack'/.default=1em,
  tick text at low/.is if=tikz@dv@min@tick@node,
  tick text at high/.is if=tikz@dv@max@tick@node,
  no tick text/.style={tick text at low=false,tick text at high=false},
  %
  every major ticks/.style={style={line cap=round},tick length=2pt},
  every minor ticks/.style={style={solid, help lines,thin,line cap=round},tick length=1.4pt},
  every subminor ticks/.style={style={solid, help lines,line cap=round},tick length=0.8pt},
  clean ticks/.style={node style={fill=white}},
  % Default grid styles
  every grid/.style={high=max,low=min},
  every major grid/.style={style={solid, help lines,thin,black!25}},
  every minor grid/.style={style={solid, help lines,black!25}},
  every subminor grid/.style={style={solid, help lines,black!10}},
  at default ticks/.code={%
    \expandafter\pgfkeysalso\expandafter{\tikz@lib@dv@ticks@default@at}},
  at ticks/.code={%
    \expandafter\pgfkeysalso\expandafter{\tikz@lib@dv@ticks@default@at}%
    \expandafter\pgfkeysalso\expandafter{\tikz@lib@dv@ticks@at}},
}

\def\tikz@lib@dv@add@#1#2{\pgfkeysaddvalue{/tikz/data visualization/#1}{}{,#2}}

\def\tikz@dv@lib@parse@scaling#1 at#2and #3 at#4\pgf@stop{%
  \pgfmathsetmacro{\tikz@dv@lib@min@at}{#2}
  \pgfmathsetmacro{\tikz@dv@lib@max@at}{#4}
  \edef\tikz@temp{#1 at \tikz@dv@lib@min@at and #3 at \tikz@dv@lib@max@at}%
}


% Ticks at
\tikzdatavisualizationset{
  at/.code={\def\tikz@dv@at@list{#1}},
  also at/.code={\expandafter\def\expandafter\tikz@dv@at@list\expandafter{\tikz@dv@at@list,{#1}}},
  major at/.style={major={at={#1}}},
  minor at/.style={minor={at={#1}}},
  subminor at/.style={subminor={at={#1}}},
  major also at/.style={major={also at={#1}}},
  minor also at/.style={minor={also at={#1}}},
  subminor also at/.style={subminor={also at={#1}}},
  options at/.code={\expandafter\def\expandafter\tikz@dv@style@at@list\expandafter{\tikz@dv@style@at@list,{#1}}},
  no tick text at/.style={options at={#1 as [no tick text]}}
}


\def\tikz@lib@dv@do@axis#1{%
  \def\tikz@marshal{#1=}
  \expandafter\expandafter\expandafter\tikzdatavisualizationset%
  \expandafter\expandafter\expandafter{\expandafter\tikz@marshal\expandafter{\tikz@lib@dv@args}}
}

\def\tikz@do@axis@options#1#2{
  \pgfkeys{/tikz/data visualization/axis options/.cd,#2}
  \def\tikz@dv@axis{#1}
}
\let\tikz@dv@axis\pgfutil@empty

\tikzdatavisualizationset{
  every ticks/.style={
    node style={%
      font=\pgfutil@font@footnotesize,
      inner sep=1pt,
      outer sep=.1666em,
      rounded corners=1.5pt
    }
  },
  every data set label/.style={
    every ticks,
    node style={
      font=\pgfutil@font@small,
    }
  },
  @color of visualizer labels/.style={text=black},
  every label in legend/.style={
    node style={
      fill=none,
    }
  },
  every axis label/.style={
    node style={%
      font=\pgfutil@font@small,
    }
  }
}


\tikzset{
  /tikz/data visualization/axis options/.cd,
  %
  % Basic setters
  %
  attribute/.style={\tikz@dv@axis/attribute={#1}},
  function/.style={\tikz@dv@axis/function={#1}},
  scaling/.style={\tikz@dv@axis/scaling={#1}},
  padding min/.style={\tikz@dv@axis/padding min={#1}},
  padding max/.style={\tikz@dv@axis/padding max={#1}},
  padding/.style={padding min={-#1},padding max={#1}},
  label/.code={%
    \def\pgf@temp{#1}%
    \ifx\pgf@temp\tikz@lib@dv@auto@attribute%
      \tikzdatavisualizationset{\tikz@dv@axis/label/.expanded=$\noexpand\mathit{\pgfkeysvalueof{\tikz@dv@axis/attribute}}$}%
    \else
      \tikzdatavisualizationset{\tikz@dv@axis/label={#1}}%
    \fi
  },
  label/.default=\tikz@lib@dv@auto@attribute,
  %
  % Strategies
  %
  tick placement strategy/.style={\tikz@dv@axis/@compute at positions={#1}},
  linear steps/.style={tick placement strategy=\tikz@lib@dv@compute@at@linear},
  %
  % Attribute setter
  %
  goto/.code={\tikz@dv@goto{\tikz@dv@axis}{#1}},
  goto pos/.code={\tikz@dv@goto@pos{\tikz@dv@axis}{#1}},
  anchor at min/.code={\tikz@lib@dv@special@at{\tikz@dv@axis}{\tikz@dv@min@anchor}},
  anchor at max/.code={\tikz@lib@dv@special@at{\tikz@dv@axis}{\tikz@dv@max@anchor}},
  %
  % Visualization setters
  %
  visualize axis/.code=\expandafter\tikz@lib@dv@av\expandafter{\tikz@dv@axis}{#1},
  %
  % Ticks settings
  %
  ticks/.style={\tikz@dv@axis/ticks at/.append={,#1}},
  ticks/.default=some,
  visualize ticks/.code=\expandafter\tikz@lib@dv@tv\expandafter{\tikz@dv@axis}{#1},
  %
  % Grid settings
  %
  grid/.style={\tikz@dv@axis/grid at/.append={,#1}},
  grid/.default=at default ticks,
  visualize grid/.code=\expandafter\tikz@lib@dv@gv\expandafter{\tikz@dv@axis}{#1},
  % 
  ticks and grid/.style={\tikz@dv@axis/ticks at/.append={,#1},\tikz@dv@axis/grid at/.append={,#1}},
  % 
  % Visualizing axis labels
  % 
  visualize label/.code=\expandafter\tikz@lib@dv@lv\expandafter{\tikz@dv@axis}{#1},
}

\def\tikz@lib@dv@auto@attribute{\tikz@lib@dv@auto@attribute}


% Range options
\tikzdatavisualizationset{
  axis options/.cd,
  % 
  % Including a value in the range 
  %
  include value/.style={%
    /tikz/data visualization/before survey/.expanded={%
      \noexpand\pgfkeysgetvalue{\tikz@dv@axis/scaling mapper}\noexpand\tikz@dv@axis@mapper%
      \noexpand\foreach \noexpand\tikz@lib@dv@temp in {#1} {%
        \noexpand\tikz@dv@axis@mapper.include in value(\noexpand\tikz@lib@dv@temp)%
      }%
    }%
  },
  % 
  % Directly setting the min or max
  % 
  min value/.style={
    /tikz/data visualization/at end survey/.expanded={%
      \noexpand\pgfkeysgetvalue{\tikz@dv@axis/scaling mapper}\noexpand\tikz@dv@axis@mapper%
      \noexpand\tikz@lib@dv@set\noexpand\tikz@dv@axis@mapper{#1}{min}%
    }
  },
  max value/.style={
    /tikz/data visualization/at end survey/.expanded={%
      \noexpand\pgfkeysgetvalue{\tikz@dv@axis/scaling mapper}\noexpand\tikz@dv@axis@mapper%
      \noexpand\tikz@lib@dv@set\noexpand\tikz@dv@axis@mapper{#1}{max}%
    }
  },
}

\def\tikz@lib@dv@set#1#2#3{%
  \pgfdvmathenter{\pgf@dv@value}{#2}%
  #1.get in range interval()%
  \pgfdvinrangeinterval.let #3(\pgf@dv@value)%
}

% Layer options
\tikzdatavisualizationset{
  axis layer/.style=on background layer,
  ticks layer/.style=on background layer,
  ticks node layer/.style=,
  grid layer/.style=on background layer,
}


% Axis visualization
%
% #1 = name of the to-be-visualized axis name
% #2 = options for the visualization

\def\tikz@lib@dv@av#1#2{
  \tikzdatavisualizationset{
    axes actions/.append={\tikz@lib@dv@show@axis{#1}{#2}}
  }
}

\def\tikz@lib@dv@show@axis#1#2{%
  \scope[data visualization/axis layer,/tikz/data visualization/.cd,low=min,high=max,every axis/.try,#2]
    \pgfkeysgetvalue{#1/scaling mapper}\tikz@dv@axis@mapper
    % Ok, calculate direction vector:
    \tikzpointandanchordirection{\tikz@dv@axis@mapper.set in to(min)}{\tikz@dv@axis@mapper.set in to(max)}
    \xdef\tikz@dv@axis@dir{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}
    \path[draw,/tikz/data visualization/styling]
    \pgfextra{
      {
        \tikz@dv@goto{#1}{\pgfkeysvalueof{/tikz/data visualization/low}}%
        \pgfpathdvmoveto%
      }
      {
        \tikz@dv@goto{#1}{\pgfkeysvalueof{/tikz/data visualization/high}}%
        \pgfpathdvlineto%
      }
    };
  \endscope
}

\def\tikz@dv@goto#1#2{%
  \edef\pgf@@temp{#2}%
  \ifx\pgf@@temp\tikz@lib@dv@padded@min@text%
    \pgfkeysvalueof{#1/scaling mapper}.set in to(min)%
    \pgfkeysvalueof{#1/scaling mapper}.get out()%
    \pgfkeysgetvalue{#1/padding min}\pgf@temp%
    \pgfmathparse{\pgf@temp}%
    \pgfkeyslet{/data point/\pgfdvout/offset}\pgfmathresult%
  \else%
    \ifx\pgf@@temp\tikz@lib@dv@padded@max@text%
      \pgfkeysvalueof{#1/scaling mapper}.set in to(max)%
      \pgfkeysvalueof{#1/scaling mapper}.get out()%
      \pgfkeysgetvalue{#1/padding max}\pgf@temp%
      \pgfmathparse{\pgf@temp}%
      \pgfkeyslet{/data point/\pgfdvout/offset}\pgfmathresult%
    \else%
      \pgfkeysvalueof{#1/scaling mapper}.set in to(#2)%
    \fi%
  \fi%
}

\def\tikz@dv@goto@pos#1#2{%
  \pgfkeyssetvalue{/data point/\pgfkeysvalueof{#1/attribute}/out pos}{#2}%
}

\def\tikz@lib@dv@padded@min@text{padded min}
\def\tikz@lib@dv@padded@max@text{padded max}
     
\def\tikz@lib@dv@special@at#1#2{%
  % Ok, calculate direction vector:
  \tikzpointandanchordirection{\pgfkeysvalueof{#1/scaling mapper}.set in to(min)}{\pgfkeysvalueof{#1/scaling mapper}.set in to(max)}
  \tikzset{anchor/.expanded=#2}
}


% Ticks visualization 
%
% #1 = name of axis on which ticks should be shown
% #2 = options for the visualization

\def\tikz@lib@dv@tv#1#2{
  \tikzdatavisualizationset{
    ticks actions/.append={\tikz@lib@dv@default@action{ticks}{#1}{#2}},
    major ticks actions/.append={\tikz@lib@dv@show@ticks{major}{#1}{#2}},
    minor ticks actions/.append={\tikz@lib@dv@show@ticks{minor}{#1}{#2}},
    subminor ticks actions/.append={\tikz@lib@dv@show@ticks{subminor}{#1}{#2}}
  }
}

\def\tikz@lib@dv@default@action#1#2#3{%
  \let\tikz@marshal\pgfutil@empty%
  {%
    \let\tikz@lib@dv@ticks@at\pgfutil@empty%
    \pgfkeysgetvalue{#2/ticks at}\tikz@lib@dv@ticks@default@at%
    \pgfkeysgetvalue{#2/#1 at}\tikz@lib@dv@settings%
    \pgfkeysgetvalue{#2/scaling mapper}\tikz@lib@dv@mapper
    % Normal minor etc. have no effect.
    \tikzdatavisualizationset{major/.code=,minor/.code=,subminor/.code=,common/.code=}
    \expandafter\tikzdatavisualizationset\expandafter{\tikz@lib@dv@settings}%
    \tikzdatavisualizationset{@setup at setters}%
    \pgfkeysgetvalue{/tikz/data visualization/compute step}\tikz@temp@step%
    \ifx\tikz@temp@step\pgfutil@empty%
    % do nothing
    \else%
      \pgfkeysvalueof{#2/@compute at positions}%
      \xdef\tikz@marshal{
        major={\pgfkeysvalueof{/tikz/data visualization/major}},
        minor={\pgfkeysvalueof{/tikz/data visualization/minor}},
        subminor={\pgfkeysvalueof{/tikz/data visualization/subminor}}}
    \fi
  }%
  \pgfkeyslet{#2/default #1 at}\tikz@marshal
}

\def\tikz@lib@dv@show@ticks#1#2#3{%
  % First, check whether there is anything to do at all:
  \pgfkeysgetvalue{#2/default ticks at}\tikz@lib@dv@default@settings%
  \ifx\tikz@lib@dv@default@settings\pgfutil@empty%
    \pgfkeysgetvalue{#2/ticks at}\tikz@lib@dv@settings%
  \else%
    \pgfkeysgetvalue{#2/ticks at}\tikz@lib@dv@settings%
    \expandafter\expandafter\expandafter\def%
    \expandafter\expandafter\expandafter\tikz@lib@dv@settings%
    \expandafter\expandafter\expandafter{\expandafter\tikz@lib@dv@default@settings\expandafter,\tikz@lib@dv@settings}
  \fi%
  \ifx\tikz@lib@dv@settings\pgfutil@empty%
    % Great, nothing to do
  \else
    {%
      \let\tikz@dv@at@list\pgfutil@empty%
      \let\tikz@dv@style@at@list\pgfutil@empty%
      \pgfkeysgetvalue{#2/scaling mapper}\tikz@lib@dv@mapper
      \expandafter\tikzdatavisualizationset\expandafter{\tikz@lib@dv@settings}%
      \scope[/tikz/data visualization/.cd,every ticks/.try,every #1 ticks/.try,#3]%
        % Setup options
        \pgfkeysgetvalue{/tikz/data visualization/common}\tikz@temp
        \expandafter\tikzdatavisualizationset\expandafter{\tikz@temp}
        \pgfkeysgetvalue{/tikz/data visualization/#1}\tikz@temp
        \expandafter\tikzdatavisualizationset\expandafter{\tikz@temp}
        \pgfkeysgetvalue{/tikz/data visualization/\pgfkeysvalueof{/tikz/data visualization/direction axis}/scaling mapper}\pgf@dv@tick@dir@mapper
        % Ok, now it's time to draw the ticks!
        \foreach \tikz@dv@tick@pos[count=\tikz@dv@tick@count] in \tikz@dv@at@list 
        {
          \ifx\tikz@dv@tick@pos\pgfutil@empty
            \c@pgf@counta=\tikz@dv@tick@count\relax%
            \advance\c@pgf@counta by-1\relax%
            \edef\tikz@dv@tick@count{\the\c@pgf@counta}%
          \else
            \expandafter\tikz@lib@dv@parse\tikz@dv@tick@pos\pgf@stop%
            \expandafter\tikzdatavisualizationset\expandafter{\tikz@lib@dv@tick@opt}%
            \tikz@lib@dv@mapper.set in to(\tikz@dv@tick@pos)%
            % First, compute position of tick:
            \pgf@process{\pgfpointdvlocaldatapoint}
            \xdef\pgf@dv@tick@origin{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}
            % Ok, calculate direction vector:
            \tikzpointandanchordirection{\pgf@dv@tick@dir@mapper.set in to(min)}{\pgf@dv@tick@dir@mapper.set in to(max)}
            \xdef\pgf@dv@tick@dir{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}
            % Now, show something:
            \tikz@lib@handle@at@style%
            \pgfkeysgetvalue{/tikz/data visualization/high}\tikz@dv@max@val%
            \pgfkeysgetvalue{/tikz/data visualization/low}\tikz@dv@min@val%
            \iftikz@dv@max@tick@node\pgfmathsetmacro\tikz@dv@max@val{%
              \tikz@dv@max@val+(\pgfkeysvalueof{%
                /tikz/data  visualization/tick text high
                \ifodd\tikz@dv@tick@count odd \else even \fi padding}%
              )}%
            \fi%
            \iftikz@dv@min@tick@node\pgfmathsetmacro\tikz@dv@min@val{%
              \tikz@dv@min@val+(\pgfkeysvalueof{%
                /tikz/data  visualization/tick text low
                \ifodd\tikz@dv@tick@count odd \else even \fi padding}%
              )}%
            \fi%
            \pgf@process{\pgfpointadd{\pgf@dv@tick@origin}{\pgfpointscale{\tikz@dv@max@val}{\pgf@dv@tick@dir}}}
            \xdef\tikz@dv@max@tick{\the\pgf@x,\the\pgf@y}
            \pgf@process{\pgfpointadd{\pgf@dv@tick@origin}{\pgfpointscale{\tikz@dv@min@val}{\pgf@dv@tick@dir}}}
            \xdef\tikz@dv@min@tick{\the\pgf@x,\the\pgf@y}
            \scope[data visualization/ticks layer]
              \tikzdatavisualizationset{every \ifodd\tikz@dv@tick@count odd \else even \fi tick/.try}
              \draw [/tikz/data visualization/styling] (\tikz@dv@min@tick) -- (\tikz@dv@max@tick);
            \endscope
            \iftikz@dv@min@tick@node
              \scope[data visualization/ticks node layer]
                \tikzdatavisualizationset{every \ifodd\tikz@dv@tick@count odd \else even \fi tick/.try}
                \path [/tikz/data visualization/styling] (\tikz@dv@min@tick) \tikz@dv@handle@tick{\tikz@dv@min@anchor};
              \endscope
            \fi
            \iftikz@dv@max@tick@node
              \scope[data visualization/ticks node layer]
                \tikzdatavisualizationset{every \ifodd\tikz@dv@tick@count odd \else even \fi tick/.try}
                \path [/tikz/data visualization/styling] (\tikz@dv@max@tick)   \tikz@dv@handle@tick{\tikz@dv@max@anchor};
              \endscope
            \fi
          \fi      
        }
      \endscope
    }
  \fi
}

\def\tikz@lib@dv@parse#1\pgf@stop{%
  \pgfutil@in@{as}{#1}%
  \ifpgfutil@in@%
    \tikz@lib@dv@parse@as#1\pgf@stop% 
  \else%
    \tikz@lib@dv@parse@as#1as\tikz@lib@dv@typeset\pgf@stop%
  \fi%
}
\def\tikz@lib@dv@parse@as#1as{%
  \def\tikz@dv@tick@pos{#1}%
  \pgfutil@ifnextchar[{\tikz@lib@dv@parse@as@opt}{\tikz@lib@dv@parse@as@opt[]}%]
}
\def\tikz@lib@dv@parse@as@opt[#1]{%
  \def\tikz@lib@dv@tick@opt{#1}%
  \pgfutil@ifnextchar\pgf@stop{\tikz@lib@dv@parse@as@text\tikz@lib@dv@typeset}{\tikz@lib@dv@parse@as@text}
}
\def\tikz@lib@dv@parse@as@text#1\pgf@stop{%
  \def\tikz@lib@dv@tick@text{#1}%
}

\def\tikz@lib@dv@typeset{%
  \pgfdvmathenter{\tikz@lib@dv@typesetnum}{\tikz@dv@tick@pos}%
  \pgfdvmathexitbyscientificformat{\tikz@lib@dv@typesetnum}{\tikz@lib@dv@typesetnum}% hmm... not sure about this...
  \pgfkeysvalueof{/tikz/data visualization/tick prefix}%
  \pgfkeys{/tikz/data visualization/tick typesetter=\tikz@lib@dv@typesetnum}%
  \pgfkeysvalueof{/tikz/data visualization/tick suffix}%
}

\newif\iftikz@dv@min@tick@node
\newif\iftikz@dv@max@tick@node

\def\tikz@dv@handle@tick#1{%
  \pgfextra{
    \ifx\tikz@lib@dv@tick@text\pgfutil@empty%
      \global\let\tikz@dv@tick@marshal=\pgfutil@empty% Skip!
    \else
      \def\tikz@dv@tick@marshal{node[anchor=#1,/tikz/data visualization/node styling]}%
      \expandafter\pgfutil@g@addto@macro\expandafter\tikz@dv@tick@marshal\expandafter{\expandafter{\tikz@lib@dv@tick@text}}
    \fi
  \expandafter}%
  \tikz@dv@tick@marshal
}       


\def\tikz@lib@handle@at@style{%
  \ifx\tikz@dv@style@at@list\pgfutil@empty% nothing to do
  \else%
    \let\tikz@dv@lib@this@at@style=\pgfutil@empty%
    \pgfdvmathenter{\tikz@temp}{\tikz@dv@tick@pos}%
    \pgfdvmathexitbyscientificformat{\tikz@dv@compare@to}{\tikz@temp}%
    \foreach \tikz@dv@at@style in \tikz@dv@style@at@list {%
      \ifx\tikz@dv@at@style\pgfutil@empty%
      \else%
        \expandafter\tikz@dv@lib@handle@one@at@style\tikz@dv@at@style\tikz@stop%
      \fi%
    }
    \ifx\tikz@dv@lib@this@at@style\pgfutil@empty%
    \else%
      \expandafter\tikzdatavisualizationset\expandafter{\tikz@dv@lib@this@at@style}%
    \fi%
  \fi%
}

\def\tikz@dv@lib@handle@one@at@style#1as#2[#3]#4\tikz@stop{%
  \pgfdvmathenter{\tikz@lib@dv@at@math@var}{#1}%
  \pgfdvmathexitbyscientificformat{\tikz@dv@temp}{\tikz@lib@dv@at@math@var}%
  \ifx\tikz@dv@temp\tikz@dv@compare@to%
    % Bingo!
    \expandafter\gdef\expandafter\tikz@dv@lib@this@at@style\expandafter{\tikz@dv@lib@this@at@style,#3}%
  \fi%
}


% Help function
\def\tikzpointandanchordirection#1#2{%
  % This function works like pgfpointdvdirection, but also computes
  % appropriate "min" and "max" anchors.
  \pgf@process{\pgfpointdvdirection{#1}{#2}}
  {
    \pgf@ya=\pgf@y
    \pgf@y=-\pgf@x
    \pgf@x=\pgf@ya
    \tikz@auto@anchor
    \xdef\tikz@dv@max@anchor{\tikz@anchor}
    \tikz@auto@anchor@prime
    \xdef\tikz@dv@min@anchor{\tikz@anchor}
  }
}




% Grid visualization 
%
% #1 = name of axis on which grid lines should be shown
% #2 = options for the visualization

\def\tikz@lib@dv@gv#1#2{
  \tikzdatavisualizationset{
    grid actions/.append={\tikz@lib@dv@default@action{grid}{#1}{#2}},
    major grid actions/.append={\tikz@lib@dv@show@grid{major}{#1}{#2}},
    minor grid actions/.append={\tikz@lib@dv@show@grid{minor}{#1}{#2}},
    subminor grid actions/.append={\tikz@lib@dv@show@grid{subminor}{#1}{#2}},
  }
}

\def\tikz@lib@dv@show@grid#1#2#3{%
  % First, check whether there is anything to do at all:
  \pgfkeysgetvalue{#2/default grid at}\tikz@lib@dv@default@settings%
  \ifx\tikz@lib@dv@default@settings\pgfutil@empty%
    \pgfkeysgetvalue{#2/grid at}\tikz@lib@dv@settings%
  \else%
    \pgfkeysgetvalue{#2/grid at}\tikz@lib@dv@settings%
    \expandafter\expandafter\expandafter\def%
    \expandafter\expandafter\expandafter\tikz@lib@dv@settings%
    \expandafter\expandafter\expandafter{\expandafter\tikz@lib@dv@default@settings\expandafter,\tikz@lib@dv@settings}
  \fi%
  \ifx\tikz@lib@dv@settings\pgfutil@empty%
    % Great, nothing to do
  \else
    {%
      \let\tikz@dv@at@list\pgfutil@empty
      \let\tikz@dv@style@at@list\pgfutil@empty
      \pgfkeysgetvalue{#2/scaling mapper}\tikz@lib@dv@mapper
      \let\tikz@lib@dv@ticks@default@at\pgfutil@empty%
      \scope[data visualization/grid layer,/tikz/data visualization/.cd,every grid,every #1 grid/.try,#3]
        % Setup options
        \pgfkeysgetvalue{#2/ticks at}\tikz@lib@dv@ticks@at%
        \expandafter\tikzdatavisualizationset\expandafter{\tikz@lib@dv@settings}%
        \pgfkeysgetvalue{/tikz/data visualization/common}\tikz@temp
        \expandafter\tikzdatavisualizationset\expandafter{\tikz@temp}
        \pgfkeysgetvalue{/tikz/data visualization/#1}\tikz@temp
        \expandafter\tikzdatavisualizationset\expandafter{\tikz@temp}
        \edef\tikz@lib@dv@dir@axis{/tikz/data visualization/\pgfkeysvalueof{/tikz/data visualization/direction axis}}%
        % Ok, now it's time to draw the grid!
        \foreach \tikz@dv@grid@pos in \tikz@dv@at@list 
        {
          \ifx\tikz@dv@grid@pos\pgfutil@empty
          \else
            \expandafter\tikz@lib@dv@parse\tikz@dv@grid@pos\pgf@stop%
            \expandafter\tikzdatavisualizationset\expandafter{\tikz@lib@dv@tick@opt}%
            \tikz@lib@dv@mapper.set in to(\tikz@dv@tick@pos)%
            \draw[/tikz/data visualization/styling]
              \pgfextra{
                % First, compute start of grid:
                \tikz@dv@goto{\tikz@lib@dv@dir@axis}{\pgfkeysvalueof{/tikz/data visualization/low}}%
                \pgfpathdvmoveto%
                \tikz@dv@goto{\tikz@lib@dv@dir@axis}{\pgfkeysvalueof{/tikz/data visualization/high}}%
                \pgfpathdvlineto%
              };
          \fi
        }
      \endscope
    }
  \fi
}









% 
% Label visualization 
%

\def\tikz@lib@dv@lv#1#2{
  \tikzdatavisualizationset{
    label actions/.append={\tikz@lib@dv@show@label{#1}{#2}}
  }
}

\def\tikz@lib@dv@show@label#1#2{%
  % First, check whether there is anything to do at all:
  \pgfkeysgetvalue{#1/label}\tikz@dv@lib@label%
  \ifx\tikz@dv@lib@label\pgfutil@empty%
    % Great, nothing to do
  \else
    \scope[anchor=center,/tikz/data visualization/.cd,every axis label/.try,#2]
      \expandafter\tikz@lib@dv@parse@node\tikz@dv@lib@label\pgf@stop
    \endscope
  \fi
}

\def\tikz@lib@dv@parse@node{\pgfutil@ifnextchar[\tikz@lib@dv@parse@node@opt{\tikz@lib@dv@parse@node@opt[]}}%}
\def\tikz@lib@dv@parse@node@opt[#1]#2\pgf@stop{
  \tikzdatavisualizationset{#1}
  \pgftransformshift{\pgfpointdvlocaldatapoint}%           
  \node [/tikz/data visualization/node styling] {#2};
}



%
% Tick placement strategies
%

\tikzdatavisualizationset{
  compute step/.initial=,
  step/.style={compute step=\def\tikz@lib@dv@step{#1}},
  minor steps between steps/.initial=,
  minor steps between steps/.default=9,
  phase/.initial=0,
  tick typesetter/.code=\pgfmathprintnumber{#1},
  tick prefix/.initial=,
  tick suffix/.initial=,
  tick unit/.style={tick suffix={$\,\rm#1$}},% this is an alias
}

\def\tikz@lib@dv@compute@at@linear{%
  % Setup about:
  \let\tikz@lib@dv@compute@about=\tikz@lib@dv@about@linear%
  \let\tikz@lib@dv@step\relax%
  \pgfkeysvalueof{/tikz/data visualization/compute step}
  \ifx\tikz@lib@dv@step\relax%
  \else%
    % Gather interesting values
    \tikz@lib@dv@mapper.get in range interval()%
    \pgfdvinrangeinterval.get min and max()%
    \pgfkeysgetvalue{/tikz/data visualization/phase}\tikz@temp
    \pgfdvmathenter{\tikz@dv@lib@phase}{\tikz@temp}
    \pgfdvmathenter{\tikz@dv@lib@step}{\tikz@lib@dv@step}
    % Compute start:
    \pgfdvmathsub{\tikz@dv@lib@temp}{\pgfdvmin}{\tikz@dv@lib@phase}% temp = dvmin - phase
    \pgfdvmathdiv{\tikz@dv@lib@temp}{\tikz@dv@lib@temp}{\tikz@dv@lib@step}% temp = temp/step
    \pgfdvmathfloor{\tikz@dv@lib@temp}{\tikz@dv@lib@temp}% temp = floor(temp)
    \pgfdvmathmul{\tikz@lib@dv@current}{\tikz@dv@lib@temp}{\tikz@dv@lib@step}% current = temp*step ...
    \pgfdvmathadd{\tikz@lib@dv@current}{\tikz@lib@dv@current}{\tikz@dv@lib@phase}% + phase
    \let\tikz@lib@dv@ats\pgfutil@empty%
    \let\tikz@lib@dv@minor@ats\pgfutil@empty%
    \tikz@lib@dv@mapper.get function(\tikz@temp)%
    \ifx\tikz@temp\pgfutil@empty%
      \pgfdvmathenter{\tikz@one@hundreth}{0.001}%
      \pgfdvmathsub{\tikz@lib@temp}{\pgfdvmax}{\pgfdvmin}%
      \pgfdvmathmul{\tikz@lib@dv@epsilon}{\tikz@lib@temp}{\tikz@one@hundreth}% epsilon = (max - min)/1000
    \else
      \let\tikz@lib@dv@epsilon\pgfdvmathalwayszero
    \fi
    \pgfdvmathsub{\tikz@lib@dv@min@minus@epsilon}{\pgfdvmin}{\tikz@lib@dv@epsilon}%
    \pgfdvmathadd{\tikz@lib@dv@max@plus@epsilon}{\pgfdvmax}{\tikz@lib@dv@epsilon}%
    \pgfkeysgetvalue{/tikz/data visualization/minor steps between steps}\tikz@lib@dv@substeps%
    \ifx\tikz@lib@dv@substeps\pgfutil@empty
    \else
      \pgfmathsetmacro\tikz@temp{\tikz@lib@dv@substeps+1}%
      \pgfdvmathenter{\tikz@dv@lib@substeps}{\tikz@temp}%
      \pgfdvmathdiv{\tikz@lib@dv@substep}{\tikz@dv@lib@step}{\tikz@dv@lib@substeps}%
    \fi
    \loop%
      \ifx\tikz@lib@dv@substeps\pgfutil@empty%
      \else%
        \let\tikz@lib@dv@subcurrent=\tikz@lib@dv@current%
        \pgfmathsetcount{\c@pgf@counta}{\tikz@lib@dv@substeps}%
        \let\tikz@lib@dv@next=\tikz@lib@dv@subloop%
        \tikz@lib@dv@subloop
      \fi%
      \pgfdvmathifless{\tikz@lib@dv@current}{\tikz@lib@dv@min@minus@epsilon}{}{%
        \pgfdvmathexitbyserializing{\tikz@temp}{\tikz@lib@dv@current}%
        \edef\tikz@lib@dv@ats{\tikz@lib@dv@ats,\tikz@temp}%
      }
      \pgfdvmathadd{\tikz@lib@dv@current}{\tikz@lib@dv@current}{\tikz@dv@lib@step}%
      \pgfdvmathifless{\tikz@lib@dv@current}{\tikz@lib@dv@max@plus@epsilon}{\tikz@lib@dv@continuetrue}{\tikz@lib@dv@continuefalse}%
    \iftikz@lib@dv@continue%
    \repeat%    
    \tikzdatavisualizationset{major/.expanded={at={\tikz@lib@dv@ats}},minor/.expanded={at={\tikz@lib@dv@minor@ats}}}%
  \fi%
}
\newif\iftikz@lib@dv@continue

\def\tikz@lib@dv@subloop{
  \pgfdvmathadd{\tikz@lib@dv@subcurrent}{\tikz@lib@dv@subcurrent}{\tikz@lib@dv@substep}%
  \pgfdvmathifless{\tikz@lib@dv@subcurrent}{\pgfdvmin}{}{%
    \pgfdvmathifless{\tikz@lib@dv@subcurrent}{\pgfdvmax}{%
      \pgfdvmathexitbyserializing{\tikz@temp}{\tikz@lib@dv@subcurrent}%
      \edef\tikz@lib@dv@minor@ats{\tikz@lib@dv@minor@ats,\tikz@temp}
      }{}}
  \advance\c@pgf@counta by-1\relax%
  \ifnum\c@pgf@counta=0\relax%
    \let\tikz@lib@dv@next=\relax
  \fi
  \tikz@lib@dv@next
}



%
% Ticks about settings
% 

\tikzdatavisualizationset{
  about/.style={compute step=\tikz@lib@dv@compute@about{#1}},
  about strategy/.initial=,
  standard about strategy/.style={about strategy={1.5/1.0,2.3/2.0,4/2.5,7/5,11/10}},
  standard about strategy,
  euro about strategy/.style={about strategy={1.5/1.0,3/2.0,7/5,11/10}},
  decimal about strategy/.style={about strategy={3/1.0,11/10}},
  half about strategy/.style={about strategy={2/1.0,7/5,11/10}},
  quarter about strategy/.style={about strategy={1.8/1.0,4/2.5,7/5,11/10}},
  int about strategy/.style={about strategy={1.5/1.0,2.5/2.0,3.5/3.0,4.5/4.0,7/5,11/10}},
  none/.style={compute step=},
  few/.style={about=3},
  some/.style={about=5},
  many/.style={about=10},
}

\def\tikz@lib@dv@about@linear#1{%
  \tikz@lib@dv@mapper.get in range interval()%
  \pgfdvinrangeinterval.get min and max()%
  \pgfdvmathsub{\tikz@lib@dv@diff}{\pgfdvmax}{\pgfdvmin}
  \pgfdvmathenter{\tikz@lib@dv@about@val}{#1}%
  \pgfdvmathdiv{\tikz@lib@dv@around}{\tikz@lib@dv@diff}{\tikz@lib@dv@about@val}%
  % Make mantisse sensible
  \pgfmathfloattomacro{\tikz@lib@dv@around}{\tikz@lib@dv@flags}{\tikz@lib@dv@mant}{\tikz@lib@dv@exp}
  \pgf@xc=\tikz@lib@dv@mant pt%
  \pgfkeysgetvalue{/tikz/data visualization/about strategy}\tikz@lib@dv@strat
  \foreach \tikz@lib@dv@threshold/\tikz@lib@replace in \tikz@lib@dv@strat
  {
    \ifdim\pgf@xc<\tikz@lib@dv@threshold pt%
      \global\pgf@xc=\tikz@lib@replace pt%
      \breakforeach
    \fi
  }
  \ifdim\pgf@xc<10pt%
    \pgfmathfloatcreate{\tikz@lib@dv@flags}{\pgf@sys@tonumber{\pgf@xc}}{\tikz@lib@dv@exp}
  \else
    \pgfmathsetmacro\tikz@lib@dv@exp{\tikz@lib@dv@exp+1}
    \divide\pgf@xc by 10\relax  
    \pgfmathfloatcreate{\tikz@lib@dv@flags}{\pgf@sys@tonumber{\pgf@xc}}{\tikz@lib@dv@exp}
  \fi
  \pgfmathfloattofixed{\pgfmathresult}
  \let\tikz@lib@dv@step=\pgfmathresult
}





%
% Logarithmic axes
%

\tikzset{
  /tikz/data visualization/axis options/.cd,
  exponential steps/.style={tick placement strategy=\tikz@lib@dv@compute@at@log},
  %
  % Basic setters
  %
  logarithmic/.style={
    \tikz@dv@axis/function=\pgfdvmathln{\pgfvalue}{\pgfvalue},
    \tikz@dv@axis/scaling/default=1 at 0 and 10 at 1,
    exponential steps
  }
}

\def\tikz@lib@dv@compute@at@log{%
  % Setup about:
  \let\tikz@lib@dv@compute@about=\tikz@lib@dv@about@log%
  \let\tikz@lib@dv@step\relax%
  \pgfkeysvalueof{/tikz/data visualization/compute step}
  \ifx\tikz@lib@dv@step\relax%
  \else%
    % Gather interesting values
    \tikz@lib@dv@mapper.get in range interval()%
    \pgfdvinrangeinterval.get min and max()%
    \pgfdvmathlog{\pgfdvminlog}{\pgfdvmin}%
    \pgfdvmathlog{\pgfdvmaxlog}{\pgfdvmax}%
    \pgfkeysgetvalue{/tikz/data visualization/phase}\tikz@temp
    \pgfdvmathenter{\tikz@dv@lib@phase}{\tikz@temp}
    \pgfdvmathenter{\tikz@dv@lib@step}{\tikz@lib@dv@step}
    % Compute start:
    \pgfdvmathsub{\tikz@dv@lib@temp}{\pgfdvminlog}{\tikz@dv@lib@phase}% temp = dvmin - phase
    \pgfdvmathdiv{\tikz@dv@lib@temp}{\tikz@dv@lib@temp}{\tikz@dv@lib@step}% temp = temp/step
    \pgfdvmathfloor{\tikz@dv@lib@temp}{\tikz@dv@lib@temp}% temp = floor(temp)
    \pgfdvmathmul{\tikz@lib@dv@current}{\tikz@dv@lib@temp}{\tikz@dv@lib@step}% current = temp*step ...
    \pgfdvmathadd{\tikz@lib@dv@current}{\tikz@lib@dv@current}{\tikz@dv@lib@phase}% + phase
    \let\tikz@lib@dv@ats\pgfutil@empty%
    \let\tikz@lib@dv@minor@ats\pgfutil@empty%
    \pgfdvmathenter{\tikz@one@hundreth}{0.001}%
    \pgfdvmathsub{\tikz@lib@temp}{\pgfdvmaxlog}{\pgfdvminlog}%
    \pgfdvmathmul{\tikz@lib@dv@epsilon}{\tikz@lib@temp}{\tikz@one@hundreth}% epsilon = (max - min)/100
    \pgfdvmathsub{\tikz@lib@dv@min@minus@epsilon}{\pgfdvminlog}{\tikz@lib@dv@epsilon}%
    \pgfdvmathadd{\tikz@lib@dv@max@plus@epsilon}{\pgfdvmaxlog}{\tikz@lib@dv@epsilon}%
    \pgfkeysgetvalue{/tikz/data visualization/minor steps between steps}\tikz@lib@dv@substeps%
    \ifx\tikz@lib@dv@substeps\pgfutil@empty
    \else
      \pgfmathsetmacro\tikz@temp{\tikz@lib@dv@substeps+1}%
      \pgfdvmathenter{\tikz@dv@lib@substeps}{\tikz@temp}%
    \fi
    \loop%
      \ifx\tikz@lib@dv@substeps\pgfutil@empty%
      \else%
        \let\tikz@lib@dv@subcurrent=\tikz@lib@dv@current%
        \pgfdvmathadd{\tikz@lib@dv@subcurrent@next}{\tikz@lib@dv@subcurrent}{\tikz@dv@lib@step}%
        \pgfdvmathpowten{\tikz@lib@dv@subcurrent}{\tikz@lib@dv@subcurrent}%
        \pgfdvmathpowten{\tikz@lib@dv@subcurrent@max}{\tikz@lib@dv@subcurrent@next}%
        \pgfdvmathsub{\tikz@lib@dv@subcurrent@diff}{\tikz@lib@dv@subcurrent@max}{\tikz@lib@dv@subcurrent}%
        \pgfdvmathdiv{\tikz@lib@dv@substep}{\tikz@lib@dv@subcurrent@diff}{\tikz@dv@lib@substeps}%
        \pgfmathsetcount{\c@pgf@counta}{\tikz@lib@dv@substeps}%
        \let\tikz@lib@dv@next=\tikz@lib@dv@subloop%
        \tikz@lib@dv@subloop
      \fi%
      \pgfdvmathifless{\tikz@lib@dv@current}{\tikz@lib@dv@min@minus@epsilon}{}{%
        \pgfdvmathpowten{\tikz@lib@dv@current@pow}{\tikz@lib@dv@current}%
        \pgfdvmathexitbyserializing{\tikz@temp}{\tikz@lib@dv@current@pow}%
        \edef\tikz@lib@dv@ats{\tikz@lib@dv@ats,\tikz@temp}%
      }
      \pgfdvmathadd{\tikz@lib@dv@current}{\tikz@lib@dv@current}{\tikz@dv@lib@step}%
      \pgfdvmathifless{\tikz@lib@dv@current}{\tikz@lib@dv@max@plus@epsilon}{\tikz@lib@dv@continuetrue}{\tikz@lib@dv@continuefalse}%
      \iftikz@lib@dv@continue%
    \repeat%    
    \tikzdatavisualizationset{major/.expanded={at={\tikz@lib@dv@ats}},minor/.expanded={at={\tikz@lib@dv@minor@ats}}}%
  \fi%
}
\newif\iftikz@lib@dv@continue


\def\tikz@lib@dv@about@log#1{%
  \tikz@lib@dv@mapper.get in range interval()%
  \pgfdvinrangeinterval.get min and max()%
  \pgfdvmathlog{\pgfdvmin}{\pgfdvmin}%
  \pgfdvmathlog{\pgfdvmax}{\pgfdvmax}%
  \pgfdvmathsub{\tikz@lib@dv@diff}{\pgfdvmax}{\pgfdvmin}
  \pgfdvmathenter{\tikz@lib@dv@about@val}{#1}%
  \pgfdvmathdiv{\tikz@lib@dv@around}{\tikz@lib@dv@diff}{\tikz@lib@dv@about@val}%
  % Make mantisse sensible
  \pgfmathfloattomacro{\tikz@lib@dv@around}{\tikz@lib@dv@flags}{\tikz@lib@dv@mant}{\tikz@lib@dv@exp}
  \ifdim\tikz@lib@dv@exp pt<0pt%
    \pgfmathfloatcreate{1}{1.0}{0}%
  \else
    \pgf@xc=\tikz@lib@dv@mant pt\relax%
    \ifdim\pgf@xc<2.5pt
      \pgfmathfloatcreate{1}{1.0}{\tikz@lib@dv@exp}
    \else\ifdim\pgf@xc<5.1pt
      \pgfmathfloatcreate{1}{3.0}{\tikz@lib@dv@exp}
    \else
      \pgfmathfloatcreate{1}{6.0}{\tikz@lib@dv@exp}
    \fi\fi
  \fi%
  \pgfmathfloattofixed{\pgfmathresult}
  \let\tikz@lib@dv@step=\pgfmathresult
}







%
% Cartesian axes
%

\tikzdatavisualizationset{%
  new Cartesian axis/.style={
    new axis base={#1},
    new object={
      class=linear transformer,
      store=/tikz/data visualization/#1/linear transformer,
      arg1/.expanded=\pgfkeysvalueof{/tikz/data visualization/#1/attribute}/scaled,
      arg2 from key=/tikz/data visualization/#1/unit vector,
    },
    #1/scaling/default/.initial=0 at 0 and 1 at 1cm,
    #1/unit vector/.initial=\pgfqpoint{1pt}{0pt},
  }
}

\tikzset{
  /tikz/data visualization/axis options/.cd,
  unit vector/.code=\tikz@scan@one@point\tikz@lib@dv@uv#1,
  length/.style={\tikz@dv@axis/scaling=min at 0 and max at #1},
  unit length/.code={\tikz@dv@parse@unit@length{#1}},
  power unit length/.style={\tikz@dv@axis/scaling=1 at 0 and 10 at #1}
}

\def\tikz@lib@dv@uv#1{%
  \pgfkeyssetvalue{\tikz@dv@axis/unit vector}{#1}
}

\def\tikz@dv@parse@unit@length#1{
  \pgfutil@in@{per}{#1}
  \ifpgfutil@in@%
    \tikz@dv@parse@unit@length@#1\pgf@stop%
  \else%
    \tikz@dv@parse@unit@length@#1per1units\pgf@stop%
  \fi%
}
\def\tikz@dv@parse@unit@length@#1per#2units{
  \pgfkeysalso{\tikz@dv@axis/scaling=0 at 0 and #2 at #1}
}


% 
% Common visualizer interface 
%

\tikzdatavisualizationset{
  new visualizer/.style n args={3}{
    #1/.code={
      \def\tikz@visualizer{#1}%
      \pgfkeys{/tikz/data visualization/visualizer options/.cd,##1}
      \pgf@dv@do@adddata{\pgfkeysvalueof{/pgf/data visualization/obj}.add data(\pgfkeys{/data point/set=#1})}%
    },
    /utils/exec={
      \advance\tikzdvvisualizercounter by 1\relax
      \edef\tikz@temp{/data point/set/#1/.initial=\the\tikzdvvisualizercounter}
      \expandafter\tikzset\expandafter{\tikz@temp}
    },
    /data point/#1/execute at begin/.initial={
      \pgfkeyssetvalue{/data point/set}{#1}
      \scope[
        #2,
        /tikz/data visualization/every visualizer/.try,
        /tikz/data visualization/visualizers/#1/signal,
        /tikz/data visualization/visualizers/#1/styling/.try]
    },
    /data point/#1/execute at end/.initial={
        \path; % invokes every path implicitly
      \endscope
    },
    /tikz/data visualization/visualizers/#1/signal/.code=\pgf@signalstyle.emit(),
    /tikz/data visualization/visualizers/#1/styling/.style=,
    /tikz/data visualization/visualizers/#1/label in legend options/.style={#3},
  },
  style sheet/.style={/data point/set/.style sheet={#1}},
  /pgf/data/set/.style={/data point/set=#1},
}

\tikzdatavisualizationset{
  new sub visualizer/.style n args={4}{
    #4/#1/.code={
      \def\tikz@visualizer{#4/#1}%
      \pgfkeys{/tikz/data visualization/visualizer options/.cd,##1}
    },
    /data point/#4/#1/execute at begin/.initial={
      \pgfkeyssetvalue{/data point/set}{#4}
      \scope[
        #2,
        /tikz/data visualization/every visualizer/.try,
        /tikz/data visualization/visualizers/#4/signal,
        /tikz/data visualization/visualizers/#4/styling/.try,
        /tikz/data visualization/visualizers/#4/#1/styling/.try]
    },
    /data point/#4/#1/execute at end/.initial={
        \path; % invokes every path implicitly
      \endscope
    },
    /tikz/data visualization/visualizers/#4/#1/styling/.style=,
    /tikz/data visualization/visualizers/#4/#1/label in legend options/.style={#3},
  }
}


\def\tikz@do@visualizer#1#2{%
  \tikzdatavisualizationset{
    #2=#1
  }
}

\newcount\tikzdvvisualizercounter

\newif\iftikz@dv@visualizer@label@inline

\tikzdatavisualizationset{visualizer options/.cd,
  @set/.style 2 args={
    /tikz/data visualization/visualizers/\tikz@visualizer/styling/.append style={/utils/exec={\let\tikz@dv@plot@handler=#1}},
    /tikz/data visualization/visualizers/\tikz@visualizer/label in legend options/.append style={#2}
  },
  no lines/.style={@set={\pgfplothandlerdiscard}{default label in legend mark}},
  smooth line/.style={@set={\pgfplothandlercurveto}{default label in legend path}},
  smooth cycle/.style={@set={\pgfplothandlerclosedcurve}{default label in legend closed path}},
  straight line/.style={@set={\pgfplothandlerlineto}{default label in legend path}},
  straight cycle/.style={@set={\pgfplothandlerpolygon}{default label in legend closed path}},
  polygon/.style={straight cycle},% alias
  gap line/.style={@set={\pgfplothandlergaplineto}{default label in legend path}},
  gap cycle/.style={@set={\pgfplothandlergapcycle}{gap circular label in legend line}}
}



% 
% Label visualizer 
%

\tikzdatavisualizationset{
  new label visualizer/.style 2 args={
    new object={
      when=before visualization,
      class=label visualizer,
      before creation={
        \begingroup
        \def\tikz@visualizer{#1}%
        \pgfkeys{/tikz/data visualization/visualizer label options/.cd,
          #2}
        \pgfkeysgetvalue{/tikz/data visualization/visualizer label options/text}\tikz@dv@temp@lab
        \def\tikz@tempa{
          \scope[
          /utils/exec=\def\tikz@visualizer{#1},%
          /tikz/data visualization/visualizer label options/.cd,
          #2]
          \tikzdatavisualizationset{every data set label/.try}
          \path [
            /data point/set=#1,/utils/exec=\pgf@signalstyle.emit(),
            /tikz/data visualization/.cd,every label in data/.try]
          (label visualizer coordinate') --
          (label visualizer coordinate)
          node [
            auto,
            at end,
            /tikz/data visualization/node styling]
        }
        \expandafter\def\expandafter\tikz@tempb\expandafter{\expandafter{\tikz@dv@temp@lab};}%
        \expandafter\expandafter\expandafter\gdef%
        \expandafter\expandafter\expandafter\tikz@dv@label@code%
        \expandafter\expandafter\expandafter{\expandafter\expandafter\expandafter\relax%
          \expandafter\expandafter\expandafter{\expandafter\tikz@tempa\tikz@tempb\endscope}}
        \global\let\tikz@dv@label@attribute=\tikz@dv@label@attribute
        \global\let\tikz@dv@label@threshold=\tikz@dv@label@threshold
        \endgroup
      },
      arg1/.expand once=\tikz@dv@label@attribute,
      arg2=\tikz@dv@label@threshold,
      arg3/.expand once=\tikz@dv@label@code,
      arg4=\pgfdvvisualizerfilter{#1}
    },
    /utils/exec=\tikz@create@label@count{#1}
  },
  % Label style
  text colored/.style={node style={text=visualizer color}}
}

\def\tikz@create@label@count#1{
  \tikzdatavisualizationset{
    new object={
      when=before survey,
      store=/tikz/data visualization/visualizers/#1/count/obj,
      class=count,
      arg1=set/#1/count,
      after creation={\tikzdvobj.set filter(\pgfdvvisualizerfilter{#1})}
    }
  }
}

\pgfkeys{
  /tikz/data visualization/visualizer label options/.cd,
  when/.code args={#1 is#2}{%
    \def\tikz@dv@label@attribute{#1}%
    \def\tikz@dv@label@threshold{#2}%
  },
  index/.code={%
    \edef\tikz@dv@label@attribute{set/\tikz@visualizer/count}%
    \def\tikz@dv@label@threshold{#1}%
  },
  pos/.code={%
    \edef\tikz@dv@label@attribute{set/\tikz@visualizer/count}%
    \pgfkeysvalueof{/tikz/data visualization/visualizers/\tikz@visualizer/count/obj}.get max(\tikz@lib@max)
    \edef\tikz@dv@label@threshold{(#1*\tikz@lib@max)}%
  },
  auto/.code={%
    \edef\tikz@dv@label@attribute{set/\tikz@visualizer/count}%
    \pgfkeysvalueof{/tikz/data visualization/visualizers/\tikz@visualizer/count/obj}.get max(\tikz@lib@max)
    \edef\tikz@dv@label@threshold{({(\pgfkeysvalueof{/data point/set/\tikz@visualizer}-0.5)/\the\tikzdvvisualizercounter*\tikz@lib@max})}
  },
  text/.initial=,
  text'/.style={text={#1},node style=swap,/utils/exec=\def\tikz@lib@dv@pin@sign{-}},
  node style/.style={/tikz/data visualization/node style={#1}},
  text colored/.style=/tikz/data visualization/text colored,
  pin angle/.store in=\tikz@lib@dv@pin@dir,
  pin length/.style={node style={pin distance={#1}}},
}

\let\tikz@lib@dv@pin@sign\pgfutil@empty

\let\tikz@dv@label@attribute\pgfutil@empty
\let\tikz@dv@label@threshold\pgfutil@empty
\let\tikz@dv@label@code\pgfutil@empty




%
% Legend handling
%

\tikzdatavisualizationset{
  new legend/.code={
    \pgfkeysifdefined{/tikz/data visualization/#1/at}{}
    {\tikzdatavisualizationset{
    new object={
      class=legend,
      store=/tikz/data visualization/#1/obj,
      arg1 from key=/tikz/data visualization/#1/@columns or rows,
      arg2 from key=/tikz/data visualization/#1/@ideal,
      arg3 from key=/tikz/data visualization/#1/max entries,
      arg4 from key=/tikz/data visualization/#1/@strategy,
      after creation={
        \tikzdatavisualizationset{
          legend actions/.append={
            \pgfkeysgetvalue{/tikz/data visualization/#1/obj}\pgf@dv@legend%
            {
              \pgf@dv@legend.get arrangement(\pgf@dv@temp)%
              \pgfkeysgetvalue{/tikz/data visualization/#1/at}\pgf@dv@at%
              \pgfkeysgetvalue{/tikz/data visualization/#1/anchor}\pgf@dv@anchor%
              \let\pgfdvnextcell=\pgfmatrixnextcell%
              \let\pgfdvendrow=\pgfmatrixendrow%
              \def\pgf@marshal{
                \matrix[at/.expand once=\pgf@dv@at,matrix anchor/.expand
                once=\pgf@dv@anchor,/tikz/data visualization/#1/matrix node styling]
              }
              \expandafter\pgf@marshal\expandafter{\pgf@dv@temp};
            }
          }
        }
      }
    },
    #1/@columns or rows/.initial=columns,
    #1/@ideal/.initial=1,
    #1/max entries/.initial=100,
    #1/@strategy/.initial=down then right,
    #1/anchor/.initial=west,
    #1/at/.initial=(data visualization bounding box.east),
    #1/matrix node styling/.style={row sep=0pt,column sep=.8em},
    % 
    % 
    %
    #1/.code={
      \let\tikz@temp\tikz@dv@legend%
      \def\tikz@dv@legend{/tikz/data visualization/#1}%
      \expandafter\tikz@do@legend@options\expandafter{\tikz@temp}{##1}%
    },
    #1={every new legend}
  }}},
  new legend/.default=main legend,
  legend/.style={
    new legend,
    main legend={#1}
  }
}

\def\tikz@do@legend@options#1#2{
  \pgfkeys{/tikz/data visualization/legend options/.cd,#2}
  \def\tikz@dv@legend{#1}
}
\let\tikz@dv@legend\pgfutil@empty


\tikzset{
  /tikz/data visualization/legend options/.cd,
  %
  % How to arrange the entries in the legend
  %
  ideal number of columns/.style={\tikz@dv@legend/@columns or rows=columns,\tikz@dv@legend/@ideal={#1}},
  ideal number of rows/.style={\tikz@dv@legend/@columns or rows=rows,\tikz@dv@legend/@ideal={#1}},
  columns/.style={ideal number of columns={#1}},% alias
  rows/.style={ideal number of rows={#1}},% alias
  max rows/.style={\tikz@dv@legend/@columns or rows=columns,\tikz@dv@legend/max entries={#1}},
  max columns/.style={\tikz@dv@legend/@columns or rows=rows,\tikz@dv@legend/max entries={#1}},
  down then right/.style={\tikz@dv@legend/@strategy=down then right},
  down then left/.style={\tikz@dv@legend/@strategy=down then left},
  up then right/.style={\tikz@dv@legend/@strategy=up then right},
  up then left/.style={\tikz@dv@legend/@strategy=up then left},
  right then down/.style={\tikz@dv@legend/@strategy=right then down},
  left then down/.style={\tikz@dv@legend/@strategy=left then down},
  right then up/.style={\tikz@dv@legend/@strategy=right then up},
  left then up/.style={\tikz@dv@legend/@strategy=left then up},
  % 
  % Where to put the legend 
  % 
  anchor/.style={\tikz@dv@legend/anchor={#1}},
  at/.style={\tikz@dv@legend/at={#1}},
  % Outer placements
  right/.style={east outside},
  left/.style={west outside},
  above/.style={north outside},
  below/.style={south outside},
  east outside/.style={
    columns=1,
    at={([xshift=.8em]data visualization bounding box.east)},
    anchor=west,
  },
  north east outside/.style={
    columns=1,
    at={([xshift=.8em]data visualization bounding box.north east|-
      data bounding box.north)},
    anchor=north west,
  },
  south east outside/.style={
    columns=1,
    at={([xshift=.8em]data visualization bounding box.south east |-
      data bounding box.south)},
    anchor=south west,
  },
  west outside/.style={
    columns=1,
    label style=text left,
    at={([xshift=-.8em]data visualization bounding box.west)},
    anchor=east,
  },
  north west outside/.style={
    columns=1,
    label style=text left,
    at={([xshift=-.8em]data visualization bounding box.north west |-
      data bounding box.north)},
    anchor=north east,
  },
  south west outside/.style={
    columns=1,
    label style=text left,
    at={([xshift=-.8em]data visualization bounding box.south west |-
      data bounding box.south)},
    anchor=south east,
  },
  south outside/.style={
    rows=1,
    at={([yshift=-.5em]data visualization bounding box.south)},
    anchor=north,
  },
  north outside/.style={
    rows=1,
    at={([yshift=.5em]data visualization bounding box.north)},
    anchor=south,
  },
  every new legend/.style={east outside,label style=text right},
  % 
  % Inner placements
  % 
  % First, styling
  every legend inside/.style={
    opaque=white,
    label style={node style={font=\pgfutil@font@footnotesize}}
  },
  opaque/.style={
    matrix node style={
      inner sep=.333ex,
      outer sep=.5ex,
      rounded corners=3pt,
      execute at begin cell={\tikzset{sharp corners}}, % get rid of
                                % rounded corners in cells of the
                                % legend matrix
      fill=#1
    },
  },
  opaque/.default=white,
  transparent/.style={matrix node style={fill=none}},
  % Second, the placements
  north east inside/.style={
    columns=1,
    at={([xshift=-.3em]data bounding box.north east)},
    anchor=north east,
    every legend inside
  },
  south west inside/.style={
    columns=1,
    at={([xshift=.3em]data bounding box.south west)},
    anchor=south west,
    every legend inside
  },
  north west inside/.style={
    columns=1,
    at={([xshift=.3em]data bounding box.north west)},
    anchor=north west,
    every legend inside
  },
  south east inside/.style={
    columns=1,
    at={([xshift=-.3em]data bounding box.south east)},
    anchor=south east,
    every legend inside
  },
  west inside/.style={
    columns=1,
    at={([xshift=.3em]data bounding box.west)},
    anchor=west,
    every legend inside
  },
  east inside/.style={
    columns=1,
    at={([xshift=.3em]data bounding box.east)},
    anchor=east,
    every legend inside
  },
  north inside/.style={
    rows=1,
    at={(data bounding box.north)},
    anchor=north,
    every legend inside
  },
  south inside/.style={
    rows=1,
    at={(data bounding box.south)},
    anchor=south,
    every legend inside
  },
  % Additional inner placements
  at values/.style={
    at={(visualization cs:#1)},
    anchor=center,
    every legend inside
  },
  right of/.style={
    at={(visualization cs:#1)},
    anchor=west,
    every legend inside
  },
  left of/.style={
    at={(visualization cs:#1)},
    anchor=east,
    every legend inside
  },
  above of/.style={
    at={(visualization cs:#1)},
    anchor=south,
    every legend inside
  },
  below of/.style={
    at={(visualization cs:#1)},
    anchor=north,
    every legend inside
  },
  above right of/.style={
    at={(visualization cs:#1)},
    anchor=south west,
    every legend inside
  },
  above left of/.style={
    at={(visualization cs:#1)},
    anchor=south east,
    every legend inside
  },
  below right of/.style={
    at={(visualization cs:#1)},
    anchor=north west,
    every legend inside
  },
  below left of/.style={
    at={(visualization cs:#1)},
    anchor=north east,
    every legend inside
  },
  %  
  %
  % 
  % Label text styling 
  % 
  label style/.style={
    matrix node style={/tikz/data visualization/every label in legend/.append style={#1}}
  },
  % 
  % Styling 
  %
  matrix node style/.style={\tikz@dv@legend/matrix node styling/.append style={#1}},
}


\tikzdatavisualizationset{
  new legend entry/.code={
    \begingroup
      \pgfkeys{/tikz/data visualization/legend entry options/.cd,#1}
      \pgfkeysgetvalue{/tikz/data visualization/legend entry options/legend}\tikz@dv@temp@legend
      \global\let\tikz@dv@temp@legend\tikz@dv@temp@legend  
    \endgroup
    \tikzdatavisualizationset{new legend/.expanded=\tikz@dv@temp@legend}%
    \expandafter\tikz@dv@add@legend@entry\expandafter{\tikz@dv@temp@legend}{#1}
  }
}

\def\tikz@dv@add@legend@entry#1#2{
  \tikz@main@dv.at start survey({
      \pgfkeysgetvalue{/tikz/data visualization/#1/obj}\pgf@temp
      \pgf@temp.add entry(\tikz@dv@render@legend@entry{legend=#1,#2})
    })
}

\def\tikz@dv@render@legend@entry#1{
  \pgfkeys{/tikz/data visualization/.cd,every data set label}
  \pgfkeys{/tikz/data visualization/legend entry options/.cd,
    /tikz/data visualization/every label in legend,#1}%
  \pgfkeysgetvalue{/tikz/data visualization/legend entry options/text}\tikz@dv@temp@lab    
  \pgfkeysgetvalue{/tikz/data visualization/@node styling}\tikz@dv@temp@style
  \pgfkeysgetvalue{/tikz/data visualization/legend entry options/setup}\tikz@dv@temp@setup
  \pgfkeysgetvalue{/tikz/data visualization/legend entry options/visualizer in legend styling}\tikz@dv@temp@visual@styling
  \scope[/utils/exec=\expandafter\pgfkeysalso\expandafter{\tikz@dv@temp@setup},
         /utils/exec=\pgf@signalstyle.emit()]
    \node[/tikz/data visualization/node styling,
          /utils/exec=\expandafter\pgfkeysalso\expandafter{\tikz@dv@temp@style}]
    {\tikz@dv@pre@height\tikz@dv@temp@lab\tikz@dv@post@height};
    \scope[/utils/exec=\expandafter\pgfkeysalso\expandafter{\tikz@dv@temp@visual@styling}]
      \iftikz@lib@dv@text@only
      \else
        \pgfkeysvalueof{/tikz/data visualization/legend entry options/visualizer in legend}
      \fi
    \endscope
  \endscope
}

\def\tikz@dv@pre@height{\hbox{\vrule height .75em width0pt}}
\def\tikz@dv@post@height{\hbox{\vrule depth .25em width0pt}}



\pgfkeys{
  /tikz/data visualization/legend entry options/.cd,
  % 
  % General options
  % 
  text/.initial=,
  node style/.style={/tikz/data visualization/node style={#1}},
  legend/.initial=main legend,
  setup/.initial=,
  visualizer in legend/.initial=,
  visualizer in legend styling/.initial=,
  visualizer in legend style/.style={visualizer in legend styling/.append={,#1}},
  % 
  % Legend visualizers for plots
  % 
  text right/.style={
    node style={anchor=mid west,inner ysep=1pt,inner xsep=0pt,reset cm,xshift=.333em},
    visualizer in legend style={reset cm},
  },
  text left/.style={
    node style={anchor=mid east,inner ysep=1pt,inner xsep=0pt,reset
      cm,xshift=-.333em,align=right},
    visualizer in legend style={reset cm,xscale=-1},
  },
  text only/.style={
    node style={anchor=mid west,inner ysep=1pt,inner xsep=0pt,reset cm,text=visualizer color},
    /utils/exec=\tikz@lib@dv@text@onlytrue
  },
  text colored/.style=/tikz/data visualization/text colored,
}
\let\tikz@lib@dv@pin@dir\pgfutil@empty
\newif\iftikz@lib@dv@text@only

\pgfkeys{
  /tikz/data visualization/visualizer options/.cd,
  label in legend/.code={\expandafter\tikz@dv@new@label@in@legend@for@visualizer\expandafter{\tikz@visualizer}{#1}},
  label in data/.code=\tikzdatavisualizationset{new label visualizer/.expand once=\expandafter{\tikz@visualizer}{auto,#1}},
  pin in data/.style={label in data={%
      node style={%
        /utils/exec={
          \ifx\tikz@lib@dv@pin@dir\pgfutil@empty
            \pgf@process{\pgfpointnormalised{%
                \pgfpointdiff%
                {\pgfpointanchor{label visualizer coordinate}{center}}%
                {\pgfpointanchor{label visualizer coordinate'}{center}}}}%
            \pgf@x=-\pgf@x\relax%
            \edef\tikz@lib@dv@temp@rot{\noexpand\pgfqpoint{\the\pgf@y}{\the\pgf@x}}%
            \tikz@addtransform{\pgftransformshift{\pgfpointscale{\tikz@lib@dv@pin@sign\tikz@pin@distance}{\tikz@lib@dv@temp@rot}}}
          \else%
            \tikz@addtransform{\pgftransformshift{\pgfpointpolar{\tikz@lib@dv@pin@dir}{\tikz@lib@dv@pin@sign\tikz@pin@distance}}}
          \fi%
        },
        append after command={
          \bgroup
            [current point is local=true]
            (\tikzlastnode) edge [solid, every pin edge] (label visualizer coordinate)
          \egroup%
      }},
      ,#1}},
  style/.style={/tikz/data visualization/visualizers/\tikz@visualizer/styling/.append style={,#1}},
  label in legend options/.style={/tikz/data visualization/visualizers/\tikz@visualizer/label in legend options/.append style={,#1}},
  ignore style sheets/.style={/tikz/data visualization/visualizers/\tikz@visualizer/signal/.code=,/utils/exec=\advance\tikzdvvisualizercounter by -1\relax},
}

\def\tikz@dv@new@label@in@legend@for@visualizer#1#2{
  \tikzdatavisualizationset{
    new legend entry={
      visualizer in legend style={/tikz/data visualization/visualizers/#1/styling/.try},
      /tikz/data visualization/every label in legend/.try,
      /tikz/.cd,
      every label/.try,
      /tikz/data visualization/legend entry options/.cd,
      setup={/data point/set=#1},
      /tikz/data visualization/visualizers/#1/label in legend options/.try,
      #2,
    }
  }
}

\def\tikz@dv@legend@entry@as@example{
  \pgfkeysgetvalue{/data point/set}{\tikz@visualizer}
  \pgfkeysvalueof{/data point/\tikz@visualizer/execute at begin}
  \tikz@dv@plot@handler
  \pgfplotstreamstart
  \pgfkeysgetvalue{/tikz/data visualization/legend entry options/label in legend line coordinates}{\tikz@dv@temp}
  \foreach \coordinate in \tikz@dv@temp
  { \pgfplotstreampoint{\expandafter\tikz@scan@one@point\expandafter\pgfutil@firstofone\coordinate} }
  \pgfplotstreamend
  \pgfkeysvalueof{/data point/\tikz@visualizer/execute at end}
  \pgfkeysvalueof{/data point/\tikz@visualizer/execute at begin}
  \tikz@dv@plot@mark@maker
  \pgfplotstreamstart
  \pgfkeysgetvalue{/tikz/data visualization/legend entry options/label in legend mark coordinates}{\tikz@dv@temp}
  \foreach \coordinate in \tikz@dv@temp
  { \pgfplotstreampoint{\expandafter\tikz@scan@one@point\expandafter\pgfutil@firstofone\coordinate} }
  \pgfplotstreamend
  \pgfkeysvalueof{/data point/\tikz@visualizer/execute at end}
}


\tikzdatavisualizationset{
  legend entry options/.cd,
  label in legend line coordinates/.initial=,
  label in legend rectangle coordinates/.initial={(-1ex,-.5ex),(-1ex,0.968ex),(0ex,0.968ex),(0ex,-.5ex)},
  label in legend mark coordinates/.initial=,
  label in legend one mark/.style={
    label in legend line coordinates={},
    label in legend mark coordinates={(0,0)},
  },
  label in legend three marks/.style={
    label in legend line coordinates={},
    label in legend mark coordinates={(-3ex,-.3ex),(-1.5ex,.3ex),(0,0)},
  },
  straight label in legend line/.style={
    label in legend line coordinates={(-2em,0),(-1.5em,0),(-.5em,0),(0,0)},
    label in legend mark coordinates={(-1.5em,0),(-.5em,0)},
  },
  zig zag label in legend line/.style={
    label in legend line coordinates={(-2em,0),(-1.5em,.3ex),(-.5em,-.3ex),(0,0)},
    label in legend mark coordinates={(-1.5em,.3ex),(-.5em,-.3ex)},
  },
  circular label in legend line/.style={
    label in legend line coordinates={%
      ([xshift=-1em]0:.9em and .35ex),%
      ([xshift=-1em]45:.9em and .35ex),%
      ([xshift=-1em]90:.9em and .35ex),%
      ([xshift=-1em]135:.9em and .35ex),%
      ([xshift=-1em]180:.9em and .35ex),%
      ([xshift=-1em]225:.9em and .35ex),%
      ([xshift=-1em]270:.9em and .35ex),%
      ([xshift=-1em]315:.9em and .35ex)},%
    label in legend mark coordinates={([xshift=-1em]120:.9em and .35ex),([xshift=-1em]-60:.9em and .35ex)},
  },  
  gap circular label in legend line/.style={
    label in legend line coordinates={%
      ([xshift=-1em,yshift=.2ex]90:1.4ex and 0.9ex),%
      ([xshift=-1em,yshift=.2ex]162:1.4ex and 0.9ex),%
      ([xshift=-1em,yshift=.2ex]234:1.4ex and 0.9ex),%
      ([xshift=-1em,yshift=.2ex]306:1.4ex and 0.9ex),%
      ([xshift=-1em,yshift=.2ex]18:1.4ex and 0.9ex)},
    label in legend mark coordinates={
      ([xshift=-1em,yshift=.2ex]90:1.4ex and 0.9ex),%
      ([xshift=-1em,yshift=.2ex]162:1.4ex and 0.9ex),%
      ([xshift=-1em,yshift=.2ex]234:1.4ex and 0.9ex),%
      ([xshift=-1em,yshift=.2ex]306:1.4ex and 0.9ex),%
      ([xshift=-1em,yshift=.2ex]18:1.4ex and 0.9ex)}
  },  
  default label in legend path/.style={zig zag label in legend line},
  default label in legend closed path/.style={circular label in legend line},
  default label in legend mark/.style={label in legend one mark},
}


\def\tikz@dv@legend@entry@visualizer@visualizer{
}



%
% Basic visualizers
%

\tikzdatavisualizationset{
  visualize as line/.style={
    new object={
      when=after survey,
      store=/tikz/data visualization/visualizers/#1,
      class=plot handler visualizer,
      arg1=#1,
      arg2={\tikz@dv@plot@handler,\tikz@dv@plot@mark@maker}
    },
    new visualizer={#1}{%
      every path/.style={draw},
      style={every mark/.append style={color=visualizer color}},
      mark size=2pt,
      semithick,
      color=visualizer color,
      mark=none,
      /tikz/data visualization/every visualize as line/.try,
    }{visualizer in legend=\tikz@dv@legend@entry@as@example},
    #1={straight line}
  },
  visualize as line/.default=line,
  visualize as smooth line/.style={
    visualize as line={#1},
    #1={smooth line}
  },
  visualize as smooth line/.default=line,
  visualize as scatter/.style={
    new object={
      when=after survey,
      store=/tikz/data visualization/visualizers/#1,
      class=plot handler visualizer,
      arg1=#1,
      arg2={\tikz@dv@plot@mark@maker}
    },
    new visualizer={#1}{%
      mark=x,
      mark size=2pt,
      style={every mark/.append style={color=visualizer color}},
      /tikz/data visualization/every visualize as scatter/.try,
    }{visualizer in legend=\tikz@dv@legend@entry@as@example},
    #1={no lines}
  },
  visualize as scatter/.default=scatter
}

\def\tikz@dv@plot@mark@maker{
  \let\tikz@options=\pgfutil@empty%
  \let\tikz@transform=\pgfutil@empty%
  \tikzset{solid,shift only,every mark}%
  \tikz@options%
  \ifx\tikz@plot@mark\pgfutil@empty%
    \pgfplothandlerdiscard
  \else
    \pgfplothandlermark{\tikz@transform\pgfuseplotmark{\tikz@plot@mark}}
  \fi
}



%
% Rectangle visualizers
%


\tikzdatavisualizationset{
  visualize as rectangles/.style={
    new object={
      when=before survey,
      store=/tikz/data visualization/visualizers/#1,
      class=rectangle visualizer,
      arg1=#1
    },
    /data point/#1/attribute 1/.initial=x,
    /data point/#1/attribute 2/.initial=y,
    new visualizer={#1}{%
      every path/.style={draw},
      semithick,
      color=visualizer color,
      /tikz/data visualization/every visualize as rectangles/.try,
    }{visualizer in legend=\tikz@dv@legend@entry@as@rectangle},
    #1={}
  },
  visualize as rectangles/.default=rectangles,
  % 
  % 
  %
  visualizer options/.cd,
  attribute 1/.style={/data point/\tikz@visualizer/attribute 1=#1},
  attribute 2/.style={/data point/\tikz@visualizer/attribute 2=#1},
}



\def\tikz@dv@legend@entry@as@rectangle{
  \pgfkeysgetvalue{/data point/set}{\tikz@visualizer}
  \pgfkeysvalueof{/data point/\tikz@visualizer/execute at begin}
  \pgfplothandlerpolygon
  \pgfplotstreamstart
  \pgfkeysgetvalue{/tikz/data visualization/legend entry options/label in legend rectangle coordinates}{\tikz@dv@temp}
  \foreach \coordinate in \tikz@dv@temp
  { \pgfplotstreampoint{\expandafter\tikz@scan@one@point\expandafter\pgfutil@firstofone\coordinate} }
  \pgfplotstreamend
  \pgfkeysvalueof{/data point/\tikz@visualizer/execute at end}
}




%
% Style sheets
% 

% Style sheet handler

\pgfkeysdef{/handlers/.style sheet}{%
  \edef\pgf@marshal{
    \noexpand \pgfoonew \noexpand\tikz@dv@temp=new style attribute(\pgfkeyscurrentpath,#1)
    \noexpand \tikz@dv@temp.default connects()
  }
  \pgf@marshal
}

\tikzset{
  visualizer color/.code=\colorlet{visualizer color}{#1},
  visualizer color=black
}

% Default style sheets

\pgfdvdeclarestylesheet{vary thickness}
{
  default style/.style={line width={0.3pt+#1*0.2pt}}
}
  
\pgfdvdeclarestylesheet{vary dashing}
{
  default style/.style=solid,
  1/.style=solid,
  2/.style={dash pattern=on 5\pgflinewidth off 2\pgflinewidth},
  3/.style={dash pattern=on 1.5\pgflinewidth off 1.5\pgflinewidth},
  4/.style={dash pattern=on 5\pgflinewidth off 1.5\pgflinewidth on 1.5\pgflinewidth off 1.5\pgflinewidth},
  5/.style={dash pattern=on 10\pgflinewidth off 3\pgflinewidth},
  6/.style={dash pattern=on 10\pgflinewidth off 2\pgflinewidth on 2\pgflinewidth off 2\pgflinewidth},
  7/.style={dash pattern=on 8\pgflinewidth off 2\pgflinewidth on
    1.5\pgflinewidth off 1.5\pgflinewidth on 1.5\pgflinewidth off
    1.5\pgflinewidth on 1.5\pgflinewidth off 1.5\pgflinewidth}
}

\pgfdvdeclarestylesheet{vary thickness and dashing}
{
  default style/.style=thin,
  1/.style=thin,
  2/.style=thick,
  3/.style={
    dash pattern=on 5\pgflinewidth off 2\pgflinewidth,
    thin
  },
  4/.style={
    dash pattern=on 5\pgflinewidth off 2\pgflinewidth,
    thick,
  },
  5/.style={
    dash pattern=on 1.5\pgflinewidth off 1.5\pgflinewidth,
    thin
  },
  6/.style={
    dash pattern=on 1.5\pgflinewidth off 1.5\pgflinewidth,
    thick
  },
  7/.style={
    dash pattern=on 5\pgflinewidth off 1.5\pgflinewidth on
    1.5\pgflinewidth off 1.5\pgflinewidth,
    thin
  },
  8/.style={
    dash pattern=on 5\pgflinewidth off 1.5\pgflinewidth on
    1.5\pgflinewidth off 1.5\pgflinewidth,
    thick
  },
  9/.style={
    dash pattern=on 10\pgflinewidth off 3\pgflinewidth,
    thin
  },
  10/.style={
    dash pattern=on 10\pgflinewidth off 3\pgflinewidth,
    thick
  },
  11/.style={
    dash pattern=on 10\pgflinewidth off 2\pgflinewidth on
    2\pgflinewidth off 2\pgflinewidth,
    thin
  },
  12/.style={
    dash pattern=on 10\pgflinewidth off 2\pgflinewidth on
    2\pgflinewidth off 2\pgflinewidth,
    thick
  },
  13/.style={
    dash pattern=on 8\pgflinewidth off 2\pgflinewidth on
    1.5\pgflinewidth off 1.5\pgflinewidth on 1.5\pgflinewidth off
    1.5\pgflinewidth on 1.5\pgflinewidth off 1.5\pgflinewidth,
    thin
  },
  14/.style={
    dash pattern=on 8\pgflinewidth off 2\pgflinewidth on
    1.5\pgflinewidth off 1.5\pgflinewidth on 1.5\pgflinewidth off
    1.5\pgflinewidth on 1.5\pgflinewidth off 1.5\pgflinewidth,
    thick
  }  
}


\pgfdvdeclarestylesheet{strong colors}
{
  default style/.style={visualizer color=black},
  1/.style={visualizer color=black},
  2/.style={visualizer color=red!80!black},
  3/.style={visualizer color=blue!80!black},
  4/.style={visualizer color=green!60!black},
  5/.style={visualizer color=orange!80!black},
  6/.style={visualizer color=black!60}
}


\pgfdvdeclarestylesheet{cross marks}
{
  default style/.style={mark=x,every mark/.append style=thin,mark size=2pt},
  1/.style={mark=x,every mark/.append style=thin,mark size=2pt},
  2/.style={mark=+,every mark/.append style=thin,mark size=2pt},
  3/.style={mark=Mercedes star,every mark/.append style=thin,mark size=2pt},
  4/.style={mark=Mercedes star flipped,every mark/.append style=thin,mark size=2pt},
  5/.style={mark=star,every mark/.append style=thin,mark size=2pt},
  6/.style={mark=10-pointed star,every mark/.append style={line width=.3pt,mark size=1.8pt}}
}


\pgfdvdeclarestylesheet{* mark}
{
  default style/.style={mark=*,every mark/.append style=thin,mark size=1.4pt},
}

\pgfdvdeclarestylesheet{dot mark}
{
  default style/.style={mark=*,every mark/.append style=thin,mark size=0.6pt},
}


\pgfdvdeclarestylesheet{o mark}
{
  default style/.style={mark=o,every mark/.append style=thin,mark size=1.4pt},
}



% Declare a color series style sheet
% 
% #1 = name of the style sheet
% #2 = color model
% #3 = initial color
% #4 = step
% 
% Description:
% 
% This function declares a style sheet that changes colors according
% to the value of the attribute. No test is made that the attribute is
% a number.

\def\tikzdvdeclarestylesheetcolorseries#1#2#3#4{
  \definecolorseries{tikzdvcolorseries#1}{#2}{step}[#2]{#3}{#4}
  \resetcolorseries{tikzdvcolorseries#1}
  \pgfdvdeclarestylesheet{#1}
  {
    default style/.style={
      /utils/exec=\colorlet{tikz@dv@temp}[rgb]{tikzdvcolorseries#1!![##1]},
      visualizer color=tikz@dv@temp
    }
  }
}

\tikzdvdeclarestylesheetcolorseries{vary hue}{hsb}{.4,0.9,0.8}{.213,0,0}
\tikzdvdeclarestylesheetcolorseries{shades of blue}{hsb}{.65,1.4,1}{0,-.4,-.0}
\tikzdvdeclarestylesheetcolorseries{shades of red}{hsb}{0,1.4,1}{0,-.4,-.0}
\tikzdvdeclarestylesheetcolorseries{gray scale}{hsb}{0,0,-.34}{0,0,.34}





%
% Basic Axes & Coordinate Systems
%


%
%
% Basic axis systems
%
%

\tikzdatavisualizationset{
  xy Cartesian/.style={
    new Cartesian axis=x axis,
    x axis={attribute=x,unit vector={(1pt,0cm)}},
    new Cartesian axis=y axis,
    y axis={attribute=y,unit vector={(0cm,1pt)}}
  },
  Xy axes/.style={x axis={#1},y axis={#1}},
  uv Cartesian/.style={
    new Cartesian axis=u axis,
    u axis={attribute=u,unit vector={(1pt,0cm)}},
    new Cartesian axis=v axis,
    v axis={attribute=v,unit vector={(0cm,1pt)}}
  },
  uv axes/.style={u axis={#1},v axis={#1}},
}

\tikzdatavisualizationset{
  xyz Cartesian cabinet/.style={
    xy Cartesian,
    new Cartesian axis=z axis,
    z axis={attribute=z,unit vector={(-0.353553pt,-0.353553pt)}}
  },
  xyz axes/.style={x axis={#1},y axis={#1},z axis={#1}},
  uvw Cartesian cabinet/.style={
    uv Cartesian,
    new Cartesian axis=w axis,
    w axis={attribute=w,unit vector={(-0.353553pt,-0.353553pt)}}
  }
  uvw axes/.style={u axis={#1},v axis={#1},w axis={#1}},
}



% 
% Create a new axis system 
%

\tikzdatavisualizationset{
  new axis system/.style n args={4}{
    #1/.style={
      #2,
      #1/.cd,
      #3,
      /tikz/data visualization/every #1/.try,
      ##1,
      /tikz/data visualization/.cd,
      #4,
    }
  }
}


% The school book axes
%
% This coordinate system can be used to create plots that look like
% plots in a typical school book: There are two axes called "x axis"
% and "y axis" that meet at the origin, there are arrows at the ends
% of the axes, pointing in the directions of the positive axes. No
% scaling is done by default, rather one unit equals one 1cm. This
% ensures that the even when multiple plots are created, the same
% scaling will be used each time.
% 
% To change the scaling, say "all axes={unit length=1mm}" for
% instance. 

\tikzdatavisualizationset{
  new axis system={school book axes}{%
    xy Cartesian,
    x axis={
      include value=0,
      scaling=0 at 0 and \pgfkeysvalueof{/tikz/data visualization/school book axes/unit} at 1cm,
      visualize axis={y axis={goto=0},style=->,padded},
      visualize ticks={common={y axis={goto=0},direction axis=y axis},
        major={tick text at low,
          options at=0 as [{style={draw=none},no tick text}]
        }},
      visualize grid={common={direction axis=y axis,padded}},
      ticks={step=\pgfkeysvalueof{/tikz/data visualization/school book axes/unit}},
      padding=0.75em
    },
    y axis={
      include value=0,
      scaling=0 at 0 and \pgfkeysvalueof{/tikz/data visualization/school book axes/unit} at 1cm,
      visualize axis={x axis={goto=0},style=->,padded},
      visualize ticks={
        common={x axis={goto=0},direction axis=x axis},
        major={tick text at low,options at=0 as [{high=0,low=0,style={draw=none},node style={anchor=north east}}]}
      },
      visualize grid={common={direction axis=x axis,padded}},
      ticks={step=\pgfkeysvalueof{/tikz/data visualization/school book axes/unit}},
      padding=0.75em
    }
  }{%
    standard labels
  }{%
    @make labels
  },
  school book axes/.cd,
  % Possible axis positionings:
  % 
  % Place labels at the ends of the axes
  %
  standard labels/.style={
    /tikz/data visualization/@make labels/.style={
      x axis={
        visualize label={
          x axis={goto=padded max, anchor at max},
          y axis={goto=0}
        }
      },
      y axis={
        visualize label={
          y axis={goto=padded max, anchor at max},
          x axis={goto=0}
        }
      }
    }
  },
  % 
  % Basic unit 
  % 
  unit/.initial=1,
}




% The scientific axes
%
% The scientific axes is a 2d plot that has a predetermined width and
% height. The data is then scaled in such a way that it fits inside
% this given rectangle. 

\tikzdatavisualizationset{
  new axis system={scientific axes}{%
    xy Cartesian,
    every axis/.append style={style={draw=black!50}},
    every ticks/.append style={style={draw=black!50}},
    x axis={
      length=\pgfkeysvalueof{/tikz/data visualization/scientific axes/width},
      ticks
    },
    y axis={
      length=\pgfkeysvalueof{/tikz/data visualization/scientific axes/height},
      ticks
    }
  }{%
    standard labels,
    outer ticks,
  }{%
    @make axes,
    @make labels
  },
  scientific axes/.cd,
  width/.initial=5cm,
  height/.initial=0.618*\pgfkeysvalueof{/tikz/data visualization/scientific axes/width},% golden ratio...
  outer ticks/.style={
    /tikz/data visualization/@make axes/.style={
      x axis={
        visualize ticks={common={y axis={goto=padded min},direction axis=y axis,high=0pt},major={tick text at low}},
        visualize ticks={common={y axis={goto=padded max},direction axis=y axis,low=0pt}},
        visualize axis={y axis={goto=padded min},padded},
        visualize axis={y axis={goto=padded max},padded},
        visualize grid={common={direction axis=y axis,padded}},
      },
      y axis={
        visualize ticks={common={x axis={goto=padded min},direction axis=x axis,high=0pt},major={tick text at low}},
        visualize ticks={common={x axis={goto=padded max},direction axis=x axis,low=0pt}},
        visualize axis={x axis={goto=padded min},padded},
        visualize axis={x axis={goto=padded max},padded},
        visualize grid={common={direction axis=x axis,padded}},
      }
    }
  },
  inner ticks/.style={
    /tikz/data visualization/@make axes/.style={
      x axis={
        visualize ticks={common={y axis={goto=padded min},direction axis=y axis,low=0pt},major={tick text at low}},
        visualize ticks={common={y axis={goto=padded max},direction axis=y axis,high=0pt}},
        visualize axis={y axis={goto=padded min},padded},
        visualize axis={y axis={goto=padded max},padded},
        visualize grid={common={direction axis=y axis,padded}},
      },
      y axis={
        visualize ticks={common={x axis={goto=padded min},direction axis=x axis,low=0pt},major={tick text at low}},
        visualize ticks={common={x axis={goto=padded max},direction axis=x axis,high=0pt}},
        visualize axis={x axis={goto=padded min},padded},
        visualize axis={x axis={goto=padded max},padded},
        visualize grid={common={direction axis=x axis,padded}},
      }
    }
  },
  clean/.style={
    /tikz/data visualization/@make axes/.style={
      x axis={
        visualize ticks={common={y axis={goto=padded min},direction axis=y axis,high=0pt},major={tick text at low}},
        visualize axis={y axis={goto=padded min}},
        visualize axis={y axis={goto=min}, style={black!25, line cap=rect}},
        visualize axis={y axis={goto=max}, style={black!25, line cap=rect}},
        visualize grid={common={direction axis=y axis}},
        padding=.5em,
      },
      y axis={
        visualize ticks={common={x axis={goto=padded min},direction axis=x axis,high=0pt},major={tick text at low}},
        visualize axis={x axis={goto=padded min}},
        visualize axis={x axis={goto=min}, style={black!25, line cap=rect}},
        visualize axis={x axis={goto=max}, style={black!25, line cap=rect}},
        visualize grid={common={direction axis=x axis}},
        padding=.5em
      },
    }
  },
  % Possible axis positionings:
  % 
  % Place axes labels below and left, where left label is rotated 
  %
  standard labels/.style={
    /tikz/data visualization/@make labels/.style={
      x axis={
        visualize label={
          x axis={goto pos=.5},
          % Vertical position comes from bounding box:
          node style={
            at={(0,0 |- data visualization bounding box.south)},
            below
          }
        }
      },
      y axis={
        visualize label={
          y axis={goto pos=.5},
          % Horizontal position comes from bounding box:
          node style={
            at={(0,0 -| data visualization bounding box.west)},
            rotate=90,
            above}
        }
      }
    }
  },
  % 
  % Place axes labels below and left, no rotation
  %
  upright labels/.style={
    /tikz/data visualization/@make labels/.style={
      x axis={
        visualize label={
          x axis={goto pos=.5},
          % Vertical position comes from bounding box:
          node style={
            at={(0,0 |- data visualization bounding box.south)},
            below
          }
        }
      },
      y axis={
        visualize label={
          y axis={goto pos=.5},
          % Horizontal position comes from bounding box:
          node style={
            at={(0,0 -| data visualization bounding box.west)},
            left
          }
        }
      }
    }    
  },
  % 
  % Place axes at the ends of the axes
  %
  end labels/.style={
    /tikz/data visualization/@make labels/.style={
      x axis={
        visualize label={
          y axis={goto=padded min},
          % Vertical position comes from bounding box:
          node style={
            at={(0,0 -| data visualization bounding box.east)},
            right
          }
        }
      },
      y axis={
        visualize label={
          x axis={goto=padded min},
          % Horizontal position comes from bounding box:
          node style={
            at={(0,0 |- data visualization bounding box.north)},
            above
          }
        }
      }
    }
  }
}



\endinput


tikzlibrarydatavisualization.formats.functions.code.tex
% Copyright 2008 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/datavisualization/tikzlibrarydatavisualization.formats.functions.code.tex,v 1.1 2008/12/09 00:12:10 tantau Exp $

\usetikzlibrary{datavisualization}
\usepgflibrary{datavisualization.formats.functions}


\endinput

tikzlibrarydatavisualization.polar.code.tex
% Copyright 2008 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/datavisualization/tikzlibrarydatavisualization.polar.code.tex,v 1.8 2011/05/06 11:15:33 tantau Exp $

\usetikzlibrary{datavisualization}
\usepgflibrary{datavisualization.polar}


\tikzdatavisualizationset{%
  new polar axes/.style 2 args={
    new axis base=#1,
    #1={attribute=angle},
    new axis base=#2,
    #2={attribute=radius},
    #2/scaling/default=0 at 0 and 1 at 1cm,
    new object={
      store=/tikz/data visualization/#1/polar transformer,
      class=polar transformer,
      arg1/.expanded=\pgfkeysvalueof{/tikz/data visualization/angle axis/attribute}/scaled,
      arg2/.expanded=\pgfkeysvalueof{/tikz/data visualization/radius axis/attribute}/scaled,
      arg3 from key=/tikz/data visualization/#1/unit vector 0 degrees,
      arg4 from key=/tikz/data visualization/#1/unit vector 90 degrees
    },
    /tikz/data visualization/#1/unit vector 0 degrees/.initial=\pgfqpoint{1pt}{0pt},
    /tikz/data visualization/#1/unit vector 90 degrees/.initial=\pgfqpoint{0pt}{1pt},
  },
  new polar axes/.default={angle axis}{radius axis}
}
\def\tikz@lib@dv@polar@a#1{
  \pgfkeyssetvalue{\tikz@dv@axis/unit vector 0 degrees}{#1}
}
\def\tikz@lib@dv@polar@b#1{
  \pgfkeyssetvalue{\tikz@dv@axis/unit vector 90 degrees}{#1}
}



%
% Scientific polar axes
%

\tikzset{
  /tikz/data visualization/axis options/.cd,
  unit vectors/.code 2 args={
    \tikz@scan@one@point\tikz@lib@dv@polar@a#1
    \tikz@scan@one@point\tikz@lib@dv@polar@b#2
  },
  degrees/.style={\tikz@dv@axis/scaling=0 at 0 and 1 at 1},
  radians/.style={\tikz@dv@axis/scaling=0 at 0 and 0.03141592653589793 at 1.8},
}



\tikzdatavisualizationset{
  new axis system={scientific polar axes}{%
    new polar axes,
    angle axis={attribute=angle},
    radius axis={attribute=radius},
    every axis/.append style={style={draw=black!50}},
    every ticks/.append style={style={draw=black!50}},
  }{%
    0 to 360,%
    outer ticks,
  }{%
    @make axes,
    scientific polar axes/@setup axes,
    /utils/exec={
      \edef\pgf@marshal{\noexpand\tikzdatavisualizationset{\pgfkeysvalueof{/tikz/data visualization/@which visualize radius axis}/.list={\pgfkeysvalueof{/tikz/data visualization/\pgfkeysvalueof{/tikz/data visualization/@which radius axes at}}}}}
      \pgf@marshal
    },
    @make labels
  },
  @which radius axes at/.initial=@inner radius axes at,
  @which visualize radius axis/.initial=@visualize radius axis,
  @inner radius axes at/.initial=,
  @clean radius axes at/.initial=,
  @visualize radius axis/.style 2 args={
    radius axis={
      visualize axis={angle axis={goto=#1},high=padded max,low=0},
      visualize ticks={
        common={angle axis={goto=#1}, direction axis=angle axis},
        major={tick text at #2,
          options at=0 as [{style={draw=none},no tick text}]
        }
      }
    }
  },
  @visualize clean radius axis/.style n args={5}{
    radius axis={
      visualize axis={angle
        axis={goto=#1},high=max,low=0,style={black!25,line cap=rect}},
      visualize axis={angle
        axis={goto=#1},high=max,low=0,style={line cap=rect,#4}},
      visualize ticks={
        style={#4},
        common={angle axis={goto=#1}, direction axis=angle axis, #3=0},
        major={tick text at #2,#5}
      }
    }
  },
  @visualize zero/.style={@inner visualize zero={#1}},
  @clean visualize zero/.style={},
  @inner visualize zero/.style={
    radius axis={
      visualize ticks={
        common={angle axis={goto=0}, direction axis=angle axis},
        major={tick text at low,low=0,high=0,at=0 as
          [{style={draw=none},node style={anchor=#1}}]
        }
      }
    }
  },
  @degrees/.style={
    angle axis={degrees, ticks={step=15, tick suffix=$^\circ$, major={
          options at=360 as [{style={draw=none},no tick text}],
          options at=-180 as [{style={draw=none},no tick text}]}}}
  },
  @rad/.style={
    angle axis={radians, ticks={
        step=(pi/12),
        node style={
          /pgf/number format/frac,
          /pgf/number format/frac shift={1}
        },
        tick typesetter/.code={%
          \pgfmathsetmacro{\tikz@lib@dv@pol}{round(####1*3.819718634205488)/12}%
          \pgfmathapproxequalto{\tikz@lib@dv@pol}{0}%
          \ifdim\pgfmathresult pt=1.0pt%
            $0$%
          \else%
            \pgfmathapproxequalto{\tikz@lib@dv@pol}{1}%
            \ifdim\pgfmathresult pt=1.0pt%
              $\pi$%
            \else
              \pgfmathapproxequalto{\tikz@lib@dv@pol}{-1}%
              \ifdim\pgfmathresult pt=1.0pt%
                $-\pi$%
              \else%
                \pgfmathprintnumber{\tikz@lib@dv@pol}$\pi$%
              \fi%
            \fi%
          \fi%
        },
        major={
          options at=6.2831985e0 as [{style={draw=none},no tick text}],
          options at=6.2831192e0 as [{style={draw=none},no tick text}],   
          options at=6.2830794e0 as [{style={draw=none},no tick text}],   
          options at=6.2828787e0 as [{style={draw=none},no tick text}],   
          options at=6.2831598e0 as [{style={draw=none},no tick text}],   
          options at=-3.1415991e0 as [{style={draw=none},no tick text}],
          options at=-3.1415802e0 as [{style={draw=none},no tick text}],
          options at=-3.1415602e0 as [{style={draw=none},no tick text}],
          options at=-3.14153961e0 as [{style={draw=none},no tick text}],
          options at=-3.1414406e0 as [{style={draw=none},no tick text}],
        } 
      }
    }
  },
  @make labels/.style={},
}

\tikzdatavisualizationset{
  scientific polar axes/.cd,
  % 
  % 
  % 
  outer ticks/.style={
    /tikz/data visualization/@make axes/.style={
      radius axis={
        min value=0,
        length=\pgfkeysvalueof{/tikz/data visualization/scientific polar axes/radius},
        padding=0em,
        ticks={few},
        visualize grid={common={direction axis=angle axis,low=min,high=max}},
      },
      angle axis={
        visualize axis={radius axis={goto=padded max},low=min,high=max},
        visualize ticks={common={radius axis={goto=padded max},direction
            axis=radius axis},common={low=0},major={tick text at high}},
        visualize grid={common={direction axis=radius axis},low=0,high=padded max},
      }
    },
    /tikz/data visualization/@which radius axes at=@inner radius axes at,
    /tikz/data visualization/@which visualize radius axis=@visualize radius axis,
    /tikz/data visualization/@visualize zero/.style={@inner visualize zero={##1}},
  },
  inner ticks/.style={
    /tikz/data visualization/@make axes/.style={
      radius axis={
        min value=0,
        length=\pgfkeysvalueof{/tikz/data visualization/scientific polar axes/radius},
        padding=0em,
        ticks={few},
        visualize grid={common={direction axis=angle axis,low=min,high=max}},
      },
      angle axis={
        visualize axis={radius axis={goto=padded max},low=min,high=max},
        visualize ticks={common={radius axis={goto=padded max},direction
            axis=radius axis},common={high=0},major={tick text at high}},
        visualize grid={common={direction axis=radius axis},low=0,high=padded max},
      }
    },
    /tikz/data visualization/@which radius axes at=@inner radius axes at,
    /tikz/data visualization/@which visualize radius axis=@visualize radius axis,
    /tikz/data visualization/@visualize zero/.style={@inner visualize zero={##1}},
  },
  clean/.style={
    /tikz/data visualization/@make axes/.style={
      radius axis={
        min value=0,
        length=\pgfkeysvalueof{/tikz/data visualization/scientific polar axes/radius},
        padding=.5em,
        ticks={few},
        visualize grid={common={direction axis=angle axis,low=min,high=max}},
      },
      angle axis={
        padding=.5em,
        visualize axis={radius axis={goto=max}, style={black!25, line cap=rect},low=min,high=max},
        visualize axis={radius axis={goto=padded max}, style={line cap=rect}, low=min,high=max},
        visualize ticks={common={radius axis={goto=padded max}, direction axis=radius axis},common={low=0},major={tick text at high}},
        visualize grid={common={direction axis=radius axis},low=0,high=max},
      }
    },
    /tikz/data visualization/@which radius axes at=@clean radius axes at,
    /tikz/data visualization/@which visualize radius axis=@visualize clean radius axis,
    /tikz/data visualization/@visualize zero/.style={@clean visualize zero={##1}},
  },
  radius/.initial=3.25cm,
  % 
  % First quadrant 
  %
  0 to pi half/.style={
    @setup axes/.style={
      angle axis={min value=0, max value=1.570796326794897},
      @rad,
      @visualize zero=north east,
      @inner radius axes at={{0}{low},{1.570796326794897}{high}},
      @clean radius axes at={%
        {0}{low}{high}{yshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {1.570796326794897}{high}{low}{xshift=-\pgfkeysvalueof{/tikz/data visualization/angle axis/padding max}}{}
      }
    }
  },
  0 to 90/.style={
    @setup axes/.style={
      angle axis={min value=0, max value=90},
      @degrees,
      @visualize zero=north east,
      @inner radius axes at={{0}{low},{90}{high}},
      @clean radius axes at={%
        {0}{low}{high}{yshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {90}{high}{low}{xshift=-\pgfkeysvalueof{/tikz/data visualization/angle axis/padding max}}{}
      }
    }
  },
  quadrant/.style={
    @setup axes/.style={
      angle axis={scaling=min at 0 and max at 90, ticks},
      @visualize zero=north east,
      @inner radius axes at={{min}{low},{max}{high}},
      @clean radius axes at={%
        {min}{low}{high}{yshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {max}{high}{low}{xshift=-\pgfkeysvalueof{/tikz/data visualization/angle axis/padding max}}{}
      }
    }
  },
  quadrant clockwise/.style={
    @setup axes/.style={
      angle axis={scaling=min at 90 and max at 0, ticks},
      @visualize zero=north east,
      @inner radius axes at={{min}{low},{max}{high}},
      @clean radius axes at={%
        {max}{high}{low}{yshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {min}{low}{high}{xshift=-\pgfkeysvalueof{/tikz/data visualization/angle axis/padding max}}{}
      }
    }
  },
  % 
  % Fourth quadrant 
  %
  -pi half to 0/.style={
    @setup axes/.style={
      angle axis={min value=-1.570796326794897, max value=0},
      @rad,
      @visualize zero=south east,
      @inner radius axes at={{-1.570796326794897}{low},{0}{high}},
      @clean radius axes at={%
        {-1.570796326794897}{low}{high}{xshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {0}{high}{low}{yshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding max}}{}
      }
    }
  },
  -90 to 0/.style={
    @setup axes/.style={
      angle axis={min value=-90, max value=0},
      @degrees,
      @visualize zero=south east,
      @inner radius axes at={{-90}{low},{0}{high}},
      @clean radius axes at={%
        {-90}{low}{high}{xshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {0}{high}{low}{yshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding max}}{}
      }
    }
  },
  fourth quadrant/.style={
    @setup axes/.style={
      angle axis={scaling=min at -90 and max at 0, ticks},
      @visualize zero=south east,
      @inner radius axes at={{min}{low},{max}{high}},
      @clean radius axes at={%
        {min}{low}{high}{xshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {max}{high}{low}{yshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding max}}{}
      }
    }
  },
  fourth quadrant clockwise/.style={
    @setup axes/.style={
      angle axis={scaling=min at 0 and max at -90, ticks},
      @visualize zero=south east,
      @inner radius axes at={{min}{low},{max}{high}},
      @clean radius axes at={%
        {max}{high}{low}{xshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {min}{low}{high}{yshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding max}}{}
      }
    }
  },
  % 
  % Upper half  
  %
  0 to pi/.style={
    @setup axes/.style={
      angle axis={min value=0, max value=3.141592653589793},
      @rad,
      @visualize zero=north,
      @inner radius axes at={{0}{low},{1.570796326794897}{high},{3.141592653589793}{high}},
      @clean radius axes at={%
        {0}{low}{high}{yshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {3.141592653589793}{high}{low}{yshift=-\pgfkeysvalueof{/tikz/data
            visualization/angle axis/padding max}}{options at=0 as
          [{style={draw=none}, no tick text}]}
      }
    }
  },
  0 to 180/.style={
    @setup axes/.style={
      angle axis={min value=0, max value=180},
      @degrees,
      @visualize zero=north,
      @inner radius axes at={{0}{low},{90}{high},{180}{high}},
      @clean radius axes at={%
        {0}{low}{high}{yshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {180}{high}{low}{yshift=-\pgfkeysvalueof{/tikz/data
            visualization/angle axis/padding max}}{options at=0 as
          [{style={draw=none}, no tick text}]}
      }
    }
  },
  upper half/.style={
    @setup axes/.style={
      angle axis={scaling=min at 0 and max at 180, ticks},
      @visualize zero=north,
      @inner radius axes at={{min}{low},{max}{high}},
      @clean radius axes at={%
        {min}{low}{high}{yshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {max}{high}{low}{yshift=-\pgfkeysvalueof{/tikz/data
            visualization/angle axis/padding max}}{options at=0 as
          [{style={draw=none}, no tick text}]}
      }
    }
  },
  upper half clockwise/.style={
    @setup axes/.style={
      angle axis={scaling=min at 180 and max at 0, ticks},
      @visualize zero=north,
      @inner radius axes at={{min}{low},{max}{high}},
      @clean radius axes at={%
        {min}{low}{high}{yshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {max}{high}{low}{yshift=-\pgfkeysvalueof{/tikz/data
            visualization/angle axis/padding max}}{options at=0 as
          [{style={draw=none}, no tick text}]}
      }
    }
  },
  % 
  % Lower half 
  %
  lower half/.style={
    @setup axes/.style={
      angle axis={scaling=min at -180 and max at 0, ticks},
      @visualize zero=south,
      @inner radius axes at={{min}{low},{max}{high}},
      @clean radius axes at={%
        {min}{low}{high}{yshift=-\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {max}{high}{low}{yshift=\pgfkeysvalueof{/tikz/data
            visualization/angle axis/padding max}}{options at=0 as
          [{style={draw=none}, no tick text}]}
      }
    }
  },
  lower half clockwise/.style={
    @setup axes/.style={
      angle axis={scaling=min at 0 and max at -180, ticks},
      @visualize zero=south,
      @inner radius axes at={{min}{low},{max}{high}},
      @clean radius axes at={%
        {min}{low}{high}{yshift=-\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {max}{high}{low}{yshift=\pgfkeysvalueof{/tikz/data
            visualization/angle axis/padding max}}{options at=0 as
          [{style={draw=none}, no tick text}]}
      }
    }
  },
  % 
  % Right half
  %
  -pi half to pi half/.style={
    @setup axes/.style={
      @rad,
      angle axis={min value=-1.570796326794897, max value=1.570796326794897},
      @visualize zero=east,
      @inner radius axes at={{0}{low},{1.570796326794897}{low},{-1.570796326794897}{high}},
      @clean radius axes at={%
        {-1.570796326794897}{low}{high}{xshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {1.570796326794897}{high}{low}{xshift=-\pgfkeysvalueof{/tikz/data
            visualization/angle axis/padding max}}{options at=0 as
          [{style={draw=none}, no tick text}]}
      }
    }
  },
  -90 to 90/.style={
    @setup axes/.style={
      angle axis={min value=-90, max value=90},
      @degrees,
      @visualize zero=east,
      @inner radius axes at={{-90}{low},{0}{low},{90}{high}},
      @clean radius axes at={%
        {-90}{low}{high}{xshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {90}{high}{low}{xshift=-\pgfkeysvalueof{/tikz/data
            visualization/angle axis/padding max}}{options at=0 as
          [{style={draw=none}, no tick text}]}
      }
    }
  },
  right half/.style={
    @setup axes/.style={
      angle axis={scaling=min at -90 and max at 90, ticks},
      @visualize zero=east,
      @inner radius axes at={{min}{low},{max}{high}},
      @clean radius axes at={%
        {min}{low}{high}{xshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {max}{high}{low}{xshift=-\pgfkeysvalueof{/tikz/data
            visualization/angle axis/padding max}}{options at=0 as
          [{style={draw=none}, no tick text}]}
      }
    }
  },
  right half clockwise/.style={
    @setup axes/.style={
      angle axis={scaling=min at 90 and max at -90, ticks},
      @visualize zero=east,
      @inner radius axes at={{min}{low},{max}{high}},
      @clean radius axes at={%
        {min}{low}{high}{xshift=\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {max}{high}{low}{xshift=-\pgfkeysvalueof{/tikz/data
            visualization/angle axis/padding max}}{options at=0 as
          [{style={draw=none}, no tick text}]}
      }
    }
  },
  % 
  % Left half 
  %
  left half/.style={
    @setup axes/.style={
      angle axis={scaling=min at 90 and max at 270, ticks},
      @visualize zero=west,
      @inner radius axes at={{min}{low},{max}{high}},
      @clean radius axes at={%
        {min}{low}{high}{xshift=-\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {max}{high}{low}{xshift=\pgfkeysvalueof{/tikz/data
            visualization/angle axis/padding max}}{options at=0 as
          [{style={draw=none}, no tick text}]}
      }
    }
  },
  left half clockwise/.style={
    @setup axes/.style={
      angle axis={scaling=min at 270 and max at 90, ticks},
      @visualize zero=west,
      @inner radius axes at={{min}{low},{max}{high}},
      @clean radius axes at={%
        {min}{low}{high}{xshift=-\pgfkeysvalueof{/tikz/data visualization/angle axis/padding min}}{},%
        {max}{high}{low}{xshift=\pgfkeysvalueof{/tikz/data
            visualization/angle axis/padding max}}{options at=0 as
          [{style={draw=none}, no tick text}]}
      }
    }
  },
  % 
  % Full circle 
  % 
  0 to 2pi/.style={
    @setup axes/.style={
      angle axis={min value=0, max value=6.283185307179586},
      @rad,
      @visualize zero=north east,
      @inner radius axes at={{0}{low},{1.570796326794897}{high},{3.141592653589793}{high},{4.71238898038469}{low}},
      @clean radius axes at={{0}{low}{high}{}{}}
    }
  },
  -pi to pi/.style={
    @setup axes/.style={
      angle axis={min value=-3.141592653589793, max value=3.141592653589793},
      @rad,
      @visualize zero=north east,
      @inner radius axes at={{0}{low},{1.570796326794897}{high},{3.141592653589793}{high},{-1.57079632679489}{low}},
      @clean radius axes at={{0}{low}{high}{}{}}
    }
  },
  0 to 360/.style={
    @setup axes/.style={
      angle axis={min value=0, max value=360},
      @degrees,
      @visualize zero=north east,
      @inner radius axes at={{0}{low},{90}{high},{180}{high},{270}{low}},
      @clean radius axes at={{0}{low}{high}{}{}}
    }
  },
  -180 to 180/.style={
    @setup axes/.style={
      angle axis={min value=-180, max value=180},
      @degrees,
      @visualize zero=north east,
      @inner radius axes at={{0}{low},{90}{high},{180}{high},{-90}{low}},
      @clean radius axes at={{0}{low}{high}{}{}}
    }
  },
}




%
% Pie-charts -- still under construction...
%

\tikzset{
  /tikz/data visualization/axis options/.cd,
  percent/.style={\tikz@dv@axis/scaling=0 at 0 and 1 at 3.6},
  full circle/.style={\tikz@dv@axis/scaling=min at 0 and max at 360},
  half circle/.style={\tikz@dv@axis/scaling=min at 0 and max at 180},
  quarter circle/.style={\tikz@dv@axis/scaling=min at 0 and max at 90}
}




\endinput

tikzlibrarydatavisualization.sparklines.code.tex
% Copyright 2008 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/datavisualization/tikzlibrarydatavisualization.sparklines.code.tex,v 1.1 2008/12/17 22:48:46 tantau Exp $

\usetikzlibrary{datavisualization}




% 
% Sparklines (not yet usable...)
%

\tikzdatavisualizationset{
  spark line/.style={
    xy Cartesian,
    x axis={
      unit length={1pt}
    },
    y axis={
      scaling={min at -0.2em and max at 0.8em}
    },
    new line plot,
    every spark line plot/.try
  }  
}



\endinput


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.footprints.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.footprints}

\endinput

tikzlibrarydecorations.fractals.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.fractals}

\endinput

tikzlibrarydecorations.markings.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.markings}

% Upgrade \arrow command
\def\pgf@lib@dec@doarrowhead{%
  \pgfutil@ifnextchar[{\tikz@lib@dec@doarrowhead}{\tikz@lib@dec@doarrowhead[]}%]
}
\def\tikz@lib@dec@doarrowhead[#1]#2{%
  \scope[#1]
    \pgf@lib@dec@arrowhead{1}{#2}%
  \endscope
}
\def\pgf@lib@dec@doarrowheadrev{%
  \pgfutil@ifnextchar[{\tikz@lib@dec@doarrowheadrev}{\tikz@lib@dec@doarrowheadrev[]}%]
}
\def\tikz@lib@dec@doarrowheadrev[#1]#2{%
  \scope[#1]
    \pgf@lib@dec@arrowhead{-1}{#2}%
  \endscope
}

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

\endinput

tikzlibrarydecorations.text.code.tex
% Copyright 2013 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.text}


% Code for the `text effects along path' decoration

% Some text constants
% To do: merge these with existing text constants
\def\tikz@lib@dec@te@space@text{space}
\def\tikz@lib@dec@align@left@text{left}
\def\tikz@lib@dec@align@right@text{right}
\def\tikz@lib@dec@align@center@text{center}
\def\tikz@lib@dec@te@none@text{none}

% Some ifs
\newif\iftikz@lib@dec@te@pathfromtext
\newif\iftikz@lib@dec@te@segmentfromwidth
\newif\iftikz@lib@dec@te@scaletexttopath
\newif\iftikz@lib@dec@te@fittexttopath
\newif\iftikz@lib@dec@te@wordsep
\newif\iftikz@lib@dec@te@finalletter


% Utility macros
% To do: integrate with exisiting pgf macros
\def\tikz@lib@dec@te@addto@macro#1#2{%
  \expandafter\def\expandafter#1\expandafter{#1#2}%
}

\def\tikz@lib@dec@te@namelet#1#2{%
  \expandafter\expandafter\expandafter\let\expandafter\expandafter\csname\expandafter#1\expandafter\endcsname\expandafter=\csname#2\endcsname%
}

\def\tikz@lib@dec@te@advancecountmacro#1#2{%
  \pgfutil@tempcnta=#1\relax%
  \advance\pgfutil@tempcnta by#2\relax%
  \edef#1{\the\pgfutil@tempcnta}%
}

\def\tikz@lib@dec@te@advancedimenmacro#1#2{%
  \pgf@x=#1\relax%
  \advance\pgf@x by#2\relax%
  \edef#1{\the\pgf@x}%
}

% Macros for defining and updating text parameters
\def\tikz@lib@dec@te@start@parameters#1{%
 \expandafter\let\csname tikz@lib@dec@te@character@#1\endcsname=\pgfutil@empty%
}

\def\tikz@lib@dec@te@addto@parameters#1#2{%
 \expandafter\tikz@lib@dec@te@addto@macro\expandafter%
   {\csname tikz@lib@dec@te@character@#1\endcsname}{#2}%
}
\def\tikz@lib@dec@te@addmacroto@parameters#1#2{%
 \def\tikz@lib@dec@te@marshal{\expandafter\tikz@lib@dec@te@addto@macro\expandafter%
   {\csname tikz@lib@dec@te@character@#1\endcsname}}%
  \expandafter\tikz@lib@dec@te@marshal\expandafter{\expandafter\def\expandafter#2\expandafter{#2}}%
}

\def\tikz@lib@dec@te@getparameters#1{\csname tikz@lib@dec@te@character@#1\endcsname}



\let\tikz@lib@dec@te@textoptions=\pgfutil@empty
\let\tikz@lib@dec@te@widthoptions=\pgfutil@empty
\let\tikz@lib@dec@te@charactercountvar=\pgfutil@empty
\let\tikz@lib@dec@te@charactertotalvar=\pgfutil@empty
\let\tikz@lib@dec@te@lettercountvar=\pgfutil@empty
\let\tikz@lib@dec@te@lettertotalvar=\pgfutil@empty
\let\tikz@lib@dec@te@wordcountvar=\pgfutil@empty
\let\tikz@lib@dec@te@wordctotalvar=\pgfutil@empty
\let\tikz@lib@dec@te@transformtext=\pgfutil@empty%


% Keys... lots of them...
\pgfkeys{/pgf/decoration/text effects/.cd,
   .unknown/.code={\let\tikz@lib@dec@te@key@tmp=\pgfkeyscurrentname%
    \pgfkeysalso{/tikz/\tikz@lib@dec@te@key@tmp={#1}}},
   path from text/.is if=tikz@lib@dec@te@pathfromtext,
   path from text angle/.store in=\tikz@lib@dec@te@pathfromtextangle,
   path from text angle=0,
   fit text to path/.is if=tikz@lib@dec@te@fittexttopath,
   characters/.style={/pgf/decoration/text effects/every character/.style={#1}},
   characters/.append/.code={\pgfkeysalso{/pgf/decoration/text effects/every character/.append style={#1}}},
   character widths/.code={\pgfkeysalso{/pgf/decoration/text effects/every character width/.style={#1}}},
   character widths/.append/.code={\pgfkeysalso{/pgf/decoration/text effects/every character width/.append style={#1}}},
   character count/.store in=\tikz@lib@dec@te@charactercountvar,
   character count=,
   character total/.store in=\tikz@lib@dec@te@charactertotalvar,
   character total=,
   letter count/.store in=\tikz@lib@dec@te@lettercountvar,
   letter count=,
   letter total/.store in=\tikz@lib@dec@te@lettertotalvar,
   letter total=,
   word count/.store in=\tikz@lib@dec@te@wordcountvar,
   word count=,
   word total/.store in=\tikz@lib@dec@te@wordtotalvar,
   word total=,
   %
   style characters/.code args={#1 with #2}{\tikz@lib@dec@te@parse@stylecharacters{#1}{#2}},
   text along path/.style={
     inner xsep=0pt,
     anchor=base,
     transform shape
   },
   segment from width/.is if=tikz@lib@dec@te@segmentfromwidth,
   segment from width=true,
   word separator/.code={%
     \def\tikz@lib@dec@te@tmp{#1}%
     \ifx\tikz@lib@dec@te@tmp\tikz@lib@dec@te@space@text%
       \let\tikz@lib@dec@te@wordsep=\tikz@lib@dec@te@spacetoken%
     \else%
       \def\tikz@lib@dec@te@wordsep{#1}
     \fi},
   word separator=space,
   character command/.code={%
   	\def\tikz@lib@dec@te@tmp{#1}%
   	\ifx\tikz@lib@dec@te@tmp\pgfutil@empty%
  		\def\tikz@lib@dec@te@charactercommand{\tikz@lib@dec@te@charactertypesetonly}%
  	\else%
  		\def\tikz@lib@dec@te@charactercommand{#1}%
  	\fi%
   },
   character command=,
   every character width/.style={/pgf/decoration/text effects/every character/.try},
   every character/.style={},
   reverse text/.code={\tikz@lib@dec@te@addto@macro\tikz@lib@dec@te@transformtext%
     {\tikz@lib@dec@te@reversetext}},
   group letters into words/.code={\tikz@lib@dec@te@addto@macro\tikz@lib@dec@te@transformtext%
     {\tikz@lib@dec@te@groupletters}},
   group letters/.code={\tikz@lib@dec@te@addto@macro\tikz@lib@dec@te@transformtext%
     {\tikz@lib@dec@te@groupletters}},
   replace characters/.code args={#1 with #2}{\tikz@lib@dec@te@parse@replacecharacters{#1}{#2}},
   scale text to path/.is if=tikz@lib@dec@te@scaletexttopath,
   fit text to path/.is if=tikz@lib@dec@te@fittexttopath,
   repeat text/.store in=\tikz@lib@dec@te@repeattext,
   repeat text/.default=-1,
   repeat text=0,
}


\def\tikz@lib@dec@te@charactertypesetonly#1{#1}

\tikzset{%
  text effects/.code={\pgfkeysalso{/pgf/decoration/text effects/.cd,#1}},
}






% Prepare the decoration text
%
% This sets up all the character/letter/word, counts/totals
% and caluclates the default width of the characters/text 
% (which may be modified later).
%
\def\tikz@lib@dec@te@preparetext{%
  % Step 1: scan all the characters in the decoration text
  \let\tikz@lib@dec@te@text=\pgfdecorationtext%
  \tikz@lib@dec@te@scancharacters{%
    \expandafter\let\csname tikz@lib@dec@te@character@\tikz@lib@dec@te@scancount @token\endcsname=%
      \tikz@lib@dec@te@character%
  }%
  \let\tikz@lib@dec@te@charactertotalcount=\tikz@lib@dec@te@scancount%
  % Step 2: reverse and/or group characters/letters.
  \ifx\tikz@lib@dec@te@transformtext\pgfutil@empty%
  \else%
    \tikz@lib@dec@te@transformtext%
  \fi%
  % Step 3: get the character/letter/word counts
  \def\tikz@lib@dec@te@charactercount{0}%
  \def\tikz@lib@dec@te@wordcount{0}%
  \def\tikz@lib@dec@te@wordsepcount{0}%
  \def\tikz@lib@dec@te@lettercount{0}%
  \def\tikz@lib@dec@te@lastcharacter{0}%
  \pgfmathloop%
  \ifnum\pgfmathcounter>\tikz@lib@dec@te@charactertotalcount%
    \ifnum\tikz@lib@dec@te@lettercount>0\relax%
      \tikz@lib@dec@te@addto@parameters{\tikz@lib@dec@te@lastcharactercount}{\tikz@lib@dec@te@finallettertrue}%
    \fi
  \else%
    \expandafter\let\expandafter\tikz@lib@dec@te@character\expandafter=\csname tikz@lib@dec@te@character@\pgfmathcounter @token\endcsname%
    \tikz@lib@dec@te@advancecountmacro{\tikz@lib@dec@te@charactercount}{1}%
    \tikz@lib@dec@te@start@parameters{\tikz@lib@dec@te@charactercount}%
    \tikz@lib@dec@te@addmacroto@parameters{\tikz@lib@dec@te@charactercount}{\tikz@lib@dec@te@charactercount}%
    \ifx\tikz@lib@dec@te@character\tikz@lib@dec@te@wordsep%
      \tikz@lib@dec@te@advancecountmacro{\tikz@lib@dec@te@wordsepcount}{1}%
      \ifnum\tikz@lib@dec@te@lettercount>0\relax%
        \tikz@lib@dec@te@addto@parameters{\tikz@lib@dec@te@lastcharactercount}{\tikz@lib@dec@te@finallettertrue}%
      \fi
      \def\tikz@lib@dec@te@lettercount{0}%
      \tikz@lib@dec@te@addto@parameters{\tikz@lib@dec@te@charactercount}{\tikz@lib@dec@te@wordseptrue}%    
    \else
      \ifnum\tikz@lib@dec@te@lettercount=0\relax%
        \tikz@lib@dec@te@advancecountmacro\tikz@lib@dec@te@wordcount{1}%
      \fi%
      \tikz@lib@dec@te@addto@parameters{\tikz@lib@dec@te@charactercount}{\tikz@lib@dec@te@finalletterfalse}%
      \tikz@lib@dec@te@advancecountmacro{\tikz@lib@dec@te@lettercount}{1}%            
      \tikz@lib@dec@te@addto@parameters{\tikz@lib@dec@te@charactercount}{\tikz@lib@dec@te@wordsepfalse}%
       \expandafter\let\csname tikz@lib@dec@te@word \tikz@lib@dec@te@wordcount @lettercount\endcsname=\tikz@lib@dec@te@lettercount%
    \fi%
    \tikz@lib@dec@te@addmacroto@parameters{\tikz@lib@dec@te@charactercount}{\tikz@lib@dec@te@lettercount}%
    \tikz@lib@dec@te@addmacroto@parameters{\tikz@lib@dec@te@charactercount}{\tikz@lib@dec@te@wordcount}%
    \tikz@lib@dec@te@addmacroto@parameters{\tikz@lib@dec@te@charactercount}{\tikz@lib@dec@te@character}%
    \let\tikz@lib@dec@te@lastcharactercount=\pgfmathcounter%
  \repeatpgfmathloop%
  \let\tikz@lib@dec@te@wordtotal=\tikz@lib@dec@te@wordcount%
  % Step 4: add character/letter/word totals
  \pgfmathloop
  \ifnum\pgfmathcounter>\tikz@lib@dec@te@charactertotalcount%
  \else%
    \tikz@lib@dec@te@addmacroto@parameters{\pgfmathcounter}{\tikz@lib@dec@te@charactertotalcount}%
    \tikz@lib@dec@te@addmacroto@parameters{\pgfmathcounter}{\tikz@lib@dec@te@wordtotal}%
    \expandafter\let\expandafter\tikz@lib@dec@te@lettertotalcount\expandafter=\csname tikz@lib@dec@te@word \tikz@lib@dec@te@wordcount @lettercount\endcsname%
    \tikz@lib@dec@te@addmacroto@parameters{\pgfmathcounter}{\tikz@lib@dec@te@lettertotalcount}%
  \repeatpgfmathloop%
  % Step 5: calculate the the text and character width
  % but do not add to the parameters yet.
  \def\tikz@lib@dec@te@textwidth{0pt}%
  \pgfmathloop%
  \ifnum\pgfmathcounter>\tikz@lib@dec@te@charactertotalcount%
  \else%
    \def\tikz@lib@dec@te@characterwidth{0pt}%
    \tikz@lib@dec@te@getcharacterwidth{\pgfmathcounter}%
    \expandafter\let\csname tikz@lib@dec@te@character@\pgfmathcounter @width\endcsname=\tikz@lib@dec@te@characterwidth%
    \pgf@x=\tikz@lib@dec@te@characterwidth\relax%
    \pgf@x=0.5\pgf@x%
    \expandafter\edef\csname tikz@lib@dec@te@character@\pgfmathcounter @prewidth\endcsname{\the\pgf@x}%
    \expandafter\edef\csname tikz@lib@dec@te@character@\pgfmathcounter @postwidth\endcsname{\the\pgf@x}%
    \tikz@lib@dec@te@advancedimenmacro{\tikz@lib@dec@te@textwidth}{\tikz@lib@dec@te@characterwidth}%
  \repeatpgfmathloop%
}

% Does the category code of the space matter?
\def\tikz@lib@dec@te@spacetoken{ }

\let\tikz@lib@dec@te@wordsep=\tikz@lib@dec@te@spacetoken


% Scan and count the characters in \tikz@lib@dec@te@text
%
% Create macros \tikz@lib@dec@te@character@<n>@token containing
% the nth character.
%
% Total number of characters is store in 
% \tikz@lib@dec@te@chractertotal@count
%
\def\tikz@lib@dec@te@scancharacters#1{%
  \def\tikz@lib@dec@te@@@scancharacters@process{#1}%
  \def\tikz@lib@dec@te@scancount{0}%
  \expandafter\tikz@lib@dec@te@@scancharacters\tikz@lib@dec@te@text\tikz@lib@dec@te@scancharacters}%

\def\tikz@lib@dec@te@@scancharacters{%
  \futurelet\tikz@lib@dec@te@token\tikz@lib@dec@te@@@scancharacters}

\def\tikz@lib@dec@te@@@scancharacters{%
  \ifx\tikz@lib@dec@te@token\tikz@lib@dec@te@scancharacters%
    \let\tikz@lib@dec@te@next=\tikz@lib@dec@te@@@@scancharacters%
  \else%
    \tikz@lib@dec@te@advancecountmacro\tikz@lib@dec@te@scancount{1}%
    \ifx\tikz@lib@dec@te@token\pgfutil@sptoken%
      \let\tikz@lib@dec@te@next=\tikz@lib@dec@te@@@scancharacters@space%
    \else%
      \ifx\tikz@lib@dec@te@token\bgroup%
        \let\tikz@lib@dec@te@next=\tikz@lib@dec@te@@@scancharacters@bgroup%
      \else%
        \let\tikz@lib@dec@te@next=\tikz@lib@dec@te@@@scancharacters@normal%
      \fi%
    \fi%
  \fi%
  \tikz@lib@dec@te@next%
}

\def\tikz@lib@dec@te@@@scancharacters@space{%
  \let\tikz@lib@dec@te@character=\tikz@lib@dec@te@spacetoken%
  \tikz@lib@dec@te@@@scancharacters@process%
  \pgfutil@ifnextchar x\tikz@lib@dec@te@@scancharacters\tikz@lib@dec@te@@scancharacters%
}

\def\tikz@lib@dec@te@@@scancharacters@bgroup#1{%
  \def\tikz@lib@dec@te@character{{#1}}%
  \tikz@lib@dec@te@@@scancharacters@process%
  \tikz@lib@dec@te@@scancharacters%
}

\def\tikz@lib@dec@te@@@scancharacters@normal#1{%
  \def\tikz@lib@dec@te@character{#1}%
  \tikz@lib@dec@te@@@scancharacters@process%
  \tikz@lib@dec@te@@scancharacters%
}


\def\tikz@lib@dec@te@@@@scancharacters#1\tikz@lib@dec@te@scancharacters{}


% Reverse the order of the scanned chracters in the text
% (Actually reverse the ordering of the macros containing the characters)
\def\tikz@lib@dec@te@reversetext{%
  \c@pgf@counta=\tikz@lib@dec@te@charactertotalcount%
  \pgfmathloop%
  \ifnum\pgfmathcounter>\c@pgf@counta%
  \else%
    \tikz@lib@dec@te@namelet{tikz@lib@dec@te@tmp}{tikz@lib@dec@te@character@\pgfmathcounter @token}%
    \tikz@lib@dec@te@namelet{tikz@lib@dec@te@character@\pgfmathcounter @token}{tikz@lib@dec@te@character@\the\c@pgf@counta @token}%
    \tikz@lib@dec@te@namelet{tikz@lib@dec@te@character@\the\c@pgf@counta @token}{tikz@lib@dec@te@tmp}%
    \advance\c@pgf@counta by-1\relax%
  \repeatpgfmathloop%
}

% Group letters (i.e., anything that isn't the word separator)
% as single characters (words).
\def\tikz@lib@dec@te@groupletters{%
  \c@pgf@counta=0\relax%
  \let\tikz@lib@dec@te@tmp=\pgfutil@empty%
  \let\tikz@lib@dec@te@@tmp=\pgfutil@empty%
  \pgfmathloop%
  \ifnum\pgfmathcounter>\tikz@lib@dec@te@charactertotalcount%
    \ifx\tikz@lib@dec@te@@tmp\pgfutil@empty%
    \else%
      \advance\c@pgf@counta by1\relax%
      \tikz@lib@dec@te@namelet{tikz@lib@dec@te@character@\the\c@pgf@counta @token}{tikz@lib@dec@te@@tmp}%
    \fi%
  \else%
    \tikz@lib@dec@te@namelet{tikz@lib@dec@te@tmp}{tikz@lib@dec@te@character@\pgfmathcounter @token}%
    \ifx\tikz@lib@dec@te@tmp\tikz@lib@dec@te@wordsep%
      \advance\c@pgf@counta by1\relax%
      \tikz@lib@dec@te@namelet{tikz@lib@dec@te@character@\the\c@pgf@counta @token}{tikz@lib@dec@te@@tmp}%
      \let\tikz@lib@dec@te@@tmp=\pgfutil@empty%
      \advance\c@pgf@counta by1\relax%
      \tikz@lib@dec@te@namelet{tikz@lib@dec@te@character@\the\c@pgf@counta @token}{tikz@lib@dec@te@wordsep}%
    \else%
      \expandafter\tikz@lib@dec@te@addto@macro\expandafter{\expandafter\tikz@lib@dec@te@@tmp\expandafter}\expandafter{\tikz@lib@dec@te@tmp}%
    \fi%
  \repeatpgfmathloop%
  \edef\tikz@lib@dec@te@charactertotalcount{\the\c@pgf@counta}%
}


% Get width of node containing only the current character.
\def\tikz@lib@dec@te@getcharacterwidth#1{%
  \csname tikz@lib@dec@te@character@#1\endcsname%
  \tikz@lib@dec@te@getoptions{every character width/.try}%
  \let\tikz@lib@dec@te@lastcharacterwidth=\tikz@lib@dec@te@characterwidth%
  \pgfpositionnodelater\tikz@lib@dec@te@@getcharacterwidth%
  \pgfutil@ifundefined{tikz@lib@dec@te@character@replacements@\meaning\tikz@lib@dec@te@character @code}{%
    \expandafter\node\expandafter[\tikz@lib@dec@te@options,scale=\tikz@lib@dec@scaledcharacterwidthfactor]%
    {\hbox{\tikz@lib@dec@te@charactercommand{\tikz@lib@dec@te@character}}};%
    \let\tikz@lib@dec@te@characterwidth=\tikz@lib@dec@te@characterwidth@tmp%
  }{%
    \tikz@lib@dec@te@getcharacter@replacementwidth{\tikz@lib@dec@te@character}%
    \let\tikz@lib@dec@te@characterwidth=\tikz@lib@dec@te@character@replacementwidth%
  }%
}

% Update the character parameters with the widths.
\def\tikz@lib@dec@te@addwidthstoparameters{%
  \pgfmathloop%
  \ifnum\pgfmathcounter>\tikz@lib@dec@te@charactertotalcount%
  \else%
    \tikz@lib@dec@te@namelet{tikz@lib@dec@te@characterwidth}{tikz@lib@dec@te@character@\pgfmathcounter @width}%
    \tikz@lib@dec@te@namelet{tikz@lib@dec@te@characterprewidth}{tikz@lib@dec@te@character@\pgfmathcounter @prewidth}%
    \tikz@lib@dec@te@namelet{tikz@lib@dec@te@characterpostwidth}{tikz@lib@dec@te@character@\pgfmathcounter @postwidth}%
    \tikz@lib@dec@te@addmacroto@parameters{\pgfmathcounter}{\tikz@lib@dec@te@characterwidth}%
    \tikz@lib@dec@te@addmacroto@parameters{\pgfmathcounter}{\tikz@lib@dec@te@characterprewidth}%
    \tikz@lib@dec@te@addmacroto@parameters{\pgfmathcounter}{\tikz@lib@dec@te@characterpostwidth}%
  \repeatpgfmathloop%
}

% Get the options to applied to a character node.

\def\tikz@lib@dec@te@addoptions#1{%
  \expandafter\def\expandafter\tikz@lib@dec@te@options\expandafter{\tikz@lib@dec@te@options,#1}%
}

\def\tikz@lib@dec@te@getoptions#1{%
  \let\tikz@lib@dec@te@lastcharactercommand=\tikz@lib@dec@te@charactercommand%
  \def\tikz@lib@dec@te@options{/pgf/decoration/text effects/.cd}%
  \tikz@lib@dec@te@addoptions{#1}%
  \let\tikzdecorationcharactercount=\tikz@lib@dec@te@charactercount%
  \let\tikzdecorationcharactertotal=\tikz@lib@dec@te@charactertotalcount%
  \let\tikzdecorationlettercount=\tikz@lib@dec@te@lettercount%
  \let\tikzdecorationlettertotal=\tikz@lib@dec@te@lettertotalcount%
  \let\tikzdecorationwordcount=\tikz@lib@dec@te@wordcount%
  \let\tikzdecorationwordtotal=\tikz@lib@dec@te@wordtotal%
  \let\tikzdecorationcharacter=\tikz@lib@dec@te@character%
  %
  % Define the count variables (if required)
  \ifx\tikz@lib@dec@te@charactercountvar\pgfutil@empty%
  \else%
    \expandafter\let\tikz@lib@dec@te@charactercountvar=\tikz@lib@dec@te@charactercount%
  \fi%
  %
  \ifx\tikz@lib@dec@te@charactertotalvar\pgfutil@empty%
  \else%
    \expandafter\let\tikz@lib@dec@te@charactertotalvar=\tikz@lib@dec@te@charactertotalcount%
  \fi%
  %
  \ifx\tikz@lib@dec@te@wordcountvar\pgfutil@empty%
  \else%
    \expandafter\let\tikz@lib@dec@te@wordcountvar=\tikz@lib@dec@te@wordcount%
  \fi%
  %
  \ifx\tikz@lib@dec@te@wordtotalvar\pgfutil@empty%
    \else%
      \expandafter\let\tikz@lib@dec@te@wordtotalvar=\tikz@lib@dec@te@wordtotal%
    \fi%
  %
  \ifx\tikz@lib@dec@te@lettercountvar\pgfutil@empty%
  \else%
    \expandafter\let\tikz@lib@dec@te@lettercountvar=\tikz@lib@dec@te@lettercount%
  \fi%
  %
  \ifx\tikz@lib@dec@te@lettertotalvar\pgfutil@empty%
  \else%
    \expandafter\let\tikz@lib@dec@te@lettertotalvar=\tikz@lib@dec@te@lettetotal%
  \fi%
  %
  \edef\tikz@lib@dec@te@tmp{character \tikz@lib@dec@te@charactercount/.try,%
    character {\meaning\tikz@lib@dec@te@character}/.try}%
  \expandafter\tikz@lib@dec@te@addoptions\expandafter{\tikz@lib@dec@te@tmp}%
  \ifx\tikz@lib@dec@te@character\tikz@lib@dec@te@wordsep%
    \tikz@lib@dec@te@addoptions{/pgf/decoration/text effects/every word separator/.try}%
  \else%
	  \ifnum\tikz@lib@dec@te@wordcount>0\relax%
	    \edef\tikz@lib@dec@te@tmp{every word/.try, word \tikz@lib@dec@te@wordcount/.try}%
	    \expandafter\tikz@lib@dec@te@addoptions\expandafter{\tikz@lib@dec@te@tmp}%
	    \ifnum\tikz@lib@dec@te@lettercount>0\relax%
	      \edef\tikz@lib@dec@te@tmp{every letter/.try,every \tikz@lib@dec@te@lettercount\space letter/.try}%
	      \expandafter\tikz@lib@dec@te@addoptions\expandafter{\tikz@lib@dec@te@tmp}%
	      \ifnum\tikz@lib@dec@te@lettercount=1\relax%
	        \edef\tikz@lib@dec@te@tmp{every first letter/.try}%
	        \expandafter\tikz@lib@dec@te@addoptions\expandafter{\tikz@lib@dec@te@tmp}%
	      \fi%
	      \iftikz@lib@dec@te@finalletter%
	        \tikz@lib@dec@te@addoptions{every final letter/.try}%
	      \fi%
	    \fi%
	  \fi% 
  \fi%
}

% Called by `late positioning' of the node
% to get the width of the bounding box
% of a character.
\def\tikz@lib@dec@te@@getcharacterwidth{%
  \iftikz@lib@dec@te@segmentfromwidth%
    \pgf@x=\pgfpositionnodelatermaxx\relax%
    \advance\pgf@x by-\pgfpositionnodelaterminx\relax%
  \else%
    \pgf@x=\pgfpositionnodelatermaxy\relax%
    \advance\pgf@x by-\pgfpositionnodelaterminy\relax%
  \fi%
  \xdef\tikz@lib@dec@te@characterwidth@tmp{\the\pgf@x}%
}


\def\tikz@lib@dec@te@drawcharacter{%
  \csname tikz@lib@dec@te@character@\tikz@lib@dec@te@charactercount\endcsname%
  \tikz@lib@dec@te@getoptions{every character/.try}%
  \pgfpositionnodelater\relax%
  \pgfutil@ifundefined{tikz@lib@dec@te@character@replacements@\meaning\tikz@lib@dec@te@character @code}{%
    \expandafter\node\expandafter[\tikz@lib@dec@te@options, scale=\tikz@lib@dec@scaledcharacterwidthfactor]{\hbox{\tikz@lib@dec@te@charactercommand{\tikz@lib@dec@te@character}}};%
  }{\tikz@lib@dec@te@drawcharacter@replacement{\tikz@lib@dec@te@character}}%
}

% Replace the character #1 with a character@replacement
%
\def\tikz@lib@dec@te@drawcharacter@replacement#1{%
  \pgfscope%
  \expandafter\tikzset\expandafter{\tikz@lib@dec@te@options}%
  \csname tikz@lib@dec@te@character@replacements@\meaning#1@code\endcsname%
  \endpgfscope%
}

% Get the width of the character@replacement associated with
% the character #1
%
\newbox\tikz@lib@dec@te@box
\def\tikz@lib@dec@te@getcharacter@replacementwidth#1{%
  \pgfinterruptpicture%
  \setbox\tikz@lib@dec@te@box=\hbox{%
  \pgfpicture
  \expandafter\tikzset\expandafter{\tikz@lib@dec@te@options}%
  \csname tikz@lib@dec@te@character@replacements@\meaning#1@code\endcsname%
  \endpgfpicture}%
  \xdef\tikz@lib@dec@te@character@replacementwidth{\the\wd\tikz@lib@dec@te@box}%
  \endpgfinterruptpicture%
}

\def\tikz@lib@dec@scaledcharacterwidthfactor{1}%

% Set up the decoration
\def\tikz@lib@dec@te@state@setup@precomputation{%
  \def\tikz@lib@te@alignshift{0pt}%
  \iftikz@lib@dec@te@pathfromtext%
    % The width of the text and characters has already been calculated.
  \else%
    \let\tikz@lib@dec@te@text=\pgfdecorationtext%
    % Get the chracter tokens and the total number of characters.
    \tikz@lib@dec@te@preparetext%
    \iftikz@lib@dec@te@scaletexttopath%
      % OK, *scaling* text to path is easy.
      % Simply divide the path length by the text width to
      % obtain the scaling factor which will be applied 
      % "at the last minute"...
      \pgfmathdivide{\pgfdecoratedpathlength}{\tikz@lib@dec@te@textwidth}%
      \let\tikz@lib@dec@scaledcharacterwidthfactor=\pgfmathresult%
      \expandafter\pgfkeys\expandafter{\tikz@lib@dec@te@tmp}%
      % ... and recalulate the (pre and post) widths.
      \pgfmathloop
      \ifnum\pgfmathcounter>\tikz@lib@dec@te@charactertotalcount%
      \else%
        \pgf@x=\csname tikz@lib@dec@te@character@\pgfmathcounter @prewidth\endcsname\relax%
        \pgf@x=\tikz@lib@dec@scaledcharacterwidthfactor\pgf@x%                      
        \expandafter\edef\csname tikz@lib@dec@te@character@\pgfmathcounter @prewidth\endcsname{\the\pgf@x}%
        %
        \pgf@x=\csname tikz@lib@dec@te@character@\pgfmathcounter @postwidth\endcsname\relax%
        \pgf@x=\tikz@lib@dec@scaledcharacterwidthfactor\pgf@x%                      
        \expandafter\edef\csname tikz@lib@dec@te@character@\pgfmathcounter @postwidth\endcsname{\the\pgf@x}%
      \repeatpgfmathloop%
      % Update parameters with thewidths.
      \tikz@lib@dec@te@addwidthstoparameters%
      \let\tikz@lib@dec@te@textwidth=\pgfdecoratedpathlength%
    \else%
      \iftikz@lib@dec@te@fittexttopath%
        % *Fitting* text is less easy.
        % The pre and post width of all except the first and last characters 
        % must be recalculated.
        % Only the post width of the first character and the pre width
        % of the final character are scaled as these characters should be
        % fixed and the start and end of the path, respectively.
        %
        % We hope that the decoration engine is accurate enough to position
        % the last word correctly.
        \pgf@x=\pgfdecoratedpathlength%
        \pgf@xa=\csname tikz@lib@dec@te@character@1@postwidth\endcsname\relax%
        \pgf@xb=\csname tikz@lib@dec@te@character@\tikz@lib@dec@te@charactertotalcount @prewidth\endcsname\relax%
        \advance\pgf@x by-\pgf@xa%
        \advance\pgf@x by-\pgf@xb%
        \pgf@y=\tikz@lib@dec@te@textwidth\relax%
        \advance\pgf@y by-\pgf@xa%
        \advance\pgf@y by-\pgf@xb%
        %
        \pgfmathdivide{\the\pgf@x}{\the\pgf@y}%
        \let\tikz@lib@dec@characterwidthscale=\pgfmathresult%      
        \pgfmathloop
        \ifnum\pgfmathcounter>\tikz@lib@dec@te@charactertotalcount\relax%
        \else%
        \ifnum\pgfmathcounter>1\relax%
          \pgf@x=\csname tikz@lib@dec@te@character@\pgfmathcounter @prewidth\endcsname\relax%
          \pgf@x=\tikz@lib@dec@characterwidthscale\pgf@x%  
            \expandafter\edef\csname tikz@lib@dec@te@character@\pgfmathcounter @prewidth\endcsname{\the\pgf@x}%
          \fi%
          \ifnum\pgfmathcounter<\tikz@lib@dec@te@charactertotalcount\relax%
            \pgf@x=\csname tikz@lib@dec@te@character@\pgfmathcounter @postwidth\endcsname\relax%
            \pgf@x=\tikz@lib@dec@characterwidthscale\pgf@x%  
            \expandafter\edef\csname tikz@lib@dec@te@character@\pgfmathcounter @postwidth\endcsname{\the\pgf@x}%
          \fi%
        \repeatpgfmathloop%
        % Update parameters with widths.
        \tikz@lib@dec@te@addwidthstoparameters%
        \let\tikz@lib@dec@te@textwidth=\pgfdecoratedpathlength%
      \else%
        % Calculate the distance to move along the path for alignment.
        \pgfkeysgetvalue{/pgf/decoration/text align/align}{\tikz@lib@dec@align}%
        \ifx\tikz@lib@dec@align\tikz@lib@dec@align@center@text%
           \pgf@x=\pgfdecoratedpathlength\relax%
           \advance\pgf@x by-\tikz@lib@dec@te@textwidth\relax%
           \ifdim\pgf@x<0pt\relax%
             \pgf@x=0pt\relax%
           \fi%
           \divide\pgf@x by2\relax%
           % Adjust the pre-width of the first character...
           \pgf@xa=\csname tikz@lib@dec@te@character@1@prewidth\endcsname\relax%
           \advance\pgf@xa by\pgf@x%
           \expandafter\edef\csname tikz@lib@dec@te@character@1@prewidth\endcsname{\the\pgf@xa}%
           % ...and the post-width of the last character.
           \pgf@xa=\csname tikz@lib@dec@te@character@\tikz@lib@dec@te@charactertotalcount @postwidth\endcsname\relax%
           \advance\pgf@xa by\pgf@x%
           \expandafter\edef\csname tikz@lib@dec@te@character@\tikz@lib@dec@te@charactertotalcount @postwidth\endcsname{\the\pgf@xa}%
        \else%
          \ifx\tikz@lib@dec@align\tikz@lib@dec@align@right@text%
            \pgf@x=\pgfdecoratedpathlength\relax%
            \advance\pgf@x by-\tikz@lib@dec@te@textwidth\relax%
            \ifdim\pgf@x<0pt\relax%
              \pgf@x=0pt\relax%
            \fi%
            % Adjust the pre-width of the first character...
            \pgf@xa=\csname tikz@lib@dec@te@character@1@prewidth\endcsname\relax%
            \advance\pgf@xa by\pgf@x%
            \expandafter\edef\csname tikz@lib@dec@te@character@1@prewidth\endcsname{\the\pgf@xa}%
          \fi%
        \fi%
        \tikz@lib@dec@te@addwidthstoparameters%
      \fi%
    \fi%
  \fi%
}


% Evil hack into the decoration code.
%
% If the path contains single move to and the `path from text'
% key is set to true. The width of the text is calcuated here
% and the (straight line) path automatically calculated.
%
\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%
     \iftikz@lib@dec@te@pathfromtext%
       % Get the start position...
      \pgfextract@process\tikz@lib@dec@te@pathstart{}%
      \tikz@lib@dec@te@preparetext%
      \tikz@lib@dec@te@addwidthstoparameters%
      % ... and create a lineto path of the correct length.
      \pgfsetpath\pgfutil@empty%
      \pgfpathmoveto{\tikz@lib@dec@te@pathstart}%
      \pgfpathlineto{\pgfpointadd{\tikz@lib@dec@te@pathstart}%
        {\pgfpointpolar{\tikz@lib@dec@te@pathfromtextangle}{\tikz@lib@dec@te@textwidth}}}%
      \pgfgetpath\pgfdecoratedpath%
      \pgfsetpath\pgfutil@empty%
    \else%
      #5%
    \fi%
  \else%
    \tikz@lib@dec@te@pathfromtextfalse%
    #6%
  \fi%
}


\pgfdeclaredecoration{text effects along path}{setup}{
  \state{setup}[width=+0pt, next state=scan, persistent precomputation={%
    \tikz@lib@dec@te@state@setup@precomputation%
    \def\tikz@lib@dec@te@charactercount{0}% 
  }]{}
  %
\state{scan}[width=+0pt, next state=pre token, persistent precomputation={%
  \tikz@lib@dec@te@advancecountmacro\tikz@lib@dec@te@charactercount{1}%
  % Usual switch to final state is based on distance.
  % Here we also need it to be on the number of the 
  % current character.
  \ifnum\tikz@lib@dec@te@charactercount>\tikz@lib@dec@te@charactertotalcount\relax%
    \ifnum\tikz@lib@dec@te@repeattext=0\relax%
      \def\pgf@decorate@next@state{final}%
    \else%
      \tikz@lib@dec@te@advancecountmacro\tikz@lib@dec@te@repeattext{-1}%
      \def\tikz@lib@dec@te@charactercount{1}%
    \fi%
  \fi%
  % Install parameters for this character.
  \csname tikz@lib@dec@te@character@\tikz@lib@dec@te@charactercount\endcsname%
}]{}
%
\state{pre token}[width=+\tikz@lib@dec@te@characterprewidth, next state=token]{}
\state{token}[width=+0pt, next state=post token]
{%
  \tikz@lib@dec@te@drawcharacter%
}
\state{post token}[width=+\tikz@lib@dec@te@characterpostwidth, next state=scan]{}
}


% Parse styles for individual characters
% #1 a string of characters (e.g., aieou{\"U}{\"a"})
% #2 the options for to apply to each character.
%
\def\tikz@lib@dec@te@parse@stylecharacters#1#2{%
  \def\tikz@lib@dec@te@text{#1}%
  \tikz@lib@dec@te@scancharacters{%
    \pgfkeysalso{/pgf/decoration/text effects/character {\meaning\tikz@lib@dec@te@character}/.style={#2}}%
  }%
}

% Parse replacment code for for individual characters
% #1 a string of characters (e.g., aieou{\"U}{\"a"})
% #2 the code to execute to each character.
%
\def\tikz@lib@dec@te@parse@replacecharacters#1#2{%
  \def\tikz@lib@dec@te@text{#1}%
  \tikz@lib@dec@te@scancharacters{%
    \expandafter\def\csname tikz@lib@dec@te@character@replacements@\meaning\tikz@lib@dec@te@character @code\endcsname{#2}%
  }%
}

\endinput

tikzlibraryer.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/tikzlibraryer.code.tex,v 1.2 2008/02/20 11:00:42 tantau Exp $

\usetikzlibrary{shapes.geometric}

% Styles for entity types:

\tikzstyle{every entity}=           []
\tikzstyle{entity}=                 [rectangle,draw,
                                     minimum height=2\baselineskip,
                                     minimum width=4\baselineskip,every entity]


% Styles for relationship types:

\tikzstyle{every relationship}=     []
\tikzstyle{relationship}=           [diamond,draw,
                                     minimum size=1.5\baselineskip,
                                     inner sep=1pt,
                                     every relationship]


% Styles for relationship types:

\tikzstyle{every attribute}=        []
\tikzstyle{attribute}=              [minimum size=1.5\baselineskip,ellipse,draw,every attribute]
\tikzstyle{key attribute}=          [font=\itshape,attribute]




\endinput

tikzlibraryfadings.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/tikzlibraryfadings.code.tex,v 1.2 2009/11/15 18:53:00 ludewich Exp $

\usepgflibrary{fadings}

%
% Environments for creating fadings
%

\def\tikzfadingfrompicture{%
  \begingroup%
    \setbox\pgfpic=\hbox\bgroup%
      \tikzpicture%
}
\def\endtikzfadingfrompicture{%
        \global\let\tikz@smuggle=\tikz@fig@name%
      \endtikzpicture
    \egroup%
    \pgfdeclarefading{\tikz@smuggle}{\box\pgfpic}%
  \endgroup%
}

% This makes it easier to maintain compatibility with the external lib:
\def\starttikzfadingfrompicture{\tikzfadingfrompicture}
\def\stopttikzfadingfrompicture{\endtikzfadingfrompicture}

\def\tikzfading[#1]{%
  {%
    \setbox\pgfpic=\hbox{%
      \tikzset{#1}%
      \global\let\tikz@smuggle=\tikz@fig@name%
      \tikz{%
        \useasboundingbox(0,0) (100bp,100bp);
        \node at (50bp,50bp) [rotate=\tikz@shade@angle]
        {\pgfuseshading{\tikz@shading}};
      }%
    }%
    \pgfdeclarefading{\tikz@smuggle}{\box\pgfpic}%    
  }%
}

tikzlibraryfit.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[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/frontendlayer/tikz/libraries/tikzlibraryfit.code.tex,v 1.5 2013/07/12 17:33:49 tantau Exp $

\pgfkeys{/tikz/fit/.code=\tikz@lib@fit{#1},
  /tikz/rotate fit/.code=\def\tikz@lib@fit@rotate{#1}\pgfkeysalso{/tikz/rotate=#1}
}

\def\tikz@lib@fit@rotate{0}

\def\tikz@lib@fit#1{%
  \pgf@xb=-16000pt\relax%
  \pgf@xa=16000pt\relax%
  \pgf@yb=-16000pt\relax%
  \pgf@ya=16000pt\relax%
  %
  \pgfmathsetmacro\tikz@lib@fit@rotate{\tikz@lib@fit@rotate}%
  %
  % Now iterate over the coordinates
  \tikz@lib@fit@scan#1\pgf@stop%
  % Now, let's see what has happend
  \ifdim\pgf@xa>\pgf@xa%
    % Nothing... Ok, let's just ignore this.
  \else%
    % Ok, compute center and width and height
    \pgf@x=\pgf@xb%
    \advance\pgf@x by-\pgf@xa%
    \pgf@y=\pgf@yb%
    \advance\pgf@y by-\pgf@ya%
    \advance\pgf@xa by.5\pgf@x%
    \advance\pgf@ya by.5\pgf@y%
    \ifdim\tikz@lib@fit@rotate pt=0pt\relax%
      {%
        \pgftransforminvert%
        \pgf@pos@transform{\pgf@xa}{\pgf@ya}% 
        \global\pgf@xa\pgf@xa
        \global\pgf@ya\pgf@ya
      }
    \else%
      \pgf@xc=\pgf@x%
      \pgf@yc=\pgf@y%
      {%
        \pgf@xc=\pgf@xa%
        \pgf@yc=\pgf@ya%
        \pgftransforminvert%
        \pgf@pos@transform{\pgf@xc}{\pgf@yc}%
        \pgftransformreset%
        \pgftransformrotate{\tikz@lib@fit@rotate}%
        \pgf@pos@transform{\pgf@xc}{\pgf@yc}%
        \global\pgf@x=\pgf@xc%
        \global\pgf@y=\pgf@yc%
      }%
      \pgf@xa=\pgf@x%
      \pgf@ya=\pgf@y%
      \pgf@x=\pgf@xc%
      \pgf@y=\pgf@yc%
    \fi%
    \edef\tikz@node@at{\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}%
    \pgfkeysalso{/tikz/anchor=center,/tikz/text badly centered}%
    \pgfkeysalso{/tikz/text width/.expanded=\the\pgf@x}%
    \pgf@x=\pgf@y%
    \pgf@y=.5\pgf@y%
    \pgfkeysalso{
      /tikz/text height/.expanded=\the\pgf@y-.5\dp\pgfnodeparttextbox,
      /tikz/text depth/.expanded=\the\pgf@x-\noexpand\the\ht\pgfnodeparttextbox}%
    \pgfkeysalso{every fit/.try}%
  \fi%
}

\def\tikz@lib@fit@scan{%
  \pgfutil@ifnextchar\pgf@stop{\pgfutil@gobble}
  {\tikz@scan@one@point\tikz@lib@fit@scan@handle}}

\def\tikz@lib@fit@scan@handle#1{%
  \iftikz@shapeborder%
    % Ok, fit all four external anchors, if they exist
    \tikz@lib@fit@adjust{\pgfpointanchor{\tikz@shapeborder@name}{west}}%
    \tikz@lib@fit@adjust{\pgfpointanchor{\tikz@shapeborder@name}{east}}%
    \tikz@lib@fit@adjust{\pgfpointanchor{\tikz@shapeborder@name}{north}}%
    \tikz@lib@fit@adjust{\pgfpointanchor{\tikz@shapeborder@name}{south}}%
  \else%
    \tikz@lib@fit@adjust{#1}%
  \fi%
  \tikz@lib@fit@scan%
}

\def\tikz@lib@fit@adjust#1{%
  \ifdim\tikz@lib@fit@rotate pt=0pt\relax%
    \pgf@process{\pgfpointtransformed{#1}}%
  \else%
    {%
      \pgf@process{\pgfpointtransformed{#1}}%
      \pgf@xc=\pgf@x%
      \pgf@yc=\pgf@y%
      \pgfgettransform\tikz@lib@fit@transform%
      \pgftransforminvert%
      \pgf@pos@transform{\pgf@xc}{\pgf@yc}%
      \pgftransformreset%
      \pgftransformrotate{-\tikz@lib@fit@rotate}%
      \pgf@pos@transform{\pgf@xc}{\pgf@yc}%
      \pgfsettransform\tikz@lib@fit@transform%
      \pgf@pos@transform{\pgf@xc}{\pgf@yc}%
      \global\pgf@x=\pgf@xc%
      \global\pgf@y=\pgf@yc%    
    }%
  \fi%
  \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%
}


\endinput

tikzlibraryfixedpointarithmetic.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.

\usepgflibrary{fixedpointarithmetic}

tikzlibraryfolding.code.tex
% Copyright 2006 by Till Tantau
% Copyright 2013 by Nico Van Cleemput
%
% 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/tikzlibraryfolding.code.tex,v 1.3 2013/08/28 11:00:54 tantau Exp $


%
% Length of a standard line in a folding
% 

\tikzoption{folding line length}{\pgfmathsetlength\tikz@lib@fold@length{#1}}
\newdimen\tikz@lib@fold@length
\tikz@lib@fold@length=2cm

% Faces
% -----

\def\tikz@lib@fold@triangle#1#2#3#4{%
  \begin{scope}[xshift=.5\tikz@lib@fold@length,yshift=.28868\tikz@lib@fold@length]
    #1
  \end{scope}
  \begin{scope}[shift={(60:\tikz@lib@fold@length)},rotate=-60]
    #2
  \end{scope}
  \begin{scope}[xshift=\tikz@lib@fold@length,rotate=180]
    #3
  \end{scope}
  \begin{scope}[rotate=60]
    #4
  \end{scope}
}

\def\tikz@lib@fold@square#1#2#3#4#5{%
  \begin{scope}[xshift=.5\tikz@lib@fold@length,yshift=.5\tikz@lib@fold@length]
    #1
  \end{scope}
  \begin{scope}[yshift=\tikz@lib@fold@length]
    #2
  \end{scope}
  \begin{scope}[xshift=\tikz@lib@fold@length,yshift=\tikz@lib@fold@length,rotate=-90]
    #3
  \end{scope}
  \begin{scope}[xshift=\tikz@lib@fold@length,rotate=180]
    #4
  \end{scope}
  \begin{scope}[rotate=90]
    #5
  \end{scope}
}

\def\tikz@lib@fold@pentagon#1#2#3#4#5#6{%
  \begin{scope}[xshift=.5\tikz@lib@fold@length,yshift=0.68819\tikz@lib@fold@length]
    #1
  \end{scope}
  \begin{scope}[shift={(108:\tikz@lib@fold@length)},shift={(36:\tikz@lib@fold@length)},rotate=-36]
    #2
  \end{scope}
  \begin{scope}[xshift=\tikz@lib@fold@length,shift={(72:\tikz@lib@fold@length)},rotate=-108]
    #3
  \end{scope}
  \begin{scope}[xshift=\tikz@lib@fold@length,rotate=180]
    #4
  \end{scope}
  \begin{scope}[rotate=108]
    #5
  \end{scope}
  \begin{scope}[shift={(108:\tikz@lib@fold@length)},rotate=36]
    #6
  \end{scope}
}

\def\tikz@lib@fold@hexagon#1#2#3#4#5#6#7{%
  \begin{scope}
          [shift={(60:\tikz@lib@fold@length)}]
    #1
  \end{scope}
  \begin{scope}
          [shift={(120:\tikz@lib@fold@length)},
           shift={(60:\tikz@lib@fold@length)}]
    #2
  \end{scope}
   \begin{scope}
           [shift={(120:\tikz@lib@fold@length)},
            shift={(60:\tikz@lib@fold@length)},
            xshift=\tikz@lib@fold@length,
            rotate=-60]
    #3
  \end{scope}
  \begin{scope}
          [xshift=\tikz@lib@fold@length,
           shift={(60:\tikz@lib@fold@length)},
           rotate=-120]
    #4
  \end{scope}
  \begin{scope}
          [xshift=\tikz@lib@fold@length,
           rotate=180]
    #5
  \end{scope}
  \begin{scope}
          [rotate=120]
    #6
  \end{scope}
  \begin{scope}
          [shift={(120:\tikz@lib@fold@length)},
           rotate=60]
    #7
  \end{scope}
}

\def\tikz@lib@fold@octagon#1#2#3#4#5#6#7#8#9{%
  \begin{scope}[xshift=.5\tikz@lib@fold@length,yshift=1.20711\tikz@lib@fold@length]
    #1
  \end{scope}
  \begin{scope}[yshift=2.41421\tikz@lib@fold@length]
    #2
  \end{scope}
  \begin{scope}[xshift=\tikz@lib@fold@length,yshift=2.41421\tikz@lib@fold@length,rotate=-45]
    #3
  \end{scope}
  \begin{scope}[xshift=1.70711\tikz@lib@fold@length,yshift=1.70711\tikz@lib@fold@length,rotate=-90]
    #4
  \end{scope}
  \begin{scope}[xshift=1.70711\tikz@lib@fold@length,yshift=.70711\tikz@lib@fold@length,rotate=-135]
    #5
  \end{scope}
  \begin{scope}[xshift=\tikz@lib@fold@length,rotate=180]
    #6
  \end{scope}
  \begin{scope}[rotate=135]
    #7
  \end{scope}
  \begin{scope}[xshift=-.70711\tikz@lib@fold@length,yshift=.70711\tikz@lib@fold@length,rotate=90]
    #8
  \end{scope}
  \begin{scope}[xshift=-.70711\tikz@lib@fold@length,yshift=1.70711\tikz@lib@fold@length,rotate=45]
    #9
  \end{scope}
}

\def\tikz@lib@fold@decagon#1#2#3#4#5#6#7{%
  \begin{scope}[shift={(72:1.61803\tikz@lib@fold@length)}] %decagon inside a circle with radius the golden ratio has side length 1
    #1
  \end{scope}
  \begin{scope}
          [shift={(36:\tikz@lib@fold@length)},
           shift={(72:\tikz@lib@fold@length)},
           shift={(108:\tikz@lib@fold@length)},
           shift={(144:\tikz@lib@fold@length)}]
    #2
  \end{scope}
  \begin{scope}
          [xshift=\tikz@lib@fold@length,
           shift={(36:\tikz@lib@fold@length)},
           shift={(72:\tikz@lib@fold@length)},
           shift={(108:\tikz@lib@fold@length)},
           shift={(144:\tikz@lib@fold@length)},
           rotate=-36]
    #3
  \end{scope}
  \begin{scope}
          [xshift=\tikz@lib@fold@length,
           shift={(36:\tikz@lib@fold@length)},
           shift={(72:\tikz@lib@fold@length)},
           shift={(108:\tikz@lib@fold@length)},
           rotate=-72]
    #4
  \end{scope}
  \begin{scope}
          [xshift=\tikz@lib@fold@length,
           shift={(36:\tikz@lib@fold@length)},
           shift={(72:\tikz@lib@fold@length)},
           rotate=-108]
    #5
  \end{scope}
  \begin{scope}
          [xshift=\tikz@lib@fold@length,
           shift={(36:\tikz@lib@fold@length)},
           rotate=-144]
    #6
  \end{scope}
  \begin{scope}
          [xshift=\tikz@lib@fold@length,
           rotate=180]
    #7
  \end{scope}
  \tikz@lib@fold@decagonbis
}

\def\tikz@lib@fold@decagonbis#1#2#3#4{%
  \begin{scope}
          [rotate=144]
    #1
  \end{scope}
  \begin{scope}
          [shift={(144:\tikz@lib@fold@length)},
           rotate=108]
    #2
  \end{scope}
  \begin{scope}
          [shift={(144:\tikz@lib@fold@length)},
           shift={(108:\tikz@lib@fold@length)},
           rotate=72]
    #3
  \end{scope}
  \begin{scope}
          [shift={(144:\tikz@lib@fold@length)},
           shift={(108:\tikz@lib@fold@length)},
           shift={(72:\tikz@lib@fold@length)},
           rotate=36]
    #4
  \end{scope}
}

\def\tikz@lib@fold@path{\draw[every fold](0,0) -- (\tikz@lib@fold@length,0pt);}
\def\tikz@lib@fold@cut@path{\draw[every cut](0,0) -- (\tikz@lib@fold@length,0pt);}
\def\tikz@lib@fold@ear@path{
  \path[every ear] (0,0) -- (.5\tikz@lib@fold@length,.2\tikz@lib@fold@length) --(\tikz@lib@fold@length,0pt) --(0,0) -- cycle;
  \draw[every fold](0,0) -- (\tikz@lib@fold@length,0pt);
  \draw[every cut] (0,0) -- (.5\tikz@lib@fold@length,.2\tikz@lib@fold@length) --(\tikz@lib@fold@length,0pt);}
\def\tikz@lib@fold@ear@custom@left@path#1{
  \path[every ear] (0,0) -- (#1:.66\tikz@lib@fold@length) -- (\tikz@lib@fold@length,0pt) --(0,0) -- cycle;
  \draw[every fold](0,0) -- (\tikz@lib@fold@length,0pt);
  \draw[every cut] (0,0) -- (#1:.66\tikz@lib@fold@length) -- (\tikz@lib@fold@length,0pt);}
\def\tikz@lib@fold@ear@custom@right@path#1{
  \path[every ear] (0,0) -- (\tikz@lib@fold@length,0pt) -- ++(-#1:-.66\tikz@lib@fold@length) --(0,0) -- cycle;
  \draw[every fold](0,0) -- (\tikz@lib@fold@length,0pt);
  \draw[every cut] (\tikz@lib@fold@length,0pt) -- ++(-#1:-.66\tikz@lib@fold@length) -- (0,0);}

\tikzstyle{every ear}=[]
\tikzstyle{every cut}=[]
\tikzstyle{every fold}=[help lines]

\tikzoption{face 1}{\def\tikz@lib@fold@face@A{#1}}
\tikzoption{face 2}{\def\tikz@lib@fold@face@B{#1}}
\tikzoption{face 3}{\def\tikz@lib@fold@face@C{#1}}
\tikzoption{face 4}{\def\tikz@lib@fold@face@D{#1}}
\tikzoption{face 5}{\def\tikz@lib@fold@face@E{#1}}
\tikzoption{face 6}{\def\tikz@lib@fold@face@F{#1}}
\tikzoption{face 7}{\def\tikz@lib@fold@face@G{#1}}
\tikzoption{face 8}{\def\tikz@lib@fold@face@H{#1}}
\tikzoption{face 9}{\def\tikz@lib@fold@face@I{#1}}
\tikzoption{face 10}{\def\tikz@lib@fold@face@J{#1}}
\tikzoption{face 11}{\def\tikz@lib@fold@face@K{#1}}
\tikzoption{face 12}{\def\tikz@lib@fold@face@L{#1}}
\tikzoption{face 13}{\def\tikz@lib@fold@face@M{#1}}
\tikzoption{face 14}{\def\tikz@lib@fold@face@N{#1}}
\tikzoption{face 15}{\def\tikz@lib@fold@face@O{#1}}
\tikzoption{face 16}{\def\tikz@lib@fold@face@P{#1}}
\tikzoption{face 17}{\def\tikz@lib@fold@face@Q{#1}}
\tikzoption{face 18}{\def\tikz@lib@fold@face@R{#1}}
\tikzoption{face 19}{\def\tikz@lib@fold@face@S{#1}}
\tikzoption{face 20}{\def\tikz@lib@fold@face@T{#1}}
\tikzoption{face 21}{\def\tikz@lib@fold@face@U{#1}}
\tikzoption{face 22}{\def\tikz@lib@fold@face@V{#1}}
\tikzoption{face 23}{\def\tikz@lib@fold@face@W{#1}}
\tikzoption{face 24}{\def\tikz@lib@fold@face@X{#1}}
\tikzoption{face 25}{\def\tikz@lib@fold@face@Y{#1}}
\tikzoption{face 26}{\def\tikz@lib@fold@face@Z{#1}}
\tikzoption{face 27}{\def\tikz@lib@fold@face@AA{#1}}
\tikzoption{face 28}{\def\tikz@lib@fold@face@AB{#1}}
\tikzoption{face 29}{\def\tikz@lib@fold@face@AC{#1}}
\tikzoption{face 30}{\def\tikz@lib@fold@face@AD{#1}}
\tikzoption{face 31}{\def\tikz@lib@fold@face@AE{#1}}
\tikzoption{face 32}{\def\tikz@lib@fold@face@AF{#1}}
\tikzoption{face 33}{\def\tikz@lib@fold@face@AG{#1}}
\tikzoption{face 34}{\def\tikz@lib@fold@face@AH{#1}}
\tikzoption{face 35}{\def\tikz@lib@fold@face@AI{#1}}
\tikzoption{face 36}{\def\tikz@lib@fold@face@AJ{#1}}
\tikzoption{face 37}{\def\tikz@lib@fold@face@AK{#1}}
\tikzoption{face 38}{\def\tikz@lib@fold@face@AL{#1}}
\tikzoption{face 39}{\def\tikz@lib@fold@face@AM{#1}}
\tikzoption{face 40}{\def\tikz@lib@fold@face@AN{#1}}
\tikzoption{face 41}{\def\tikz@lib@fold@face@AO{#1}}
\tikzoption{face 42}{\def\tikz@lib@fold@face@AP{#1}}
\tikzoption{face 43}{\def\tikz@lib@fold@face@AQ{#1}}
\tikzoption{face 44}{\def\tikz@lib@fold@face@AR{#1}}
\tikzoption{face 45}{\def\tikz@lib@fold@face@AS{#1}}
\tikzoption{face 46}{\def\tikz@lib@fold@face@AT{#1}}
\tikzoption{face 47}{\def\tikz@lib@fold@face@AU{#1}}
\tikzoption{face 48}{\def\tikz@lib@fold@face@AV{#1}}
\tikzoption{face 49}{\def\tikz@lib@fold@face@AW{#1}}
\tikzoption{face 50}{\def\tikz@lib@fold@face@AX{#1}}
\tikzoption{face 51}{\def\tikz@lib@fold@face@AY{#1}}
\tikzoption{face 52}{\def\tikz@lib@fold@face@AZ{#1}}
\tikzoption{face 53}{\def\tikz@lib@fold@face@BA{#1}}
\tikzoption{face 54}{\def\tikz@lib@fold@face@BB{#1}}
\tikzoption{face 55}{\def\tikz@lib@fold@face@BC{#1}}
\tikzoption{face 56}{\def\tikz@lib@fold@face@BD{#1}}
\tikzoption{face 57}{\def\tikz@lib@fold@face@BE{#1}}
\tikzoption{face 58}{\def\tikz@lib@fold@face@BF{#1}}
\tikzoption{face 59}{\def\tikz@lib@fold@face@BG{#1}}
\tikzoption{face 60}{\def\tikz@lib@fold@face@BH{#1}}
\tikzoption{face 61}{\def\tikz@lib@fold@face@BI{#1}}
\tikzoption{face 62}{\def\tikz@lib@fold@face@BJ{#1}}
\tikzoption{face 63}{\def\tikz@lib@fold@face@BK{#1}}
\tikzoption{face 64}{\def\tikz@lib@fold@face@BL{#1}}
\tikzoption{face 65}{\def\tikz@lib@fold@face@BM{#1}}
\tikzoption{face 66}{\def\tikz@lib@fold@face@BN{#1}}
\tikzoption{face 67}{\def\tikz@lib@fold@face@BO{#1}}
\tikzoption{face 68}{\def\tikz@lib@fold@face@BP{#1}}
\tikzoption{face 69}{\def\tikz@lib@fold@face@BQ{#1}}
\tikzoption{face 70}{\def\tikz@lib@fold@face@BR{#1}}
\tikzoption{face 71}{\def\tikz@lib@fold@face@BS{#1}}
\tikzoption{face 72}{\def\tikz@lib@fold@face@BT{#1}}
\tikzoption{face 73}{\def\tikz@lib@fold@face@BU{#1}}
\tikzoption{face 74}{\def\tikz@lib@fold@face@BV{#1}}
\tikzoption{face 75}{\def\tikz@lib@fold@face@BW{#1}}
\tikzoption{face 76}{\def\tikz@lib@fold@face@BX{#1}}
\tikzoption{face 77}{\def\tikz@lib@fold@face@BY{#1}}
\tikzoption{face 78}{\def\tikz@lib@fold@face@BZ{#1}}
\tikzoption{face 79}{\def\tikz@lib@fold@face@CA{#1}}
\tikzoption{face 80}{\def\tikz@lib@fold@face@CB{#1}}
\tikzoption{face 81}{\def\tikz@lib@fold@face@CC{#1}}
\tikzoption{face 82}{\def\tikz@lib@fold@face@CD{#1}}
\tikzoption{face 83}{\def\tikz@lib@fold@face@CE{#1}}
\tikzoption{face 84}{\def\tikz@lib@fold@face@CF{#1}}
\tikzoption{face 85}{\def\tikz@lib@fold@face@CG{#1}}
\tikzoption{face 86}{\def\tikz@lib@fold@face@CH{#1}}
\tikzoption{face 87}{\def\tikz@lib@fold@face@CI{#1}}
\tikzoption{face 88}{\def\tikz@lib@fold@face@CJ{#1}}
\tikzoption{face 89}{\def\tikz@lib@fold@face@CK{#1}}
\tikzoption{face 90}{\def\tikz@lib@fold@face@CL{#1}}
\tikzoption{face 91}{\def\tikz@lib@fold@face@CM{#1}}
\tikzoption{face 92}{\def\tikz@lib@fold@face@CN{#1}}


\let\tikz@lib@fold@face@A=\pgfutil@empty
\let\tikz@lib@fold@face@B=\pgfutil@empty
\let\tikz@lib@fold@face@C=\pgfutil@empty
\let\tikz@lib@fold@face@D=\pgfutil@empty
\let\tikz@lib@fold@face@E=\pgfutil@empty
\let\tikz@lib@fold@face@F=\pgfutil@empty
\let\tikz@lib@fold@face@G=\pgfutil@empty
\let\tikz@lib@fold@face@H=\pgfutil@empty
\let\tikz@lib@fold@face@I=\pgfutil@empty
\let\tikz@lib@fold@face@J=\pgfutil@empty
\let\tikz@lib@fold@face@K=\pgfutil@empty
\let\tikz@lib@fold@face@L=\pgfutil@empty
\let\tikz@lib@fold@face@M=\pgfutil@empty
\let\tikz@lib@fold@face@N=\pgfutil@empty
\let\tikz@lib@fold@face@O=\pgfutil@empty
\let\tikz@lib@fold@face@P=\pgfutil@empty
\let\tikz@lib@fold@face@Q=\pgfutil@empty
\let\tikz@lib@fold@face@R=\pgfutil@empty
\let\tikz@lib@fold@face@S=\pgfutil@empty
\let\tikz@lib@fold@face@T=\pgfutil@empty
\let\tikz@lib@fold@face@U=\pgfutil@empty
\let\tikz@lib@fold@face@V=\pgfutil@empty
\let\tikz@lib@fold@face@W=\pgfutil@empty
\let\tikz@lib@fold@face@X=\pgfutil@empty
\let\tikz@lib@fold@face@Y=\pgfutil@empty
\let\tikz@lib@fold@face@Z=\pgfutil@empty
\let\tikz@lib@fold@face@AA=\pgfutil@empty
\let\tikz@lib@fold@face@AB=\pgfutil@empty
\let\tikz@lib@fold@face@AC=\pgfutil@empty
\let\tikz@lib@fold@face@AD=\pgfutil@empty
\let\tikz@lib@fold@face@AE=\pgfutil@empty
\let\tikz@lib@fold@face@AF=\pgfutil@empty
\let\tikz@lib@fold@face@AG=\pgfutil@empty
\let\tikz@lib@fold@face@AH=\pgfutil@empty
\let\tikz@lib@fold@face@AI=\pgfutil@empty
\let\tikz@lib@fold@face@AJ=\pgfutil@empty
\let\tikz@lib@fold@face@AK=\pgfutil@empty
\let\tikz@lib@fold@face@AL=\pgfutil@empty
\let\tikz@lib@fold@face@AM=\pgfutil@empty
\let\tikz@lib@fold@face@AN=\pgfutil@empty
\let\tikz@lib@fold@face@AO=\pgfutil@empty
\let\tikz@lib@fold@face@AP=\pgfutil@empty
\let\tikz@lib@fold@face@AQ=\pgfutil@empty
\let\tikz@lib@fold@face@AR=\pgfutil@empty
\let\tikz@lib@fold@face@AS=\pgfutil@empty
\let\tikz@lib@fold@face@AT=\pgfutil@empty
\let\tikz@lib@fold@face@AU=\pgfutil@empty
\let\tikz@lib@fold@face@AV=\pgfutil@empty
\let\tikz@lib@fold@face@AW=\pgfutil@empty
\let\tikz@lib@fold@face@AX=\pgfutil@empty
\let\tikz@lib@fold@face@AY=\pgfutil@empty
\let\tikz@lib@fold@face@AZ=\pgfutil@empty
\let\tikz@lib@fold@face@BA=\pgfutil@empty
\let\tikz@lib@fold@face@BB=\pgfutil@empty
\let\tikz@lib@fold@face@BC=\pgfutil@empty
\let\tikz@lib@fold@face@BD=\pgfutil@empty
\let\tikz@lib@fold@face@BE=\pgfutil@empty
\let\tikz@lib@fold@face@BF=\pgfutil@empty
\let\tikz@lib@fold@face@BG=\pgfutil@empty
\let\tikz@lib@fold@face@BH=\pgfutil@empty
\let\tikz@lib@fold@face@BI=\pgfutil@empty
\let\tikz@lib@fold@face@BJ=\pgfutil@empty
\let\tikz@lib@fold@face@BK=\pgfutil@empty
\let\tikz@lib@fold@face@BL=\pgfutil@empty
\let\tikz@lib@fold@face@BM=\pgfutil@empty
\let\tikz@lib@fold@face@BN=\pgfutil@empty
\let\tikz@lib@fold@face@BO=\pgfutil@empty
\let\tikz@lib@fold@face@BP=\pgfutil@empty
\let\tikz@lib@fold@face@BQ=\pgfutil@empty
\let\tikz@lib@fold@face@BR=\pgfutil@empty
\let\tikz@lib@fold@face@BS=\pgfutil@empty
\let\tikz@lib@fold@face@BT=\pgfutil@empty
\let\tikz@lib@fold@face@BU=\pgfutil@empty
\let\tikz@lib@fold@face@BV=\pgfutil@empty
\let\tikz@lib@fold@face@BW=\pgfutil@empty
\let\tikz@lib@fold@face@BX=\pgfutil@empty
\let\tikz@lib@fold@face@BY=\pgfutil@empty
\let\tikz@lib@fold@face@BZ=\pgfutil@empty
\let\tikz@lib@fold@face@CA=\pgfutil@empty
\let\tikz@lib@fold@face@CB=\pgfutil@empty
\let\tikz@lib@fold@face@CC=\pgfutil@empty
\let\tikz@lib@fold@face@CD=\pgfutil@empty
\let\tikz@lib@fold@face@CE=\pgfutil@empty
\let\tikz@lib@fold@face@CF=\pgfutil@empty
\let\tikz@lib@fold@face@CG=\pgfutil@empty
\let\tikz@lib@fold@face@CH=\pgfutil@empty
\let\tikz@lib@fold@face@CI=\pgfutil@empty
\let\tikz@lib@fold@face@CJ=\pgfutil@empty
\let\tikz@lib@fold@face@CK=\pgfutil@empty
\let\tikz@lib@fold@face@CL=\pgfutil@empty
\let\tikz@lib@fold@face@CM=\pgfutil@empty
\let\tikz@lib@fold@face@CN=\pgfutil@empty


\tikzstyle{numbered faces}=[%
	face 1={\node{1};},
	face 2={\node{2};},
	face 3={\node{3};},
	face 4={\node{4};},
	face 5={\node{5};},
	face 6={\node{6};},
	face 7={\node{7};},
	face 8={\node{8};},
	face 9={\node{9};},
	face 10={\node{10};},
	face 11={\node{11};},
	face 12={\node{12};},
	face 13={\node{13};},
	face 14={\node{14};},
	face 15={\node{15};},
	face 16={\node{16};},
	face 17={\node{17};},
	face 18={\node{18};},
	face 19={\node{19};},
	face 20={\node{20};},
	face 21={\node{21};},
	face 22={\node{22};},
	face 23={\node{23};},
	face 24={\node{24};},
	face 25={\node{25};},
	face 26={\node{26};},
	face 27={\node{27};},
	face 28={\node{28};},
	face 29={\node{29};},
	face 30={\node{30};},
	face 31={\node{31};},
	face 32={\node{32};},
	face 33={\node{33};},
	face 34={\node{34};},
	face 35={\node{35};},
	face 36={\node{36};},
	face 37={\node{37};},
	face 38={\node{38};},
	face 39={\node{39};},
	face 40={\node{40};},
	face 41={\node{41};},
	face 42={\node{42};},
	face 43={\node{43};},
	face 44={\node{44};},
	face 45={\node{45};},
	face 46={\node{46};},
	face 47={\node{47};},
	face 48={\node{48};},
	face 49={\node{49};},
	face 50={\node{50};},
	face 51={\node{51};},
	face 52={\node{52};},
	face 53={\node{53};},
	face 54={\node{54};},
	face 55={\node{55};},
	face 56={\node{56};},
	face 57={\node{57};},
	face 58={\node{58};},
	face 59={\node{59};},
	face 60={\node{60};},
	face 61={\node{61};},
	face 62={\node{62};},
	face 63={\node{63};},
	face 64={\node{64};},
	face 65={\node{65};},
	face 66={\node{66};},
	face 67={\node{67};},
	face 68={\node{68};},
	face 69={\node{69};},
	face 70={\node{70};},
	face 71={\node{71};},
	face 72={\node{72};},
	face 73={\node{73};},
	face 74={\node{74};},
	face 75={\node{75};},
	face 76={\node{76};},
	face 77={\node{77};},
	face 78={\node{78};},
	face 79={\node{79};},
	face 80={\node{80};},
	face 81={\node{81};},
	face 82={\node{82};},
	face 83={\node{83};},
	face 84={\node{84};},
	face 85={\node{85};},
	face 86={\node{86};},
	face 87={\node{87};},
	face 88={\node{88};},
	face 89={\node{89};},
	face 90={\node{90};},
	face 91={\node{91};},
	face 92={\node{92};}]
        
% The foldings defined here:
        
\tikzset{
  pics/dodecahedron folding/.style            = {code=\tikzfoldingdodecahedron[];},
  pics/tetrahedron folding/.style             = {code=\tikzfoldingtetrahedron[];},
  pics/tetrahedron truncated folding/.style   = {code=\tikzfoldingtruncatedtetrahedron[];},
  pics/cube folding/.style                    = {code=\tikzfoldingcube[];},
  pics/cube truncated folding/.style          = {code=\tikzfoldingtruncatedcube[];},
  pics/octahedron folding/.style              = {code=\tikzfoldingoctahedron[];},
  pics/octahedron truncated folding/.style    = {code=\tikzfoldingtruncatedoctahedron[];},
  pics/dodecahedron folding/.style            = {code=\tikzfoldingdodecahedron[];},
  pics/dodecahedron' folding/.style           = {code=\tikzfoldingalternatedodecahedron[];},
  pics/cuboctahedron folding/.style           = {code=\tikzfoldingoctahedron[];},
  pics/cuboctahedron truncated folding/.style = {code=\tikzfoldingtruncatedoctahedron[];},
  pics/icosahedron folding/.style             = {code=\tikzfoldingicosahedron[];},
  pics/rhombicuboctahedron folding/.style     = {code=\tikzfoldingrhombicuboctahedron[];},
  pics/snub cube folding/.style               = {code=\tikzfoldingsnubcube[];},
  pics/icosidodecahedron folding/.style       = {code=\tikzfoldingicosahedron[];}
}


        
% Platonic solids
% ---------------
        
\def\tikzfoldingdodecahedron#1[#2]#3;{%
  \begingroup%
    \tikzset{#2}%
    \tikz@lib@fold@pentagon
        {\tikz@lib@fold@face@A}
        {\tikz@lib@fold@pentagon
             {\tikz@lib@fold@face@B}
             {\tikz@lib@fold@pentagon
                  {\tikz@lib@fold@face@C}
                  {\tikz@lib@fold@ear@path}
                  {\tikz@lib@fold@ear@path}
                  {\tikz@lib@fold@path}
                  {\tikz@lib@fold@ear@path}
                  {\tikz@lib@fold@ear@path}
             }
             {\tikz@lib@fold@ear@path}
             {\tikz@lib@fold@path}
             {\tikz@lib@fold@ear@path}
             {\tikz@lib@fold@ear@path}
        }
        {\tikz@lib@fold@pentagon
             {\tikz@lib@fold@face@D}
             {\tikz@lib@fold@pentagon
                  {\tikz@lib@fold@face@E}
                  {\tikz@lib@fold@ear@path}
                  {\tikz@lib@fold@ear@path}
                  {\tikz@lib@fold@path}
                  {\tikz@lib@fold@cut@path}
                  {\tikz@lib@fold@ear@path}
             }
             {\tikz@lib@fold@ear@path}
             {\tikz@lib@fold@path}
             {\tikz@lib@fold@cut@path}
             {\tikz@lib@fold@cut@path}
        }
        {\tikz@lib@fold@pentagon
             {\tikz@lib@fold@face@F}
             {\tikz@lib@fold@pentagon
                  {\tikz@lib@fold@face@G}
                  {\tikz@lib@fold@ear@path}
                  {\tikz@lib@fold@ear@path}
                  {\tikz@lib@fold@path}
                  {\tikz@lib@fold@cut@path}
                  {\tikz@lib@fold@ear@path}
             }
             {\tikz@lib@fold@ear@path}
             {\tikz@lib@fold@path}
             {\tikz@lib@fold@cut@path}
             {\tikz@lib@fold@cut@path}
        }
        {\tikz@lib@fold@pentagon
             {\tikz@lib@fold@face@H}
             {\tikz@lib@fold@pentagon
                  {\tikz@lib@fold@face@I}
                  {\tikz@lib@fold@ear@path}
                  {\tikz@lib@fold@ear@path}
                  {\tikz@lib@fold@path}
                  {\tikz@lib@fold@cut@path}
                  {\tikz@lib@fold@ear@path}
             }
             {\tikz@lib@fold@ear@path}
             {\tikz@lib@fold@path}
             {\tikz@lib@fold@cut@path}
             {\tikz@lib@fold@cut@path}
        }
        {\tikz@lib@fold@pentagon
             {\tikz@lib@fold@face@J}
             {\tikz@lib@fold@pentagon
                  {\tikz@lib@fold@face@K}
                  {\tikz@lib@fold@cut@path}
                  {\tikz@lib@fold@cut@path}
                  {\tikz@lib@fold@path}
                  {\tikz@lib@fold@cut@path}
                  {\tikz@lib@fold@pentagon
                       {\tikz@lib@fold@face@L}
                       {\tikz@lib@fold@cut@path}
                       {\tikz@lib@fold@cut@path}
                       {\tikz@lib@fold@path}
                       {\tikz@lib@fold@cut@path}
                       {\tikz@lib@fold@cut@path}
                  }
             }
             {\tikz@lib@fold@cut@path}
             {\tikz@lib@fold@path}
             {\tikz@lib@fold@cut@path}
             {\tikz@lib@fold@cut@path}
        }
  \endgroup
}

%alternative dodecahedron: larger format possible  

\def\tikzfoldingalternatedodecahedron#1[#2]#3;{%
  \begingroup%
    \tikzset{#2}%
    \tikz@lib@fold@pentagon
        {\tikz@lib@fold@face@A}
        {\tikz@lib@fold@pentagon
             {\tikz@lib@fold@face@B}
             {\tikz@lib@fold@cut@path}
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@cut@path}
	         {\tikz@lib@fold@pentagon
	              {\tikz@lib@fold@face@C}
		          {\tikz@lib@fold@pentagon
		               {\tikz@lib@fold@face@D}
			           {\tikz@lib@fold@ear@path}
			           {\tikz@lib@fold@ear@path}
			           {\tikz@lib@fold@path}
			           {\tikz@lib@fold@cut@path}
			           {\tikz@lib@fold@ear@path}
		          }
		          {\tikz@lib@fold@pentagon
		               {\tikz@lib@fold@face@E}
			           {\tikz@lib@fold@ear@path}
			           {\tikz@lib@fold@ear@path}
		               {\tikz@lib@fold@path}
                       {\tikz@lib@fold@cut@path}
                       {\tikz@lib@fold@ear@path}
		          }
		          {\tikz@lib@fold@path}
		          {\tikz@lib@fold@pentagon
		               {\tikz@lib@fold@face@F}
			           {\tikz@lib@fold@ear@path}
                       {\tikz@lib@fold@ear@path}
                       {\tikz@lib@fold@path}
                       {\tikz@lib@fold@ear@path}
			           {\tikz@lib@fold@cut@path}
		          }
		          {\tikz@lib@fold@pentagon
		               {\tikz@lib@fold@face@G}
			           {\tikz@lib@fold@ear@path}
			           {\tikz@lib@fold@ear@path}
			           {\tikz@lib@fold@path}
			           {\tikz@lib@fold@cut@path}
			           {\tikz@lib@fold@ear@path}
		          }
	         }
        }
        {\tikz@lib@fold@ear@path}
        {\tikz@lib@fold@pentagon
             {\tikz@lib@fold@face@H}
	         {\tikz@lib@fold@pentagon
	              {\tikz@lib@fold@face@I}
		          {\tikz@lib@fold@cut@path}
		          {\tikz@lib@fold@ear@path}
		          {\tikz@lib@fold@path}
		          {\tikz@lib@fold@cut@path}
		          {\tikz@lib@fold@cut@path}
	         }
	         {\tikz@lib@fold@pentagon
	              {\tikz@lib@fold@face@J}
		          {\tikz@lib@fold@cut@path}
		          {\tikz@lib@fold@cut@path}
		          {\tikz@lib@fold@path}
		          {\tikz@lib@fold@cut@path}
		    {\tikz@lib@fold@cut@path}
	    }
	    {\tikz@lib@fold@path}
	    {\tikz@lib@fold@pentagon
	         {\tikz@lib@fold@face@K}
		     {\tikz@lib@fold@cut@path}
		     {\tikz@lib@fold@ear@path}
		     {\tikz@lib@fold@path}
		     {\tikz@lib@fold@cut@path}
		     {\tikz@lib@fold@cut@path}
	    }
	    {\tikz@lib@fold@pentagon
	         {\tikz@lib@fold@face@L}
		     {\tikz@lib@fold@cut@path}
		     {\tikz@lib@fold@ear@path}
		     {\tikz@lib@fold@path}
		     {\tikz@lib@fold@cut@path}
		     {\tikz@lib@fold@cut@path}
	    }
    }
    {\tikz@lib@fold@ear@path}
    {\tikz@lib@fold@ear@path}
  \endgroup
}


%tetrahedron  

\def\tikzfoldingtetrahedron#1[#2]#3;{%
  \begingroup%
    \tikzset{#2}%
    \tikz@lib@fold@triangle
        {\tikz@lib@fold@face@A}
        {\tikz@lib@fold@triangle
             {\tikz@lib@fold@face@B}
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@cut@path}
        }
        {\tikz@lib@fold@triangle
             {\tikz@lib@fold@face@C}
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@cut@path}
        }
        {\tikz@lib@fold@triangle
             {\tikz@lib@fold@face@D}
             {\tikz@lib@fold@ear@path}
             {\tikz@lib@fold@path}
             {\tikz@lib@fold@cut@path}
    }
  \endgroup
}

%cube  

\def\tikzfoldingcube#1[#2]#3;{%
  \begingroup%
    \tikzset{#2}%
    \tikz@lib@fold@square{\tikz@lib@fold@face@A}
    {
			\tikz@lib@fold@square{\tikz@lib@fold@face@B}
	    {\tikz@lib@fold@cut@path}
	    {\tikz@lib@fold@ear@path}
	    {\tikz@lib@fold@path}
	    {\tikz@lib@fold@ear@path}
    }
    {
			\tikz@lib@fold@square{\tikz@lib@fold@face@C}
	    {\tikz@lib@fold@cut@path}
	    {\tikz@lib@fold@cut@path}
	    {\tikz@lib@fold@path}
	    {\tikz@lib@fold@cut@path}
    }
    {
			\tikz@lib@fold@square{\tikz@lib@fold@face@D}
	    {
				\tikz@lib@fold@square{\tikz@lib@fold@face@E}
		    {\tikz@lib@fold@ear@path}
		    {\tikz@lib@fold@cut@path}
		    {\tikz@lib@fold@path}
		    {\tikz@lib@fold@ear@path}
	    }
	    {\tikz@lib@fold@ear@path}
	    {\tikz@lib@fold@path}
	    {\tikz@lib@fold@ear@path}
    }
    {
			\tikz@lib@fold@square{\tikz@lib@fold@face@F}
	    {\tikz@lib@fold@ear@path}
	    {\tikz@lib@fold@cut@path}
	    {\tikz@lib@fold@path}
	    {\tikz@lib@fold@cut@path}
    }
  \endgroup
}


%octahedron  

\def\tikzfoldingoctahedron#1[#2]#3;{%
  \begingroup%
    \tikzset{#2}%
    \tikz@lib@fold@triangle
        {\tikz@lib@fold@face@A}
        {\tikz@lib@fold@triangle
             {\tikz@lib@fold@face@B}
	         {\tikz@lib@fold@triangle
	              {\tikz@lib@fold@face@C}
		          {\tikz@lib@fold@cut@path}
		          {\tikz@lib@fold@path}
		          {\tikz@lib@fold@triangle
		               {\tikz@lib@fold@face@D}
			           {\tikz@lib@fold@cut@path}
			           {\tikz@lib@fold@path}
			           {\tikz@lib@fold@cut@path}
		          }
	         }
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@triangle
                  {\tikz@lib@fold@face@E}
                  {\tikz@lib@fold@ear@path}
                  {\tikz@lib@fold@path}
		          {\tikz@lib@fold@ear@path}
	         }
        }
        {\tikz@lib@fold@triangle
             {\tikz@lib@fold@face@F}
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@ear@path}
        }
        {\tikz@lib@fold@triangle
             {\tikz@lib@fold@face@G}
	         {\tikz@lib@fold@cut@path}
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@triangle
	              {\tikz@lib@fold@face@H}
		          {\tikz@lib@fold@ear@path}
		          {\tikz@lib@fold@path}
		          {\tikz@lib@fold@cut@path}
	         }
        }
  \endgroup
}


%icosahedron  

\def\tikzfoldingicosahedron#1[#2]#3;{%
  \begingroup%
    \tikzset{#2}%
    \tikz@lib@fold@triangle
        {\tikz@lib@fold@face@A}
        {\tikz@lib@fold@triangle
             {\tikz@lib@fold@face@B}
	         {\tikz@lib@fold@triangle
	              {\tikz@lib@fold@face@C}
		          {\tikz@lib@fold@triangle
		               {\tikz@lib@fold@face@D}
			           {\tikz@lib@fold@cut@path}
			           {\tikz@lib@fold@path}
			           {\tikz@lib@fold@triangle
			                {\tikz@lib@fold@face@E}
				            {\tikz@lib@fold@cut@path}
				            {\tikz@lib@fold@path}
				            {\tikz@lib@fold@triangle
				                 {\tikz@lib@fold@face@F}
		                         {\tikz@lib@fold@ear@path}
			                     {\tikz@lib@fold@path}
			                     {\tikz@lib@fold@triangle
			                          {\tikz@lib@fold@face@G}
			                          {\tikz@lib@fold@ear@path}
			                          {\tikz@lib@fold@path}
			                          {\tikz@lib@fold@cut@path}
			                     }
		                    }
			           }
		          }
                  {\tikz@lib@fold@path}
                  {\tikz@lib@fold@ear@path}
	         }
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@ear@path}
        }
        {\tikz@lib@fold@triangle
             {\tikz@lib@fold@face@H}
	         {\tikz@lib@fold@triangle
	              {\tikz@lib@fold@face@I}
		          {\tikz@lib@fold@triangle
		               {\tikz@lib@fold@face@J}
			           {\tikz@lib@fold@cut@path}
			           {\tikz@lib@fold@path}
			           {\tikz@lib@fold@triangle
			                {\tikz@lib@fold@face@K}
				            {\tikz@lib@fold@cut@path}
				            {\tikz@lib@fold@path}
				            {\tikz@lib@fold@triangle
				                 {\tikz@lib@fold@face@L}
					             {\tikz@lib@fold@triangle
					                  {\tikz@lib@fold@face@M}
						              {\tikz@lib@fold@cut@path}
						              {\tikz@lib@fold@path}
						              {\tikz@lib@fold@cut@path}
					             }
					             {\tikz@lib@fold@path}
					             {\tikz@lib@fold@triangle
					                  {\tikz@lib@fold@face@N}
						              {\tikz@lib@fold@ear@path}
						              {\tikz@lib@fold@path}
						              {\tikz@lib@fold@cut@path}
					             }
				            }
			           }
		          }
		          {\tikz@lib@fold@path}
		          {\tikz@lib@fold@ear@path}
	         }
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@ear@path}
        }
        {\tikz@lib@fold@triangle
             {\tikz@lib@fold@face@O}
	         {\tikz@lib@fold@triangle
	              {\tikz@lib@fold@face@P}
		          {\tikz@lib@fold@triangle
		               {\tikz@lib@fold@face@Q}
			           {\tikz@lib@fold@cut@path}
			           {\tikz@lib@fold@path}
			           {\tikz@lib@fold@triangle
			                {\tikz@lib@fold@face@R}
				            {\tikz@lib@fold@cut@path}
				            {\tikz@lib@fold@path}
				            {\tikz@lib@fold@triangle
				                 {\tikz@lib@fold@face@S}
				                 {\tikz@lib@fold@ear@path}
					             {\tikz@lib@fold@path}
					             {\tikz@lib@fold@triangle
                                      {\tikz@lib@fold@face@T}
                                      {\tikz@lib@fold@ear@path}
						              {\tikz@lib@fold@path}
						              {\tikz@lib@fold@cut@path}
					             }
				            }
			           }
		          }
		          {\tikz@lib@fold@path}
		          {\tikz@lib@fold@ear@path}
	         }
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@ear@path}
        }
  \endgroup
}

% Archimedean solids
% ------------------

%truncated tetrahedron  

\def\tikzfoldingtruncatedtetrahedron#1[#2]#3;{%
  \begingroup%
    \tikzset{#2}%
    \tikz@lib@fold@hexagon
        {\tikz@lib@fold@face@A}
        {\tikz@lib@fold@hexagon
             {\tikz@lib@fold@face@B}
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@cut@path}
        }
        {\tikz@lib@fold@triangle
             {\tikz@lib@fold@face@C}
	         {\tikz@lib@fold@cut@path}
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@cut@path}
        }
        {\tikz@lib@fold@hexagon
             {\tikz@lib@fold@face@D}
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@cut@path}
        }
        {\tikz@lib@fold@triangle
             {\tikz@lib@fold@face@E}
	         {\tikz@lib@fold@cut@path}
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@cut@path}
        }
        {\tikz@lib@fold@hexagon
             {\tikz@lib@fold@face@F}
	         {\tikz@lib@fold@triangle
	              {\tikz@lib@fold@face@G}
		          {\tikz@lib@fold@cut@path}
		          {\tikz@lib@fold@path}
		          {\tikz@lib@fold@cut@path}
	         }
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@cut@path}
        }
        {\tikz@lib@fold@triangle
             {\tikz@lib@fold@face@H}
	         {\tikz@lib@fold@cut@path}
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@cut@path}
        }
  \endgroup
}

%cuboctahedron  

\def\tikzfoldingcuboctahedron#1[#2]#3;{%
  \begingroup%
    \tikzset{#2}%
    \tikz@lib@fold@square
        {\tikz@lib@fold@face@A}
        {\tikz@lib@fold@triangle
             {\tikz@lib@fold@face@B}
	         {\tikz@lib@fold@square
	              {\tikz@lib@fold@face@C}
		          {\tikz@lib@fold@triangle
		               {\tikz@lib@fold@face@D}
			           {\tikz@lib@fold@cut@path}
			           {\tikz@lib@fold@path}
			           {\tikz@lib@fold@square
		                    {\tikz@lib@fold@face@E}
		                    {\tikz@lib@fold@ear@path}
		                    {\tikz@lib@fold@ear@path}
		                    {\tikz@lib@fold@path}
		                    {\tikz@lib@fold@ear@path}
                       }
		          }
		          {\tikz@lib@fold@ear@path}
		          {\tikz@lib@fold@path}
		          {\tikz@lib@fold@ear@path}
	         }
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@cut@path}
        }
        {\tikz@lib@fold@triangle
             {\tikz@lib@fold@face@F}
	         {\tikz@lib@fold@square
	              {\tikz@lib@fold@face@G}
                  {\tikz@lib@fold@ear@path}
                  {\tikz@lib@fold@ear@path}
                  {\tikz@lib@fold@path}
                  {\tikz@lib@fold@ear@path}
             }
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@cut@path}
        }
        {\tikz@lib@fold@triangle
             {\tikz@lib@fold@face@H}
	         {\tikz@lib@fold@square
	              {\tikz@lib@fold@face@I}
		          {\tikz@lib@fold@ear@path}
		          {\tikz@lib@fold@ear@path}
		          {\tikz@lib@fold@path}
		          {\tikz@lib@fold@triangle
		               {\tikz@lib@fold@face@J}
			           {\tikz@lib@fold@cut@path}
			           {\tikz@lib@fold@path}
			           {\tikz@lib@fold@cut@path}
		          }
	         }
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@cut@path}
        }
        {\tikz@lib@fold@triangle
             {\tikz@lib@fold@face@K}
	         {\tikz@lib@fold@square
	              {\tikz@lib@fold@face@L}
		          {\tikz@lib@fold@triangle
		               {\tikz@lib@fold@face@M}
			           {\tikz@lib@fold@cut@path}
			           {\tikz@lib@fold@path}
			           {\tikz@lib@fold@cut@path}
		          }
		          {\tikz@lib@fold@ear@path}
		          {\tikz@lib@fold@path}
		          {\tikz@lib@fold@triangle
                       {\tikz@lib@fold@face@N}
			           {\tikz@lib@fold@cut@path}
			           {\tikz@lib@fold@path}
			           {\tikz@lib@fold@cut@path}
		          }
	         }
	    {\tikz@lib@fold@path}
	    {\tikz@lib@fold@cut@path}
    }
  \endgroup
}

%truncated cube

\def\tikzfoldingtruncatedcube#1[#2]#3;{%
  \begingroup%
    \tikzset{#2}%
    \tikz@lib@fold@octagon
        {\tikz@lib@fold@face@A}
        {\tikz@lib@fold@octagon
             {\tikz@lib@fold@face@B}
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@triangle
                     {\tikz@lib@fold@face@C}
	             {\tikz@lib@fold@ear@path}
	             {\tikz@lib@fold@path}
	             {\tikz@lib@fold@ear@path}
                 }
	         {\tikz@lib@fold@cut@path}
	         {\tikz@lib@fold@triangle
                     {\tikz@lib@fold@face@D}
	             {\tikz@lib@fold@ear@path}
	             {\tikz@lib@fold@path}
	             {\tikz@lib@fold@ear@path}
                 }
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@triangle
                     {\tikz@lib@fold@face@E}
	             {\tikz@lib@fold@ear@path}
	             {\tikz@lib@fold@path}
	             {\tikz@lib@fold@ear@path}
                 }
	         {\tikz@lib@fold@cut@path}
	         {\tikz@lib@fold@triangle
                     {\tikz@lib@fold@face@F}
	             {\tikz@lib@fold@ear@path}
	             {\tikz@lib@fold@path}
	             {\tikz@lib@fold@ear@path}
                 }
        }
        {\tikz@lib@fold@cut@path}
        {\tikz@lib@fold@octagon
             {\tikz@lib@fold@face@G}
	         {\tikz@lib@fold@cut@path}
	         {\tikz@lib@fold@cut@path}
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@triangle
                     {\tikz@lib@fold@face@H}
	             {\tikz@lib@fold@ear@path}
	             {\tikz@lib@fold@path}
	             {\tikz@lib@fold@ear@path}
                 }
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@cut@path}
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@cut@path}
        }
        {\tikz@lib@fold@cut@path}
        {\tikz@lib@fold@octagon
             {\tikz@lib@fold@face@I}
	         {\tikz@lib@fold@octagon
                     {\tikz@lib@fold@face@J}
	             {\tikz@lib@fold@cut@path}
	             {\tikz@lib@fold@cut@path}
	             {\tikz@lib@fold@ear@path}
	             {\tikz@lib@fold@triangle
                         {\tikz@lib@fold@face@K}
	                 {\tikz@lib@fold@ear@path}
	                 {\tikz@lib@fold@path}
	                 {\tikz@lib@fold@ear@path}
                     }
	             {\tikz@lib@fold@path}
	             {\tikz@lib@fold@triangle
                         {\tikz@lib@fold@face@L}
	                 {\tikz@lib@fold@ear@path}
	                 {\tikz@lib@fold@path}
	                 {\tikz@lib@fold@ear@path}
                     }
	             {\tikz@lib@fold@ear@path}
	             {\tikz@lib@fold@cut@path}
                 }
	         {\tikz@lib@fold@cut@path}
	         {\tikz@lib@fold@cut@path}
	         {\tikz@lib@fold@cut@path}
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@cut@path}
	         {\tikz@lib@fold@cut@path}
	         {\tikz@lib@fold@cut@path}
        }
        {\tikz@lib@fold@cut@path}
        {\tikz@lib@fold@octagon
             {\tikz@lib@fold@face@M}
	         {\tikz@lib@fold@cut@path}
	         {\tikz@lib@fold@cut@path}
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@cut@path}
	         {\tikz@lib@fold@path}
	         {\tikz@lib@fold@triangle
                     {\tikz@lib@fold@face@N}
	             {\tikz@lib@fold@ear@path}
	             {\tikz@lib@fold@path}
	             {\tikz@lib@fold@ear@path}
                 }
	         {\tikz@lib@fold@ear@path}
	         {\tikz@lib@fold@cut@path}
        }
        {\tikz@lib@fold@cut@path}
  \endgroup
}


%truncated octahedron

\def\tikzfoldingtruncatedoctahedron#1[#2]#3;{%
  \begingroup%
    \tikzset{#2}%
    \tikz@lib@fold@hexagon
        {\tikz@lib@fold@face@A}
        {\tikz@lib@fold@hexagon
            {\tikz@lib@fold@face@B}
            {\tikz@lib@fold@square
                {\tikz@lib@fold@face@C}
                {\tikz@lib@fold@ear@path}
                {\tikz@lib@fold@cut@path}
                {\tikz@lib@fold@path}
                {\tikz@lib@fold@cut@path}
            }
            {\tikz@lib@fold@hexagon
                {\tikz@lib@fold@face@D}
                {\tikz@lib@fold@ear@path}
                {\tikz@lib@fold@ear@path}
                {\tikz@lib@fold@ear@path}
                {\tikz@lib@fold@path}
                {\tikz@lib@fold@ear@path}
                {\tikz@lib@fold@ear@path}
            }
            {\tikz@lib@fold@square
                {\tikz@lib@fold@face@E}
                {\tikz@lib@fold@ear@path}
                {\tikz@lib@fold@ear@path}
                {\tikz@lib@fold@path}
                {\tikz@lib@fold@cut@path}
            }
            {\tikz@lib@fold@path}
            {\tikz@lib@fold@square
                {\tikz@lib@fold@face@F}
                {\tikz@lib@fold@ear@path}
                {\tikz@lib@fold@cut@path}
                {\tikz@lib@fold@path}
                {\tikz@lib@fold@ear@path}
            }
            {\tikz@lib@fold@hexagon
                {\tikz@lib@fold@face@G}
                {\tikz@lib@fold@ear@path}
                {\tikz@lib@fold@ear@path}
                {\tikz@lib@fold@ear@path}
                {\tikz@lib@fold@path}
                {\tikz@lib@fold@ear@path}
                {\tikz@lib@fold@ear@path}
            }
        }
        {\tikz@lib@fold@cut@path}
        {\tikz@lib@fold@ear@path}
        {\tikz@lib@fold@square
            {\tikz@lib@fold@face@H}
            {\tikz@lib@fold@hexagon
                {\tikz@lib@fold@face@I}
                {\tikz@lib@fold@hexagon
                    {\tikz@lib@fold@face@J}
                    {\tikz@lib@fold@cut@path}
                    {\tikz@lib@fold@cut@path}
                    {\tikz@lib@fold@ear@path}
                    {\tikz@lib@fold@path}
                    {\tikz@lib@fold@ear@path}
                    {\tikz@lib@fold@cut@path}
                }
                {\tikz@lib@fold@square
                    {\tikz@lib@fold@face@K}
                    {\tikz@lib@fold@cut@path}
                    {\tikz@lib@fold@ear@path}
                    {\tikz@lib@fold@path}
                    {\tikz@lib@fold@cut@path}
                }
                {\tikz@lib@fold@hexagon
                    {\tikz@lib@fold@face@L}
                    {\tikz@lib@fold@cut@path}
                    {\tikz@lib@fold@cut@path}
                    {\tikz@lib@fold@cut@path}
                    {\tikz@lib@fold@path}
                    {\tikz@lib@fold@cut@path}
                    {\tikz@lib@fold@cut@path}
                }
                {\tikz@lib@fold@path}
                {\tikz@lib@fold@hexagon
                    {\tikz@lib@fold@face@M}
                    {\tikz@lib@fold@cut@path}
                    {\tikz@lib@fold@cut@path}
                    {\tikz@lib@fold@cut@path}
                    {\tikz@lib@fold@path}
                    {\tikz@lib@fold@cut@path}
                    {\tikz@lib@fold@cut@path}
                }
                {\tikz@lib@fold@square
                    {\tikz@lib@fold@face@N}
                    {\tikz@lib@fold@cut@path}
                    {\tikz@lib@fold@cut@path}
                    {\tikz@lib@fold@path}
                    {\tikz@lib@fold@ear@path}
                }
            }
            {\tikz@lib@fold@ear@path}
            {\tikz@lib@fold@path}
            {\tikz@lib@fold@ear@path}
        }
        {\tikz@lib@fold@ear@path}
        {\tikz@lib@fold@cut@path}
  \endgroup
}


%rhombicuboctahedron

\def\tikzfoldingrhombicuboctahedron#1[#2]#3;{%
  \begingroup%
    \tikzset{#2}%
    \tikz@lib@fold@square
        {\tikz@lib@fold@face@A}
        {\tikz@lib@fold@square
            {\tikz@lib@fold@face@B}
            {\tikz@lib@fold@square
                {\tikz@lib@fold@face@C}
                {\tikz@lib@fold@square
                    {\tikz@lib@fold@face@D}
                    {\tikz@lib@fold@square
                        {\tikz@lib@fold@face@E}
                        {\tikz@lib@fold@cut@path}
                        {\tikz@lib@fold@square
                            {\tikz@lib@fold@face@F}
                            {\tikz@lib@fold@ear@path}
                            {\tikz@lib@fold@ear@path}
                            {\tikz@lib@fold@path}
                            {\tikz@lib@fold@cut@path}
                        }
                        {\tikz@lib@fold@path}
                        {\tikz@lib@fold@square
                            {\tikz@lib@fold@face@G}
                            {\tikz@lib@fold@ear@path}
                            {\tikz@lib@fold@cut@path}
                            {\tikz@lib@fold@path}
                            {\tikz@lib@fold@ear@path}
                        }
                    }
                    {\tikz@lib@fold@triangle
                        {\tikz@lib@fold@face@H}
                        {\tikz@lib@fold@ear@path}
                        {\tikz@lib@fold@path}
                        {\tikz@lib@fold@cut@path}
                    }
                    {\tikz@lib@fold@path}
                    {\tikz@lib@fold@triangle
                        {\tikz@lib@fold@face@I}
                        {\tikz@lib@fold@cut@path}
                        {\tikz@lib@fold@path}
                        {\tikz@lib@fold@ear@path}
                    }
                }
                {\tikz@lib@fold@square
                    {\tikz@lib@fold@face@J}
                    {\tikz@lib@fold@ear@path}
                    {\tikz@lib@fold@ear@path}
                    {\tikz@lib@fold@path}
                    {\tikz@lib@fold@cut@path}
                }
                {\tikz@lib@fold@path}
                {\tikz@lib@fold@square
                    {\tikz@lib@fold@face@K}
                    {\tikz@lib@fold@ear@path}
                    {\tikz@lib@fold@cut@path}
                    {\tikz@lib@fold@path}
                    {\tikz@lib@fold@ear@path}
                }
            }
            {\tikz@lib@fold@triangle
                {\tikz@lib@fold@face@L}
                {\tikz@lib@fold@ear@path}
                {\tikz@lib@fold@path}
                {\tikz@lib@fold@cut@path}
            }
            {\tikz@lib@fold@path}
            {\tikz@lib@fold@triangle
                {\tikz@lib@fold@face@M}
                {\tikz@lib@fold@cut@path}
                {\tikz@lib@fold@path}
                {\tikz@lib@fold@ear@path}
            }
        }
        {\tikz@lib@fold@square
            {\tikz@lib@fold@face@N}
            {\tikz@lib@fold@square
                {\tikz@lib@fold@face@O}
                {\tikz@lib@fold@cut@path}
                {\tikz@lib@fold@cut@path}
                {\tikz@lib@fold@path}
                {\tikz@lib@fold@cut@path}
            }
            {\tikz@lib@fold@ear@path}
            {\tikz@lib@fold@path}
            {\tikz@lib@fold@cut@path}
        }
        {\tikz@lib@fold@square
            {\tikz@lib@fold@face@P}
            {\tikz@lib@fold@square
                {\tikz@lib@fold@face@Q}
                {\tikz@lib@fold@square
                    {\tikz@lib@fold@face@R}
                    {\tikz@lib@fold@ear@path}
                    {\tikz@lib@fold@triangle
                        {\tikz@lib@fold@face@S}
                        {\tikz@lib@fold@cut@path}
                        {\tikz@lib@fold@path}
                        {\tikz@lib@fold@ear@path}
                    }
                    {\tikz@lib@fold@path}
                    {\tikz@lib@fold@triangle
                        {\tikz@lib@fold@face@T}
                        {\tikz@lib@fold@ear@path}
                        {\tikz@lib@fold@path}
                        {\tikz@lib@fold@cut@path}
                    }
                }
                {\tikz@lib@fold@square
                    {\tikz@lib@fold@face@U}
                    {\tikz@lib@fold@ear@path}
                    {\tikz@lib@fold@cut@path}
                    {\tikz@lib@fold@path}
                    {\tikz@lib@fold@ear@path}
                }
                {\tikz@lib@fold@path}
                {\tikz@lib@fold@square
                    {\tikz@lib@fold@face@V}
                    {\tikz@lib@fold@ear@path}
                    {\tikz@lib@fold@ear@path}
                    {\tikz@lib@fold@path}
                    {\tikz@lib@fold@cut@path}
                }
            }
            {\tikz@lib@fold@triangle
                {\tikz@lib@fold@face@W}
                {\tikz@lib@fold@cut@path}
                {\tikz@lib@fold@path}
                {\tikz@lib@fold@ear@path}
            }
            {\tikz@lib@fold@path}
            {\tikz@lib@fold@triangle
                {\tikz@lib@fold@face@X}
                {\tikz@lib@fold@ear@path}
                {\tikz@lib@fold@path}
                {\tikz@lib@fold@cut@path}
            }
        }
        {\tikz@lib@fold@square
            {\tikz@lib@fold@face@Y}
            {\tikz@lib@fold@square
                {\tikz@lib@fold@face@Z}
                {\tikz@lib@fold@cut@path}
                {\tikz@lib@fold@cut@path}
                {\tikz@lib@fold@path}
                {\tikz@lib@fold@cut@path}
            }
            {\tikz@lib@fold@cut@path}
            {\tikz@lib@fold@path}
            {\tikz@lib@fold@ear@path}
        }
  \endgroup
}

%truncated cuboctahedron

\def\tikzfoldingtruncatedcuboctahedron#1[#2]#3;{%
  \begingroup%
    \tikzset{#2}%
    \tikz@lib@fold@square
        {\tikz@lib@fold@face@A}
        {\tikz@lib@fold@octagon
            {\tikz@lib@fold@face@B}
            {\tikz@lib@fold@square
                {\tikz@lib@fold@face@C}
	       {\tikz@lib@fold@octagon
	           {\tikz@lib@fold@face@D}
	           {\tikz@lib@fold@square
	               {\tikz@lib@fold@face@E}
	               {\tikz@lib@fold@cut@path}
	               {\tikz@lib@fold@hexagon
	                   {\tikz@lib@fold@face@F}
	                   {\tikz@lib@fold@ear@path}
	                   {\tikz@lib@fold@ear@path}
	                   {\tikz@lib@fold@ear@custom@right@path{15}}
	                   {\tikz@lib@fold@path}
	                   {\tikz@lib@fold@ear@path}
	                   {\tikz@lib@fold@ear@path}
	               }
	               {\tikz@lib@fold@path}
	               {\tikz@lib@fold@hexagon
	                   {\tikz@lib@fold@face@G}
	                   {\tikz@lib@fold@ear@path}
	                   {\tikz@lib@fold@ear@path}
	                   {\tikz@lib@fold@ear@path}
	                   {\tikz@lib@fold@path}
	                   {\tikz@lib@fold@ear@custom@left@path{15}}
	                   {\tikz@lib@fold@ear@path}
	               }
	           }
	           {\tikz@lib@fold@cut@path}
	           {\tikz@lib@fold@square
	               {\tikz@lib@fold@face@H}
	               {\tikz@lib@fold@ear@path}
	               {\tikz@lib@fold@cut@path}
	               {\tikz@lib@fold@path}
	               {\tikz@lib@fold@cut@path}
	           }
	           {\tikz@lib@fold@cut@path}
	           {\tikz@lib@fold@path}
	           {\tikz@lib@fold@cut@path}
	           {\tikz@lib@fold@square
	               {\tikz@lib@fold@face@I}
	               {\tikz@lib@fold@ear@path}
	               {\tikz@lib@fold@cut@path}
	               {\tikz@lib@fold@path}
	               {\tikz@lib@fold@cut@path}
	           }
	           {\tikz@lib@fold@cut@path}
	       }
	       {\tikz@lib@fold@hexagon
	           {\tikz@lib@fold@face@J}
	           {\tikz@lib@fold@ear@path}
	           {\tikz@lib@fold@ear@path}
	           {\tikz@lib@fold@ear@custom@right@path{15}}
	           {\tikz@lib@fold@path}
	           {\tikz@lib@fold@ear@custom@left@path{15}}
	           {\tikz@lib@fold@ear@path}
	       }
	       {\tikz@lib@fold@path}
	       {\tikz@lib@fold@hexagon
	           {\tikz@lib@fold@face@K}
	           {\tikz@lib@fold@ear@path}
	           {\tikz@lib@fold@ear@path}
	           {\tikz@lib@fold@ear@custom@right@path{15}}
	           {\tikz@lib@fold@path}
	           {\tikz@lib@fold@ear@custom@left@path{15}}
	           {\tikz@lib@fold@ear@path}
	       }
            }
            {\tikz@lib@fold@cut@path}
            {\tikz@lib@fold@square
                {\tikz@lib@fold@face@L}
	       {\tikz@lib@fold@ear@path}
	       {\tikz@lib@fold@cut@path}
	       {\tikz@lib@fold@path}
	       {\tikz@lib@fold@cut@path}
            }
            {\tikz@lib@fold@cut@path}
            {\tikz@lib@fold@path}
            {\tikz@lib@fold@cut@path}
            {\tikz@lib@fold@square
                {\tikz@lib@fold@face@M}
	       {\tikz@lib@fold@ear@path}
	       {\tikz@lib@fold@cut@path}
	       {\tikz@lib@fold@path}
	       {\tikz@lib@fold@cut@path}
            }
            {\tikz@lib@fold@cut@path}
        }
        {\tikz@lib@fold@hexagon
            {\tikz@lib@fold@face@N}
            {\tikz@lib@fold@ear@path}
            {\tikz@lib@fold@ear@path}
            {\tikz@lib@fold@ear@custom@right@path{15}}
            {\tikz@lib@fold@path}
            {\tikz@lib@fold@ear@custom@left@path{15}}
            {\tikz@lib@fold@ear@path}
        }
        {\tikz@lib@fold@octagon
            {\tikz@lib@fold@face@O}
            {\tikz@lib@fold@square
                {\tikz@lib@fold@face@P}
	       {\tikz@lib@fold@octagon
	           {\tikz@lib@fold@face@Q}
	           {\tikz@lib@fold@ear@path}
	           {\tikz@lib@fold@cut@path}
	           {\tikz@lib@fold@square
	               {\tikz@lib@fold@face@R}
	               {\tikz@lib@fold@ear@path}
	               {\tikz@lib@fold@cut@path}
	               {\tikz@lib@fold@path}
	               {\tikz@lib@fold@cut@path}
	           }
	           {\tikz@lib@fold@cut@path}
	           {\tikz@lib@fold@path}
	           {\tikz@lib@fold@cut@path}
	           {\tikz@lib@fold@square
	               {\tikz@lib@fold@face@S}
	               {\tikz@lib@fold@ear@path}
	               {\tikz@lib@fold@cut@path}
	               {\tikz@lib@fold@path}
	               {\tikz@lib@fold@cut@path}
	           }
	           {\tikz@lib@fold@cut@path}
	       }
	       {\tikz@lib@fold@hexagon
	           {\tikz@lib@fold@face@T}
	           {\tikz@lib@fold@ear@path}
	           {\tikz@lib@fold@ear@path}
	           {\tikz@lib@fold@ear@custom@right@path{15}}
	           {\tikz@lib@fold@path}
	           {\tikz@lib@fold@ear@custom@left@path{15}}
	           {\tikz@lib@fold@ear@path}
	       }
	       {\tikz@lib@fold@path}
	       {\tikz@lib@fold@hexagon
	           {\tikz@lib@fold@face@U}
	           {\tikz@lib@fold@ear@path}
	           {\tikz@lib@fold@ear@path}
	           {\tikz@lib@fold@ear@custom@right@path{15}}
	           {\tikz@lib@fold@path}
	           {\tikz@lib@fold@ear@custom@left@path{15}}
	           {\tikz@lib@fold@ear@path}
	       }
            }
            {\tikz@lib@fold@cut@path}
            {\tikz@lib@fold@square
                {\tikz@lib@fold@face@V}
	       {\tikz@lib@fold@octagon
	           {\tikz@lib@fold@face@W}
	           {\tikz@lib@fold@cut@path}
	           {\tikz@lib@fold@cut@path}
	           {\tikz@lib@fold@cut@path}
	           {\tikz@lib@fold@cut@path}
	           {\tikz@lib@fold@path}
	           {\tikz@lib@fold@cut@path}
	           {\tikz@lib@fold@cut@path}
	           {\tikz@lib@fold@cut@path}
	       }
	       {\tikz@lib@fold@cut@path}
	       {\tikz@lib@fold@path}
	       {\tikz@lib@fold@cut@path}
            }
            {\tikz@lib@fold@cut@path}
            {\tikz@lib@fold@path}
            {\tikz@lib@fold@cut@path}
            {\tikz@lib@fold@square
                {\tikz@lib@fold@face@X}
	       {\tikz@lib@fold@octagon
	           {\tikz@lib@fold@face@Y}
	           {\tikz@lib@fold@cut@path}
	           {\tikz@lib@fold@cut@path}
	           {\tikz@lib@fold@cut@path}
	           {\tikz@lib@fold@cut@path}
	           {\tikz@lib@fold@path}
	           {\tikz@lib@fold@cut@path}
	           {\tikz@lib@fold@cut@path}
	           {\tikz@lib@fold@cut@path}
	       }
	       {\tikz@lib@fold@cut@path}
	       {\tikz@lib@fold@path}
	       {\tikz@lib@fold@cut@path}
            }
            {\tikz@lib@fold@cut@path}
        }
        {\tikz@lib@fold@hexagon
            {\tikz@lib@fold@face@Z}
            {\tikz@lib@fold@ear@path}
            {\tikz@lib@fold@ear@path}
            {\tikz@lib@fold@ear@custom@right@path{15}}
            {\tikz@lib@fold@path}
            {\tikz@lib@fold@ear@custom@left@path{15}}
            {\tikz@lib@fold@ear@path}
        }
  \endgroup
}

%snub cube  

\def\tikzfoldingsnubcube#1[#2]#3;{%
  \begingroup%
    \tikzset{#2}%
    \tikz@lib@fold@square{\tikz@lib@fold@face@A}
    {
        \tikz@lib@fold@triangle{\tikz@lib@fold@face@B}
	    {
	        \tikz@lib@fold@triangle{\tikz@lib@fold@face@C}
	        {
	            \tikz@lib@fold@triangle{\tikz@lib@fold@face@D}
	            {\tikz@lib@fold@ear@path}
	            {\tikz@lib@fold@path}
	            {
	                \tikz@lib@fold@square{\tikz@lib@fold@face@E}
	                {
	                    \tikz@lib@fold@triangle{\tikz@lib@fold@face@F}
	                    {
	                        \tikz@lib@fold@triangle{\tikz@lib@fold@face@G}
	                        {\tikz@lib@fold@ear@path}
	                        {\tikz@lib@fold@path}
	                        {\tikz@lib@fold@ear@path}
	                    }
	                    {\tikz@lib@fold@path}
	                    {
	                        \tikz@lib@fold@triangle{\tikz@lib@fold@face@H}
	                        {\tikz@lib@fold@ear@path}
	                        {\tikz@lib@fold@path}
	                        {\tikz@lib@fold@cut@path}
	                    }
	                }
	                {
	                    \tikz@lib@fold@triangle{\tikz@lib@fold@face@I}
	                    {\tikz@lib@fold@ear@path}
	                    {\tikz@lib@fold@path}
	                    {\tikz@lib@fold@ear@path}
	                }
	                {\tikz@lib@fold@path}
	                {
	                    \tikz@lib@fold@triangle{\tikz@lib@fold@face@J}
	                    {\tikz@lib@fold@cut@path}
	                    {\tikz@lib@fold@path}
	                    {\tikz@lib@fold@cut@path}
	                }
	            }
	        }
	        {\tikz@lib@fold@path}
	        {\tikz@lib@fold@cut@path}
	    }
	    {\tikz@lib@fold@path}
	    {\tikz@lib@fold@cut@path}
    }
    {
        \tikz@lib@fold@triangle{\tikz@lib@fold@face@K}
	    {
	        \tikz@lib@fold@triangle{\tikz@lib@fold@face@L}
	        {
	            \tikz@lib@fold@triangle{\tikz@lib@fold@face@M}
	            {\tikz@lib@fold@ear@path}
	            {\tikz@lib@fold@path}
	            {
	                \tikz@lib@fold@square{\tikz@lib@fold@face@N}
	                {
	                    \tikz@lib@fold@triangle{\tikz@lib@fold@face@O}
	                    {
	                        \tikz@lib@fold@triangle{\tikz@lib@fold@face@P}
	                        {\tikz@lib@fold@ear@path}
	                        {\tikz@lib@fold@path}
	                        {\tikz@lib@fold@ear@path}
	                    }
	                    {\tikz@lib@fold@path}
	                    {
	                        \tikz@lib@fold@triangle{\tikz@lib@fold@face@Q}
	                        {\tikz@lib@fold@ear@path}
	                        {\tikz@lib@fold@path}
	                        {\tikz@lib@fold@cut@path}
	                    }
	                }
	                {
	                    \tikz@lib@fold@triangle{\tikz@lib@fold@face@R}
	                    {\tikz@lib@fold@ear@path}
	                    {\tikz@lib@fold@path}
	                    {\tikz@lib@fold@ear@path}
	                }
	                {\tikz@lib@fold@path}
	                {
	                    \tikz@lib@fold@triangle{\tikz@lib@fold@face@S}
	                    {\tikz@lib@fold@cut@path}
	                    {\tikz@lib@fold@path}
	                    {\tikz@lib@fold@cut@path}
	                }
	            }
	        }
	        {\tikz@lib@fold@path}
	        {\tikz@lib@fold@cut@path}
	    }
	    {\tikz@lib@fold@path}
	    {\tikz@lib@fold@cut@path}
    }
    {
        \tikz@lib@fold@triangle{\tikz@lib@fold@face@T}
	    {
	        \tikz@lib@fold@triangle{\tikz@lib@fold@face@U}
	        {
	            \tikz@lib@fold@triangle{\tikz@lib@fold@face@V}
	            {\tikz@lib@fold@ear@path}
	            {\tikz@lib@fold@path}
	            {
	                \tikz@lib@fold@square{\tikz@lib@fold@face@W}
	                {
	                    \tikz@lib@fold@triangle{\tikz@lib@fold@face@X}
	                    {
	                        \tikz@lib@fold@triangle{\tikz@lib@fold@face@Y}
	                        {\tikz@lib@fold@ear@path}
	                        {\tikz@lib@fold@path}
	                        {\tikz@lib@fold@ear@path}
	                    }
	                    {\tikz@lib@fold@path}
	                    {
	                        \tikz@lib@fold@triangle{\tikz@lib@fold@face@Z}
	                        {\tikz@lib@fold@ear@path}
	                        {\tikz@lib@fold@path}
	                        {\tikz@lib@fold@cut@path}
	                    }
	                }
	                {
	                    \tikz@lib@fold@triangle{\tikz@lib@fold@face@AA}
	                    {\tikz@lib@fold@ear@path}
	                    {\tikz@lib@fold@path}
	                    {\tikz@lib@fold@ear@path}
	                }
	                {\tikz@lib@fold@path}
	                {
	                    \tikz@lib@fold@triangle{\tikz@lib@fold@face@AB}
	                    {\tikz@lib@fold@cut@path}
	                    {\tikz@lib@fold@path}
	                    {\tikz@lib@fold@cut@path}
	                }
	            }
	        }
	        {\tikz@lib@fold@path}
	        {\tikz@lib@fold@cut@path}
	    }
	    {\tikz@lib@fold@path}
	    {\tikz@lib@fold@cut@path}
    }
    {
        \tikz@lib@fold@triangle{\tikz@lib@fold@face@AC}
	    {
	        \tikz@lib@fold@triangle{\tikz@lib@fold@face@AD}
	        {
	            \tikz@lib@fold@triangle{\tikz@lib@fold@face@AE}
	            {\tikz@lib@fold@ear@path}
	            {\tikz@lib@fold@path}
	            {
	                \tikz@lib@fold@square{\tikz@lib@fold@face@AF}
	                {
	                    \tikz@lib@fold@triangle{\tikz@lib@fold@face@AG}
	                    {
	                        \tikz@lib@fold@triangle{\tikz@lib@fold@face@AH}
	                        {\tikz@lib@fold@ear@path}
	                        {\tikz@lib@fold@path}
	                        {\tikz@lib@fold@ear@path}
	                    }
	                    {\tikz@lib@fold@path}
	                    {
	                        \tikz@lib@fold@triangle{\tikz@lib@fold@face@AI}
	                        {
	                            \tikz@lib@fold@square{\tikz@lib@fold@face@AJ}
	                            {\tikz@lib@fold@cut@path}
	                            {\tikz@lib@fold@cut@path}
	                            {\tikz@lib@fold@path}
	                            {\tikz@lib@fold@cut@path}
	                        }
	                        {\tikz@lib@fold@path}
	                        {\tikz@lib@fold@cut@path}
	                    }
	                }
	                {
	                    \tikz@lib@fold@triangle{\tikz@lib@fold@face@AK}
	                    {\tikz@lib@fold@ear@path}
	                    {\tikz@lib@fold@path}
	                    {\tikz@lib@fold@ear@path}
	                }
	                {\tikz@lib@fold@path}
	                {
	                    \tikz@lib@fold@triangle{\tikz@lib@fold@face@AL}
	                    {\tikz@lib@fold@cut@path}
	                    {\tikz@lib@fold@path}
	                    {\tikz@lib@fold@cut@path}
	                }
	            }
	        }
	        {\tikz@lib@fold@path}
	        {\tikz@lib@fold@cut@path}
	    }
	    {\tikz@lib@fold@path}
	    {\tikz@lib@fold@cut@path}
    }
  \endgroup
}

% icosidodecahedron

\def\tikzfoldingicosidodecahedron#1[#2]#3;{%
  \begingroup%
    \tikzset{#2}%
    \tikz@lib@fold@pentagon{\tikz@lib@fold@face@A}
        {
             \tikz@lib@fold@triangle{\tikz@lib@fold@face@B}
             {
                  \tikz@lib@fold@pentagon{\tikz@lib@fold@face@C}
                  {
                      \tikz@lib@fold@triangle{\tikz@lib@fold@face@D}
                      {\tikz@lib@fold@ear@path}
                      {\tikz@lib@fold@path}
                      {\tikz@lib@fold@ear@path}
                  }
                  {\tikz@lib@fold@ear@custom@right@path{24}}
                  {\tikz@lib@fold@path}
                  {\tikz@lib@fold@cut@path}
                  {
                      \tikz@lib@fold@triangle{\tikz@lib@fold@face@E}
                      {\tikz@lib@fold@ear@path}
                      {\tikz@lib@fold@path}
                      {\tikz@lib@fold@cut@path}
                  }
             }
             {\tikz@lib@fold@path}
             {\tikz@lib@fold@cut@path}
         }
        {
             \tikz@lib@fold@triangle{\tikz@lib@fold@face@F}
             {
                  \tikz@lib@fold@pentagon{\tikz@lib@fold@face@G}
                  {\tikz@lib@fold@ear@path}
                  {\tikz@lib@fold@ear@custom@right@path{24}}
                  {\tikz@lib@fold@path}
                  {\tikz@lib@fold@cut@path}
                  {
                      \tikz@lib@fold@triangle{\tikz@lib@fold@face@H}
                      {\tikz@lib@fold@ear@path}
                      {\tikz@lib@fold@path}
                      {
                          \tikz@lib@fold@pentagon{\tikz@lib@fold@face@I}
                          {\tikz@lib@fold@ear@path}
                          {
                              \tikz@lib@fold@triangle{\tikz@lib@fold@face@J}
                              {\tikz@lib@fold@ear@path}
                              {\tikz@lib@fold@path}
                              {\tikz@lib@fold@ear@path}
                          }
                          {\tikz@lib@fold@path}
                          {\tikz@lib@fold@cut@path}
                          {\tikz@lib@fold@cut@path}
                      }
                  }
             }
             {\tikz@lib@fold@path}
             {\tikz@lib@fold@cut@path}
         }
        {
             \tikz@lib@fold@triangle{\tikz@lib@fold@face@K}
             {\tikz@lib@fold@ear@custom@right@path{24}}
             {\tikz@lib@fold@path}
             {\tikz@lib@fold@cut@path}
        }
        {
            \tikz@lib@fold@triangle{\tikz@lib@fold@face@L}
            {
                \tikz@lib@fold@pentagon{\tikz@lib@fold@face@M}
                {
                    \tikz@lib@fold@triangle{\tikz@lib@fold@face@N}
                    {\tikz@lib@fold@ear@path}
                    {\tikz@lib@fold@path}
                    {
                        \tikz@lib@fold@pentagon{\tikz@lib@fold@face@O}
                        {
                            \tikz@lib@fold@triangle{\tikz@lib@fold@face@P}
                            {\tikz@lib@fold@ear@path}
                            {\tikz@lib@fold@path}
                            {\tikz@lib@fold@ear@path}
                        }
                        {\tikz@lib@fold@ear@path}
                        {\tikz@lib@fold@path}
                        {\tikz@lib@fold@cut@path}
                        {\tikz@lib@fold@cut@path}
                    }
                }
                {\tikz@lib@fold@ear@custom@right@path{24}}
                {\tikz@lib@fold@path}
                {\tikz@lib@fold@cut@path}
                {
                    \tikz@lib@fold@triangle{\tikz@lib@fold@face@Q}
                    {\tikz@lib@fold@ear@custom@right@path{24}}
                    {\tikz@lib@fold@path}
                    {\tikz@lib@fold@cut@path}
                }
            }
            {\tikz@lib@fold@path}
            {
                \tikz@lib@fold@pentagon{\tikz@lib@fold@face@R}
                {
                    \tikz@lib@fold@triangle{\tikz@lib@fold@face@S}
                    {
                        \tikz@lib@fold@pentagon{\tikz@lib@fold@face@T}
                        {\tikz@lib@fold@ear@path}
                        {\tikz@lib@fold@ear@custom@right@path{24}}
                        {\tikz@lib@fold@path}
                        {
                            \tikz@lib@fold@triangle{\tikz@lib@fold@face@U}
                            {
                                 \tikz@lib@fold@pentagon{\tikz@lib@fold@face@V}
                                 {\tikz@lib@fold@cut@path}
                                 {\tikz@lib@fold@ear@custom@right@path{24}}
                                 {\tikz@lib@fold@path}
                                 {\tikz@lib@fold@cut@path}
                                 {\tikz@lib@fold@ear@path}
                            }
                            {\tikz@lib@fold@path}
                            {\tikz@lib@fold@cut@path}
                        }
                        {
                            \tikz@lib@fold@triangle{\tikz@lib@fold@face@W}
                            {\tikz@lib@fold@ear@path}
                            {\tikz@lib@fold@path}
                            {\tikz@lib@fold@cut@path}
                        }
                    }
                    {\tikz@lib@fold@path}
                    {\tikz@lib@fold@cut@path}
                }
                {
                    \tikz@lib@fold@triangle{\tikz@lib@fold@face@X}
                    {\tikz@lib@fold@ear@custom@right@path{24}}
                    {\tikz@lib@fold@path}
                    {\tikz@lib@fold@cut@path}
                }
                {\tikz@lib@fold@path}
                {\tikz@lib@fold@cut@path}
                {
                    \tikz@lib@fold@triangle{\tikz@lib@fold@face@Y}
                    {
                        \tikz@lib@fold@pentagon{\tikz@lib@fold@face@Z}
                        {\tikz@lib@fold@ear@path}
                        {\tikz@lib@fold@ear@custom@right@path{24}}
                        {\tikz@lib@fold@path}
                        {\tikz@lib@fold@cut@path}
                        {\tikz@lib@fold@cut@path}
                    }
                    {\tikz@lib@fold@path}
                    {\tikz@lib@fold@cut@path}
                }
            }
        }
        {
             \tikz@lib@fold@triangle{\tikz@lib@fold@face@AA}
             {
                 \tikz@lib@fold@pentagon{\tikz@lib@fold@face@AB}
                 {
                    \tikz@lib@fold@triangle{\tikz@lib@fold@face@AC}
                    {\tikz@lib@fold@ear@path}
                    {\tikz@lib@fold@path}
                    {
                       \tikz@lib@fold@pentagon{\tikz@lib@fold@face@AD}
                       {
                           \tikz@lib@fold@triangle{\tikz@lib@fold@face@AE}
                           {\tikz@lib@fold@cut@path}
                           {\tikz@lib@fold@path}
                           {\tikz@lib@fold@cut@path}
                       }
                       {\tikz@lib@fold@ear@path}
                       {\tikz@lib@fold@path}
                       {\tikz@lib@fold@cut@path}
                       {\tikz@lib@fold@cut@path}
                    }
                 }
                 {\tikz@lib@fold@ear@custom@right@path{24}}
                 {\tikz@lib@fold@path}
                 {\tikz@lib@fold@cut@path}
                 {
                    \tikz@lib@fold@triangle{\tikz@lib@fold@face@AF}
                    {\tikz@lib@fold@ear@custom@right@path{24}}
                    {\tikz@lib@fold@path}
                    {\tikz@lib@fold@cut@path}
                 }
             }
             {\tikz@lib@fold@path}
             {\tikz@lib@fold@cut@path}
        }
  \endgroup
}

tikzlibraryfpu.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.

\usepgflibrary{fpu}

tikzlibrarygraphdrawing.code.tex
% Copyright 2010 by Renée Ahrens, Olof Frahm, Jens Kluttig, Matthias Schulz, Stephan Schuster
% Copyright 2011 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/graphdrawing/tex/tikzlibrarygraphdrawing.code.tex,v 1.20 2013/08/05 18:22:47 tantau Exp $

\usepgflibrary{graphdrawing}

\def\tikz@lib@ensure@gd@loaded{}


% Patch the level and sibling distances so that gd and plain tikz are
% in sync
\tikzset{level distance=1cm, sibling distance=1cm}

% Patch node distance because of its special syntax.

\pgfkeysgetvalue{/graph drawing/node distance/.@cmd}\tikz@lib@gd@node@dist@path
\pgfkeyslet{/graph drawing/node distance/orig/.@cmd}\tikz@lib@gd@node@dist@path

\pgfkeysdef{/graph drawing/node distance}{
  \pgfutil@in@{ and }{#1}%
  \ifpgfutil@in@%
    \tikz@gd@convert@and#1\pgf@stop%
  \else%
    \tikz@gd@convert@and#1 and #1\pgf@stop%
  \fi%
}
\def\tikz@gd@convert@and#1 and #2\pgf@stop{\pgfkeys{/graph drawing/node distance/orig={#1}}}




%
% Setup graph drawing for tikz
% 

\def\tikz@gd@request@callback#1#2{%
  \tikzset{
    execute at begin scope={
      \tikzset{ 
        --/.style={arrows=-},
        -!-/.style={draw=none,fill=none},
      }   
      \pgfgdsetedgecallback{\pgfgdtikzedgecallback}%
      % 
      % Setup for plain syntax
      % 
      \pgfgdaddspecificationhook{\tikz@lib@gd@spec@hook}%
      #1
      \let\tikzgdeventcallback\pgfgdevent%
      \let\tikzgdeventgroupcallback\pgfgdeventgroup%
      \let\tikzgdlatenodeoptionacallback\pgfgdsetlatenodeoption%
    },
    execute at end scope={%
      #2%
    }
  }%
}

\pgfgdsetrequestcallback\tikz@gd@request@callback



\pgfgdappendtoforwardinglist{/tikz/,/tikz/graphs/}

\def\tikz@lib@gd@spec@hook{%
  \tikzset{
    edge macro=\tikz@gd@plain@edge@macro,
    /tikz/at/.style={/graph drawing/desired at={##1}},
    % 
    % Setup for the tree syntax (do this late so that grow options
    % are still valid after a layout has been chosen)
    % 
    /tikz/growth function=\relax,
    /tikz/edge from parent macro=\tikz@gd@edge@from@parent@macro,
    % 
    % Setup for the graphs syntax 
    % 
    /tikz/graphs/new ->/.code n args={4}{\pgfgdedge{##1}{##2}{->}{/tikz,##3}{##4}},
    /tikz/graphs/new <-/.code n args={4}{\pgfgdedge{##1}{##2}{<-}{/tikz,##3}{##4}},
    /tikz/graphs/new --/.code n args={4}{\pgfgdedge{##1}{##2}{--}{/tikz,##3}{##4}},
    /tikz/graphs/new <->/.code n args={4}{\pgfgdedge{##1}{##2}{<->}{/tikz,##3}{##4}},
    /tikz/graphs/new -!-/.code n args={4}{\pgfgdedge{##1}{##2}{-!-}{/tikz,##3}{##4}},
    /tikz/graphs/placement/compute position/.code=,%
  }
}

\pgfgdaddprepareedgehook{
  \tikz@enable@edge@quotes%
  \let\tikz@transform=\pgfutil@empty%
  \let\tikz@options=\pgfutil@empty%
  \let\tikz@tonodes=\pgfutil@empty%
}


\tikzset{
  parent anchor/.forward to=/graph drawing/tail anchor,
  child anchor/.forward to=/graph drawing/head anchor
}

\def\pgfgdtikzedgecallback#1#2#3#4#5#6#7{%
  \draw (#1)
    edge [to path={#7 \tikztonodes},#3,#4,/graph drawing/.cd,#6,/tikz/.cd]
    #5
    (#2);
}

\def\tikz@gd@edge@from@parent@macro#1#2{
  [/utils/exec=\pgfgdedge{\tikzparentnode}{\tikzchildnode}{--}{/tikz,#1}{#2}]
}

\def\tikz@gd@plain@edge@macro#1#2{
  \pgfgdedge{\tikztostart}{\tikztotarget}{--}{/tikz,#1}{#2}
}



% 
% Conversions: Convert coordinates into pairs of values surrounded by
% braces. 
%

\pgfgdset{
  conversions/canvas coordinate/.code={%
    \tikz@scan@one@point\pgf@process#1%
    \pgfmathsetmacro{\tikz@gd@temp@x}{\pgf@x}
    \pgfmathsetmacro{\tikz@gd@temp@y}{\pgf@y}
    \edef\pgfgdresult{pgf.gd.model.Coordinate.new(\tikz@gd@temp@x,\tikz@gd@temp@y)}
  },
  conversions/coordinate/.code={%
    \tikz@scan@one@point\pgf@process#1%
    \pgfmathsetmacro{\tikz@gd@temp@x}{\pgf@x}
    \pgfmathsetmacro{\tikz@gd@temp@y}{\pgf@y}
    \edef\pgfgdresult{pgf.gd.model.Coordinate.new(\tikz@gd@temp@x,\tikz@gd@temp@y)}
  }
}



%
% Overwrite node callback
%

\def\pgfgdcallbackcreatevertex#1#2#3#4{%
  \node[every generated node/.try,name={#1},shape={#2},/graph drawing/.cd,#3]{#4};%
}


% 
% Subgraph handling 
%

% "General" text placement for subgraph nodes that works with all node
% kinds.

\tikzset{
  subgraph text top/.code=\tikz@lg@simple@contents@top{#1},%
  subgraph text top/.default=text ragged,
  subgraph text bottom/.code=\tikz@lg@simple@contents@bottom{#1},%
  subgraph text bottom/.default=text ragged,
  subgraph text sep/.initial=.1em,
  subgraph text none/.code={
    \def\pgfgdsubgraphnodecontents##1{%
      \pgf@y=\pgfkeysvalueof{/graph drawing/subgraph bounding box height}\relax%
      \hbox to \pgfkeysvalueof{/graph drawing/subgraph bounding box width}{%
        \vrule width0pt height.5\pgf@y depth.5\pgf@y\hfil}%
    }%
  },
}

\def\tikz@lg@simple@contents@top#1{%
  \def\pgfgdsubgraphnodecontents##1{%
    \vbox{%
      \def\pgf@temp{##1}%
      \ifx\pgf@temp\pgfutil@empty%
      \else%
        \ifx\pgf@temp\pgfutil@sptoken%
        \else%
            \hbox to \pgfkeysvalueof{/graph drawing/subgraph bounding box width}{%
              \hsize=\pgfkeysvalueof{/graph drawing/subgraph bounding box width}\relax%
              \vbox{\noindent\strut\tikzset{#1}\tikz@text@action\pgf@temp}%
            }%
        \fi%
      \fi%
      \pgfmathparse{\pgfkeysvalueof{/tikz/subgraph text sep}}%
      \kern\pgfmathresult pt\relax%  
      \pgf@y=\pgfkeysvalueof{/graph drawing/subgraph bounding box height}\relax%
      \hbox to \pgfkeysvalueof{/graph drawing/subgraph bounding box width}{%
      \vrule width0pt height.5\pgf@y depth.5\pgf@y\hfil}%
    }%
  }%
}

\def\tikz@lg@simple@contents@bottom#1{%
  \def\pgfgdsubgraphnodecontents##1{%
    {%
      \pgf@y=\pgfkeysvalueof{/graph drawing/subgraph bounding box height}\relax%
      \setbox0=\vbox{%
        \hbox to \pgfkeysvalueof{/graph drawing/subgraph bounding box width}{\vrule width0pt height\pgf@y\hfil}%
        \pgfmathparse{\pgfkeysvalueof{/tikz/subgraph text sep}}%
        \kern\pgfmathresult pt\relax%  
        \def\pgf@temp{##1}%
        \ifx\pgf@temp\pgfutil@empty%
        \else%
          \ifx\pgf@temp\pgfutil@sptoken%
          \else%
            \hbox to \pgfkeysvalueof{/graph drawing/subgraph bounding box width}{%
              \hsize=\pgfkeysvalueof{/graph drawing/subgraph bounding box width}\relax%
              \vbox{\noindent\strut\tikzset{#1}\tikz@text@action\pgf@temp}%
            }%
          \fi%
        \fi%
      }%
      \pgf@ya=\ht0\relax%
      \advance\pgf@ya by-.5\pgf@y\relax%
      \ht0=.5\pgf@y\relax%
      \dp0=\pgf@ya\relax%
      \box0\relax%
    }%
  }%
}

\tikzset{subgraph text top}

\tikzset{
  subgraph nodes/.style={/tikz/every subgraph node/.style={#1}},
  graphs/subgraph nodes/.style={/tikz/every subgraph node/.style={#1}},
  graphs/@graph drawing setup/.style={/graph drawing/anchor at={(\tikz@lastx,\tikz@lasty)}}
}



\endinput

tikzlibrarygraphs.code.tex
% Copyright 2010 by Till Tantau
% Copyright 2011 by Jannis Pohlmann
%
% 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/graphs/tikzlibrarygraphs.code.tex,v 1.43 2013/10/10 09:08:58 tantau Exp $


% 
% Interface keys 
%

\def\tikzgraphsset{\pgfqkeys{/tikz/graphs}}

\tikzgraphsset{
  new ->/.code n args={4}{%
    \path [->,every new ->/.try]
      (#1\tikzgraphleftanchor)
      edge[#3] #4
      (#2\tikzgraphrightanchor);},
  new --/.code n args={4}{
      \path [-,every new --/.try]
      (#1\tikzgraphleftanchor)
      edge[#3] #4
      (#2\tikzgraphrightanchor);},
  new <->/.code n args={4}{
    \path [<->,every new <->/.try]
      (#1\tikzgraphleftanchor)
      edge[#3] #4
      (#2\tikzgraphrightanchor);},
  new -!-/.code n args={4}{},
  new <-/.code n args={4}{%
    \path [<-,every new <-/.try]
      (#1\tikzgraphleftanchor)
      edge[#3] #4
      (#2\tikzgraphrightanchor);
  }
}


\def\tikz@lib@graph@store@anchor#1#2{%
  \def\tikz@temp{#1}
  \ifx\tikz@temp\pgfutil@empty%
    \let#2\tikz@temp%
  \else%
    \def\tikz@temp{.#1}
    \let#2\tikz@temp%
  \fi%    
}

\tikzgraphsset{
  default edge kind/.initial=--,
  --/.style={default edge kind=--},
  ->/.style={default edge kind=->},
  <-/.style={default edge kind=<-},
  <->/.style={default edge kind=<->},
  -!-/.style={default edge kind=-!-},
  default edge operator/.initial=matching and star,
  left anchor/.code=\tikz@lib@graph@store@anchor{#1}{\tikzgraphleftanchor},
  right anchor/.code=\tikz@lib@graph@store@anchor{#1}{\tikzgraphrightanchor},
  left anchor=,
  right anchor=
}


%
% Keys for using nodes declared outside a graph inside a graph as if
% it were declared there
% 

\tikzgraphsset{
  use existing nodes/.is if=tikz@lib@graph@all
}

\tikzset{
  new set/.code={
    \expandafter\global\expandafter\let\csname tikz@lg@node@set #1\endcsname\pgfutil@empty%
  },
  set/.code={
    \tikz@fig@mustbenamed%
    \expandafter\def\expandafter\tikz@alias\expandafter{\tikz@alias%
      \expandafter\def\expandafter\pgf@temp\expandafter{\csname tikz@lg@node@set #1\endcsname}%
      \expandafter\expandafter\expandafter\pgfutil@g@addto@macro\expandafter\pgf@temp\expandafter{\expandafter\tikz@lg@do\expandafter{\tikz@fig@name}}%
    }%
  },%
}

\newif\iftikz@lib@graph@all


% 
% Simple versus multi graphs 
%
\tikzgraphsset{
  simple/.code={
    \iftikz@lib@graph@simple%
      % is already simple, ignore
    \else
      \tikz@lib@graph@simpletrue%
      \pgfkeysalso{operator=\tikz@lib@graph@simple@done}%
    \fi%
  },
  multi/.code={
    \tikz@lib@graph@simplefalse%
  }
}

\newif\iftikz@lib@graph@simple

\def\tikz@lib@graph@set@simple@edge#1#2#3#4#5{%
  % #1 = kind (<-, ->, ...)
  % #2 = from
  % #3 = to
  % #4 = options
  % #5 = edge nodes
  % 
  % Ok, first, test, whether edge exists:
  \ifcsname tikz@lg@e@#3@#2\endcsname%
    \expandafter\global\expandafter\let\csname tikz@lg@e@#3@#2\endcsname\relax% reset
  \fi%
  \expandafter\gdef\csname tikz@lg@e@#2@#3\endcsname{\tikz@lib@graph@make@simple@edge{#1}{#2}{#3}{#4}{#5}}%
}

\def\tikz@lib@graph@make@simple@edge#1#2#3#4#5{%
  \pgfqkeys{/tikz/graphs}{new #1={#2}{#3}{#4}{#5}}%
}


\def\tikz@lib@graph@simple@done{%
  \tikz@lib@graph@pack@node@list%
  {%
    \let\tikz@lg@do\tikz@lib@graph@simple@node%
    \tikz@lib@graph@node@list
  }%
}

\def\tikz@lib@graph@simple@node#1{%
  {%
    \def\tikz@lib@graph@simple@from@node{#1}%
    \let\tikz@lg@do\tikz@lib@graph@simple@other@node%
    \tikz@lib@graph@node@list%
  }%    
}

\def\tikz@lib@graph@simple@other@node#1{%
  \ifcsname tikz@lg@e@\tikz@lib@graph@simple@from@node @#1\endcsname%
    \csname tikz@lg@e@\tikz@lib@graph@simple@from@node @#1\endcsname%
    \expandafter\global\expandafter\let\csname tikz@lg@e@\tikz@lib@graph@simple@from@node @#1\endcsname\relax%
  \fi%
}


% 
% Basic options 
%

\tikzgraphsset{
  @nodes styling/.style=,
  nodes/.style={/tikz/graphs/@nodes styling/.append style={,#1}},
  @edges styling/.initial=,
  edges/.style={/tikz/graphs/@edges styling/.append={,#1}},
  edge/.style={edges={#1}},
  @edges node/.initial=,
  edge node/.style={/tikz/graphs/@edges node/.append={#1}},
  edge label/.style={/tikz/graphs/@edges node/.append={node[auto]{#1}}},
  edge label'/.style={/tikz/graphs/@edges node/.append={node[auto,swap]{#1}}},
  @operators/.initial=,
  operator/.style={/tikz/graphs/@operators/.append={#1}},
  @extra group options/.style=,
}


\def\tikzgraphinvokeoperator#1{%
  {%
    \pgfkeyslet{/tikz/graphs/@operators}\pgfutil@empty%
    \pgfkeys{/tikz/graphs/.cd,#1}%
    \pgfkeysgetvalue{/tikz/graphs/@operators}\tikz@lib@graph@temp%
    \global\let\tikz@lib@graph@temp\tikz@lib@graph@temp%
  }%
  \tikz@lib@graph@temp%
  \global\let\tikz@lib@graph@temp\relax%
}


% 
% The parser 
%

\def\tikz@lib@graph@parser{%
  \pgfutil@ifnextchar[{\tikz@lib@graph@parser@}{\tikz@lib@graph@parser@[]}%]
}

\def\tikz@lib@graph@parser@[#1]{%
  \setbox\tikz@whichbox=\hbox\bgroup%
    \unhbox\tikz@whichbox%
    \hbox\bgroup
      \bgroup%
        \pgfinterruptpath%
          \scope[graphs/.cd,@graph drawing setup/.try,@operators=,every graph/.try,#1]%
            \begingroup%
            \iftikz@graph@quick%
              \expandafter\tikz@lib@graphs@parse@quick@graph%
            \else%
              \expandafter\tikz@lib@graphs@normal@main%
            \fi%
}

\long\def\tikz@lib@graphs@normal@main#1{%
              \pgfkeysgetvalue{/tikz/graphs/@operators}\tikz@lib@graph@outer@operators%
              \let\tikz@lib@graph@options\pgfutil@empty%
              \let\tikz@lib@graph@node@list\pgfutil@empty%
              \pgfkeyssetvalue{/tikz/graphs/placement/depth}{0}%
              \pgfkeyssetvalue{/tikz/graphs/placement/width}{0}%
              \pgfkeyssetvalue{/tikz/graphs/placement/level}{0}%
              \tikz@lib@graph@start@hint@group%
                \tikz@lib@graph@parse@group{#1}%
              \tikz@lib@graph@end@hint@group
              \tikz@lib@graph@outer@operators%  
              \let\tikz@lg@do=\tikz@lib@graph@cleanup%
              \tikz@lib@graph@node@list%
              \tikz@lib@graph@main@done%
}

\def\tikz@lib@graph@main@done{%
            \endgroup%
          \endscope%
        \endpgfinterruptpath%
      \egroup
    \egroup%
  \egroup%
  \tikz@lib@graph@parser@done%
}





\def\tikz@lib@graph@start@hint@group{%
  \pgfkeyssetvalue{/tikz/graphs/placement/local depth}{0}%
  \pgfkeyssetvalue{/tikz/graphs/placement/local width}{0}%
  \pgfkeyssetvalue{/tikz/graphs/placement/chain count}{0}%
  \pgfkeyssetvalue{/tikz/graphs/placement/element count}{0}%
}

\def\tikz@lib@graph@end@hint@group{%
  % Get local depth and width outside
  \xdef\tikz@lib@graph@group@depth{\pgfkeysvalueof{/tikz/graphs/placement/local depth}}
  \xdef\tikz@lib@graph@group@width{\pgfkeysvalueof{/tikz/graphs/placement/local width}}
}

\def\tikz@lib@graph@hint@aftergroup{%
  \pgfkeysgetvalue{/tikz/graphs/placement/width}\tikz@temp@h%
  \pgfkeysgetvalue{/tikz/graphs/placement/local width}\tikz@temp@lh%
  \pgfkeysgetvalue{/tikz/graphs/placement/local depth}\tikz@temp@lw%
  \pgfmathsetmacro\tikz@temp@h{\tikz@lib@graph@group@width+\tikz@temp@h}
  \pgfmathsetmacro\tikz@temp@lh{\tikz@lib@graph@group@width+\tikz@temp@lh}
  \pgfmathsetmacro\tikz@temp@lw{max(\tikz@lib@graph@group@depth,\tikz@temp@lw)}
  \pgfkeyslet{/tikz/graphs/placement/width}\tikz@temp@h%
  \pgfkeyslet{/tikz/graphs/placement/local width}\tikz@temp@lh%
  \pgfkeyslet{/tikz/graphs/placement/local depth}\tikz@temp@lw%
  % 
  \pgfkeysgetvalue{/tikz/graphs/placement/element count}\tikz@temp%
  \c@pgf@counta=\tikz@temp\relax%
  \advance\c@pgf@counta by1\relax%
  \edef\tikz@temp{\the\c@pgf@counta}%
  \pgfkeyslet{/tikz/graphs/placement/element count}\tikz@temp%  
}

\def\tikz@lib@graph@placement@update{%
  \pgfkeys{/tikz/graphs/placement/logical node depth/.expand once=\tikz@lib@graph@name}
  \let\tikz@lib@graph@node@depth\pgfmathresult
  \pgfkeys{/tikz/graphs/placement/logical node width/.expand once=\tikz@lib@graph@name}
  \let\tikz@lib@graph@node@width\pgfmathresult
  % This is a single node, so update the lengths accordingly
  \pgfkeysgetvalue{/tikz/graphs/placement/width}\tikz@temp@h%
  \pgfkeysgetvalue{/tikz/graphs/placement/local width}\tikz@temp@lh%
  \pgfkeysgetvalue{/tikz/graphs/placement/local depth}\tikz@temp@lw%
  \pgfmathsetmacro\tikz@temp@h{\tikz@lib@graph@node@width+\tikz@temp@h}
  \pgfmathsetmacro\tikz@temp@lh{\tikz@lib@graph@node@width+\tikz@temp@lh}
  \pgfmathsetmacro\tikz@temp@lw{max(\tikz@lib@graph@node@depth,\tikz@temp@lw)}
  \pgfkeyslet{/tikz/graphs/placement/width}\tikz@temp@h%
  \pgfkeyslet{/tikz/graphs/placement/local width}\tikz@temp@lh%
  \pgfkeyslet{/tikz/graphs/placement/local depth}\tikz@temp@lw%
  % 
  \pgfkeysgetvalue{/tikz/graphs/placement/element count}\tikz@temp%
  \c@pgf@counta=\tikz@temp\relax%
  \advance\c@pgf@counta by1\relax%
  \edef\tikz@temp{\the\c@pgf@counta}%
  \pgfkeyslet{/tikz/graphs/placement/element count}\tikz@temp%  
}

\def\tikz@lib@graph@placement@after@chain@update{%
  \pgfkeysgetvalue{/tikz/graphs/placement/depth}\tikz@temp@w%
  \pgfkeysgetvalue{/tikz/graphs/placement/local width}\tikz@temp@lh%
  \pgfkeysgetvalue{/tikz/graphs/placement/local depth}\tikz@temp@lw%
  \pgfmathsetmacro\tikz@temp@w{\tikz@lib@graph@chain@depth+\tikz@temp@w}%
  \pgfmathsetmacro\tikz@temp@lw{\tikz@lib@graph@chain@depth+\tikz@temp@lw}%
  \pgfmathsetmacro\tikz@temp@lh{max(\tikz@lib@graph@chain@width,\tikz@temp@lh)}%
  \pgfkeyslet{/tikz/graphs/placement/depth}\tikz@temp@w%
  \pgfkeyslet{/tikz/graphs/placement/local width}\tikz@temp@lh%
  \pgfkeyslet{/tikz/graphs/placement/local depth}\tikz@temp@lw%
  % 
  \pgfkeysgetvalue{/tikz/graphs/placement/chain count}\tikz@temp%
  \c@pgf@counta=\tikz@temp\relax%
  \advance\c@pgf@counta by1\relax%
  \edef\tikz@temp{\the\c@pgf@counta}%
  \pgfkeyslet{/tikz/graphs/placement/chain count}\tikz@temp%  
}


%
% Parse a group
% 

\long\def\tikz@lib@graph@parse@group#1{
  \let\tikz@lib@graph@group@qa\pgfutil@empty%
  \let\tikz@lib@graph@group@q\pgfutil@empty%
  \let\tikz@lib@graph@group@c\pgfutil@empty%
  \let\tikz@lib@graph@group@cont\pgfutil@empty%
  \let\tikz@lib@graph@group@conta\pgfutil@empty%
  \tikz@lib@graph@group@check#1\par\pgf@stop@eogroup%
}



% 
% Start of a group 
%
\def\tikz@lib@graph@group@check{%
  \pgfutil@ifnextchar[\tikz@lib@graph@group@opt{\tikz@lib@graph@group@opt[]}%]
}

\def\tikz@lib@graph@group@opt[#1]{%
  \let\tikz@lib@graph@parse@extras\pgfutil@empty%
  \tikzgraphsset{
    @operators=,
    every group/.try,
    @extra group options,
    @extra group options/.style=,%
    #1}%
  \expandafter\tikz@lib@graph@par\tikz@lib@graph@parse@extras%
}

\tikzgraphsset{
  parse/.code={\expandafter\def\expandafter\tikz@lib@graph@parse@extras\expandafter{\tikz@lib@graph@parse@extras#1}},
}



% 
% Remove \par 
%

\def\tikz@lib@graph@par{%
  \pgfutil@ifnextchar\bgroup{\tikz@lib@graph@par@@}{\tikz@lib@graph@par@}%
}
\long\def\tikz@lib@graph@par@#1\par{%
  \pgfutil@ifnextchar\pgf@stop@eogroup{%
    \expandafter\tikz@lib@graph@quotes\tikz@lib@graph@group@c#1"}{%
    \expandafter\def\expandafter\tikz@lib@graph@group@c\expandafter{\tikz@lib@graph@group@c#1}%
    \tikz@lib@graph@par%
  }%
}
\long\def\tikz@lib@graph@par@@#1{%
  \expandafter\def\expandafter\tikz@lib@graph@group@c\expandafter{\tikz@lib@graph@group@c{#1}}%
  \tikz@lib@graph@par
}



% 
% Replace ..."..."... by ..."{...}"...
% 
\def\tikz@lib@graph@quotes{%
  \pgfutil@ifnextchar\bgroup{\tikz@lib@graph@quotes@@}{\tikz@lib@graph@quotes@}%
}%
\def\tikz@lib@graph@quotes@#1"{%
  \pgfutil@ifnextchar\pgf@stop@eogroup{%
    \tikz@lib@graph@passon{#1}%
  }{%
    \expandafter\def\expandafter\tikz@lib@graph@group@q\expandafter{\tikz@lib@graph@group@q#1"}%
    \tikz@lib@graph@quotes@cont%
  }%
}

\def\tikz@lib@graph@quotes@cont#1"#2"{%
  \pgfutil@ifnextchar\pgf@stop@eogroup{%
    \tikz@lib@graph@passon{{#1}"#2}}{%
    \expandafter\def\expandafter\tikz@lib@graph@group@q\expandafter{\tikz@lib@graph@group@q{#1}"#2"}%
    \tikz@lib@graph@quotes@cont}%
}

\def\tikz@lib@graph@quotes@@#1{%
  \expandafter\def\expandafter\tikz@lib@graph@group@q\expandafter{\tikz@lib@graph@group@q{#1}}%
  \tikz@lib@graph@quotes%
}



% 
% Replace ..."..."... by ..."{...}"... (active version)
%
{
  \catcode`\"=13\relax

  \gdef\tikz@lib@graph@passon#1{\expandafter\tikz@lib@graph@quotesactive\tikz@lib@graph@group@q#1"}%
  
  \gdef\tikz@lib@graph@quotesactive{%
    \pgfutil@ifnextchar\bgroup{\tikz@lib@graph@quotesactive@@}{\tikz@lib@graph@quotesactive@}%
  }%
  \gdef\tikz@lib@graph@quotesactive@#1"{%
    \pgfutil@ifnextchar\pgf@stop@eogroup{%
      \expandafter\tikz@lib@graph@encloser\tikz@lib@graph@group@qa#1[%
    }{%
      \expandafter\def\expandafter\tikz@lib@graph@group@qa\expandafter{\tikz@lib@graph@group@qa#1"}%
      \tikz@lib@graph@quotesactive@cont%
    }%
  }
  
  \gdef\tikz@lib@graph@quotesactive@cont#1"#2"{%
    \pgfutil@ifnextchar\pgf@stop@eogroup{%
      \expandafter\tikz@lib@graph@encloser\tikz@lib@graph@group@qa{#1}"#2[}{%
      \expandafter\def\expandafter\tikz@lib@graph@group@qa\expandafter{\tikz@lib@graph@group@qa{#1}"#2"}%
      \tikz@lib@graph@quotesactive@cont}%
  }
  
  \gdef\tikz@lib@graph@quotesactive@@#1{%
    \expandafter\def\expandafter\tikz@lib@graph@group@qa\expandafter{\tikz@lib@graph@group@qa{#1}}%
    \tikz@lib@graph@quotesactive%
  }
}




% 
% Replace ...[...]... by ...[{...}]...
% 
\def\tikz@lib@graph@encloser{%
  \pgfutil@ifnextchar\bgroup{\tikz@lib@graph@encloser@@}{\tikz@lib@graph@encloser@}%
}%
\def\tikz@lib@graph@encloser@#1[{%
  \pgfutil@ifnextchar\pgf@stop@eogroup{%
    \expandafter\tikz@lib@graph@semi\tikz@lib@graph@group@cont#1;%
  }{%
    \expandafter\def\expandafter\tikz@lib@graph@group@cont\expandafter{\tikz@lib@graph@group@cont#1[}%]
    \tikz@lib@graph@encloser@cont%
  }%
}

\def\tikz@lib@graph@encloser@cont#1]#2[{%
  \pgfutil@ifnextchar\pgf@stop@eogroup{%
    \expandafter\tikz@lib@graph@semi\tikz@lib@graph@group@cont{#1}]#2;}{%
    \expandafter\def\expandafter\tikz@lib@graph@group@cont\expandafter{\tikz@lib@graph@group@cont{#1}]#2[}%
    \tikz@lib@graph@encloser@cont}%
}

\def\tikz@lib@graph@encloser@@#1{%
  \expandafter\def\expandafter\tikz@lib@graph@group@cont\expandafter{\tikz@lib@graph@group@cont{#1}}%
  \tikz@lib@graph@encloser%
}




% 
% Replace ; by , 
%

\def\tikz@lib@graph@semi{%
  \pgfutil@ifnextchar\bgroup{\tikz@lib@graph@semi@@}{\tikz@lib@graph@semi@}%
}
\def\tikz@lib@graph@semi@#1;{%
  \pgfutil@ifnextchar\pgf@stop@eogroup{%
    \expandafter\tikz@lib@graph@main@parser\tikz@lib@graph@group@conta#1,}{%
    \expandafter\def\expandafter\tikz@lib@graph@group@conta\expandafter{\tikz@lib@graph@group@conta#1,}%
    \tikz@lib@graph@semi%
  }%
}
\def\tikz@lib@graph@semi@@#1{%
  \expandafter\def\expandafter\tikz@lib@graph@group@conta\expandafter{\tikz@lib@graph@group@conta{#1}}%
  \tikz@lib@graph@semi%
}


% 
% Main parse 
%

\def\tikz@lib@graph@main@parser{%
  \begingroup%
    \pgfkeyssetvalue{/tikz/graphs/placement/local depth}{0}%
    \pgfkeyssetvalue{/tikz/graphs/placement/local width}{0}%
    \let\tikz@lib@graph@stored@actions\pgfutil@empty%
    \let\tikz@lib@graph@node@list\pgfutil@empty% reset
    \tikz@lib@graph@main@parser@start%
}
\def\tikz@lib@graph@main@parser@start{%
  \pgfutil@ifnextchar\bgroup{\tikz@lib@graph@protect@group}{\tikz@lib@graph@main@parser@cont}%
}

\def\tikz@lib@graph@protect@group#1{% skip space
  \pgfutil@ifnextchar\relax{\tikz@lib@graph@main@parser@cont{{#1}}}{\tikz@lib@graph@main@parser@cont{{#1}}}%
}

\def\tikz@lib@graph@main@parser@cont{\tikz@lib@graph@check@quotes\tikz@lib@graph@main@parser@cont@normal}
\def\tikz@lib@graph@main@parser@cont@normal#1,{%
  \tikz@lib@graph@parse@one#1-\pgf@stop@eodashes%
}

\def\tikz@lib@graph@parse@one{%
  \pgfutil@ifnextchar\bgroup\tikz@lib@graph@scope\tikz@lib@graph@node%
}



% Special quoted nodes

\def\tikz@lib@graph@check@quotes#1{%
  \let\tikz@lib@graph@cont@quote#1%
  \pgfutil@ifnextchar"{\begingroup\pgfkeys@temptoks{}\pgfutil@empty\tikz@lib@graph@quote@parser}{\tikz@lib@graph@check@quotes@active}%
}
{
  \catcode`\"=13\relax
  \gdef\tikz@lib@graph@check@quotes@active{%
    \pgfutil@ifnextchar"{\begingroup\pgfkeys@temptoks{}\pgfutil@empty\tikz@lib@graph@quote@parser@active}{\tikz@lib@graph@cont@quote}%
  }
  \gdef\tikz@lib@graph@quote@parser@active"#1"{%
    \pgfkeys@temptoks\expandafter{\the\pgfkeys@temptoks #1}%
    \pgfutil@ifnextchar"{\pgfkeys@temptoks\expandafter{\the\pgfkeys@temptoks "}\tikz@lib@graph@quote@parser@active}{\tikz@lib@graph@quote@parser@done}%
  }
}

\def\tikz@lib@graph@quote@parser"#1"{%
  \pgfkeys@temptoks\expandafter{\the\pgfkeys@temptoks #1}%
  \pgfutil@ifnextchar"{\pgfkeys@temptoks\expandafter{\the\pgfkeys@temptoks "}\tikz@lib@graph@quote@parser}{\tikz@lib@graph@quote@parser@done}%
}

\def\tikz@lib@graph@quote@parser@done{%
  {\expandafter\scantokens\expandafter{%
    \expandafter\expandafter\expandafter\tikzlibgraphactivations\expandafter\expandafter\expandafter\tikzlibgraphdoedef\expandafter{\the\pgfkeys@temptoks}%
  }}%
  {\expandafter\scantokens\expandafter{\expandafter\tikzlibgraphactivationsbrace\expandafter\xdef\expandafter\tikzlibgraphreplaced\expandafter<\tikzlibgraphreplaced>\catcode`\}=2\relax}}% 
  \edef\tikzlibgraphreplaced{\expandafter\detokenize\expandafter{\tikzlibgraphreplaced}}
  \pgfutil@ifnextchar/\tikz@lib@graph@quotes@slash\tikz@lib@graph@quotes@no@slash%
}
\def\tikz@lib@graph@quotes@no@slash{%
  \expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter%
  \tikz@smuggle\expandafter\expandafter\expandafter{\expandafter\tikzlibgraphreplaced\expandafter/\expandafter{\the\pgfkeys@temptoks}}%
  \expandafter\endgroup\expandafter\tikz@lib@graph@cont@quote\tikz@smuggle%
}
\def\tikz@lib@graph@quotes@slash/{%
  \pgfutil@ifnextchar/% Ah, double slash...
  {\tikz@lib@graph@quotes@no@slash/}{\expandafter\endgroup\expandafter\tikz@lib@graph@cont@quote\tikzlibgraphreplaced/}%
}
\def\tikzlibgraphdoedef{\xdef\tikzlibgraphreplaced}

\def\tikz@lib@prepare@active#1#2#3{%
  {%
    \catcode`#1=13\relax%
    \scantokens{\gdef\tikzlibgraphactivator{\def#2{@#3@}}}%
  }
  \pgfutil@g@addto@macro\tikzlibgraphactivations{\catcode`#1=13\relax}  
  \expandafter\pgfutil@g@addto@macro\expandafter\tikzlibgraphactivations\expandafter{\tikzlibgraphactivator}
}

\let\tikzlibgraphactivations\pgfutil@empty

%
% Remove \outer from \+ for plain TeX
%

\outer\def\tikz@lib@outer@test{\tabalign}
\ifx\+\tikz@lib@outer@test
  \def\+{\tabalign}
\fi

\tikz@lib@prepare@active{\$}{$}{DOLLAR SIGN}% $
\tikz@lib@prepare@active{\&}{&}{AMPERSAND}%
\tikz@lib@prepare@active{\^}{^}{CIRCUMFLEX ACCENT}%
\tikz@lib@prepare@active{\~}{~}{TILDE}%
\tikz@lib@prepare@active{\_}{_}{LOW LINE}%
\tikz@lib@prepare@active{\|}{|}{VERTICAL LINE}%
\tikz@lib@prepare@active{\[}{[}{LEFT SQUARE BRACKET}%
\tikz@lib@prepare@active{\]}{]}{RIGHT SQUARE BRACKET}%
\tikz@lib@prepare@active{\(}{(}{LEFT PARENTHESIS}%
\tikz@lib@prepare@active{\)}{)}{RIGHT PARENTHESIS}%
\tikz@lib@prepare@active{\/}{/}{SOLIDUS}%
\tikz@lib@prepare@active{\.}{.}{FULL STOP}%
\tikz@lib@prepare@active{\-}{-}{HYPHEN MINUS}%
\tikz@lib@prepare@active{\,}{,}{COMMA}%
\tikz@lib@prepare@active{\+}{+}{PLUS SIGN}%
\tikz@lib@prepare@active{\*}{*}{ASTERISK}%
\tikz@lib@prepare@active{\'}{'}{APOSTROPHE}%
\tikz@lib@prepare@active{\!}{!}{EXCLAMATION MARK}%
\tikz@lib@prepare@active{\"}{"}{QUOTATION MARK}%
\tikz@lib@prepare@active{\:}{:}{COLON}%
\tikz@lib@prepare@active{\;}{;}{SEMINCOLON}%
\tikz@lib@prepare@active{\<}{<}{LESS THAN SIGN}%
\tikz@lib@prepare@active{\=}{=}{EQUALS SIGN}%
\tikz@lib@prepare@active{\>}{>}{GREATER THAN SIGN}%
\tikz@lib@prepare@active{\?}{?}{QUESTION MARK}%
%\tikz@lib@prepare@active{\@}{@}{COMMERCIAL AT}%
\tikz@lib@prepare@active{\`}{`}{GRAVE ACCENT}%
{\catcode`\%=11\catcode`\#=11
\tikz@lib@prepare@active{\%}{%}{PERCENT SIGN}
\tikz@lib@prepare@active{\#}{#}{NUMBER SIGN}
}

\pgfutil@g@addto@macro\tikzlibgraphactivations{\catcode`\\=13\relax}
{
  \catcode`\|=0\relax
  \catcode`\\=13\relax
  |pgfutil@g@addto@macro|tikzlibgraphactivations{|def\{@REVERSE SOLIDUS@}}
}
{
  \gdef\tikzlibgraphscommercialat{@COMMERCIAL AT@}
  \let\g=\pgfutil@g@addto@macro  
  \catcode`\@=13\relax
  \g\tikzlibgraphactivations{\catcode`\@=13\relax\let@=\tikzlibgraphscommercialat}
}

\def\tikzlibgraphactivationsbrace{%
  \catcode`\{=13\relax%
  \catcode`\}=13\relax%
  \catcode`\<=1\relax%
  \catcode`\>=2\relax%
}
{
  \catcode`\{=13\relax%
  \catcode`\}=13\relax%
  \catcode`\<=1\relax%
  \catcode`\>=2\relax%
  \pgfutil@g@addto@macro\tikzlibgraphactivationsbrace<\def{<@LEFT CURLY BRACE@>> %}
  \pgfutil@g@addto@macro\tikzlibgraphactivationsbrace<\def}<@RIGHT CURLY BRACE@>> %{
>

% A normal node

% First, check for special quote syntax:

\def\tikz@lib@graph@node{\tikz@lib@graph@check@quotes\tikz@lib@graph@node@normal}

\def\tikz@lib@graph@node@normal#1-{%
  % Detect trailing <
  \tikz@lib@graph@@node#1<\pgf@stop%
}

\def\tikz@lib@graph@@node#1<#2\pgf@stop%
{
  % 
  % #1 will be a node (not a group)
  % 
  % Syntax: node name [options]
  % 
  % Grab node name
  \tikz@lib@graph@grab@name#1\pgf@stop%
  \tikz@lib@graph@stored@actions%
  \pgfutil@ifnextchar\pgf@stop@eodashes{%
    \tikz@lib@graph@graph@done%
  }{%
    % 
    % Now, get arrow kind 
    % 
    \def\pgf@test{#2}% 
    \ifx\pgf@test\pgfutil@empty%
      \expandafter\tikz@lib@graph@no@back@arrow%
    \else%
      \expandafter\tikz@lib@graph@back@arrow%
    \fi%
  }%
}

\def\tikz@lib@graph@no@back@arrow{%
  \pgfutil@ifnextchar>\tikz@lib@graph@forward@arrow{%
    \pgfutil@ifnextchar-\tikz@lib@graph@undirected@arrow{%
      \pgfutil@ifnextchar!\tikz@lib@graph@no@arrow{%
        \tikzerror{One of the arrow types <-, --, ->, -!- or <-> expected}%
        \tikz@lib@graph@undirected@arrow%
      }%
    }%
  }%
}

\def\tikz@lib@graph@undirected@arrow-{%
  \def\tikz@lib@graph@arrow@type{--}%
  \tikz@lib@graph@after@arrow%
}

\def\tikz@lib@graph@forward@arrow>{%
  \def\tikz@lib@graph@arrow@type{->}%
  \tikz@lib@graph@after@arrow%
}

\def\tikz@lib@graph@bi@arrow>{%
  \def\tikz@lib@graph@arrow@type{<->}%
  \tikz@lib@graph@after@arrow%
}

\def\tikz@lib@graph@no@arrow!-{%
  \def\tikz@lib@graph@arrow@type{-!-}%
  \tikz@lib@graph@after@arrow%
}

\def\tikz@lib@graph@back@arrow{%
  \pgfutil@ifnextchar>{\tikz@lib@graph@bi@arrow}{%
    \def\tikz@lib@graph@arrow@type{<-}%
    \tikz@lib@graph@after@arrow%
  }%
}

\def\tikz@lib@graph@after@arrow{%
  \pgfutil@ifnextchar[{\tikz@lib@graph@after@arrow@opt}{\tikz@lib@graph@after@arrow@opt[]}%]
}

\def\tikz@lib@graph@after@arrow@opt[#1]{%
  % 
  % Ok, first recolor 
  %
  \tikzgraphinvokeoperator{recolor source by=source''}
  \tikzgraphinvokeoperator{recolor target by=target'}
  % Save action for next node
  \expandafter\def\expandafter\tikz@lib@graph@stored@actions\expandafter{%
    \expandafter\tikz@lib@graph@joiner\expandafter{\tikz@lib@graph@arrow@type}{#1}}%
  % 
  \tikzgdeventgroupcallback{descendants}%
  \tikz@lib@graph@parse@one%
}

\def\tikz@lib@graph@joiner#1#2{%
  \tikzgraphinvokeoperator{recolor source by=source'}
  \tikzgraphinvokeoperator{recolor source'' by=source}
  {%
    \tikz@enable@edge@quotes%
    \pgfkeyssetvalue{/tikz/graphs/default edge kind}{#1}%
    \pgfkeys{/tikz/graphs/.cd,@operators=,%
      /tikz/graphs/.unknown/.code=\tikz@lib@graph@unknown@edge@option{##1},#2}%
    \pgfkeysgetvalue{/tikz/graphs/@operators}\pgf@temp%
    \ifx\pgf@temp\pgfutil@empty%
      \edef\pgf@temp{\noexpand\pgfkeys{/tikz/graphs/.cd,\pgfkeysvalueof{/tikz/graphs/default edge operator}}}%
      \pgf@temp%
      \pgfkeysgetvalue{/tikz/graphs/@operators}\pgf@temp%
    \fi%
    \pgf@temp%
  }%
  \tikzgraphinvokeoperator{not source',not target'}
}

\def\tikz@lib@graph@unknown@edge@option#1{%
  \def\tikz@temp{/tikz/graphs/@edges styling/.append=}
  \expandafter\expandafter\expandafter\pgfkeys%
  \expandafter\expandafter\expandafter{\expandafter\tikz@temp\expandafter{\expandafter,\pgfkeyscurrentname={#1}}}
}

\def\tikz@lib@graph@graph@done\pgf@stop@eodashes{%
    % Get local depth and width outside
    \xdef\tikz@lib@graph@chain@depth{\pgfkeysvalueof{/tikz/graphs/placement/local depth}}
    \xdef\tikz@lib@graph@chain@width{\pgfkeysvalueof{/tikz/graphs/placement/local width}}
    % Get node list outside...
    \expandafter%  
  \endgroup%
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\tikz@lib@graph@node@list%
  \expandafter\expandafter\expandafter{\expandafter\tikz@lib@graph@node@list\tikz@lib@graph@node@list}%
  % Compute new local depth and width of group...
  \tikz@lib@graph@placement@after@chain@update
  % 
  \pgfutil@ifnextchar\pgf@stop@eogroup%
  \tikz@lib@graph@graph@group@done%
  \tikz@lib@graph@main@parser%
}

\def\tikz@lib@graph@graph@group@done\pgf@stop@eogroup{%
  \pgfkeysvalueof{/tikz/graphs/@operators}%
}



%
% Handle node
%
\def\tikz@lib@graph@grab@name{%
  \pgfutil@ifnextchar\foreach\tikz@lib@graph@do@foreach\tikz@lib@graph@parse@node@text%
}

\def\tikz@lib@graph@do@foreach\foreach#1in{%
  \pgfutil@ifnextchar\bgroup{\tikz@lib@graph@do@foreach@normal{#1}}{\def\tikz@temp{#1}\tikz@lib@graph@do@foreach@macro}%
}
\def\tikz@lib@graph@do@foreach@macro#1{%
  \expandafter\expandafter\expandafter\tikz@lib@graph@do@foreach@normal\expandafter\tikz@temp\expandafter{#1}%
}

\def\tikz@lib@graph@do@foreach@normal#1#2#3\pgf@stop{%
  % Ok, we do a parse on a foreach loop.
  \begingroup
    \let\tikz@lib@graph@node@list@saved\pgfutil@empty%
    \xdef\tikz@lib@graph@saved@placement{%
      {\pgfkeysvalueof{/tikz/graphs/placement/local depth}}%
      {\pgfkeysvalueof{/tikz/graphs/placement/local width}}%
      {\pgfkeysvalueof{/tikz/graphs/placement/chain count}}%
      {\pgfkeysvalueof{/tikz/graphs/placement/element count}}%
      {\pgfkeysvalueof{/tikz/graphs/placement/width}}%
      {\pgfkeysvalueof{/tikz/graphs/placement/depth}}%
    }%
    \foreach #1 in {#2}%
    {%
      \let\tikz@lib@graph@node@list\tikz@lib@graph@node@list@saved%
      \expandafter\tikz@lib@graph@setup@placement\tikz@lib@graph@saved@placement%
      \tikz@lib@graph@parse@group{#3}%
      \xdef\tikz@lib@graph@saved@placement{%
        {\pgfkeysvalueof{/tikz/graphs/placement/local depth}}%
        {\pgfkeysvalueof{/tikz/graphs/placement/local width}}%
        {\pgfkeysvalueof{/tikz/graphs/placement/chain count}}%
        {\pgfkeysvalueof{/tikz/graphs/placement/element count}}%
        {\pgfkeysvalueof{/tikz/graphs/placement/width}}%
        {\pgfkeysvalueof{/tikz/graphs/placement/depth}}%
      }%
      % TODO: Need to also save hints!
      \global\let\tikz@lib@graph@node@list@saved\tikz@lib@graph@node@list%
    }%
    \expandafter%  
  \endgroup%
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\tikz@lib@graph@node@list%
  \expandafter\expandafter\expandafter{\expandafter\tikz@lib@graph@node@list\tikz@lib@graph@node@list@saved}%  
  \expandafter\tikz@lib@graph@setup@placement\tikz@lib@graph@saved@placement%
}

\def\tikz@lib@graph@setup@placement#1#2#3#4#5#6{%
  \pgfkeyssetvalue{/tikz/graphs/placement/local depth}{#1}%
  \pgfkeyssetvalue{/tikz/graphs/placement/local width}{#2}%
  \pgfkeyssetvalue{/tikz/graphs/placement/chain count}{#3}%
  \pgfkeyssetvalue{/tikz/graphs/placement/element count}{#4}%
  \pgfkeyssetvalue{/tikz/graphs/placement/width}{#5}%
  \pgfkeyssetvalue{/tikz/graphs/placement/depth}{#6}%
}

\def\tikz@lib@graph@parse@node@text#1\pgf@stop{%
  % 
  % Ok, first test whether #1 contains "//" 
  % 
  \pgfutil@in@{//}{#1 }
  \ifpgfutil@in@%
    % Ok, a layout node: 
    \tikz@lib@parse@layout@node#1\pgf@stop%
  \else%
    \tikz@lib@graph@fake@nodefalse
    \let\tikz@lib@graph@node@parsed\tikz@lib@graph@node@opt@normal%
    \def\tikz@lib@graph@empty@node@parsed{\tikzgdeventcallback{node}{}}%
    \tikz@lib@parse@normal@node#1[\pgf@stop%
  \fi%
}


% 
% Parse the normal part of a node (name and, possibly, text after slash) 
% 

\def\tikz@lib@parse@normal@node#1[{
  % 
  % Test whether #1 contains "/" or "__" 
  % 
  \pgfutil@in@{/}{#1}%
  \ifpgfutil@in@%
    \tikz@lib@parse@node@with@slash#1\pgf@stop%
  \else
    \pgfutil@in@{__}{#1}%
    \ifpgfutil@in@%
      \tikz@lib@parse@node@with@doubleunder#1\pgf@stop%
    \else
      \pgfkeys@spdef\tikz@lib@graph@name@only{#1}%
      \let\tikz@lib@graph@node@text\tikz@lib@graph@name@only%
      \edef\tikz@lib@graph@name{\tikz@lib@graph@path\tikz@lib@graph@name@only}%
    \fi%
  \fi%
  \tikz@lib@graph@handle@node@cont%  
}

\def\tikz@lib@parse@node@with@slash#1/{
  \pgfkeys@spdef\tikz@lib@graph@name@only{#1}%
  \ifx\tikz@lib@graph@name@only\pgfutil@empty%
    \global\advance\tikz@fig@count by1\relax
    \edef\tikz@lib@graph@name@only{tikz@f@\the\tikz@fig@count}%
  \fi%  
  \edef\tikz@lib@graph@name{\tikz@lib@graph@path\tikz@lib@graph@name@only}%
  \pgfutil@ifnextchar"\tikz@lg@slash@quote{\pgfutil@ifnextchar\tikz@active@quotes@token\tikz@lg@slash@quote@active\tikz@lg@slash@cont}
}
\def\tikz@lg@slash@quote"#1"#2\pgf@stop{%
  \iftikz@handle@active@nodes%
    \def\tikz@lib@graph@node@text{\scantokens{#1}}%
  \else
    \def\tikz@lib@graph@node@text{#1}%
  \fi%
}
{\catcode`\"=13\relax
  \gdef\tikz@lg@slash@quote@active"#1"#2\pgf@stop{%
  \iftikz@handle@active@nodes%
    \def\tikz@lib@graph@node@text{\scantokens{#1}}%
  \else
    \def\tikz@lib@graph@node@text{#1}%
  \fi%
  }
}
\def\tikz@lg@slash@cont#1\pgf@stop{%
  \iftikz@handle@active@nodes%
    \def\tikz@lib@graph@node@text{\scantokens{#1}}%
  \else
    \def\tikz@lib@graph@node@text{#1}%
  \fi%
}

\def\tikz@lib@parse@node@with@doubleunder#1__{\tikz@lib@parse@node@with@slash{#1}/}

\def\tikz@lg@find@fresh@name{%
  \edef\tikz@lib@graph@name@only{\tikz@lib@graph@name@only'}%
  \edef\tikz@lib@graph@name{\tikz@lib@graph@path\tikz@lib@graph@name@only}%
  \tikz@lg@if@local@node{\tikz@lib@graph@name}{\tikz@lg@find@fresh@name}{}%
}


% 
% We have now parsed everything up to the opening "[". We continue 
%

\def\tikz@lib@graph@handle@node@cont{%
  \iftikz@lib@graph@fresh@node%
    \tikz@lg@if@local@node{\tikz@lib@graph@name}{\tikz@lg@find@fresh@name}{}%
  \fi%
  \let\tikzgraphnodeas\tikzgraphnodeas@default%
  \pgfutil@ifnextchar\pgf@stop{%
    \ifx\tikz@lib@graph@name@only\pgfutil@empty%
      \expandafter\tikz@lib@graph@node@empty@done%
    \else
      \expandafter\tikz@lib@graph@node@opt\expandafter[\expandafter]\expandafter[%
    \fi%
  }{\tikz@lib@graph@node@opt[}%
}

\def\tikzgraphnodeas@default{%
  \tikz@lib@graph@typesetter%
}

\let\tikz@lib@graph@empty@node@parsed\relax%

\def\tikz@lib@graph@node@opt[#1]#2[\pgf@stop{%
  \tikz@lib@graph@node@parsed{#1}%
}

\def\tikz@lib@graph@node@empty@done\pgf@stop{\tikz@lib@graph@empty@node@parsed}

% 
% Parse a layout node 
%

\def\tikz@lib@parse@layout@node#1//{%
  \pgf@lib@graph@empty@layout@nodefalse%
  \let\tikz@lib@graph@node@parsed\tikz@lib@layout@node@parsed%
  \let\tikz@lib@graph@empty@node@parsed\tikz@lib@graph@empty@layout@node@parsed
  \tikz@lib@parse@normal@node#1[\pgf@stop%
}

\newif\ifpgf@lib@graph@empty@layout@node

\def\tikz@lib@layout@node@parsed{%
  \tikz@lib@layout@parse@rest%
}

\def\tikz@lib@graph@empty@layout@node@parsed{%
  \pgf@lib@graph@empty@layout@nodetrue
  \tikz@lib@layout@parse@rest{}%
}

\def\tikz@lib@layout@parse@rest#1{%
  \def\tikz@lib@layout@node@options{#1}%
  \pgfutil@ifnextchar[{\tikz@lib@layout@node@opt}{\tikz@lib@layout@node@opt[]}%}
}

\def\tikz@lib@layout@node@parsed#1{%
  \def\tikz@lib@layout@node@options{#1}%
  \pgfutil@ifnextchar[{\tikz@lib@layout@node@opt}{\tikz@lib@layout@node@opt[]}%}
}

\def\tikz@lib@layout@node@opt[#1]{%
  \def\tikz@lib@layout@options{#1}%
  \pgfutil@ifnextchar\bgroup{\tikz@lib@layout@start}{\tikzerror{Opening brace at beginning of sublayout expected}}%
}


%
% Typeset a normal node
%

\def\tikz@lib@graph@node@opt@normal#1{%
  \expandafter\tikz@lib@graph@test@use@list\tikz@lib@graph@name@only\pgf@stop
  \iftikz@lib@graph@use@list%
    % Ok, make a list of the nodes stored in #1:
    \let\tikz@lg@temp\pgfutil@empty%
    \foreach \tikz@lg@node@name in \tikz@lib@graph@use@list {\expandafter\tikz@lib@graph@handle@use\expandafter{\tikz@lg@node@name}}
    % Ok, now add the nodes to the node list
    \expandafter\expandafter\expandafter\def%
    \expandafter\expandafter\expandafter\tikz@lib@graph@node@list%
    \expandafter\expandafter\expandafter{%
      \expandafter\tikz@lib@graph@node@list\tikz@lg@temp}%
    % Then color and initialize them:
    \let\tikz@lg@do\tikz@lib@graph@do@use%
    \tikz@lg@temp%
  \else%
    \edef\tikz@lib@graph@name{\tikz@lib@graph@path\tikz@lib@graph@name@only}%
    \expandafter\ifx\csname tikz@lib@graph@def@\tikz@lib@graph@name@only\endcsname\relax%
      \pgfkeysgetvalue{/tikz/graphs/placement/level}\tikz@temp%
      \c@pgf@counta=\tikz@temp\relax%
      \advance\c@pgf@counta by1\relax%
      \edef\tikz@temp{\the\c@pgf@counta}%
      \pgfkeyslet{/tikz/graphs/placement/level}\tikz@temp%  
      \tikzgraphsset{
        level/.try=\pgfkeysvalueof{/tikz/graphs/placement/level},
        level \pgfkeysvalueof{/tikz/graphs/placement/level}/.try
      }
      {%
        \edef\tikz@lib@graph@node@list{\noexpand\tikz@lg@do{\tikz@lib@graph@name}}%
        \global\tikz@lib@graph@node@createdfalse%
        \pgfkeyslet{/tikz/graphs/@operators}\pgfutil@empty%
        \tikz@lib@activate@source@target@edge@syntax%
        \tikz@lg@if@local@node{\tikz@lib@graph@name}%
        {\tikz@lg@local@node@handle{#1}}%
        {%
          \tikz@lg@init@color{\tikz@lib@graph@name}{\tikz@lgc@all@true\tikz@lgc@source@true\tikz@lgc@target@true}%
          \iftikz@lib@graph@all%
            \tikzgraphsset{#1}\pgfkeysvalueof{/tikz/graphs/@operators}%
          \else%
            \pgfkeys{/tikz/graphs/placement/place}%
            \let\tikzgraphnodetext\tikz@lib@graph@node@text%
            \let\tikzgraphnodename\tikz@lib@graph@name@only%
            \let\tikzgraphnodepath\tikz@lib@graph@path%
            \let\tikzgraphnodefullname\tikz@lib@graph@name%
            \iftikz@lib@graph@fake@node%
              {% run options in protected mode...
                \pgfkeys{
                  /tikz/graphs/.cd,%
                  .unknown/.code=,
                  /tikz/graphs/@nodes styling,%
                  #1}%
                \pgfkeysgetvalue{/tikz/graphs/@operators}\tikz@lib@graph@op@save%
                \global\let\tikz@lib@graph@op@save\tikz@lib@graph@op@save%                
              }%
            \else%
              \node [%
                name=\tikz@lib@graph@name,%
                execute at end node={%
                  \pgfkeysgetvalue{/tikz/graphs/@operators}\tikz@lib@graph@op@save%
                  \global\let\tikz@lib@graph@op@save\tikz@lib@graph@op@save%
                },%
                graphs/redirect unknown to tikz,
                /tikz/graphs/.cd,%
                /tikz/graphs/@nodes styling,%
                #1]%
                {%
                  \tikzgraphnodeas%
                };%
            \fi%
            \tikz@lib@graph@op@save\global\let\tikz@lib@graph@op@save\relax%%
            \global\tikz@lib@graph@node@createdtrue%
          \fi
        }%
      }%
      \iftikz@lib@graph@node@created\tikz@lib@graph@placement@update\fi%
      \expandafter\expandafter\expandafter\def%
      \expandafter\expandafter\expandafter\tikz@lib@graph@node@list%
      \expandafter\expandafter\expandafter{%
        \expandafter\tikz@lib@graph@node@list\expandafter\tikz@lg@do\expandafter{\tikz@lib@graph@name}}%
      \iftikz@lib@graph@trie\tikzgraphsset{name=\tikz@lib@graph@name@only}\fi%
    \else
      % The name of the node is a graph name
      \tikz@lib@graph@handle@graph{#1}%      
    \fi
  \fi%  
}

\newif\iftikz@lib@graph@fake@node

\newif\iftikz@lib@graph@use@list
\def\tikz@lib@graph@test@use@list{%
  \pgfutil@ifnextchar({\tikz@lib@graph@use@list@grap}{\tikz@lib@graph@test@use@list@done}%)
}

\def\tikz@lib@graph@test@use@list@done#1\pgf@stop{\tikz@lib@graph@use@listfalse}
\def\tikz@lib@graph@use@list@grap(#1)\pgf@stop{\def\tikz@lib@graph@use@list{#1}\tikz@lib@graph@use@listtrue}


% 
% Typeset a layout node 
%

\def\tikz@lib@layout@start#1#2\pgf@stop{%
  \tikz@lib@ensure@gd@loaded%
  % Parameters are:
  % 
  % Node name is \tikz@lib@graph@name@only
  % Node text is \tikz@lib@graph@node@text
  % Node options are \tikz@lib@layout@node@options
  % Layout options are \tikz@lib@layout@options
  % Layout is #1
  % Rest is #2 (should be empty or just whitespace)
  \tikz@lib@graph@fake@nodefalse%
  \ifpgf@lib@graph@empty@layout@node%
  \else%
    \ifx\tikz@lib@graph@name\pgfutil@empty%
      \tikzerror{Internal error: Node has no name, but it should!}%
    \else
      \tikz@lib@graph@fake@nodetrue%
      \expandafter\tikz@lib@graph@node@opt@normal\expandafter{\tikz@lib@layout@node@options}%
    \fi%
  \fi%
  \edef\tikz@lib@graph@name{\tikz@lib@graph@path\tikz@lib@graph@name@only}%
  % 
  % Prepare tikz node options 
  %
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\tikz@lib@layout@node@options\expandafter\expandafter\expandafter{\expandafter\tikz@lib@layout@startup@node@options\tikz@lib@layout@node@options,}%
  \begingroup
      % Create a subgraph node, if name is given.
    \iftikz@lib@graph@fake@node%
      \expandafter\expandafter\expandafter%
      \expandafter\expandafter\expandafter\expandafter\tikz@lib@make@subgraph@node%
      \expandafter\expandafter\expandafter%
      \expandafter\expandafter\expandafter\expandafter{%
        \expandafter\expandafter\expandafter\tikz@lib@graph@name%
        \expandafter\expandafter\expandafter}%
      \expandafter\expandafter\expandafter{%
        \expandafter\tikz@lib@graph@node@text\expandafter}\expandafter{\tikz@lib@layout@node@options}
    \fi%
  % 
  % Here comes the scope: 
  %
  \expandafter\expandafter\expandafter\scope\expandafter\expandafter\expandafter[\expandafter\tikz@lib@layout@node@options@prefix\tikz@lib@layout@options]
    \tikzgdeventgroupcallback{array}%
    \let\tikz@lib@graph@node@list\pgfutil@empty%
    \tikz@lib@graph@start@hint@group%
      \tikz@lib@graph@parse@group{#1}%
    \tikz@lib@graph@end@hint@group%
    \def\tikz@lg@old@col{\tikz@lgc@source@true}%
    \let\tikz@lg@new@col\pgfutil@empty%
    \let\tikz@lg@do\tikz@lg@change@color%
    \tikz@lib@graph@node@list%
    \def\tikz@lg@old@col{\tikz@lgc@target@true}%
    \tikz@lib@graph@node@list%
    \expandafter%  
  \endscope\expandafter%
  \endgroup%
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\tikz@lib@graph@node@list%
  \expandafter\expandafter\expandafter{\expandafter\tikz@lib@graph@node@list\tikz@lib@graph@node@list}%
  \tikz@lib@graph@hint@aftergroup%
}
\def\tikz@lib@make@subgraph@node#1#2#3{%
  \pgfgdsubgraphnode{#1}{#3}{\pgfgdsubgraphnodecontents{#2}}%
}
\def\tikz@lib@layout@startup@node@options{%
  /utils/exec=\tikzlibignorecomparisonsINTERNAL,
  /tikz/graphs/.cd,%
  redirect unknown to tikz,%
  anchor=base,%
  /tikz/every subgraph node/.try,%
}
\def\tikzlibignorecomparisonsINTERNAL{%
  \pgfkeys{/handlers/first char syntax=true}
  \pgfkeyssetvalue{/handlers/first char syntax/the character >}{\pgfutil@gobble}%
  \pgfkeyssetvalue{/handlers/first char syntax/the character <}{\pgfutil@gobble}%
}
\def\tikz@lib@layout@node@options@prefix{graphs/.cd,}

\ifx\tikz@lib@ensure@gd@loaded\pgfutil@undefined%
\def\tikz@lib@ensure@gd@loaded{\tikzerror{You must say \string\usetikzlibrary{graphdrawing} to use the (sub)layout syntax}}
\fi

\def\tikz@lg@local@node@handle#1{%
  %
  % Handle late options and operators
  \tikzgraphsset{source,target,.unknown/.code=,#1}%
  \tikzgdlatenodeoptionacallback{\tikz@lib@graph@name}%
  \node also[graphs/redirect unknown to tikz,/tikz/graphs/.cd,#1](\tikz@lib@graph@name);%
  \pgfkeysvalueof{/tikz/graphs/@operators}%
}

\tikzgraphsset{redirect unknown to tikz/.style={
    /tikz/graphs/.unknown/.code={%
      \let\tikz@key\pgfkeyscurrentname% 
      \pgfkeys{tikz/.cd,\tikz@key={##1},/tikz/graphs/.cd}%
    }}
}

\def\tikz@lib@activate@source@target@edge@syntax{%
  \pgfkeys{/handlers/first char syntax=true}
  \pgfkeyssetvalue{/handlers/first char syntax/the character >}{\tikz@lg@parse@more}%
  \pgfkeyssetvalue{/handlers/first char syntax/the character <}{\tikz@lg@parse@less}%
}

\def\tikz@lg@parse@less#1{\tikz@lg@parse@less@#1\pgf@stop}
\def\tikz@lg@parse@less@<{\pgfutil@ifnextchar"{\tikz@lg@parse@quote{source}}{\tikz@lg@parse@noquote{source}}}
\def\tikz@lg@parse@more#1{\tikz@lg@parse@more@#1\pgf@stop}
\def\tikz@lg@parse@more@>{\pgfutil@ifnextchar"{\tikz@lg@parse@quote{target}}{\tikz@lg@parse@noquote{target}}}

\def\tikz@lg@parse@noquote#1#2\pgf@stop{{\tikzgraphsset{#1 edge style={#2}}}}
\def\tikz@lg@parse@quote#1#2\pgf@stop{%
  {\tikzgraphsset{/tikz/node quotes mean={#1 edge node={node [every edge quotes,##2]{##1}}},/utils/exec=\tikz@enable@node@quotes,#2}}%
}

\tikzgraphsset{
  clear >/.style=target edge clear,
  clear </.style=source edge clear
}


% Positioning

\def\tikz@lib@graph@x{0}
\def\tikz@lib@graph@y{0}

\tikzgraphsset{
  x/.code=\def\tikz@lib@graph@x{#1}\tikz@lib@graphs@check@at,
  y/.code=\def\tikz@lib@graph@y{#1}\tikz@lib@graphs@check@at
}
\def\tikz@lib@graphs@check@at{%
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\tikz@temp%
  \expandafter\expandafter\expandafter{%
    \expandafter\expandafter\expandafter(%
    \expandafter\expandafter\expandafter{\expandafter\tikz@lib@graph@x\expandafter}%
    \expandafter,\expandafter{\tikz@lib@graph@y})}%
  \pgfqkeys{/tikz}{at/.expand once=\tikz@temp}%
}


\newif\iftikz@lib@graph@trie
\tikzgraphsset{
  trie/.is if=tikz@lib@graph@trie,
  put node text on incoming
  edges/.style={nodes={/utils/exec=\tikz@lg@make@edge@node{target}{#1}}},
  put node text on outgoing
  edges/.style={nodes={/utils/exec=\tikz@lg@make@edge@node{source}{#1}}},
  edge quotes/.style={/tikz/every edge quotes/.style={#1}},
  edge quotes center/.style={edge quotes={anchor=center}},
  edge quotes mid/.style={edge quotes={anchor=mid}}
}

\def\tikz@lg@make@edge@node#1#2{%
  \def\pgf@marshal{node[#2]}%
  \expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter\pgf@marshal\expandafter\expandafter\expandafter{\expandafter\pgf@marshal\expandafter{\tikzgraphnodetext}}%
  \pgfkeysalso{#1 edge node/.expand once=\pgf@marshal,as=}%
}

\newif\iftikz@lib@graph@fresh@node
\tikzgraphsset{fresh nodes/.is if=tikz@lib@graph@fresh@node}


\newif\iftikz@lib@graph@node@created

\def\tikz@lib@graph@handle@use#1{%
  % Is #1 the name of a node set?
  \expandafter\let\expandafter\pgf@temp\csname tikz@lg@node@set #1\endcsname
  \ifx\pgf@temp\relax
    \pgfutil@g@addto@macro\tikz@lg@temp{\tikz@lg@do{#1}}    
  \else%
    \expandafter\pgfutil@g@addto@macro\expandafter\tikz@lg@temp\expandafter{\pgf@temp}
  \fi  
}

\def\tikz@lib@graph@do@use#1{%
  \tikz@lg@init@color{#1}{\tikz@lgc@all@true\tikz@lgc@source@true\tikz@lgc@target@true}%
}

\tikzgraphsset{
  typeset/.store in=\tikz@lib@graph@typesetter,
  math nodes/.style={/tikz/graphs/typeset=$\tikzgraphnodetext$},
  empty nodes/.style={/tikz/graphs/typeset=},
  typeset=\tikzgraphnodetext
}


% 
% Handle scope 
%
\def\tikz@lib@graph@scope#1{
  \begingroup%
    \tikzgdeventgroupcallback{array}%
    \let\tikz@lib@graph@node@list\pgfutil@empty%
    \tikz@lib@graph@start@hint@group%
      \tikz@lib@graph@parse@group{#1}%
    \tikz@lib@graph@end@hint@group%
    \expandafter%  
  \endgroup%
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\tikz@lib@graph@node@list%
  \expandafter\expandafter\expandafter{\expandafter\tikz@lib@graph@node@list\tikz@lib@graph@node@list}%
  \tikz@lib@graph@hint@aftergroup%
  \tikz@lib@graph@stored@actions%
  \pgfutil@ifnextchar-{\tikz@lib@graph@scope@minus}{%
    \pgfutil@ifnextchar<{\tikz@lib@graph@scope@less}{%
      \tikzerror{One of the arrow types <-, --, ->, -!-, or <-> expected}%
    }%
  }%
}

\def\tikz@lib@graph@scope@minus-{
  \pgfutil@ifnextchar>\tikz@lib@graph@forward@arrow{%
    \pgfutil@ifnextchar-\tikz@lib@graph@undirected@arrow{%
      \pgfutil@ifnextchar!\tikz@lib@graph@no@arrow{%
        \pgfutil@ifnextchar\pgf@stop@eodashes\tikz@lib@graph@graph@done{%
          \tikzerror{One of the arrow types <-, --, ->, -!-, or <-> expected}%
          \tikz@lib@graph@undirected@arrow%
        }%
      }%
    }%
  }%
}

\def\tikz@lib@graph@scope@less<-{\tikz@lib@graph@back@arrow}%




% 
% Predefining graphs 
% 

\tikzgraphsset{
  declare/.code 2 args={\expandafter\def\csname tikz@lib@graph@def@#1\endcsname{\tikz@lib@graph@do@graph{#2}}}%
}

\def\tikz@lib@graph@handle@graph#1{%
  \begingroup%
    \let\tikz@lib@graph@node@list\pgfutil@empty%
    \tikzgraphsset{@extra group options/.style={#1}}%
    \tikz@lib@graph@start@hint@group%
      \csname tikz@lib@graph@def@\tikz@lib@graph@name@only\endcsname%
    \tikz@lib@graph@end@hint@group%
    \expandafter%  
  \endgroup%
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\tikz@lib@graph@node@list%
  \expandafter\expandafter\expandafter{\expandafter\tikz@lib@graph@node@list\tikz@lib@graph@node@list}% 
  \tikz@lib@graph@hint@aftergroup%
}

\def\tikz@lib@graph@do@graph#1{%
  \tikz@lib@graph@parse@group{#1}%
}

\let\tikz@lib@graph@path\pgfutil@empty

\tikzgraphsset{
  name separator/.store in=\tikz@lib@graph@name@separator,
  name separator=\space,
  name/.code={%
    \edef\tikz@lib@graph@path{\tikz@lib@graph@path#1\tikz@lib@graph@name@separator}%
  }%
}


%
% Colors
% 
\def\tikz@lg@newif{\csname newif\endcsname}
\tikzgraphsset{
  as/.code=\def\tikzgraphnodeas{#1},%
  color class/.style={%
    /utils/exec=\expandafter\tikz@lg@newif\csname iftikz@lgc@#1@\endcsname,
    #1/.style={operator={%
      \edef\tikz@lg@col{\expandafter\noexpand\csname tikz@lgc@#1@true\endcsname}%
      \let\tikz@lg@do\tikz@lg@colorize%
      \tikz@lib@graph@node@list%
    }},
    not #1/.style={operator={%
      \edef\tikz@lg@old@col{\expandafter\noexpand\csname tikz@lgc@#1@true\endcsname}%
      \let\tikz@lg@new@col\pgfutil@empty%
      \let\tikz@lg@do\tikz@lg@change@color%
      \tikz@lib@graph@node@list%
    }},
    recolor #1 by/.style={operator={%
      \edef\tikz@lg@old@col{\expandafter\noexpand\csname tikz@lgc@#1@true\endcsname}%
      \edef\tikz@lg@new@col{\expandafter\noexpand\csname tikz@lgc@##1@true\endcsname}%
      \let\tikz@lg@do\tikz@lg@change@color%
      \tikz@lib@graph@node@list%
    }},
    !#1/.style=not #1,
  },
  color class=source,
  color class=source',
  color class=source'',
  color class=target,
  color class=target',
  color class=all
}

\def\tikz@lg@init@color#1#2{%
  \expandafter\gdef\csname tikz@lgc@#1\endcsname{#2}%
}

\def\tikz@lib@graph@cleanup#1{%
  \expandafter\global\expandafter\let\csname tikz@lgc@#1\endcsname\relax%
  \ifcsname tikz@lgca@@#1\endcsname\expandafter\global\expandafter\let\csname tikz@lgca@@#1\endcsname\relax\fi%
  \ifcsname tikz@lgcb@@#1\endcsname\expandafter\global\expandafter\let\csname tikz@lgcb@@#1\endcsname\relax\fi%
}

\def\tikz@lg@colorize#1{%
  \expandafter\let\expandafter\pgf@temp\csname tikz@lgc@#1\endcsname%
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\pgf@temp%
  \expandafter\expandafter\expandafter{%
    \expandafter\tikz@lg@col\pgf@temp}%
  \expandafter\global\expandafter\let\csname tikz@lgc@#1\endcsname\pgf@temp%
}

\def\tikz@lg@change@color#1{%
  \def\tikz@lg@temp@save{#1}%
  \let\tikz@lg@collect\pgfutil@empty%
  \expandafter\let\expandafter\pgf@temp\csname tikz@lgc@#1\endcsname%
  \expandafter\tikz@lg@change@check\pgf@temp\pgf@stop%
}
\def\tikz@lg@change@check#1{%
  \ifx#1\pgf@stop%
    \tikz@lg@change@write@back%
  \else%
    \def\pgf@temp{#1}%
    \ifx\pgf@temp\tikz@lg@old@col%
      \expandafter\tikz@lg@change@add\expandafter{\tikz@lg@new@col}% Found!
    \else%
      \tikz@lg@change@add{#1}%
    \fi%
    \expandafter\tikz@lg@change@check
  \fi%
}
\def\tikz@lg@change@add#1{%
  \expandafter\def\expandafter\tikz@lg@collect\expandafter{\tikz@lg@collect#1}%
}

\def\tikz@lg@change@write@back{%
  \expandafter\global\expandafter\let\csname tikz@lgc@\tikz@lg@temp@save\endcsname\tikz@lg@collect%
}



\def\tikz@lg@if@has@color#1#2#3#4{%
  {%
    \csname tikz@lgc@#1\endcsname%
    \expandafter\let\expandafter\pgf@temp\csname iftikz@lgc@#2@\endcsname%
    \ifx\pgf@temp\relax%
      \tikz@lib@reset@temp%
    \fi%
    \pgf@temp%
      \global\tikz@color@testtrue%
    \else%
      \global\tikz@color@testfalse%
    \fi%
  }%
  \iftikz@color@test#3\else#4\fi%
}
\newif\iftikz@color@test

\def\tikz@lg@if@local@node#1#2#3{\expandafter\ifx\csname tikz@lgc@#1\endcsname\relax#3\else#2\fi}

\def\tikz@lib@reset@temp{\let\pgf@temp\iffalse}

% 
% Handle connection annotations 
%
\def\tikz@lib@annotate@#1#2#3#4{%
  \expandafter\ifx\csname tikz@lgc#1@@#2\endcsname\relax%
    \expandafter\gdef\csname tikz@lgc#1@@#2\endcsname{{#3}{#4}}%
  \else%  
    \expandafter\expandafter\expandafter\tikz@lib@annotate@read\csname tikz@lgc#1@@#2\endcsname{#3}{#4}%
    \expandafter\global\expandafter\let\csname tikz@lgc#1@@#2\endcsname\pgf@temp%
  \fi%
}
\def\tikz@lib@annotate@read#1#2#3#4{\def\pgf@temp{{#1,#3}{#2#4}}}

\tikzgraphsset{
  source edge style/.code=\tikz@lib@annotate@{a}{\tikz@lib@graph@name}{#1}{},
  source edge node/.code=\tikz@lib@annotate@{a}{\tikz@lib@graph@name}{}{#1},
  source edge clear/.code={
    \expandafter\global\expandafter\let\csname tikz@lgca@@\tikz@lib@graph@name\endcsname\relax%
  },
  target edge style/.code=\tikz@lib@annotate@{b}{\tikz@lib@graph@name}{#1}{},
  target edge node/.code=\tikz@lib@annotate@{b}{\tikz@lib@graph@name}{}{#1},
  target edge clear/.code={%
    \expandafter\global\expandafter\let\csname tikz@lgcb@@\tikz@lib@graph@name\endcsname\relax%
  }
}%



% Packing a node list: Replace the node list by a new node list where
% each node is mentioned at most once.

\def\tikz@lib@graph@pack@node@list{%
  {%
    \let\tikz@lg@packed\pgfutil@empty%
    \let\tikz@lg@do\tikz@lg@packer%
    \tikz@lib@graph@node@list%
    \expandafter
  }\expandafter%
  \def\expandafter\tikz@lib@graph@node@list\expandafter{\tikz@lg@packed}%
}

\def\tikz@lg@packer#1{%
  \expandafter\ifx\csname tikz@lg@p@#1\endcsname\pgf@stop%
  \else%
    \expandafter\let\csname tikz@lg@p@#1\endcsname\pgf@stop%
    \expandafter\def\expandafter\tikz@lg@packed\expandafter{\tikz@lg@packed\tikz@lg@do{#1}}
  \fi
}

%
% Color functions
%

% Do something for all nodes having a certain color
%
% #1 = the color name
% #2 = a macro
% 
% Description:
% 
% For each node having color #1, the macro #2 will be called. This
% macro should take a single parameter, which will be set 
% to the node's name.

\def\tikzgraphforeachcolorednode#1#2{%
  \tikz@lib@graph@pack@node@list%
  \expandafter\def\expandafter\iftikz@lib@graph@color@picker\expandafter{\csname iftikz@lgc@#1@\endcsname}%
  \let\tikz@lib@graph@action#2%
  \let\tikz@lg@do\tikz@lg@pick%
  \tikz@lib@graph@node@list%  
}
\def\tikz@lg@pick#1{
  {%
    \csname tikz@lgc@#1\endcsname%
    \iftikz@lib@graph@color@picker
      \global\tikz@color@testtrue%
    \else%
      \global\tikz@color@testfalse%
    \fi%
  }%
  \iftikz@color@test\tikz@lib@graph@action{#1}\fi%
}



% Prepare a color 
%
% #1 is the color name
% #2 is a counter
% #3 is a prefix
% 
% Description:
% 
% You can call this function inside a connector. It will do the
% following: First, its counts how many nodes exist that have color
% #1. This number is stored in the counter passed as #2. Furthermore,
% let <name> be the name of the <i>-th vertex that has color #1. Then, a
% macro called \#3<i> will store <name>. For instance, if #1 is "red"
% and the third red node is called foo and if #3 is "bar", then a
% macro called "\bar3" is set to "foo" as if you had said
% "\expandafter\def\csname bar3\endcsname{foo}".
% 
% The bottom line of all this is that after a preparation you can
% easily iterate over nodes having a certain color. If you wish to
% iterate over a single color, it will be quicker and easier to call
% \tikzgraphforeachcolorednode, but if you need to iterate over two
% colors simultaneously, it will be better to first prepare the color.

\def\tikzgraphpreparecolor#1#2#3{%
  \let\tikz@lib@graph@count#2%
  \tikz@lib@graph@count0\relax
  \def\tikz@lib@graph@prefix{#3}%
  \tikzgraphforeachcolorednode{#1}\tikz@lib@graph@prepare%
}

\def\tikz@lib@graph@prepare#1{%
  \advance\tikz@lib@graph@count by1\relax%
  \expandafter\def\csname\tikz@lib@graph@prefix\the\tikz@lib@graph@count\endcsname{#1}%
}




% 
% The bipartite connector 
%

\tikzgraphsset{
  complete bipartite/.style 2 args={operator={
    \def\tikz@lg@shoreb{#2}%
    \tikzgraphforeachcolorednode{#1}\tikz@lib@graph@bipartite@outer
  }},
  complete bipartite/.default={target'}{source'},
  induced complete bipartite/.style 2 args={
    induced independent set={#1},
    induced independent set={#2},
    complete bipartite={#1}{#2}
  },
  induced complete bipartite/.default={target'}{source'},
}

\def\tikz@lib@graph@bipartite@outer#1{%
  \def\tikz@lib@graph@from{#1}%
  {%
    \tikzgraphforeachcolorednode{\tikz@lg@shoreb}\tikz@lib@graph@bipartite@inner%
  }%
}

\def\tikz@lib@graph@bipartite@inner#1{%
  \def\pgf@temp{#1}%
  \ifx\pgf@temp\tikz@lib@graph@from\else%
    \tikz@lib@graph@default@new@edge{\tikz@lib@graph@from}{#1}%
  \fi%
}

\def\tikz@lib@graph@default@new@edge#1#2{%
  \pgfkeysgetvalue{/tikz/graphs/@edges styling}\pgf@temp
  \pgfkeysgetvalue{/tikz/graphs/@edges node}\pgf@temp@b
  \let\tikz@lib@add@temp\pgfutil@empty%
  \tikz@lib@graph@add@edge@annotations{a}{#1}
  \tikz@lib@graph@add@edge@annotations{b}{#2}
  \expandafter\expandafter\expandafter\def%
  \expandafter\expandafter\expandafter\pgf@temp%
  \expandafter\expandafter\expandafter{\expandafter\pgf@temp\tikz@lib@add@temp}%
  \expandafter\expandafter\expandafter\tikz@lib@graph@default@new@edge@%
  \expandafter\expandafter\expandafter{\expandafter\pgf@temp\expandafter}\expandafter{\pgf@temp@b}{#1}{#2}%
}
\def\tikz@lib@graph@default@new@edge@#1#2#3#4{%
  \iftikz@lib@graph@simple%
    \edef\tikz@temp{{\pgfkeysvalueof{/tikz/graphs/default edge kind}}{#3}{#4}}
    \expandafter\tikz@lib@graph@set@simple@edge\tikz@temp{#1}{#2}%
  \else%
    \pgfkeys{/tikz/graphs/.cd,new \pgfkeysvalueof{/tikz/graphs/default edge kind}={#3}{#4}{#1}{#2}}%
  \fi%
}
\def\tikz@lib@graph@add@edge@annotations#1#2{%
  \ifcsname tikz@lgc#1@@#2\endcsname%
    \expandafter\let\expandafter\tikz@lg@temp@\csname tikz@lgc#1@@#2\endcsname%
    \ifx\tikz@lg@temp@\relax\else
      \expandafter\tikz@lib@graph@add@edge@annotations@\tikz@lg@temp@%
      \let\tikz@lib@add@temp\tikz@lib@final@edge@style  
    \fi%
  \fi%
}
\def\tikz@lib@graph@add@edge@annotations@#1#2{
  \expandafter\def\expandafter\pgf@temp\expandafter{\pgf@temp,#1}%
  \expandafter\def\expandafter\pgf@temp@b\expandafter{\pgf@temp@b#2}%
}
\def\tikz@lib@final@edge@style{,after source and target edge/.try}

% 
% The clique connector 
%

\tikzgraphsset{
  clique/.style={operator={
      \tikzgraphpreparecolor{#1}\c@pgf@counta{tikz@lg}%
      \tikz@lg@clique@loop%
    }},
  clique/.default=all
}

\def\tikz@lg@clique@loop{%
  \ifnum\c@pgf@counta=0\relax%
  \else
    \c@pgf@countb=\c@pgf@counta\relax%
    \tikz@lg@clique@loop@inner%
    \advance\c@pgf@counta by-1\relax%
    \expandafter\tikz@lg@clique@loop%
  \fi%
}

\def\tikz@lg@clique@loop@inner{%
  \advance\c@pgf@countb by-1\relax%
  \ifnum\c@pgf@countb>0\relax%
    \tikz@lib@graph@default@new@edge{\csname tikz@lg\the\c@pgf@countb\endcsname}{\csname tikz@lg\the\c@pgf@counta\endcsname}%
    \expandafter\tikz@lg@clique@loop@inner%
  \fi%
}


% 
% The independent set connector 
%

\tikzgraphsset{
  induced independent set/.style={operator={
      \pgfkeysgetvalue{/tikz/graphs/default edge kind}\tikz@lg@default%
      \pgfkeyssetvalue{/tikz/graphs/default edge kind}{-!-}%
      \tikzgraphpreparecolor{#1}\c@pgf@counta{tikz@lg}%
      \tikz@lg@indep@loop%
      \pgfkeyslet{/tikz/graphs/default edge kind}\tikz@lg@default%
    }},
  induced independent set/.default=all
}

\def\tikz@lg@indep@loop{%
  \ifnum\c@pgf@counta=0\relax%
  \else
    \c@pgf@countb=\c@pgf@counta\relax%
    \tikz@lg@indep@loop@inner%
    \advance\c@pgf@counta by-1\relax%
    \expandafter\tikz@lg@indep@loop%
  \fi%
}

\def\tikz@lg@indep@loop@inner{%
  \advance\c@pgf@countb by-1\relax%
  \ifnum\c@pgf@countb>0\relax%
    \tikz@lib@graph@default@new@edge{\csname tikz@lg\the\c@pgf@counta\endcsname}{\csname tikz@lg\the\c@pgf@countb\endcsname}%
    \expandafter\tikz@lg@indep@loop@inner%
  \fi%
}


% 
% The path connector 
%

\tikzgraphsset{
  path/.style={operator={%
      \let\tikz@lg@prev\relax%
        \tikzgraphforeachcolorednode{#1}\tikz@lib@graph@path@do%
  }},   
  path/.default=all,
  induced path/.style={induced independent set={#1},path={#1}},
  induced path/.default=all,
}

\def\tikz@lib@graph@path@do#1{%
  \ifx\tikz@lg@prev\relax%
  \else%
    \tikz@lib@graph@default@new@edge{\tikz@lg@prev}{#1}%
  \fi
  \def\tikz@lg@prev{#1}%
}


% 
% The cycle connector 
%

\tikzgraphsset{
  cycle/.style={operator={%
    \let\tikz@lg@prev\relax%
    \let\tikz@lg@first\relax%
    \tikzgraphforeachcolorednode{#1}\tikz@lib@graph@cycle@do%
    \ifx\tikz@lg@first\relax%
    \else%
      \tikz@lib@graph@default@new@edge{\tikz@lg@prev}{\tikz@lg@first}%
    \fi%
  }},
  cycle/.default=all,
  induced cycle/.style={induced independent set={#1},cycle={#1}},
  induced cycle/.default=all,
}

\def\tikz@lib@graph@cycle@do#1{%
  \ifx\tikz@lg@prev\relax%
    \def\tikz@lg@prev{#1}%
    \let\tikz@lg@first\tikz@lg@prev%
  \else%
    \tikz@lib@graph@default@new@edge{\tikz@lg@prev}{#1}%
    \def\tikz@lg@prev{#1}%
  \fi%
}




% 
% The matching and star connector 
%

\tikzgraphsset{
  matching and star/.style 2 args={operator=%
    {%
      \tikzgraphpreparecolor{#1}\c@pgf@counta{tikz@lg}
      \c@pgf@countb=0\relax%
      \let\tikz@lg@prev\relax
      \tikzgraphforeachcolorednode{#2}\tikz@lib@graph@flow@do%
      \tikz@lib@graph@flow@rest%
    }%
  },
  matching and star/.default={target'}{source'}
}

\def\tikz@lib@graph@flow@do#1{%
  \advance\c@pgf@countb by1\relax%
  \ifnum\c@pgf@countb>\c@pgf@counta\relax%
    \c@pgf@countb=\c@pgf@counta\relax%
  \fi%
  \ifnum\c@pgf@countb>0\relax%
    \tikz@lib@graph@default@new@edge{\csname tikz@lg\the\c@pgf@countb\endcsname}{#1}%
  \fi%
  \def\tikz@lg@prev{#1}%
}

\def\tikz@lib@graph@flow@rest{%
  \ifnum\c@pgf@countb<\c@pgf@counta\relax%
    \ifnum\c@pgf@countb>0\relax%
      \advance\c@pgf@countb by1\relax%
      \tikz@lib@graph@default@new@edge{\csname tikz@lg\the\c@pgf@countb\endcsname}{\tikz@lg@prev}%
      \expandafter\tikz@lib@graph@flow@rest%
    \fi%
  \fi%
}



% 
% The matching connector 
%

\tikzgraphsset{
  matching/.style 2 args={operator=
    {%
      \tikzgraphpreparecolor{#1}\c@pgf@counta{tikz@lg}
      \c@pgf@countb=0\relax%
      \tikzgraphforeachcolorednode{#2}\tikz@lib@graph@matching@do%
    }%
  },
  matching/.default={target'}{source'}
}

\def\tikz@lib@graph@matching@do#1{%
  \advance\c@pgf@countb by1\relax%
  \ifnum\c@pgf@countb>\c@pgf@counta\relax%
  \else%
    \tikz@lib@graph@default@new@edge{\csname tikz@lg\the\c@pgf@countb\endcsname}{#1}%
  \fi%
}





% 
% The butterfly connector 
%

\tikzgraphsset{
  butterfly/.style={operator=
    {}{%
      \pgfkeys{/tikz/graphs/butterfly/.cd,#1}%
      \ifnum\pgfkeysvalueof{/tikz/graphs/butterfly/level}=0\relax%
        \tikzgraphinvokeoperator{matching and star={\pgfkeysvalueof{/tikz/graphs/butterfly/from}}{\pgfkeysvalueof{/tikz/graphs/butterfly/to}}}%
      \else%
        {%
          \tikzgraphpreparecolor{\pgfkeysvalueof{/tikz/graphs/butterfly/from}}\c@pgf@counta{tikz@lg}
          \c@pgf@countb=0\relax%
          \tikzgraphforeachcolorednode{\pgfkeysvalueof{/tikz/graphs/butterfly/to}}\tikz@lib@graph@butterfly@do%
        }%
        \iftikz@butterfly@prime\else\tikzgraphinvokeoperator{matching and star={\pgfkeysvalueof{/tikz/graphs/butterfly/from}}{\pgfkeysvalueof{/tikz/graphs/butterfly/to}}}\fi%
      \fi%
    }%
  },
  butterfly/.default=,
  butterfly/level/.initial=1,
  butterfly/from/.initial=target',
  butterfly/to/.initial=source',
  butterfly'/.style={operator={}{\tikz@butterfly@primetrue\pgfkeysalso{butterfly={#1}}}},
  butterfly'/.default=,
}

\newif\iftikz@butterfly@prime

\def\tikz@lib@graph@butterfly@do#1{%
  \advance\c@pgf@countb by1\relax%
  % Compute other side...
  \c@pgf@countc=\pgfkeysvalueof{/tikz/graphs/butterfly/level}\relax%
  {%
    % Computer countb mod (2level)
    \count0=\c@pgf@countc\relax%
    \multiply\count0 by2\relax%
    \count1=\c@pgf@countb\relax%
    \advance\count1 by-1\relax%
    \count2=\count1\relax%
    \count3=\count1\relax%
    \divide\count1 by\count0\relax%
    \multiply\count1 by\count0\relax%
    \advance\count2 by-\count1\relax%
    % count0 = 2*level
    % count2 = countb mod (2level) (starting with 0)
    % count1 = countb - count2 (starting with 0)
    \ifnum\count2<\c@pgf@countc\relax%
      \advance\count3 by \c@pgf@countc\relax%
    \else%
      \advance\count3 by -\c@pgf@countc\relax%
    \fi%
    \expandafter%
  }%
  \expandafter\c@pgf@countc\the\count3\relax%
  \advance\c@pgf@countc by1\relax%
  \ifnum\c@pgf@countc>\c@pgf@counta\relax%
    \c@pgf@countc=\c@pgf@counta\relax%
  \fi%
  \tikz@lib@graph@default@new@edge{\csname tikz@lg\the\c@pgf@countc\endcsname}{#1}%
}




% 
% The no edges connector 
%
\tikzgraphsset{no edges/.style={operator=\relax}}




%
% The grid connector
%
\tikzgraphsset{
  grid/.style={operator={
      \tikzgraphpreparecolor{#1}\c@pgf@counta{tikz@lg}%
      \c@pgf@countb=0\relax%
      \tikzgraphpreparewrapafter%
      \tikz@lg@grid@loop%
    }%
  },
  grid/.default=all
}

\def\tikzgraphpreparewrapafter{%
  \pgfkeysgetvalue{/tikz/graphs/wrap after}\tikz@temp%
  \ifnum\tikz@temp=0\relax%
    \pgfmathparse{sqrt(\tikzgraphVnum)}%
    \pgfmathint{\pgfmathresult}%
    \edef\tikzgraphwrapafter{\pgfmathresult}%
  \else%
    \edef\tikzgraphwrapafter{\tikz@temp}
  \fi%
}

\def\tikz@lg@grid@loop{%
  \ifnum\c@pgf@counta=0\relax%
  \else%
    \advance\c@pgf@countb by 1\relax%
    \pgfmathmod{\c@pgf@countb-1}{\tikzgraphwrapafter}%
    \pgfmathint{\pgfmathresult}%
    \ifnum\pgfmathresult>0%
      \pgfmathsubtract{\c@pgf@countb}{1}%
      \pgfmathint{\pgfmathresult}%
      \tikz@lib@graph@default@new@edge{\csname tikz@lg\the\c@pgf@countb\endcsname}{\csname tikz@lg\pgfmathresult\endcsname}%
    \fi%
    \pgfmathparse{\c@pgf@countb <= \tikzgraphwrapafter}%
    \ifnum\pgfmathresult=0%
      \pgfmathsubtract{\c@pgf@countb}{\tikzgraphwrapafter}%
      \pgfmathint{\pgfmathresult}%
      \tikz@lib@graph@default@new@edge{\csname tikz@lg\pgfmathresult\endcsname}{\csname tikz@lg\the\c@pgf@countb\endcsname}%
    \fi%
    \advance\c@pgf@counta by-1\relax%
    \expandafter\tikz@lg@grid@loop%
  \fi%
}




% Positioning
%
% It is not the job of the graph library to compute good positions for
% nodes in a graph. However, some basic support is provided for simple
% cases.
% 
% The idea is at follows: Graphs are specified hierarchically. For
% instance, consider the following graph specification:
% 
% graph { a, b, c -> d -> {e -> f -> g, h} -> i, j -> k }
% 
% Here, we have the *group* {e->f->g,h} inside the larger graph
% specification. Each group consists of sequence of *chains* like
% e->f->g or j->k.
% 
% In order to facilitate the automatic positioning of nodes, the graph
% library will provide you with information about the position of
% nodes inside their groups and chains.
% 
% As a chain is being parsed, a counter stored in
% /tikz/graphs/placement/element count is available that is advanced for
% each element in the chain. 
% 
% Additionally, a counter stored in placement/width is
% available. This "logical" width is defined recursively as follows: The
% width of a single node is computed by calling the key
% placement/logical node width, which should return a real or logical
% width of the node passed as a parameter in the macor \pgfmathresult. The
% width of a chain is the sum of the widths of its elements. The
% width of a  group is the maximum of the widths of its elements.
% 
%
% Symmetrically, as a group is being constructed, a counter stored in
% placement/chain count is available that is advanced for each chain
% in the group. The number placement/depth is the defined
% recursively as follows: For a single node, the depth is
% computed by the key placement/logical node depth. The depth
% of a group is the sum of the depths of its elements. The depth of a
% chain is the maximum of the depth of its elements. 
%
% 
% The above keys get updated automatically. You should setup the key
% placement/compute position such that it uses the above keys to
% compute a good position for a new node based on the above
% keys. Typically, this key should execute node={shift=(...)} to setup
% the necessary shift for a new node.
% 
% The key placement/compute position should not be called
% directly. Instead, the key placement/place should be used. This key
% has two effects: First, it calls placement/compute position. Second,
% it resets the length and normal counters. It will setup a completely
% new counting of lengths and counters inside the current scope.
% 
% The placmenet/place key is executed automatically whenever a new
% node is automatically created. Furthermore, placement strategies
% will call this key.

\tikzgraphsset{
  placement/.cd,
  compute position/.code=\tikz@lib@graph@linear@pos,
  place/.code={%
    \pgfkeys{/tikz/graphs/placement/compute position}%
    \aftergroup\tikz@lib@graph@reset@locals%
    \pgfkeyssetvalue{/tikz/graphs/placement/element count}{0}%
    \pgfkeyssetvalue{/tikz/graphs/placement/chain count}{0}%
    \pgfkeyssetvalue{/tikz/graphs/placement/depth}{0}%
    \pgfkeyssetvalue{/tikz/graphs/placement/width}{0}%
    \pgfkeyssetvalue{/tikz/graphs/placement/local depth}{0}%
    \pgfkeyssetvalue{/tikz/graphs/placement/local width}{0}%
  },
  element count/.initial=0,
  chain count/.initial=0,
  depth/.initial=0,
  width/.initial=0,
  level/.initial=0,
  logical node depth/.code=\def\pgfmathresult{1},
  logical node width/.code=\def\pgfmathresult{1},
}

\def\tikz@lib@graph@reset@locals{%
  \gdef\tikz@lib@graph@group@depth{0}%
  \gdef\tikz@lib@graph@group@width{0}%
}


% Arrange nodes evenly 
% 
% This strategy works as follows: You specify a "chain shift vector"
% and a "group shift vector". Then each new element on a chain is
% shifted by the chain shift vector relative to the previous element
% on the chain. Similarly for each new element of a group. 

\tikzgraphsset{
  Cartesian placement/.style={
    placement/place,
    placement/compute position/.code=\tikz@lib@graph@linear@pos%
  },
  chain shift/.initial={(1,0)},
  group shift/.initial={(0,-1)},
  grow right/.style={
    placement/place,
    chain shift={(#1,0)},
    @auto anchor horizontal=center,
    placement/logical node width/.code=\def\pgfmathresult{1}
  },
  grow right/.default=1,
  grow left/.style={
    placement/place,
    chain shift={(-#1,0)},
    @auto anchor horizontal=center,
    placement/logical node width/.code=\def\pgfmathresult{1}
  },
  grow left/.default=1,
  grow up/.style={
    placement/place,
    chain shift={(0,#1)},
    @auto anchor horizontal=center,
    placement/logical node width/.code=\def\pgfmathresult{1}
  },
  grow up/.default=1,
  grow down/.style={
    placement/place,
    chain shift={(0,-#1)},
    @auto anchor vertical=center,
    placement/logical node width/.code=\def\pgfmathresult{1}
  },
  grow down/.default=1,
  branch right/.style={
    placement/place,
    group shift={(#1,0)},
    @auto anchor horizontal=center,
    placement/logical node depth/.code=\def\pgfmathresult{1}
  },
  branch right/.default=1,
  branch left/.style={
    placement/place,
    group shift={(-#1,0)},
    @auto anchor horizontal=center,
    placement/logical node depth/.code=\def\pgfmathresult{1}
  },
  branch left/.default=1,
  branch up/.style={
    placement/place,
    group shift={(0,#1)},
    @auto anchor vertical=center,
    placement/logical node depth/.code=\def\pgfmathresult{1}
  },
  branch up/.default=1,
  branch down/.style={
    placement/place,
    group shift={(0,-#1)},
    @auto anchor vertical=center,
    placement/logical node depth/.code=\def\pgfmathresult{1}
  },
  branch down/.default=1,
  % 
  % Sep shifts 
  % 
  grow right sep/.style={
    Cartesian placement,
    chain shift={(1pt,0)},
    @auto anchor horizontal=west,
    placement/logical node width/.code=\tikz@lib@graph@width@sep{##1}{#1}
  },
  grow right sep/.default=1em,
  grow left sep/.style={
    Cartesian placement,
    chain shift={(-1pt,0)},
    @auto anchor horizontal=east,
    placement/logical node width/.code=\tikz@lib@graph@width@sep{##1}{#1}
  },
  grow left sep/.default=1em,
  grow up sep/.style={
    Cartesian placement,
    chain shift={(0,1pt)},
    @auto anchor vertical=south,
    placement/logical node width/.code=\tikz@lib@graph@depth@sep{##1}{#1}
  },
  grow up sep/.default=1em,
  grow down sep/.style={
    Cartesian placement,
    chain shift={(0,-1pt)},
    @auto anchor vertical=north,
    placement/logical node width/.code=\tikz@lib@graph@depth@sep{##1}{#1}
  },
  grow down sep/.default=1em,
  grow right sep/.style={
    Cartesian placement,
    chain shift={(1pt,0)},
    @auto anchor horizontal=west,
    placement/logical node width/.code=\tikz@lib@graph@width@sep{##1}{#1}
  },
  %
  branch right sep/.style={
    Cartesian placement,
    group shift={(1pt,0)},
    @auto anchor horizontal=west,
    placement/logical node depth/.code=\tikz@lib@graph@width@sep{##1}{#1}
  },
  branch right sep/.default=1em,
  branch left sep/.style={
    Cartesian placement,
    group shift={(-1pt,0)},
    @auto anchor horizontal=east,
    placement/logical node depth/.code=\tikz@lib@graph@width@sep{##1}{#1}
  },
  branch left sep/.default=1em,
  branch up sep/.style={
    Cartesian placement,
    group shift={(0,1pt)},
    @auto anchor vertical=south,
    placement/logical node depth/.code=\tikz@lib@graph@depth@sep{##1}{#1}
  },
  branch up sep/.default=1em,
  branch down sep/.style={
    Cartesian placement,
    group shift={(0,-1pt)},
    @auto anchor vertical=north,
    placement/logical node depth/.code=\tikz@lib@graph@depth@sep{##1}{#1}
  },
  branch down sep/.default=1em,
  %
  @auto anchor horizontal/.style={
    nodes={anchor=\csname tikz@lib@graph@auto@\tikz@lib@graph@auto@h @\tikz@lib@graph@auto@v\endcsname},
    /utils/exec=\def\tikz@lib@graph@auto@h{#1}
  },
  @auto anchor vertical/.style={
    nodes={anchor=\csname tikz@lib@graph@auto@\tikz@lib@graph@auto@h @\tikz@lib@graph@auto@v\endcsname},
    /utils/exec=\def\tikz@lib@graph@auto@v{#1}
  },
  % 
  % 
  no placement/.style={
    placement/place,
    placement/compute position/.code=%
  }
}

\def\tikz@lib@graph@auto@h{center}
\def\tikz@lib@graph@auto@v{center}

\def\tikz@lib@graph@auto@center@center{center}
\def\tikz@lib@graph@auto@west@center{west}
\def\tikz@lib@graph@auto@east@center{east}
\def\tikz@lib@graph@auto@center@north{north}
\def\tikz@lib@graph@auto@west@north{north west}
\def\tikz@lib@graph@auto@east@north{north east}
\def\tikz@lib@graph@auto@center@south{south}
\def\tikz@lib@graph@auto@west@south{south west}
\def\tikz@lib@graph@auto@east@south{south east}

\def\tikz@lib@graph@linear@pos{%
  \pgfkeysgetvalue{/tikz/graphs/chain shift}\tikz@temp
  \expandafter\tikz@scan@one@point\expandafter\pgf@process\tikz@temp
  \pgf@process{\pgfpointscale{\pgfkeysvalueof{/tikz/graphs/placement/width}}{}}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \pgfkeysgetvalue{/tikz/graphs/group shift}\tikz@temp
  \expandafter\tikz@scan@one@point\expandafter\pgf@process\tikz@temp
  \pgf@process{\pgfpointscale{\pgfkeysvalueof{/tikz/graphs/placement/depth}}{}}%
  \advance\pgf@xa by\pgf@x%
  \advance\pgf@ya by\pgf@y%
  \edef\tikz@lib@graph@shift{(\the\pgf@xa,\the\pgf@ya)}
  \pgfkeys{/tikz/graphs/nodes/.expanded={shift={\tikz@lib@graph@shift}}}
}


\def\tikz@lib@graph@width@sep#1#2{%
  \pgf@process{\pgfpointdiff{\pgfpointanchor{#1}{west}}{\pgfpointanchor{#1}{east}}}%
  \pgfmathparse{#2+\the\pgf@x}%
}

\def\tikz@lib@graph@depth@sep#1#2{%
  \pgf@process{\pgfpointdiff{\pgfpointanchor{#1}{south}}{\pgfpointanchor{#1}{north}}}%
  \pgfmathparse{#2+\the\pgf@y}%
}


% Circular arrangements 
% 
% This strategy works a bit like the arrange evenly strategy, but in
% polar coordinates. Both for the chains and the groups you specify a
% polar shift, which must be in the form "(delta degree:delta
% distance)". For each element in a chain, the delta degree is added
% to the chain degree, likewise for each element the delta distance is
% added. Similarly for groups.
% 
% There is an initial degree and radius, stored in the key "phase" and
% "radius".

\tikzgraphsset{,
  circular placement/.style={
    placement/place,
    placement/compute position/.code=\tikz@lib@graph@circular@pos,%
    placement/logical node depth/.code=\def\pgfmathresult{1},
    placement/logical node width/.code=\def\pgfmathresult{1},
  },
  clockwise/.style={
    circular placement,
    group polar shift={(-360/#1:0)}
  },
  clockwise/.default=\tikzgraphVnum,
  counterclockwise/.style={
    circular placement,
    group polar shift={(360/#1:0)}
  },
  counterclockwise/.default=\tikzgraphVnum,
  chain polar shift/.initial={(0:1cm)},
  group polar shift/.initial={(60:0)},
  radius/.initial=1cm,
  phase/.initial=90,
}

\def\tikz@lib@graph@circular@pos{%
  \pgfkeysgetvalue{/tikz/graphs/chain polar shift}\tikz@temp
  \expandafter\tikz@lib@graph@decompose@polar\tikz@temp%
  \pgf@process{\pgfpointscale{\pgfkeysvalueof{/tikz/graphs/placement/width}}{}}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \pgfkeysgetvalue{/tikz/graphs/group polar shift}\tikz@temp
  \expandafter\tikz@lib@graph@decompose@polar\tikz@temp%
  \pgf@process{\pgfpointscale{\pgfkeysvalueof{/tikz/graphs/placement/depth}}{}}%
  \advance\pgf@xa by\pgf@x%
  \advance\pgf@ya by\pgf@y%
  \pgfmathparse{\pgfkeysvalueof{/tikz/graphs/radius}}%
  \advance\pgf@ya by\pgfmathresult pt%
  \pgfmathsetmacro\tikz@temp{\the\pgf@xa+\pgfkeysvalueof{/tikz/graphs/phase}}%
  \edef\tikz@lib@graph@shift{(\tikz@temp:\the\pgf@ya)}
  \pgfkeys{/tikz/graphs/nodes/.expanded={shift={\tikz@lib@graph@shift}}}
}


\def\tikz@lib@graph@decompose@polar(#1:#2){%
  \pgfmathsetlength\pgf@x{#1}%
  \pgfmathsetlength\pgf@y{#2}%
}


% Grid arrangements
%
\tikzgraphsset{
  grid placement/.style={
    placement/place,
    placement/compute position/.code=\tikz@lib@graph@grid@pos,%
  },
}


\def\tikz@lib@graph@grid@pos{%
  %
  % Make sure to set \tikzgraphwrapafter before we compute
  % the positions of nodes in the grid
  %
  \tikzgraphpreparewrapafter%
  %
  % find out the coordinate in the grid
  %
  \pgfkeysgetvalue{/tikz/graphs/placement/depth}\tikz@temp@depth%
  \pgfkeysgetvalue{/tikz/graphs/placement/width}\tikz@temp@width%
  \pgfmathsetmacro{\tikz@temp}{max(\tikz@temp@depth, \tikz@temp@width)}%
  \pgfmathsetmacro{\tikz@temp@col}{mod(\tikz@temp,\tikzgraphwrapafter)}%
  \pgfmathsetmacro{\tikz@temp@row}{div(\tikz@temp,\tikzgraphwrapafter)}%
  %
  % multiply row by the group shift and col by the chain shift
  %
  \pgfkeysgetvalue{/tikz/graphs/group shift}\tikz@temp%
  \expandafter\tikz@scan@one@point\expandafter\tikz@lib@graph@grid@pos@a\tikz@temp%
  \pgfkeysgetvalue{/tikz/graphs/chain shift}\tikz@temp%
  \expandafter\tikz@scan@one@point\expandafter\tikz@lib@graph@grid@pos@b\tikz@temp%  
  %
  % apply the shift
  %
  \edef\tikz@lib@graph@shift{(\the\pgf@xa,\the\pgf@ya)}
  \pgfkeys{/tikz/graphs/nodes/.expanded={shift={\tikz@lib@graph@shift}}}
}

\def\tikz@lib@graph@grid@pos@a#1{\pgf@process{\pgfpointscale{\tikz@temp@row}{#1}}\pgf@xa=\pgf@x\relax\pgf@ya=\pgf@y\relax}
\def\tikz@lib@graph@grid@pos@b#1{\pgf@process{\pgfpointscale{\tikz@temp@col}{#1}}%
  \advance\pgf@xa by\pgf@x\relax
  \advance\pgf@ya by\pgf@y\relax}

\tikzgraphsset{
  % Grids:
  wrap after/.initial=0,
  % Node sets:
  V/.code={%
    \def\tikzgraphV{#1}
    \c@pgf@counta=0\foreach \tikz@dummy in {#1} {\global\advance\c@pgf@counta by1\relax}
    \edef\tikzgraphVnum{\the\c@pgf@counta}
  },
  V={1},
  n/.style={V={1,...,#1},name shore V/.style={name=V}},
  W/.code={%
    \def\tikzgraphW{#1}
    \c@pgf@counta=0\foreach \tikz@dummy in {#1} {\global\advance\c@pgf@counta by1\relax}
    \edef\tikzgraphWnum{\the\c@pgf@counta}
  },
  W={1},
  m/.style={W={1,...,#1},name shore W/.style={name=W}},
  % Shores:
  name shore V/.style=,
  name shore W/.style=,
}



%
% Quick graphs
%
% Parsing the graph syntax can take a lot of time for large
% graphs. This is mainly due to the transformation of commas and
% semicolons and all the internal bookkeeping.
%
% For large graphs, the quick graph syntax offers a greatly reduced
% syntax that will be processed much more quickly. This syntax is
% compatible with the normal graph syntax in the sense that all
% specifications written in the reduced syntax are also legal in the
% normal syntax, but not the other way round.
%
% The following rules apply:
%
% 1) A quick graph consists of a sequence of either nodes, edges sequences, or
% groups. These are separated by commas or semicolons.
%
% 2) Every node is of the form
%
% "node name"/"node text"[options]
%
% Here, the quotation marks are mandatory. The part '/"node text"' may
% be missing, in which case the node name is used as the node
% text. The options may also be missing. The node name may not contain
% any "funny" characters (unlike in the normal graph command).
%
% 3) Every edge is of the form
%
% <node spec> <connector> <node spec> <connector> <node spec> ... <connector> <node spec>;
%
% Here, the <node spec> are node specifications as described above,
% the <connector> is one of the four connectors "->", "<-", "--", and
% "<->", followed by optional options in square
% brackets. The semicolon may be replaced by a comma.
%
% 4) Every group is of the form
%
% { [options] lines };
%
% The options are compulsory, the lines must be a sequence of nodes,
% edges, and groups as described above. The semicolon can, again, be
% replaced by a comma.
%
%
% Things that are allowed in the normal syntax, but not in the quick
% syntax, include: 
%
% - Connecting a node and a group as in a->{b,c}.
% - Node names without quotation marks.
% - Using subgraphs (graph macros).
% - Using graph sets.
% - Using graph color classes.
% - Using anonymous nodes.
% - Using the "fresh nodes" option.
% - Using sublayouts.
% - Using the -!- edge connector.
% - Using the "simple" option.
% - Using edge annotations.
%
% Example:
%
% \graph [quick] {
%   "a"/"$a$"[red] -> "b"[blue] -> "c";
%   "b"            -> "d";
%   "c"            ->[thick] "e";
%   { [same layer] "c", "d" };
% };
%
%

\tikzgraphsset{quick/.is if=tikz@graph@quick}
\newif\iftikz@graph@quick

\def\tikz@lib@graphs@parse@quick@graph{
  % Ok, we are before the initial brace. We open a group and start
  % setting up some bookkeeping
  \begingroup%
  \global\tikz@qnode@count0\relax%
  \let\tikzgraphnodepath\pgfutil@empty%
  \tikz@q@outertrue%
  \afterassignment\tikz@lib@graphs@quick@main\let\pgf@temp=%
}

\newcount\tikz@qnode@count
\newif\iftikz@q@outer

\def\tikz@lib@graphs@quick@main{%
  \afterassignment\tikz@lib@graphs@quick@handle\let\pgf@let@token=%
}
\def\tikz@lib@graphs@quick@handle{%
  \ifx\pgf@let@token"%
    \expandafter\tikz@lib@graphs@quick@first@node%
  \else%
    \expandafter\tikz@lib@graphs@quick@other%
  \fi%
}
\def\tikz@lib@graphs@quick@other{%
  \let\tikz@next\tikz@lib@graphs@quick@error%
  \ifx\pgf@let@token\egroup%
    \let\tikz@next\tikz@lib@graphs@quick@end@group%
  \else%
    \ifx\pgf@let@token\bgroup%
      \let\tikz@next\tikz@lib@graphs@quick@start@group%
    \else%
      \ifx\pgf@let@token\par%
        \let\tikz@next\tikz@lib@graphs@quick@main%
      \fi%
    \fi
  \fi%  
  \tikz@next%
}

\def\tikz@lib@graphs@quick@error#1{\tikzerror{Unexpected token '\string#1' in quick graph syntax}\tikz@lib@graphs@quick@main}
\def\tikz@lib@graphs@quick@start@group{%
  \pgfutil@ifnextchar[\tikz@lib@graphs@quick@start@group@{\tikzerror{Group
      in quick graph syntax must start with options.}}
}

\def\tikz@lib@graphs@quick@start@group@[#1]{%
  \begingroup%
    \tikz@q@outerfalse%
    \tikzgraphsset{#1}%
    \tikz@lib@graphs@quick@main%
}
\def\tikz@lib@graphs@quick@end@group{%
  \iftikz@q@outer%
    \endgroup%
    % Ok, cleanup!
    \pgfutil@loop%
    \ifnum\tikz@qnode@count>0\relax%
      \expandafter\global\expandafter\let\csname tikz@gr@q@@\csname tikz@gr@qn@@\the\tikz@qnode@count\endcsname\endcsname\relax%
      \expandafter\global\expandafter\let\csname tikz@gr@qn@@\the\tikz@qnode@count\endcsname\relax%
      \global\advance\tikz@qnode@count by-1\relax%  
    \pgfutil@repeat%
    \expandafter\tikz@lib@graph@main@done%
  \else%
    \endgroup%
    \expandafter\tikz@lib@graphs@end@group@%  
  \fi%  
}
\def\tikz@lib@graphs@end@group@{%
  \pgfutil@ifnextchar;{\expandafter\tikz@lib@graphs@quick@main\pgfutil@gobble}{%
    \pgfutil@ifnextchar,{\expandafter\tikz@lib@graphs@quick@main\pgfutil@gobble}{%
      \tikzerror{Graph groups in quick syntax must be followed by a semicolon or a comma.}%
    }%
  }%
}


\def\tikz@lib@graphs@quick@first@node{%
  \let\tikz@quick@prev@node\relax%
  \tikz@lib@graphs@quick@node%
}

\def\tikz@lib@graphs@quick@node#1"{%
  \def\tikzgraphnodename{#1}%
  \pgfutil@ifnextchar/\tikz@lib@graphs@quick@text\tikz@lib@graphs@quick@notext%
}
\def\tikz@lib@graphs@quick@text/"#1"{%
  \def\tikzgraphnodetext{#1}%
  \tikz@lib@graphs@quick@opt%
}
\def\tikz@lib@graphs@quick@notext{%
  \let\tikzgraphnodetext\tikzgraphnodename%
  \tikz@lib@graphs@quick@opt%
}
\def\tikz@lib@graphs@quick@opt{%
  \pgfutil@ifnextchar[\tikz@lib@graphs@quick@withopt{\tikz@lib@graphs@quick@withopt[]}%]
}
\def\tikz@lib@graphs@quick@withopt[#1]{%
  % Test, whether node already exists
  \expandafter\ifx\csname tikz@gr@q@@\tikzgraphnodename\endcsname\relax%
    % New node
    \global\advance\tikz@qnode@count by1\relax%
    \expandafter\global\expandafter\let\csname tikz@gr@q@@\tikzgraphnodename\endcsname\pgfutil@empty% not relax
    \expandafter\global\expandafter\let\csname tikz@gr@qn@@\the\tikz@qnode@count\endcsname\tikzgraphnodename% back pointer
    \let\tikzgraphnodefullname\tikzgraphnodename%
    \let\tikzgraphnodeas\tikzgraphnodeas@default%
    \node [%
      name=\tikzgraphnodename,%
      graphs/redirect unknown to tikz,
      /tikz/graphs/.cd,%
      /tikz/graphs/@nodes styling,%
      #1]%
      {%
        \tikzgraphnodeas%
      };%
  \else%
    %  
    % Handle late options and operators
    \tikzgdlatenodeoptionacallback{\tikzgraphnodename}%
    \node also[graphs/redirect unknown to tikz,/tikz/graphs/.cd,#1](\tikzgraphnodename);%
  \fi%
  % Connect, if necessary 
  \tikz@lig@graph@quikc@make@edge@if@necessary%
  \tikz@lib@graphs@quick@scan@after@node%
}

\def\tikz@lig@graph@quikc@make@edge@if@necessary{%
  \ifx\tikz@quick@prev@node\relax%
  \else%
    \tikz@lib@graphs@quick@make@edge%
  \fi%
}

\def\tikz@lib@graphs@quick@scan@after@node{%
  \pgfutil@ifnextchar,\tikz@lib@graphs@quick@comma{%
    \pgfutil@ifnextchar;\tikz@lib@graphs@quick@semi{%
      \pgfutil@ifnextchar\egroup{\tikz@lib@graphs@quick@semi;}{%
        \pgfutil@ifnextchar\par{\expandafter\tikz@lib@graphs@quick@scan@after@node\tikz@lib@graphs@quick@gobble@par}%
        \tikz@lib@graphs@quick@connector}}}%    
}
\long\def\tikz@lib@graphs@quick@gobble@par#1{}%

\def\tikz@lib@graphs@quick@comma,{\tikz@lib@graphs@quick@main}
\def\tikz@lib@graphs@quick@semi;{\tikz@lib@graphs@quick@main}
\def\tikz@lib@graphs@quick@connector#1#2{%
  \def\tikz@lib@graphs@quick@edge@kind{#1#2}%
  \pgfutil@ifnextchar>\tikz@lib@graphs@back@edge{%
    \pgfutil@ifnextchar[\tikz@lib@graphs@quick@connector@handle@opt{\tikz@lib@graphs@quick@connector@handle@opt[]}%]
  }%
}
\def\tikz@lib@graphs@back@edge#1{%
  \expandafter\def\expandafter\tikz@lib@graphs@quick@edge@kind\expandafter{\tikz@lib@graphs@quick@edge@kind#1}%
  \pgfutil@ifnextchar[\tikz@lib@graphs@quick@connector@handle@opt{\tikz@lib@graphs@quick@connector@handle@opt[]}%]
}
\def\tikz@lib@graphs@quick@connector@handle@opt[#1]{%
  \def\tikz@lib@graphs@quick@edge@options{#1}%
  \let\tikz@quick@prev@node\tikzgraphnodename%
  \tikz@lib@graphs@quick@scan@after@connector%
}
\def\tikz@lib@graphs@quick@scan@after@connector{%
  \pgfutil@ifnextchar\par{\expandafter\tikz@lib@graphs@quick@scan@after@connector\tikz@lib@graphs@quick@gobble@par}{%
    \pgfutil@ifnextchar"{\expandafter\tikz@lib@graphs@quick@node\pgfutil@gobble}{%
      \tikzerror{Quotation marks expected after edge connector}%
      }%
  }%
}

\def\tikz@lib@graphs@quick@make@edge{%
  {
    \expandafter\tikz@lib@graphs@quick@make@edge@styling\expandafter{\tikz@lib@graphs@quick@edge@options}%
    \expandafter\expandafter\expandafter\tikz@lib@graphs@quick@make@edge@for%
    \expandafter\expandafter\expandafter{\expandafter\tikz@quick@prev@node\expandafter}\expandafter{\tikzgraphnodename}%
  }
}

\def\tikz@lib@graphs@quick@make@edge@styling#1{%
  \tikz@enable@edge@quotes%
  \tikzgraphsset{.unknown/.code=\tikz@lib@graph@unknown@edge@option{##1},#1}%
}

\def\tikz@lib@graphs@quick@make@edge@for#1#2{%
  \pgfkeysgetvalue{/tikz/graphs/@edges styling}\pgf@tempa
  \pgfkeysgetvalue{/tikz/graphs/@edges node}\pgf@temp@b
  \expandafter\expandafter\expandafter\tikz@lib@graphs@quick@make@edge@for@with%
  \expandafter\expandafter\expandafter{\expandafter\pgf@tempa\expandafter}\expandafter{\pgf@temp@b}{#1}{#2}%
}

\def\tikz@lib@graphs@quick@make@edge@for@with#1#2#3#4{%
  \tikzgraphsset{new \tikz@lib@graphs@quick@edge@kind={#3}{#4}{#1}{#2}}%
}

\endinput

tikzlibrarygraphs.standard.code.tex
% Copyright 2010 by Till Tantau
% Copyright 2011 by Jannis Pohlmann
%
% 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/graphs/tikzlibrarygraphs.standard.code.tex,v 1.9 2012/02/27 20:00:11 tantau Exp $


%
% Basic graphs
%


\tikzgraphsset{
  %
  % An independent set $V$ of nodes.
  %
  declare={subgraph I_n}%
  {
    \foreach \tikz@lib@graph@node@num in \tikzgraphV
    { \tikz@lib@graph@node@num }
  },
  %
  % An two-shore independent set $V$ with shores V and W.
  %
  declare={subgraph I_nm}%
  {
    subgraph I_n [name shore V] -- [no edges]
    subgraph I_n [name shore W, V/.expand once=\tikzgraphW]
  },
  %
  % The complete clique on $V$.
  %
  declare={subgraph K_n}%
  {
    [clique]
    subgraph I_n
  },
  %
  % A complete bipartite graph with shores V and W.
  % 
  declare={subgraph K_nm}%
  {
    [color class=shore V, 
     color class=shore W,
     complete bipartite={shore V}{shore W}]
    subgraph I_n [name shore V, shore V] -- [no edges]
    subgraph I_n [name shore W, V/.expand once=\tikzgraphW, shore W]
  },
  % 
  % A cycle with n nodes.
  %
  declare={subgraph C_n}%
  {
    [cycle]
    subgraph I_n
  },
  % 
  % A path with n nodes.
  % 
  declare={subgraph P_n}%
  {
    [path]
    subgraph I_n
  },
  %
  % A grid with n nodes.
  %
  declare={subgraph Grid_n}%
  {
    [grid]
    subgraph I_n
  },
  %
  % A random graph according to the G_{n,p} model: For each pair of
  % vertices there is an edge between them with probability p. 
  % 
  p/.initial=0.5,
  declare={subgraph G_np}%
  {
    [/utils/exec={
      \pgfmathsetmacro\tikz@lib@lg@p{\pgfkeysvalueof{/tikz/graphs/p}}
      \let\tikz@lib@gnp@edges\pgfutil@empty%
      \foreach \tikz@lib@graph@node@a [count=\tikz@lib@g@count@a] in \tikzgraphV
        \foreach \tikz@lib@graph@node@b [count=\tikz@lib@g@count@b] in \tikzgraphV
        {
          \ifnum\tikz@lib@g@count@a<\tikz@lib@g@count@b\relax
            \pgfmathparse{rnd}
            \ifdim\pgfmathresult pt<\tikz@lib@lg@p pt%
              \ifx\tikz@lib@gnp@edges\pgfutil@empty
                \xdef\tikz@lib@gnp@edges{\tikz@lib@graph@node@a--\tikz@lib@graph@node@b}%
              \else
                \xdef\tikz@lib@gnp@edges{\tikz@lib@gnp@edges,\tikz@lib@graph@node@a--\tikz@lib@graph@node@b}%
              \fi
            \fi
          \fi
        }
      }]
      \foreach \tikz@lg@temp in \tikz@lib@gnp@edges {
        [parse/.expand once=\tikz@lg@temp]
      }
  },
}





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

tikzlibrarylindenmayersystems.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.

\usepgflibrary{lindenmayersystems}

\def\tikz@@lsystem-system{%
	\pgfutil@ifnextchar[{\tikz@lsystem@options}{\tikz@lsystem@options[]}}

\def\tikz@lsystem indenmayer system{%
	\pgfutil@ifnextchar[{\tikz@lsystem@options}{\tikz@lsystem@options[]}}

\def\tikz@lsystem@options[#1]{%
	\tikzset{#1}%
	\ifx\tikz@lsystem@rules\pgfutil@empty%
	\else%
		\tikz@lsystem@declare%
		\def\tikz@lsystem@name{tikz@temp}%
	\fi%
	\ifx\tikz@lsystem@anchor\pgfutil@empty%
		\pgfpathmoveto{\pgfqpoint{\tikz@lastxsaved}{\tikz@lastysaved}}%
		\pgflindenmayersystem{\tikz@lsystem@name}{\tikz@lsystem@axiom}{\tikz@lsystem@order}%
	\else%
		\pgfextract@process\tikz@lsystem@pos{\pgfqpoint{\tikz@lastxsaved}{\tikz@lastysaved}}%
		\setbox\pgfnodeparttextbox=\hbox{%
			\pgfinterruptpicture%
			\pgfpicture%
				\pgfpathmoveto{\pgfpointorigin}%
				\pgflindenmayersystem{\tikz@lsystem@name}{\tikz@lsystem@axiom}{\tikz@lsystem@order}%
				\begingroup%
					\tikz@finish%
			\endpgfpicture%
			\endpgfinterruptpicture%
		}%
		{%
			\pgftransformshift{\tikz@lsystem@pos}%
			\tikzset{inner sep=0pt, outer sep=0pt, minimum size=0pt}%
			\pgfmultipartnode{rectangle}{\tikz@lsystem@anchor}{lindenmayer system}{\pgfusepath{discard}}%
		}%		
	\fi%
	\tikz@scan@next@command}

\tikzset{%
	lindenmayer system/.style={/pgf/lindenmayer system/.cd, #1,/tikz/.cd},
	l-system/.style={lindenmayer system={#1}},
}
\pgfkeys{/pgf/lindenmayer system/.cd,
	name/.code=\edef\tikz@lsystem@name{#1}\let\tikz@lsystem@rules=\pgfutil@empty,%
	axiom/.store in=\tikz@lsystem@axiom,%
	order/.store in=\tikz@lsystem@order,
	.unknown/.code={%
		\pgfutil@ifundefined{pgf@lsystem@\pgfkeyscurrentname}{%
			\pgfkeys{/errors/unknown key={/pgf/lindenmayer system/\pgfkeyscurrentname}{#1}}%
			\let\tikz@lsystem@name=\pgfutil@empty%
		}%
		{\edef\tikz@lsystem@name{\pgfkeyscurrentname}}
	},%
	anchor/.store in=\tikz@lsystem@anchor,%
	rule set/.store in=\tikz@lsystem@rules
}
\let\tikz@lsystem@anchor=\pgfutil@empty%
\let\tikz@lsystem@rules=\pgfutil@empty%

\def\tikz@lsystem@declare{%
	\expandafter\let\csname pgf@lsystem@tikz@temp\endcsname=\relax%
	\pgfdeclarelindenmayersystem{tikz@temp}{%
		\expandafter\tikz@lsystem@parse@rules\tikz@lsystem@rules,\tikz@stop,%
	}%
}
\def\tikz@lsystem@parse@rules#1,{%
	\ifx#1\tikz@stop%
	\else%
		\rule{#1}%
		\expandafter\tikz@lsystem@parse@rules%
	\fi%
}

tikzlibrarymath.code.tex
% Copyright 2013 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.



\edef\tikz@math@at@catcode{\the\catcode`\@}
\catcode`\@=11

\def\tikz@math@gobblespaces#1{\pgfutil@ifnextchar x{#1}{#1}}

\def\tikz@math@meaning@macro{macro}
\def\tikz@math@meaning@dimen{dimen}
\def\tikz@math@meaning@count{count}
\def\tikz@math@meaning@null{null}

\def\tikz@math@getmeaning#1{\expandafter\tikz@math@@getmeaning\meaning#1\tikz@math@getmeaning@stop}

\def\tikz@math@@getmeaning#1#2#3#4#5\tikz@math@getmeaning@stop{%
	\if#1u% undefined
		\let\tikz@math@meaning=\tikz@math@meaning@macro%
	\else%
		\if#1m%
			\let\tikz@math@meaning=\tikz@math@meaning@macro%
		\else%
			\if#2d%
				\let\tikz@math@meaning=\tikz@math@meaning@dimen%
			\else%
				\if#2c%
					\let\tikz@math@meaning=\tikz@math@meaning@count%
				\else%
					\if#3k% A skip. Treat like a dimen.
						\let\tikz@math@meaning=\tikz@math@meaning@dimen%
					\else%
						\let\tikz@math@meaning=\tikz@math@meaning@null%
					\fi%
				\fi%
			\fi%
		\fi%
	\fi%
}

\def\tikz@math@firstoftwo#1#2{#1}
\def\tikz@math@secondoftwo#1#2{#2}


\def\tikz@math@getvarstring#1{%
	\begingroup%
		\escapechar=-1\relax%
		\expandafter\tikz@math@@getvarstring\string#1\tikz@math}

\def\tikz@math@@getvarstring#1\tikz@math#2{%
	\endgroup%
	\def#2{#1}%		
}

\long\def\tikz@math@collecttosemicolon@other#1#2;{%
	\def\tikz@math@collected{#2}#1}
\def\tikz@math@semicolon@other{;}%

{\catcode`\;=13
\long\gdef\tikz@math@collecttosemicolon@active#1#2;{%
	\def\tikz@math@collected{#2}#1}
\gdef\tikz@math@semicolon@active{;}%
}


\def\tikz@math@setvartype#1#2{%
	\expandafter\let\csname tikz@math@var@vartype@\string#1\endcsname=#2%
}


\def\tikz@math@getvartype#1#2{%
	\def\tikz@math@marshal{\let#1=}%
	\expandafter\tikz@math@marshal\csname 
	tikz@math@var@vartype@\string#2\endcsname%
}



\def\tikz@math@ifvarcoordinate#1{%
	\expandafter\ifx\csname 
	tikz@math@var@vartype@\string#1\endcsname\tikz@math@keyword@coordinate%
		\let\tikz@math@next=\tikz@math@firstoftwo%
	\else%
		\let\tikz@math@next=\tikz@math@secondoftwo%
	\fi%
	\tikz@math@next%
}

\def\tikz@math@ifvarinteger#1{%
	\expandafter\ifx\csname 
	tikz@math@var@vartype@\string#1\endcsname\tikz@math@keyword@integer%
		\let\tikz@math@next=\tikz@math@firstoftwo%
	\else%
		\let\tikz@math@next=\tikz@math@secondoftwo%
	\fi%
	\tikz@math@next%
}


\def\tikz@math@setvarindexed#1{%
	\expandafter\let\csname 
	tikz@math@var@subtype@\string#1\endcsname=\tikz@math@subtype@indexed%
}

\def\tikz@math@clearvarindexed#1{%
	\expandafter\let\csname tikz@math@var@subtype@\string#1\endcsname=\relax%
}

\def\tikz@math@ifvarindexed#1{%
	\expandafter\ifx\csname tikz@math@var@subtype@\string#1\endcsname\relax%
		\let\tikz@math@next=\tikz@math@secondoftwo%
	\else%
		\let\tikz@math@next=\tikz@math@firstoftwo%
	\fi%
	\tikz@math@next%
}

\def\tikz@math@stop{@}

\let\tikz@math@parse@hook@before=\pgfutil@empty
\let\tikz@math@parse@hook@after=\pgfutil@empty

\def\tikz@math{%
	\ifnum\catcode`\;=13\relax%
		\let\tikz@math@semicolon=\tikz@math@semicolon@active%
		\let\tikz@math@collecttosemicolon=\tikz@math@collecttosemicolon@active%
	\else%
		\let\tikz@math@semicolon=\tikz@math@semicolon@other%
		\let\tikz@math@collecttosemicolon=\tikz@math@collecttosemicolon@other%
	\fi%
	\tikz@math@parse@hook@before%
	\tikz@@math}




\long\def\tikz@@math#1{%
	\def\tikz@math@marshal{\tikz@math@parse#1}%
	\expandafter\expandafter\expandafter\tikz@math@marshal\expandafter\tikz@math@stop\tikz@math@semicolon}
	
\def\tikz@math@parse{\pgfutil@ifnextchar\bgroup\tikz@math@@parse@bgroup\tikz@math@@parse@nobgroup}


\def\tikz@math@@parse@bgroup{%
	\tikz@math@collecttosemicolon{%
		% MW: Don't know how reliable this test is.
		\ifx\pgf@selectfontorig\tikz@math@undefined%
			\begingroup\tikz@math@collected\endgroup%
		\else%
			\begingroup\csname nullfont\endcsname\tikz@math@collected\endgroup%
		\fi\tikz@math@parse}}
	


\def\tikz@math@@parse@nobgroup{\tikz@math@collecttosemicolon{\tikz@math@@parse@@nobgroup}}

\def\tikz@math@@parse@@nobgroup{%
	\let\tikz@math@tmp=\tikz@math@collected%
	\ifx\tikz@math@tmp\tikz@math@stop%
		\def\tikz@math@next{\expandafter\tikz@math@parse@finish\tikz@math@semicolon}%
	\else%
		\def\tikz@math@next{\expandafter\expandafter\expandafter\tikz@math@parse@keyword@check\expandafter\tikz@math@tmp\tikz@math@semicolon}%
	\fi%
	\tikz@math@next%
}

\def\tikz@math@parse@finish{%
	\tikz@math@collecttosemicolon{\tikz@math@parse@hook@after}%
}



\newif\iftikz@math@let
\def\tikz@math@parse@keyword@check#1{%
	\tikz@math@letfalse%
	\tikz@math@getmeaning{#1}%
	\ifx\tikz@math@meaning\tikz@math@meaning@null%
		\let\tikz@math@next=\tikz@math@parse@keyword%
	\else%
		\let\tikz@math@next=\tikz@math@parse@nokeyword%
	\fi%
	\tikz@math@next#1}


\def\tikz@math@parse@keyword{%
	\let\tikz@math@parsed@keyword=\pgfutil@empty%
	\futurelet\tikz@math@parse@token\tikz@math@@parse@keyword}

\def\tikz@math@@parse@keyword{%
	\ifx\tikz@math@parse@token\pgfutil@sptoken%
		\let\tikz@math@next=\tikz@math@@@parse@keyword%
	\else%
		\ifx\tikz@math@parse@token(%
			\let\tikz@math@next=\tikz@math@@@parse@keyword%
		\else%
			\ifx\tikz@math@parse@token\bgroup%
				\let\tikz@math@next=\tikz@math@@@parse@keyword%
			\else%
				\let\tikz@math@next=\tikz@math@@@@parse@keyword%
			\fi%
		\fi%
	\fi%
	\tikz@math@next}

\def\tikz@math@error#1{\pgfutil@packageerror{tikz}{tikz math library: #1}{}}

\def\tikz@math@@@parse@keyword{%
		\expandafter\ifx\csname tikz@math@process@keyword@\tikz@math@parsed@keyword\endcsname\relax%
			\expandafter\ifx\csname pgfmath\tikz@math@parsed@keyword\endcsname\relax%
					\tikz@math@error{Unknown function or keyword '\tikz@math@parsed@keyword'}%
			\else%
				\def\tikz@math@next{\tikz@math@collecttosemicolon{\tikz@math@function@noassign}}%
			\fi%
		\else%
			\expandafter\def\expandafter\tikz@math@next\expandafter{\csname tikz@math@process@keyword@\tikz@math@parsed@keyword\endcsname}%
		\fi%
	\tikz@math@next}
	
\def\tikz@math@@@@parse@keyword#1{%
	\edef\tikz@math@parsed@keyword{\tikz@math@parsed@keyword#1}%
	\futurelet\tikz@math@parse@token\tikz@math@@parse@keyword%
}

\def\tikz@math@function@noassign{%
	\pgfmathparse{\tikz@math@parsed@keyword\tikz@math@collected}%
	\tikz@math@parse%
}
		
	
	

\def\tikz@math@process@keyword@count{\tikz@math@collecttosemicolon{\tikz@math@process@keyword@@count}}
\def\tikz@math@process@keyword@@count{%
\def\tikz@math@assign@register{\csname newcount\endcsname}%
\expandafter\tikz@math@gobblespaces\expandafter\tikz@math@process@registers\tikz@math@collected,@,}

\def\tikz@math@process@keyword@length{\tikz@math@collecttosemicolon{\tikz@math@process@keyword@@length}}
\def\tikz@math@process@keyword@@length{%
\def\tikz@math@assign@register{\csname newdimen\endcsname}%
\show\tikz@math@collected
\expandafter\tikz@math@gobblespaces\expandafter\tikz@math@process@registers\tikz@math@collected,@,}


\def\tikz@math@process@registers#1#2,{%
	\def\tikz@math@var{#1}%	
	\ifx\tikz@math@var\tikz@math@stop%
		\let\tikz@math@next=\tikz@math@parse%
	\else%
		\tikz@math@assign@register#1\relax%
		\let\tikz@math@next=\tikz@math@process@registers%
	\fi%
	\tikz@math@gobblespaces\tikz@math@next%
}


\def\tikz@math@process@keyword@if#1then{%
	\def\tikz@math@if@condition{#1}%
	\tikz@math@gobblespaces\tikz@math@parse@if@iftrue%
}
\def\tikz@math@parse@if@iftrue#1{%
	\def\tikz@math@if@trueaction{#1}%
	\pgfutil@ifnextchar e{\tikz@math@parse@else}{\tikz@math@if@doif}}

\def\tikz@math@parse@else else{\tikz@math@gobblespaces\tikz@math@if@doifelse}

\def\tikz@math@if@doif{\tikz@math@collecttosemicolon{\tikz@math@if@@doif}}

\def\tikz@math@if@@doif{%
	\pgfmathparse{\tikz@math@if@condition}%
	\ifdim\pgfmathresult pt=0pt\relax%
	\else%
		\expandafter\tikz@math\expandafter{\tikz@math@if@trueaction}%
	\fi%
	\tikz@math@parse%
}
\def\tikz@math@if@doifelse{\tikz@math@collecttosemicolon{\tikz@math@if@@doifelse}}
\def\tikz@math@if@@doifelse{%
	\pgfmathparse{\tikz@math@if@condition}%
	\let\tikz@math@if@falseaction=\tikz@math@collected%
	\ifdim\pgfmathresult pt=0pt\relax%
		\expandafter\tikz@math\expandafter{\tikz@math@if@falseaction}%
	\else%
		\expandafter\tikz@math\expandafter{\tikz@math@if@trueaction}%
	\fi%
	\tikz@math@parse%
}
\def\tikz@math@process@keyword@let{%
	\tikz@math@lettrue%
	\tikz@math@gobblespaces\tikz@math@parse@nokeyword%
}


\def\tikz@math@parse@nokeyword#1{%
	\def\tikz@math@var{#1}%
	\tikz@math@getvarstring{#1}\tikz@math@varstring%
	\let\tikz@math@vartype=\pgfutil@empty%
	\ifx\tikz@math@var\tikz@math@stop%
		\let\tikz@math@next=\tikz@math@parse@finish%
	\else%
         \ifx\tikz@math@semicolon\tikz@math@var%
        	\let\tikz@math@next=\tikz@math@parse%
			\else%
				\let\tikz@math@next=\tikz@math@parse@index@check%
			\fi%
	\fi%
	\tikz@math@next}

\def\tikz@math@parse@index@check{%
	\pgfutil@ifnextchar={\tikz@math@parse@noindex}{\tikz@math@parse@index}}
	
\def\tikz@math@parse@noindex{%
	\expandafter\tikz@math@clearvarindexed\tikz@math@var%
	\let\tikz@math@current@index=\pgfutil@empty%
	\tikz@math@parse@afterindex%
}

\def\tikz@math@parse@index#1{%
	\def\tikz@math@tmp{#1}%
	\expandafter\tikz@math@setvarindexed\tikz@math@var% {}
	\edef\tikz@math@current@index{#1}%
	\tikz@math@parse@afterindex%
}
\def\tikz@math@parse@afterindex#1={\tikz@math@gobblespaces\tikz@math@parse@assignment}%

\def\tikz@math@parse@assignment{\tikz@math@collecttosemicolon{\tikz@math@parse@@assignment}}
\def\tikz@math@parse@@assignment{%
	\expandafter\expandafter\expandafter\tikz@math@doassignment\expandafter\expandafter\expandafter%
		{\expandafter\tikz@math@var\expandafter}\expandafter{\tikz@math@collected}%
	\tikz@math@parse%
}

\def\tikz@math@dollar@char{$}
\def\tikz@math@dollar@char{$}% For annoying syntax highlighters

\def\tikz@math@doassignment#1#2{%
	\tikz@math@ifvarcoordinate{#1}{%
		\def\tikz@math@var{#1}% Unfortunately, we must do this again.
		\tikz@math@getvarstring{#1}\tikz@math@varstring% And this
		\expandafter\pgfutil@in@\tikz@math@dollar@char{#2}%
		\edef\tikz@math@expression{#2}%
		\ifpgfutil@in@%
			\expandafter\tikz@scan@one@point\expandafter\tikz@math@assign@coordinate\tikz@math@expression%
		\else%
			\expandafter\ifx\csname tikz@library@calc@loaded\endcsname\relax%
				\expandafter\tikz@scan@one@point\expandafter\tikz@math@assign@coordinate\tikz@math@expression%
			\else%
				\expandafter\tikz@scan@one@point\expandafter\tikz@math@assign@coordinate\expandafter%
				(\expandafter$\tikz@math@expression$)%
			\fi%
		\fi%
	}{%
		\iftikz@math@let% Not really a let
			\ifx\tikz@math@current@index\pgfutil@empty%
				\edef#1{#2}%
			\else%
				\edef\tikz@math@tmp{#2}%
				\expandafter\expandafter\expandafter\tikz@math@assign@index\expandafter\expandafter\expandafter%
					{\expandafter\tikz@math@varstring\expandafter}\expandafter{\tikz@math@tmp}%
			\fi%
			\tikz@math@letfalse%
		\else%
			\ifx\tikz@math@current@index\pgfutil@empty%
				\tikz@math@getmeaning{#1}%
				\ifx\tikz@math@meaning\tikz@math@meaning@dimen%
					\pgfmathsetlength{#1}{#2}%
					\let\tikz@math@last@assigned@value=\pgfmathresult%
				\else%
					\ifx\tikz@math@meaning\tikz@math@meaning@count%
						\pgfmathsetcount{#1}{#2}%
						\let\tikz@math@last@assigned@value=\pgfmathresult%
					\else%
						\tikz@math@ifvarinteger{#1}{\pgfmathparse{int(#2)}}{\pgfmathparse{#2}}%
						\let\tikz@math@last@assigned@value=\pgfmathresult%
						\let#1=\pgfmathresult%
					\fi%
				\fi%
			\else%
				\tikz@math@ifvarinteger{#1}{\pgfmathparse{int(#2)}}{\pgfmathparse{#2}}%
				\expandafter\tikz@math@assign@index\expandafter{\tikz@math@varstring}\pgfmathresult%
				\let\tikz@math@last@assigned@value=\pgfmathresult%
			\fi%
		\fi%
	}%
}



\def\tikz@math@assign@index#1#2{%
	\expandafter\def\csname#1\endcsname##1{\csname 
	tikz@math@var@indexed@#1@##1\endcsname}%
	\expandafter\edef\csname 
	tikz@math@var@indexed@#1@\tikz@math@current@index\endcsname{#2}\relax%
}



\def\tikz@math@assign@coordinate#1{%
	\pgf@process{#1}%
	\ifx\tikz@math@current@index\pgfutil@empty%
		\expandafter\edef\csname\tikz@math@varstring\endcsname{\the\pgf@x,\the\pgf@y}%
		\expandafter\edef\csname\tikz@math@varstring x\endcsname{\the\pgf@x}%
		\expandafter\edef\csname\tikz@math@varstring y\endcsname{\the\pgf@y}%
	\else%
		\expandafter\tikz@math@assign@index\expandafter{\tikz@math@varstring}{\the\pgf@x,\the\pgf@y}%
		\expandafter\tikz@math@assign@index\expandafter{\tikz@math@varstring x}{\the\pgf@x}%
		\expandafter\tikz@math@assign@index\expandafter{\tikz@math@varstring y}{\the\pgf@y}%
	\fi%
}



\def\tikz@math@keyword@coordinate{coordinate}
\def\tikz@math@process@keyword@coordinate{%
	\let\tikz@math@vartype=\tikz@math@keyword@coordinate%
	\tikz@math@gobblespaces\tikz@math@process@vartypes%
}

\def\tikz@math@keyword@integer{integer}
\def\tikz@math@process@keyword@integer{%
	\let\tikz@math@vartype=\tikz@math@keyword@integer%
	\tikz@math@gobblespaces\tikz@math@process@vartypes%
}
\def\tikz@math@process@keyword@int{%
	\tikz@math@process@keyword@integer%
}

\def\tikz@math@keyword@real{real}
\def\tikz@math@process@keyword@real{%
	\let\tikz@math@vartype=\tikz@math@keyword@real%
	\tikz@math@gobblespaces\tikz@math@process@vartypes%
}

\def\tikz@math@process@keyword@point{\tikz@math@process@keyword@coordinate}


\def\tikz@math@process@vartypes{\tikz@math@collecttosemicolon{\tikz@math@process@@vartypes}}

\def\tikz@math@process@@vartypes{%
	\expandafter\tikz@math@@process@vartypes\tikz@math@collected,@,\tikz@math%
}

\def\tikz@math@@process@vartypes#1#2,{%
	\def\tikz@math@var{#1}%
	\tikz@math@getvarstring{#1}\tikz@math@varstring%
	\ifx\tikz@math@var\tikz@math@stop%
		\let\tikz@math@next=\tikz@math@@@process@vartypes%
	\else%
		\expandafter\tikz@math@setvartype\tikz@math@var\tikz@math@vartype%
		\def\tikz@math@next{\tikz@math@gobblespaces\tikz@math@@process@vartypes}%
	\fi%
	\tikz@math@next%
}

\def\tikz@math@process@keyword@print{\tikz@math@collecttosemicolon{\tikz@math@process@keyword@@print}}
\def\tikz@math@process@keyword@@print{%
	\begingroup\tikz@math@collected\endgroup\tikz@math@parse%
}

\def\tikz@math@@@process@vartypes#1\tikz@math{%
	\tikz@math@parse%
}

\newcount\tikz@math@for@depth

\def\tikz@math@for@namedef#1{\expandafter\def\csname tikz@math@for@def@#1@\the\tikz@math@for@depth\endcsname}
\def\tikz@math@for@nameedef#1{\expandafter\edef\csname tikz@math@for@def@#1@\the\tikz@math@for@depth\endcsname}
\def\tikz@math@for@namelet#1{\expandafter\let\csname tikz@math@for@def@#1@\the\tikz@math@for@depth\endcsname}

\def\tikz@math@for@namegetvalue#1#2{%
	\def\tikz@math@marshal{\let#2=}%
	\expandafter\tikz@math@marshal\csname tikz@math@for@def@#1@\the\tikz@math@for@depth\endcsname}

\def\tikz@math@process@keyword@for{%
	\tikz@math@for%
}

\def\tikz@math@for@external{%
	\ifnum\catcode`\;=13\relax%
		\let\tikz@math@semicolon=\tikz@math@semicolon@active%
		\let\tikz@math@collecttosemicolon=\tikz@math@collecttosemicolon@active%
	\else%
		\let\tikz@math@semicolon=\tikz@math@semicolon@other%
		\let\tikz@math@collecttosemicolon=\tikz@math@collecttosemicolon@other%
	\fi	
	\advance\tikz@math@for@depth by1\relax%
	\tikz@math@for@namedef{execute}{\tikz@math@for@external@execute}%
	\tikz@math@for@namedef{finished}{\relax}%
	\tikz@math@gobblespaces\tikz@math@for@parsevar}

\def\tikz@math@for@external@execute#1{#1}

\def\tikz@math@for{%
	\advance\tikz@math@for@depth by1\relax%
	\tikz@math@for@namedef{execute}{\tikz@math}%
	\tikz@math@for@namedef{finished}{\tikz@math@parse}%
	\tikz@math@gobblespaces\tikz@math@for@parsevar}


\def\tikz@math@for@parsevar#1{%
	\tikz@math@for@namedef{var}{#1}%
	\tikz@math@for@parsein}

\def\tikz@math@getindex#1{%
	\tikz@math@@getindex#1\tikz@math@getindex\tikz@math@@getindex%
}

\def\tikz@math@@getindex#1#2\tikz@math@@getindex{#1}

\def\tikz@math@for@parsein#1in{%
	\def\tikz@math@tmp{#1}%
	\ifx\tikz@math@tmp\pgfutil@empty%
		\tikz@math@for@namedef{index}{}%
	\else%
		\tikz@math@for@nameedef{index}{\tikz@math@getindex{#1}}%
	\fi%
	\tikz@math@gobblespaces\tikz@math@for@parselist%
}


\long\def\tikz@math@for@parselist#1{%
	\edef\tikz@math@for@list{#1}%
	\tikz@math@collecttosemicolon{\tikz@math@for@parseaction}}

\def\tikz@math@for@parseaction{%
	\tikz@math@for@namedef{prevvalue}{}%
	\tikz@math@for@namedef{prevprevvalue}{}%
	\tikz@math@for@namelet{action}=\tikz@math@collected%
	\expandafter\tikz@math@for@scan\tikz@math@for@list,\tikz@math,\tikz@@math%
}

\def\tikz@math@token{\tikz@math}


\def\tikz@math@for@scan#1,{%
	\def\tikz@math@for@value{#1}%
	\ifx\tikz@math@for@value\tikz@math@token%
		\let\tikz@math@next=\tikz@math@for@scan@end%
	\else%
		\ifx\tikz@math@for@value\pgfutil@empty%
			\let\tikz@math@next=\tikz@math@for@scan@end%
		\else%
			\pgfutil@in@{...}{#1}%
			\ifpgfutil@in@%
				\let\tikz@math@next=\tikz@math@for@scan@dots%
			\else%
				\tikz@math@for@namegetvalue{var}{\tikz@math@var}%
				\tikz@math@for@namegetvalue{index}{\tikz@math@current@index}%
				\tikz@math@for@namegetvalue{action}{\tikz@math@action}%
				\expandafter\tikz@math@getvarstring\expandafter{\tikz@math@var}\tikz@math@varstring%
				\expandafter\tikz@math@doassignment\expandafter{\tikz@math@var}{#1}%
				\tikz@math@for@namelet{value}=\tikz@math@last@assigned@value%
				\tikz@math@for@namegetvalue{execute}{\tikz@math@execute}%
				\expandafter\tikz@math@execute\expandafter{\tikz@math@action}%
				\tikz@math@for@namegetvalue{prevvalue}{\tikz@math@prevvalue}%
				\tikz@math@for@namelet{prevprevvalue}=\tikz@math@prevvalue%
				\tikz@math@for@namegetvalue{value}{\tikz@math@value}%
				\tikz@math@for@namelet{prevvalue}=\tikz@math@value%
				\let\tikz@math@next=\tikz@math@for@scan%
			\fi%
		\fi%
	\fi%
	\tikz@math@next%	
}

\newdimen\tikz@math@dimen

\def\tikz@math@for@scan@dots#1,{%
	\pgfmathparse{#1}\let\tikz@math@value=\pgfmathresult%
	\tikz@math@for@nameedef{endvalue}{\tikz@math@value}%
	\tikz@math@for@namegetvalue{prevvalue}{\tikz@math@prevvalue}%
	\tikz@math@for@namegetvalue{prevprevvalue}{\tikz@math@prevprevvalue}%
	\tikz@math@dimen=\tikz@math@prevvalue pt\relax%
	\ifx\tikz@math@prevprevvalue\pgfutil@empty%
		\ifdim\tikz@math@prevvalue pt<\tikz@math@value pt\relax%%
			\def\tikz@math@step{1pt}%
		\else%
			\def\tikz@math@step{-1pt}%
		\fi%
	\else%	
		\tikz@math@dimen=\tikz@math@prevvalue pt\relax%
		\advance\tikz@math@dimen by-\tikz@math@prevprevvalue pt\relax%
		\edef\tikz@math@step{\the\tikz@math@dimen}%
	\fi%
	\ifdim\tikz@math@step<0pt\relax%
		\tikz@math@for@namedef{comparitor}{<}%
	\else%
		\tikz@math@for@namedef{comparitor}{>}%
	\fi%
	\tikz@math@for@nameedef{step}{\tikz@math@step}%
	\tikz@math@for@doloop%
}

\def\tikz@math@for@doloop{%
	\tikz@math@for@namegetvalue{prevvalue}{\tikz@math@prevvalue}%
	\tikz@math@for@namegetvalue{step}{\tikz@math@step}%
	\tikz@math@for@namegetvalue{comparitor}{\tikz@math@comparitor}%
	\tikz@math@for@namegetvalue{endvalue}{\tikz@math@endvalue}%
	\tikz@math@dimen=\tikz@math@prevvalue pt\relax%
	\advance\tikz@math@dimen by\tikz@math@step\relax%
	\ifdim\tikz@math@dimen\tikz@math@comparitor\tikz@math@endvalue pt\relax%
		\let\tikz@math@next=\tikz@math@for@endloop%
	\else%
		\tikz@math@for@nameedef{value}{\pgfmath@tonumber{\tikz@math@dimen}}%
		\tikz@math@for@namegetvalue{var}{\tikz@math@var}%
		\expandafter\tikz@math@getvarstring\expandafter{\tikz@math@var}\tikz@math@varstring%
		\tikz@math@for@namegetvalue{index}{\tikz@math@current@index}%
		\tikz@math@for@namegetvalue{action}{\tikz@math@action}%
		\tikz@math@for@namegetvalue{value}{\tikz@math@value}%
		\expandafter\expandafter\expandafter\tikz@math@doassignment\expandafter\expandafter\expandafter%
			{\expandafter\tikz@math@var\expandafter}\expandafter{\tikz@math@value}%
		\tikz@math@for@namegetvalue{execute}{\tikz@math@execute}%
		\expandafter\tikz@math@execute\expandafter{\tikz@math@action}%
		\tikz@math@for@namegetvalue{prevvalue}{\tikz@math@prevvalue}%
		\tikz@math@for@namelet{prevprevvalue}=\tikz@math@prevvalue%
		\tikz@math@for@namegetvalue{value}{\tikz@math@value}%
		\tikz@math@for@namelet{prevvalue}=\tikz@math@value%
		\let\tikz@math@next=\tikz@math@for@doloop%
	\fi%
	\tikz@math@next%
}

\def\tikz@math@for@endloop{%
\tikz@math@for@scan}




\def\tikz@math@for@scan@end#1\tikz@@math{%
\tikz@math@for@namegetvalue{finished}{\tikz@math@next}%
\advance\tikz@math@for@depth by-1\relax%
\tikz@math@next}





\def\tikz@math@process@keyword@return{%
	\tikz@math@collecttosemicolon{\pgfmathparse{\tikz@math@collected}\tikz@math@parse}}

\def\tikz@math@process@keyword@function{\tikz@math@collecttosemicolon{\tikz@math@process@keyword@@function}}
\def\tikz@math@process@keyword@@function{%
	\let\tikz@math@function@name=\pgfutil@empty%
	\let\tikz@math@function@arguments=\pgfutil@empty%
	\let\tikz@math@function@body=\pgfutil@empty%
	\expandafter\expandafter\expandafter\tikz@math@@declarefunction\expandafter\tikz@math@collected\tikz@math@semicolon%
}

\def\tikz@math@@declarefunction{%
	\pgfutil@ifnextchar\bgroup\tikz@math@@@collectbody\tikz@math@@@declarefunction}


\def\tikz@math@@@declarefunction#1{%
	\if#1(%)
		\let\tikz@math@next=\tikz@math@@@collectarguments%
	\else%
		\expandafter\def\expandafter\tikz@math@function@name\expandafter{\tikz@math@function@name#1}%
		\let\tikz@math@next=\tikz@math@@declarefunction%
	\fi%
	\tikz@math@next%
}
\def\tikz@math@@@collectarguments#1){%
	\def\tikz@math@function@arguments{#1}%
	\tikz@math@@declarefunction%
}

\newtoks\tikz@math@toks
\tikz@math@toks={#}
\edef\tikz@math@char@hash{\the\tikz@math@toks}
\tikz@math@toks={}

\def\tikz@math@@@collectbody{\tikz@math@collecttosemicolon{\tikz@math@@@@collectbody}}

\def\tikz@math@@@@collectbody{%
	\tikz@math@toks={}%
	\c@pgf@counta=0\relax%
	\ifx\tikz@math@function@arguments\pgfutil@empty%
	\else%
		\expandafter\tikz@math@createargumentlist\tikz@math@function@arguments,,%
		\expandafter\tikz@math@addto@toks\expandafter{\tikz@math@collected}%
	\fi%
	\edef\tikz@math@local@temp{%
		\noexpand\pgfmathdeclarefunction{\tikz@math@function@name}{\the\c@pgf@counta}%
		{\noexpand\def\noexpand\return{0}\noexpand\tikz@math{\the\tikz@math@toks}}%
	}%
	\tikz@math@local@temp
	\tikz@math@parse%
}

\def\tikz@math@addto@toks#1{%
	\expandafter\tikz@math@toks\expandafter{\the\tikz@math@toks#1}}	

\def\tikz@math@createargumentlist{%
	\pgfutil@ifnextchar 
	x\tikz@math@@createargumentlist\tikz@math@@createargumentlist}

\def\tikz@math@comma{,}
\def\tikz@math@@createargumentlist#1,{%
	\def\tikz@math@tmp{#1}%
	\ifx\tikz@math@tmp\pgfutil@empty%
		\let\tikz@math@next=\relax%
	\else%
		\advance\c@pgf@counta by1\relax%
		\tikz@math@addto@toks{#1=}%
		\expandafter\expandafter\expandafter\tikz@math@addto@toks\expandafter\expandafter\expandafter%
			{\expandafter\tikz@math@char@hash\the\c@pgf@counta;}%
		\let\tikz@math@next=\tikz@math@createargumentlist%
	\fi%
	\tikz@math@next%
}



\let\tikzmath=\tikz@math
\tikzset{evaluate/.code={\tikz@math{#1}}}
\let\tikzmathfor=\tikz@math@for@external


\catcode`\@=\tikz@math@at@catcode\relax

tikzlibrarymatrix.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/tikzlibrarymatrix.code.tex,v 1.4 2013/07/12 22:01:58 tantau Exp $


% A matrix of nodes contains a node in each cell.

\tikzstyle{matrix of nodes}=[%
   matrix,%
   cells={anchor=base},%
   execute at begin cell=\tikz@lib@matrix@start@cell,%
   execute at end cell=\tikz@lib@matrix@end@cell,%
   execute at empty cell=\tikz@lib@matrix@empty@cell,
   execute at begin matrix=\iftikz@handle@active@code\tikz@orig@shorthands\fi,%
]

\def\tikz@lib@matrix@empty@cell{\iftikz@lib@matrix@empty\node[name=\tikzmatrixname-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn]{};\fi}

\newif\iftikz@lib@matrix@plain

\def\tikz@lib@matrix@start@cell{%
  \pgfutil@ifnextchar|{\tikz@lib@matrix@with@options}{\tikz@lib@matrix@normal@start@cell}}

\def\tikz@lib@matrix@with@options|#1|{\tikz@lib@matrix@plainfalse\node%
  [name=\tikzmatrixname-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn]#1\bgroup\tikz@lib@matrix@startup}


\def\tikz@lib@matrix@normal@start@cell{\pgfutil@ifnextchar\let{\tikz@lib@matrix@check}{\tikz@lib@matrix@plainfalse\node
  [name=\tikzmatrixname-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn]\bgroup\tikz@lib@matrix@startup}}%

\def\tikz@lib@matrix@check#1{% evil hackery to find out about start of path
  \pgfutil@ifnextchar\tikz@signal@path{\tikz@lib@matrix@plaintrue\let}{\tikz@lib@matrix@plainfalse\node
  [name=\tikzmatrixname-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn]\bgroup\tikz@lib@matrix@startup\let}%
}
  
\def\tikz@lib@matrix@end@cell{%
  \iftikz@lib@matrix@plain%
  \else%
    \expandafter\egroup\expandafter;%
  \fi%    
}

\def\tikz@lib@matrix@startup{%
  \pgfutil@ifnextchar\bgroup{%
    % Save meaning of \\:
    \let\tikz@lib@matrix@saved@eol=\\%
    % Now smuggle meaning inside following group.
    \let\\=\pgfmatrixendrow%
    \afterassignment\tikz@lib@matrix@smuggle%
    \let\tikz@next}
  {\let\\=\pgfmatrixendrow}%
}
\def\tikz@lib@matrix@smuggle{%
  \bgroup%
  \let\\=\tikz@lib@matrix@saved@eol%
}


% Fill empty nodes in a matrix of nodes

\newif\iftikz@lib@matrix@empty

\tikzoption{nodes in empty cells}[true]{\csname tikz@lib@matrix@empty#1\endcsname}


% Same as a matrix of nodes, but switch on math mode in each cell
\tikzstyle{matrix of math nodes}=[%
  matrix of nodes,
  nodes={%
   execute at begin node=$,%
   execute at end node=$%
  }%
]



% Provide a delimiter

\tikzoption{left delimiter}{\tikzset{append after command={\tikz@delimiter%
    {south east}%
    {south west}%
    {every delimiter,every left delimiter}%
    {south}%
    {north}%
    {#1}%
    {.}%
    {\pgf@y}}}}

\tikzoption{right delimiter}{\tikzset{append after command={\tikz@delimiter%
    {south west}%
    {south east}%
    {every delimiter,every right delimiter}%
    {south}%
    {north}%
    {.}%
    {#1}%
    {\pgf@y}}}}

\tikzoption{above delimiter}{\tikzset{append after command={\tikz@delimiter%
    {south east}%
    {north west}%
    {every delimiter,every above delimiter,rotate=-90}%
    {west}%
    {east}%
    {#1}%
    {.}%
    {\pgf@x}}}}

\tikzoption{below delimiter}{\tikzset{append after command={\tikz@delimiter%
    {south west}%
    {south west}%
    {every delimiter,every below delimiter,rotate=-90}%
    {west}%
    {east}%
    {.}%
    {#1}%
    {\pgf@x}}}}

\def\tikz@delimiter#1#2#3#4#5#6#7#8{%
  \bgroup
    \pgfextra{\let\tikz@save@last@fig@name=\tikz@last@fig@name}%
    node[outer sep=0pt,inner sep=0pt,draw=none,fill=none,anchor=#1,at=(\tikz@last@fig@name.#2),#3]
    {%
      {\nullfont\pgf@process{\pgfpointdiff{\pgfpointanchor{\tikz@last@fig@name}{#4}}{\pgfpointanchor{\tikz@last@fig@name}{#5}}}}%
      $\left#6\vcenter{\hrule height .5#8 depth .5#8 width0pt}\right#7$%
    }
    \pgfextra{\global\let\tikz@last@fig@name=\tikz@save@last@fig@name}%
  \egroup%
}

\tikzstyle{every delimiter}=[]
\tikzstyle{every left delimiter}=[]
\tikzstyle{every right delimiter}=[]
\tikzstyle{every above delimiter}=[]
\tikzstyle{every below delimiter}=[]

\endinput

tikzlibrarymindmap.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/tikzlibrarymindmap.code.tex,v 1.10 2013/07/16 12:43:14 tantau Exp $


\usetikzlibrary{trees,decorations}


% A decoration for connecting circle nodes
%
% Parameters: start radius, end radius, amplitude, angle

\pgfdeclaredecoration{circle connection bar}{initial}
{
  \state{initial}[width=0pt,next state=bar]
  {
    {
    \pgftransformxshift{-\pgfkeysvalueof{/pgf/decoration/start radius}}%
    \pgfpathmoveto{\pgfpointpolar{\pgfdecorationsegmentangle}{\pgfkeysvalueof{/pgf/decoration/start radius}}}
    \pgfpatharc{\pgfdecorationsegmentangle}{-\pgfdecorationsegmentangle}{\pgfkeysvalueof{/pgf/decoration/start radius}}
    \pgfutil@tempcnta=-\pgfdecorationsegmentangle\relax
    \advance\pgfutil@tempcnta by90\relax
    \pgfmathsetlength\pgfutil@tempdima{\pgfkeysvalueof{/pgf/decoration/start radius}}
    \pgfmathsetlength\pgfutil@tempdimb{\pgfdecorationsegmentamplitude}
    \pgfpathcurveto
    {\pgfpointadd
      {\pgfpointpolar{-\pgfdecorationsegmentangle}{\pgfkeysvalueof{/pgf/decoration/start radius}}}
      {\pgfpointpolar{\the\pgfutil@tempcnta}{.25\pgfutil@tempdima}}}
    {\pgfqpoint{1.25\pgfutil@tempdima}{-.5\pgfutil@tempdimb}}
    {\pgfqpoint{1.5\pgfutil@tempdima}{-.5\pgfutil@tempdimb}}
    \pgfpathlineto{\pgfpoint{1.5\pgfutil@tempdima}{.5\pgfutil@tempdimb}}
    \pgfutil@tempcnta=\pgfdecorationsegmentangle\relax
    \advance\pgfutil@tempcnta by-90\relax
    \pgfpathcurveto
    {\pgfpoint{1.25\pgfutil@tempdima}{.5\pgfutil@tempdimb}}
    {\pgfpointadd
      {\pgfpointpolar{\pgfdecorationsegmentangle}{\pgfkeysvalueof{/pgf/decoration/start radius}}}
      {\pgfpointpolar{\the\pgfutil@tempcnta}{.25\pgfutil@tempdima}}}
    {\pgfpointpolar{\pgfdecorationsegmentangle}{\pgfkeysvalueof{/pgf/decoration/start radius}}}
    \pgfpathclose
    }
  }
  \state{bar}[width=0pt,next state=end]
  {
    \pgfmathsetlength\pgfutil@tempdima{\pgfkeysvalueof{/pgf/decoration/start radius}}%
    \pgfmathsetlength\pgfutil@tempdimb{\pgfkeysvalueof{/pgf/decoration/end radius}}%
    \pgfmathsetlength\pgf@xc{\pgfdecorationsegmentamplitude}%
    \pgfpathrectangle
    {\pgfqpoint{.5\pgfutil@tempdima}{-.5\pgf@xc}}
    {\pgfpoint{\pgfdecoratedremainingdistance+-.5\pgfutil@tempdimb+-.5\pgfutil@tempdima}{\pgf@xc}}
  }
  \state{end}[width=0pt,next state=final]
  {
    {
    \pgftransformxshift{\pgfdecoratedremainingdistance}%
    \pgftransformxscale{-1}%
    \pgftransformxshift{-\pgfkeysvalueof{/pgf/decoration/end radius}}%
    \pgfpathmoveto{\pgfpointpolar{\pgfdecorationsegmentangle}{\pgfkeysvalueof{/pgf/decoration/end radius}}}
    \pgfpatharc{\pgfdecorationsegmentangle}{-\pgfdecorationsegmentangle}{\pgfkeysvalueof{/pgf/decoration/end radius}}
    \pgfutil@tempcnta=-\pgfdecorationsegmentangle\relax
    \advance\pgfutil@tempcnta by90\relax
    \pgfmathsetlength\pgfutil@tempdima{\pgfkeysvalueof{/pgf/decoration/end radius}}
    \pgfmathsetlength\pgfutil@tempdimb{\pgfdecorationsegmentamplitude}%
    \pgfpathcurveto
    {\pgfpointadd
      {\pgfpointpolar{-\pgfdecorationsegmentangle}{\pgfkeysvalueof{/pgf/decoration/end radius}}}
      {\pgfpointpolar{\the\pgfutil@tempcnta}{.25\pgfutil@tempdima}}}
    {\pgfqpoint{1.25\pgfutil@tempdima}{-.5\pgfutil@tempdimb}}
    {\pgfqpoint{1.5\pgfutil@tempdima}{-.5\pgfutil@tempdimb}}
    \pgfpathlineto{\pgfpoint{1.5\pgfutil@tempdima}{.5\pgfutil@tempdimb}}
    \pgfutil@tempcnta=\pgfdecorationsegmentangle\relax
    \advance\pgfutil@tempcnta by-90\relax
    \pgfpathcurveto
    {\pgfpoint{1.25\pgfutil@tempdima}{.5\pgfutil@tempdimb}}
    {\pgfpointadd
      {\pgfpointpolar{\pgfdecorationsegmentangle}{\pgfkeysvalueof{/pgf/decoration/end radius}}}
      {\pgfpointpolar{\the\pgfutil@tempcnta}{.25\pgfutil@tempdima}}}
    {\pgfpointpolar{\pgfdecorationsegmentangle}{\pgfkeysvalueof{/pgf/decoration/end radius}}}
    \pgfpathclose
    }
  }
  \state{final}
  {}
}



\pgfkeys{/pgf/decoration/angle=20}

% To paths for connecting circle nodes

\tikzstyle{circle connection bar}=
[to path={
  \pgfextra{%
    \tikz@lib@mindmap@check{\tikztostart}%
    \tikz@compute@circle@radii\tikz@compute@segmentamplitude%
  }
  [every circle connection bar]
  decorate [decoration=circle connection bar]
  { -- (\tikztotarget) \tikztonodes}
},
append after command={[fill=\tikz@concept@color,draw=none]}
]
\tikzstyle{every circle connection bar}=[]

\def\tikz@compute@circle@radii{%
  \pgf@process{\pgfpointtransformed{\pgfpointanchor{\tikztostart}{center}}}%
  \pgf@xa=\pgf@x%
  \pgf@process{\pgfpointtransformed{\pgfpointanchor{\tikztostart}{west}}}%
  \advance\pgf@xa by-\pgf@x%
  \pgfkeys{/pgf/decoration/start radius/.expanded=\the\pgf@xa}%
  \pgf@process{\pgfpointtransformed{\pgfpointanchor{\tikztotarget}{center}}}%
  \pgf@xa=\pgf@x%
  \pgf@process{\pgfpointtransformed{\pgfpointanchor{\tikztotarget}{west}}}%
  \advance\pgf@xa by-\pgf@x%
  \pgfkeys{/pgf/decoration/end radius/.expanded=\the\pgf@xa}%
}
\def\tikz@compute@segmentamplitude{%
  \pgf@x=\pgfkeysvalueof{/pgf/decoration/start radius}\relax%
  \ifdim\pgf@x>\pgfkeysvalueof{/pgf/decoration/end radius}\relax%
    \pgf@x=\pgfkeysvalueof{/pgf/decoration/end radius}\relax%
  \fi%
  \pgf@x=.175\pgf@x\relax%
  \edef\pgfdecorationsegmentamplitude{\the\pgf@x}%
}



% Check whether start and end are nodes!

\def\tikz@lib@mindmap@check#1{%
  \pgfutil@ifundefined{pgf@sh@ns@#1}%
  {\tikzerror{You are attempting to connect two things by a circle 
      connection bar where one is not a node}}{%
    \expandafter\ifx\csname pgf@sh@ns@#1\endcsname\tikz@lib@coordinate@text%
      \tikzerror{You are attempting to connect node of shape
        'coordinate' by a circle connection bar. The shape should be
        'circle' or something similar, instead.}
    \fi%
  }
}

\def\tikz@lib@coordinate@text{coordinate}


% Switch color in a mindmap

\tikzoption{circle connection bar switch color}{\tikz@parse@switch#1\pgf@unique}
\def\tikz@parse@switch from (#1) to (#2)\pgf@unique{%
  \tikzset{to path={%
      \pgfextra{%
        \tikz@lib@mindmap@check{\tikztostart}%
        \tikz@compute@circle@radii\tikz@compute@segmentamplitude%
        \global\let\tikz@lib@save@start=\tikztostart%
        \global\let\tikz@lib@save@target=\tikztotarget%
        \pgfkeysgetvalue{/pgf/decoration/start radius}\pgf@temp%
        \global\let\tikz@lib@saved@start@radius=\pgf@temp%
        \pgfkeysgetvalue{/pgf/decoration/end radius}\pgf@temp%
        \global\let\tikz@lib@saved@end@radius=\pgf@temp%
      }%
      [every circle connection bar]
      decorate [decoration=circle connection bar]
      { -- (\tikztotarget) \tikztonodes} 
    },
    append after command={
      [fill=none,draw=none,path picture=\tikz@lib@shade@pic]
      \pgfextra{
        \pgfutil@colorlet{tikz@switch@from}{#1}%
        \pgfutil@colorlet{tikz@switch@to}{#2}%
      }}
  }
}

\def\tikz@lib@shade@pic{%
  % We have to draw the shading...
  % compute start point:
 \pgftransformreset%
 \pgf@process{\pgfpointnormalised{\pgfpointdiff{\pgfpointanchor{\tikz@lib@save@start}{center}}{\pgfpointanchor{\tikz@lib@save@target}{center}}}}%
  \edef\tikz@lib@mm@vec{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
  \pgfmathsetlength\pgf@xc{\tikz@lib@saved@start@radius}
  \pgf@process{\pgfpointadd{\pgfpointtransformed{\pgfpointanchor{\tikz@lib@save@start}{center}}}
                           {\pgfpointscale{\pgf@sys@tonumber{\pgf@xc}}{\tikz@lib@mm@vec}}}
  \edef\tikz@lib@mm@start{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
  \pgfmathsetlength\pgf@xc{\tikz@lib@saved@end@radius}
  \pgf@process{\pgfpointdiff{\tikz@lib@mm@start}{\pgfpointadd{\pgfpointtransformed{\pgfpointanchor{\tikz@lib@save@target}{center}}}
                           {\pgfpointscale{-\pgf@sys@tonumber{\pgf@xc}}{\tikz@lib@mm@vec}}}}
  \edef\tikz@lib@mm@end{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}%
  \pgftransformshift{\tikz@lib@mm@start}
   \pgflowlevelsynccm
  \pgf@process{\tikz@lib@mm@vec}
  {
    \pgf@xa=-\pgf@x%
    \pgftransformcm{\pgf@sys@tonumber{\pgf@x}}{\pgf@sys@tonumber{\pgf@y}}%
      {\pgf@sys@tonumber{\pgf@y}}{\pgf@sys@tonumber{\pgf@xa}}%
      {\pgfpointorigin}%
    \pgf@process{\pgfpointtransformed{\tikz@lib@mm@end}}%
    \expandafter
  }
  \edef\tikz@lib@mm@length{\the\pgf@x}%
  \pgf@process{\tikz@lib@mm@vec}
  \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}%
  % Y scale:
  \pgfmathsetlength\pgf@y{\tikz@lib@saved@start@radius}%
  \pgfmathsetlength\pgf@ya{\tikz@lib@saved@end@radius}%
  \ifdim\pgf@y<\pgf@ya%
    \pgf@y=\pgf@ya%
  \fi%
  \pgf@y=0.01992528\pgf@y%
  \pgftransformyscale{\pgf@sys@tonumber{\pgf@y}}%
  \pgfpathrectanglecorners
  {\pgfpoint{-\tikz@lib@saved@start@radius}{-50bp}}
  {\pgfpoint{1pt}{50bp}}
  \pgfsetfillcolor{tikz@switch@from}
  \pgfusepath{fill}
  \pgfpathrectanglecorners
  {\pgfpoint{\tikz@lib@mm@length+\tikz@lib@saved@end@radius}{-50bp}}
  {\pgfpoint{\tikz@lib@mm@length-1pt}{50bp}}
  \pgfsetfillcolor{tikz@switch@to}
  \pgfusepath{fill}
  % X scale:
  \pgf@x=\tikz@lib@mm@length%
  \pgf@x=0.009962\pgf@x%
  \pgftransformxscale{\pgf@sys@tonumber{\pgf@x}}%
  \pgftransformxshift{50bp}
  \pgflowlevelsynccm%
  \pgfuseshading{tikz@shade@bar}
}

\tikzoption{concept color}{%
  \let\tikz@old@concept@color=\tikz@concept@color%
  \def\tikz@edge@to@parent@path{
    (\tikzparentnode)
    to[circle connection bar switch color=from (\tikz@old@concept@color) to (#1)]
    (\tikzchildnode)}
  \def\tikz@concept@color{#1}%
}

\pgfdeclarehorizontalshading[tikz@switch@from,tikz@switch@to]{tikz@shade@bar}{100bp}{%
  color(0pt)=(tikz@switch@from);
  color(100bp)=(tikz@switch@to)}




% A concept node

\tikzstyle{concept}=          [circle,fill=\tikz@concept@color,draw=\tikz@concept@color,every concept]
\tikzstyle{every concept}=    []

\def\tikz@concept@color{black}

\tikzstyle{tikz@concept@setting}=[edge from parent path={(\tikzparentnode) to [circle connection bar] (\tikzchildnode)}]
\tikzstyle{tikz@concept@color@set}=[]


\tikzstyle{extra concept}=     [concept color=black!50,level 2 concept,concept,every extra concept]
\tikzstyle{every extra concept}=[]

\tikzstyle{concept connection}=[line width=1mm,shorten <=2mm,shorten >=2mm,cap=round,draw=black!50]


% A mindmap

\tikzstyle{mindmap}=
  [fill,draw,very thick,outer sep=0pt,inner sep=1pt,%
   every child/.append style={style=tikz@concept@setting,style=tikz@concept@color@set},%
   root concept,
   level 1/.append style={level 1 concept},
   level 2/.append style={level 2 concept},
   level 3/.append style={level 3 concept},
   level 4/.append style={level 4 concept},
   text centered,%       
   segment angle=20,
   style=every mindmap,
  ]
\tikzstyle{every mindmap}=[]


\tikzstyle{root concept}=   [minimum size=4cm,text width=3.5cm,font=\pgfutil@font@large]
\tikzstyle{level 1 concept}=[minimum size=2.25cm,
                             level distance=5cm,
                             text width=2cm,
                             sibling angle=60,
                             font=\pgfutil@font@small]
\tikzstyle{level 2 concept}=[minimum size=1.75cm,%
                             level distance=2.9cm,%
                             text width=1.5cm,%
                             sibling angle=60,%
                             font=\pgfutil@font@footnotesize]
\tikzstyle{level 3 concept}=[minimum size=1.15cm,%
                             text width=1cm,%
                             level distance=2.4cm,%
                             sibling angle=30,%
                             font=\pgfutil@font@tiny]
\tikzstyle{level 4 concept}=[minimum size=0.9cm,%
                             text width=0.7cm,
                             level distance=1.85cm,%
                             sibling angle=30,%
                             font=\pgfutil@font@tiny]

\tikzstyle{small mindmap}=
  [%
  root concept/.style={minimum size=2.3cm,text width=2.1cm,font=\pgfutil@font@footnotesize},
  level 1 concept/.style={%
    minimum size=1.5cm,
    level distance=2.8cm,
    text width=1.4cm,
    sibling angle=75,
    font=\pgfutil@font@scriptsize},%
  level 2 concept/.style={%
    minimum size=1.1cm,%
    level distance=2.2cm,%
    text width=1.1cm,%
    sibling angle=60,%
    font=\pgfutil@font@tiny},%
  level 3 concept/.style={%
  	level 2 concept,
    sibling angle=30,%
    font=\pgfutil@font@tiny},%
  level 4 concept/.style={%
  	level 3 concept,
  },
  mindmap,%
  line width=2pt
  ]
  
\tikzstyle{large mindmap}=
  [%
  root concept/.style={minimum size=5.6cm,text width=4.5cm,font=\pgfutil@font@Large},
  level 1 concept/.style={%
    minimum size=3.2cm,
    level distance=7cm,
    text width=2.8cm,
    sibling angle=60,
    font=},%
  level 2 concept/.style={%
    minimum size=2.45cm,%
    level distance=4cm,%
    text width=2.2cm,%
    sibling angle=60,%
    font=\pgfutil@font@small%
    },%
  level 3 concept/.style={%
    minimum size=1.63cm,%
    text width=1.4cm,%
    level distance=3.38cm,%
    sibling angle=30,%
    font=\pgfutil@font@scriptsize},%
  level 4 concept/.style={%
    minimum size=1.27cm,%
    text width=1cm,
    level distance=2.60cm,%
    sibling angle=30,%
    font=\pgfutil@font@tiny},%
  mindmap,%
  line width=2pt
  ]
  
\tikzstyle{huge mindmap}=
  [%
  root concept/.style={minimum size=8cm,text width=7cm,font=\pgfutil@font@huge},
  level 1 concept/.style={%
    minimum size=4.5cm,
    level distance=10cm,
    text width=4cm,
    sibling angle=60,
    font=\pgfutil@font@large},%
  level 2 concept/.style={%
    minimum size=3.5cm,%
    level distance=5.8cm,%
    text width=3cm,%
    sibling angle=60,%
    font=%
    },%
  level 3 concept/.style={%
    minimum size=2.3cm,%
    text width=2cm,%
    level distance=4.8cm,%
    sibling angle=30,%
    font=\pgfutil@font@footnotesize},%
  level 4 concept/.style={%
    minimum size=1.7cm,%
    text width=1.4cm,
    level distance=3.7cm,%
    sibling angle=30,%
    font=\pgfutil@font@scriptsize},%
  mindmap,%
  line width=3pt
  ]
  

% Annotations

\tikzstyle{annotation}=[shape=rectangle,
                        minimum size=0pt,
                        text width=3.5cm,
                        outer sep=1.5mm,
                        inner sep=1mm,
                        text badly ragged,
                        rounded corners,
                        font=\pgfutil@font@tiny,
                        every annotation]
\tikzstyle{every annotation}=[]



\endinput


tikzlibrarypatterns.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/tikzlibrarypatterns.code.tex,v 1.2 2008/01/15 10:27:34 tantau Exp $

\usepgflibrary{patterns}

\tikzoption{pattern color}{\edef\tikz@pattern@color{#1}}
\tikzoption{pattern}[]{%
  \edef\tikz@temp{#1}%
  \ifx\tikz@temp\tikz@nonetext%
    \tikz@addmode{\tikz@mode@fillfalse}%
  \else%
    \ifx\tikz@temp\pgfutil@empty%
    \else%
      \tikz@addoption{\pgfsetfillpattern{#1}{\tikz@pattern@color}}%
      \def\tikz@pattern{#1}%
    \fi%
    \tikz@addmode{\tikz@mode@filltrue}%
  \fi%
}
\def\tikz@pattern@color{black}
\def\tikz@pattern{dots}

\endinput

tikzlibrarypetri.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/tikzlibrarypetri.code.tex,v 1.3 2013/07/17 08:56:23 tantau Exp $


% Styles for places:

\tikzstyle{every place}=           []
\tikzstyle{place}=                 [circle,draw,inner sep=0pt,
                                    minimum size=5ex,
                                    every place]


% Styles for transition:

\tikzstyle{every transition}=      []
\tikzstyle{transition}=            [rectangle,draw,inner sep=0pt,
                                    minimum size=4mm,
                                    every transition]


% Styles for relationship types:

\tikzstyle{pre}=                   [<-,shorten <=1pt]
\tikzstyle{post}=                  [->,shorten >=1pt]
\tikzstyle{pre and post}=          [<->,shorten >=1pt,shorten <=1pt]



% Styles for marks:

\tikzstyle{every token}=           []
\tikzstyle{token}=                 [fill=black,draw=none,circle,
                                    inner sep=0.5pt,minimum size=1ex,
                                    text=white,font=\pgfutil@font@tiny,every token]

\tikzoption{token distance}{\def\tikz@token@distance{#1}}
\def\tikz@token@distance{1.5ex}

\tikzstyle{children are tokens}=   [growth function=\tikz@grow@tokens,edge from parent path=]

\tikzoption{tokens}{%
  \ifnum#1>0\relax%
    \tikzset{append after command={}
     {[children are tokens]child foreach \tikz@dummy in {1,...,#1} {node[token]{}}}}%
  \fi}

\tikzoption{colored tokens}{%
  \tikzset{append after command={}%
    {[children are tokens]child foreach \tikz@child@color in {#1} {node[token,\tikz@child@color]{}}}}%
  }

\tikzoption{structured tokens}{%
  \tikzset{append after command={}%
    {[children are tokens]child foreach \tikzpetrichildname in {#1} {node[token]{\tikzpetrichildname}}}}%
  }


\def\tikz@grow@tokens{%
  \pgfmathsetlength{\pgf@xa}{\tikz@token@distance}%
  \pgfmathsetlength{\pgf@ya}{\tikz@token@distance}%
  \pgf@xc=0pt%
  \pgf@yc=0pt%
  \csname tikz@grow@tokens@placer@\the\tikznumberofchildren @\the\tikznumberofcurrentchild\endcsname%
  \pgftransformshift{\pgfqpoint{\pgf@xc}{\pgf@yc}}%
}

\def\tikz@def@grow@tokens#1#2#3#4{%
  \expandafter\def\csname tikz@grow@tokens@placer@#1@#2\endcsname{%
    \pgf@xc=#3\pgf@xa%
    \pgf@yc=#4\pgf@ya}%
}


% Single token
\tikz@def@grow@tokens{1}{1}{0}{0}

% Two tokens
\tikz@def@grow@tokens{2}{1}{-.5}{0}
\tikz@def@grow@tokens{2}{2}{.5}{0}

% Three tokens
\tikz@def@grow@tokens{3}{1}{0} {0.57}
\tikz@def@grow@tokens{3}{2}{-.5}{-.306025}
\tikz@def@grow@tokens{3}{3}{.5} {-.306025}

% Four tokens
\tikz@def@grow@tokens{4}{1}{-.5}{.5}
\tikz@def@grow@tokens{4}{2}{.5}{.5}
\tikz@def@grow@tokens{4}{3}{-.5}{-.5}
\tikz@def@grow@tokens{4}{4}{.5}{-.5}

% Five tokens
\tikz@def@grow@tokens{5}{1}{0}{.85}
\tikz@def@grow@tokens{5}{2}{-0.808398}{0.26266}
\tikz@def@grow@tokens{5}{3}{0.808398}{0.26266}
\tikz@def@grow@tokens{5}{4}{-0.499617}{-0.687664}
\tikz@def@grow@tokens{5}{5}{0.499617}{-0.687664}

% Six tokens
\tikz@def@grow@tokens{6}{1}{-1}{.5}
\tikz@def@grow@tokens{6}{2}{0}{.5}
\tikz@def@grow@tokens{6}{3}{1}{.5}
\tikz@def@grow@tokens{6}{4}{-1}{-.5}
\tikz@def@grow@tokens{6}{5}{0}{-.5}
\tikz@def@grow@tokens{6}{6}{1}{-.5}

% Seven tokens
\tikz@def@grow@tokens{7}{1}{0}{1}
\tikz@def@grow@tokens{7}{2}{-1}{.5}
\tikz@def@grow@tokens{7}{3}{0}{0}
\tikz@def@grow@tokens{7}{4}{1}{.5}
\tikz@def@grow@tokens{7}{5}{-1}{-.5}
\tikz@def@grow@tokens{7}{6}{0}{-1}
\tikz@def@grow@tokens{7}{7}{1}{-.5}

% Eight tokens
\tikz@def@grow@tokens{8}{1}{-.5}{1}
\tikz@def@grow@tokens{8}{2}{.5}{1}
\tikz@def@grow@tokens{8}{3}{-1}{0}
\tikz@def@grow@tokens{8}{4}{0}{0}
\tikz@def@grow@tokens{8}{5}{1}{0}
\tikz@def@grow@tokens{8}{6}{-1}{-1}
\tikz@def@grow@tokens{8}{7}{0}{-1}
\tikz@def@grow@tokens{8}{8}{1}{-1}

% Eight tokens
\tikz@def@grow@tokens{9}{1}{-1}{1}
\tikz@def@grow@tokens{9}{2}{0}{1}
\tikz@def@grow@tokens{9}{3}{1}{1}
\tikz@def@grow@tokens{9}{4}{-1}{0}
\tikz@def@grow@tokens{9}{5}{0}{0}
\tikz@def@grow@tokens{9}{6}{1}{0}
\tikz@def@grow@tokens{9}{7}{-1}{-1}
\tikz@def@grow@tokens{9}{8}{0}{-1}
\tikz@def@grow@tokens{9}{9}{1}{-1}


\endinput

tikzlibraryplothandlers.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/tikzlibraryplothandlers.code.tex,v 1.1 2008/01/09 17:57:16 tantau Exp $

\usepgflibrary{plothandlers}

\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

tikzlibrarypositioning.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/tikzlibrarypositioning.code.tex,v 1.7 2008/10/06 09:35:29 tantau Exp $


\tikzset{above/.code=\tikz@lib@place@handle@{#1}{south}{0}{1}{north}{1}}
\tikzset{above left/.code=\tikz@lib@place@handle@{#1}{south east}{-1}{1}{north west}{0.707106781}}
\tikzset{above right/.code=\tikz@lib@place@handle@{#1}{south west}{1}{1}{north east}{0.707106781}}
\tikzset{base left/.code =\tikz@lib@place@handle@{#1}{base east}{-1}{0}{base west}{1}}
\tikzset{base right/.code=\tikz@lib@place@handle@{#1}{base west}{1}{0}{base east}{1}}
\tikzset{below/.code=\tikz@lib@place@handle@{#1}{north}{0}{-1}{south}{1}}
\tikzset{below left/.code=\tikz@lib@place@handle@{#1}{north east}{-1}{-1}{south west}{0.707106781}}
\tikzset{below right/.code=\tikz@lib@place@handle@{#1}{north west}{1}{-1}{south east}{0.707106781}}
\tikzset{left/.code =\tikz@lib@place@handle@{#1}{east}{-1}{0}{west}{1}}
\tikzset{mid left/.code =\tikz@lib@place@handle@{#1}{mid east}{-1}{0}{mid west}{1}}
\tikzset{mid right/.code=\tikz@lib@place@handle@{#1}{mid west}{1}{0}{mid east}{1}}
\tikzset{right/.code=\tikz@lib@place@handle@{#1}{west}{1}{0}{east}{1}}

\newif\iftikz@lib@ignore@size

% Hook into resets:
\pgfutil@g@addto@macro\tikz@node@reset@hook{\tikz@addtransform{\tikz@lib@pos@call}\let\tikz@lib@pos@call=\relax}

\tikzset{on grid/.is if=tikz@lib@ignore@size}

\tikzset{node distance=1cm and 1cm}

\def\tikz@lib@place@handle@#1#2#3#4#5#6{%
  \def\tikz@anchor{#2}%
  \let\tikz@do@auto@anchor=\relax%
  \edef\tikz@temp{#1}%
  \def\tikz@lib@place@single@factor{#6}%
  \expandafter\tikz@lib@place@handle@@\expandafter{\tikz@temp}{#3}{#4}{#5}%
}
\def\tikz@lib@place@handle@@#1#2#3#4{%
  \pgfutil@in@{of }{#1}%
  \ifpgfutil@in@%
    \tikz@lib@place@of#1\tikz@stop{#4}%
  \else%
    \edef\tikz@lib@place@nums{#1}%
  \fi%
  \ifx\tikz@lib@place@nums\pgfutil@empty%
    % Ok, nothing to do, we have set the anchor and we are happy...
  \else%
    \expandafter\tikz@lib@place@parse@nums\expandafter{\tikz@lib@place@nums}%
    \pgf@x=#2\pgf@x%
    \pgf@y=#3\pgf@y%
    \edef\tikz@lib@pos@call{\noexpand\pgftransformshift{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}}%
  \fi%
}

\def\tikz@lib@place@parse@nums#1{%
  \pgfutil@in@{and}{#1}%
  \ifpgfutil@in@%
    \tikz@lib@place@parse@nums@#1\tikz@stop%
  \else%
    \tikz@lib@place@parse@nums@#1and#1\tikz@stop%
    \pgf@x=\tikz@lib@place@single@factor\pgf@x%
    \pgf@y=\tikz@lib@place@single@factor\pgf@y%
  \fi
}
\def\tikz@lib@place@parse@nums@#1and#2\tikz@stop{%
  \pgfmathparse{#2}%
  \ifpgfmathunitsdeclared%
    \pgf@xa=\pgfmathresult pt%
    \pgf@ya=0pt%
  \else%
    \let\tikz@lib@temp=\pgfmathresult%
    \pgf@process{\pgfpointxy{\tikz@lib@temp}{0}}%
    \pgf@xa=\pgf@x%
    \pgf@ya=\pgf@y%
  \fi%
  \pgfmathparse{#1}%
  \ifpgfmathunitsdeclared%
    \advance\pgf@ya by\pgfmathresult pt%
  \else%
    \let\tikz@lib@temp=\pgfmathresult%
    \pgf@process{\pgfpointxy{0}{\tikz@lib@temp}}%
    \advance\pgf@xa by\pgf@x%
    \advance\pgf@ya by\pgf@y%
  \fi%
  \pgf@x=\pgf@xa%
  \pgf@y=\pgf@ya%
}

\def\tikz@lib@place@of#1of #2\tikz@stop#3{%
  \def\tikz@temp{#1}%
  \ifx\tikz@temp\pgfutil@empty%
    \tikz@lib@place@of@{\tikz@node@distance}{#2}{#3}%
  \else%
    \tikz@lib@place@of@{#1}{#2}{#3}%
  \fi%
}
\def\tikz@lib@place@of@#1#2#3{%
  \tikz@scan@one@point\tikz@lib@place@remember(#2)%
  \iftikz@shapeborder%
    % Ok, this is relative to a border.
    \iftikz@lib@ignore@size%
      \edef\tikz@node@at{\noexpand\pgfpointanchor{\tikz@shapeborder@name}{center}}%
      \def\tikz@anchor{center}%
    \else%
      \edef\tikz@node@at{\noexpand\pgfpointanchor{\tikz@shapeborder@name}{#3}}%
    \fi%
  \fi%
  \edef\tikz@lib@place@nums{#1}%
}
\def\tikz@lib@place@remember#1{\def\tikz@node@at{#1}}



\endinput

tikzlibraryquotes.code.tex
% Copyright 2011 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/tikzlibraryquotes.code.tex,v 1.3 2013/08/28 15:24:27 tantau Exp $

\def\tikz@quote@parser#1{\tikz@quote@@parser#1\pgf@stop}
\def\tikz@quote@@parser"#1"{%
  \pgfutil@ifnextchar\bgroup{%
    \tikz@quote@@parser@group{#1}}{%
    \pgfutil@ifnextchar'{%
      \tikz@quote@@parser@apo{#1}}{%
      \tikz@quote@@parser@normal{#1}}}}
\def\tikz@quote@@parser@apo#1'{%
  \pgfutil@ifnextchar\bgroup{\tikz@quote@@parser@apo@group{#1}}{\tikz@quote@@parser@apo@normal{#1}}}
\def\tikz@quote@@parser@group#1#2#3\pgf@stop{%
  \expandafter\def\expandafter\tikz@temp\expandafter{\tikz@quotes@as{#1}{#2}}%
  \expandafter\pgfkeysalso\expandafter{\tikz@temp}%
}
\def\tikz@quote@@parser@normal#1#2\pgf@stop{%
  \expandafter\def\expandafter\tikz@temp\expandafter{\tikz@quotes@as{#1}{#2}}%
  \expandafter\pgfkeysalso\expandafter{\tikz@temp}%
}
\def\tikz@quote@@parser@apo@group#1#2#3\pgf@stop{%
  \expandafter\def\expandafter\tikz@temp\expandafter{\tikz@quotes@as{#1}{',#2}}%
  \expandafter\pgfkeysalso\expandafter{\tikz@temp}%
}
\def\tikz@quote@@parser@apo@normal#1#2\pgf@stop{%
  \expandafter\def\expandafter\tikz@temp\expandafter{\tikz@quotes@as{#1}{',#2}}%
  \expandafter\pgfkeysalso\expandafter{\tikz@temp}%
}

\pgfkeys{/handlers/first char syntax=true}

\def\tikz@enable@node@quotes{%
  \pgfkeyssetvalue{/handlers/first char syntax/the character "}{\tikz@quote@parser}%
  \let\tikz@quotes@as\tikz@node@quotes@as%
}
\def\tikz@enable@edge@quotes{%
  \pgfkeyssetvalue{/handlers/first char syntax/the character "}{\tikz@quote@parser}%
  \let\tikz@quotes@as\tikz@edge@quotes@as%
}
\def\tikz@enable@pic@quotes{%
  \pgfkeyssetvalue{/handlers/first char syntax/the character "}{\tikz@quote@parser}%
  \let\tikz@quotes@as\tikz@pic@quotes@as%
}

\tikzset{
  node quotes mean/.code={\def\tikz@node@quotes@as##1##2{#1}},
  edge quotes mean/.code={\def\tikz@edge@quotes@as##1##2{#1}},
  pic quotes mean/.code={\def\tikz@pic@quotes@as##1##2{#1}},
  quotes mean pin/.style={node quotes mean={
      pin={[direction shorthands,every pin quotes/.try,##2]##1}}},
  quotes mean label/.style={node quotes mean={
      label={[direction shorthands,every label quotes/.try,##2]##1}}},
  quotes mean label,
  edge quotes mean={edge node={node [every edge quotes,#2]{#1}}},
  pic quotes mean={pic text={#1},pic text options={every pic quotes/.try,#2}},
  every edge quotes/.style={auto},
  direction shorthands/.code={%
    \pgfkeyslet{/tikz/above/.@cmd}\tikz@label@@above
    \pgfkeyslet{/tikz/below/.@cmd}\tikz@label@@below
    \pgfkeyslet{/tikz/left/.@cmd}\tikz@label@@left
    \pgfkeyslet{/tikz/right/.@cmd}\tikz@label@@right
    \pgfkeyslet{/tikz/above left/.@cmd}\tikz@label@@above@left
    \pgfkeyslet{/tikz/above right/.@cmd}\tikz@label@@above@right
    \pgfkeyslet{/tikz/below left/.@cmd}\tikz@label@@below@left
    \pgfkeyslet{/tikz/below right/.@cmd}\tikz@label@@below@right
  }
}

\def\tikz@label@@above#1\pgfeov{\pgfkeysalso{label position=90,pin position=90}}
\def\tikz@label@@below#1\pgfeov{\pgfkeysalso{label position=-90,pin position=-90}}
\def\tikz@label@@left#1\pgfeov{\pgfkeysalso{label position=180,pin position=180}}
\def\tikz@label@@right#1\pgfeov{\pgfkeysalso{label position=0,pin position=0}}
\def\tikz@label@@above@left#1\pgfeov{\pgfkeysalso{label position=135,pin position=135}}
\def\tikz@label@@below@left#1\pgfeov{\pgfkeysalso{label position=-135,pin position=-135}}
\def\tikz@label@@above@right#1\pgfeov{\pgfkeysalso{label position=45,pin position=45}}
\def\tikz@label@@below@right#1\pgfeov{\pgfkeysalso{label position=-45,pin position=-45}}



\endinput

tikzlibraryscopes.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/tikzlibraryscopes.code.tex,v 1.2 2008/06/27 17:00:24 vibrovski Exp $

% Redefine the after command hook...

\def\tikz@lib@scope@check{%
	\pgfutil@ifnextchar\tikz@intersect@finish{%
		\tikz@intersect@finish\afterassignment\tikz@lib@scope@check\let\tikz@next%
	}{%
	  \pgfutil@ifnextchar\par{%
	    \afterassignment\tikz@lib@scope@check\let\tikz@next%
	  }%
	  {\pgfutil@ifnextchar\bgroup{%gotcha
	      \afterassignment\tikz@lib@scope@gotcha\let\tikz@next%
	    }%
	    {}%
	  }%
	}%
}

\def\tikz@lib@scope@gotcha{%
  \pgfutil@ifnextchar[{%]
    \tikz@lib@scope@action%
  }{%
    % false alarm
    \bgroup%
  }%  
}
\def\tikz@lib@scope@action[#1]{%
  \scope[#1]\bgroup\aftergroup\endscope%
  \tikz@lib@scope@check%
}

\endinput

tikzlibraryshadings.code.tex
% Copyright 2008 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/tikzlibraryshadings.code.tex,v 1.1 2008/10/29 21:58:38 tantau Exp $

\usepgflibrary{shadings}

\tikzset{
  lower left/.style={shading=bilinear interpolation,/utils/exec=\colorlet{lower left}{#1}},
  upper left/.style={shading=bilinear interpolation,/utils/exec=\colorlet{upper left}{#1}},
  lower right/.style={shading=bilinear interpolation,/utils/exec=\colorlet{lower right}{#1}},
  upper right/.style={shading=bilinear interpolation,/utils/exec=\colorlet{upper right}{#1}}
}

\endinput

tikzlibraryshadows.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/tikzlibraryshadows.code.tex,v 1.3 2008/01/13 15:30:04 tantau Exp $

\usetikzlibrary{fadings}


% General options
\tikzset{
  /tikz/shadow scale/.initial=1,
  /tikz/shadow xshift/.initial=0pt,
  /tikz/shadow yshift/.initial=0pt,
}

% Basic shadow style
\tikzset{
  general shadow/.style={
    preaction={
      #1,
      transform canvas={
        scale around=\pgfkeysvalueof{/tikz/shadow scale}:(current path bounding box.center),
        shift={(\pgfkeysvalueof{/tikz/shadow xshift},\pgfkeysvalueof{/tikz/shadow yshift})}
      },
    }
  },
  every shadow/.style={}
}



%
% Adds a simple drop shadow to a path
%

\tikzset{
  /tikz/drop shadow/.style={
    general shadow={%
      shadow scale=1,
      shadow xshift=.5ex,
      shadow yshift=-.5ex,
      opacity=.5,
      fill=black!50,
      every shadow,
      #1
    }
  }
}


%
% Adds a circular drop shadow to a path
%

\tikzset{
  /tikz/circular drop shadow/.style={
    general shadow={%
      shadow scale=1.1,
      shadow xshift=.3ex,
      shadow yshift=-.3ex,
      fill=black!50,
      path fading={circle with fuzzy edge 15 percent},
      every shadow,
      #1
    }
  }
}



%
% Adds a circular glow to a path
%

\tikzset{
  /tikz/circular glow/.style={
    general shadow={%
      shadow scale=1.25,
      shadow xshift=0pt,
      shadow yshift=0pt,
      fill=black!50,
      path fading={circle with fuzzy edge 15 percent},
      every shadow,
      #1,
    }
  }
}





%
% Adds a "copy" version of the path behind it.
%

\tikzset{
  /tikz/copy shadow/.style={
    general shadow={%
      /utils/exec={\let\tikz@lib@shadow@fill=\tikz@fillcolor\let\tikz@lib@shadow@draw=\tikz@strokecolor},
      shadow scale=1,
      shadow xshift=.5ex,
      shadow yshift=.5ex,
      fill=\tikz@lib@shadow@fill,
      draw=\tikz@lib@shadow@draw,
      every shadow,
      #1
    }
  }
}


%
% Adds two "copies" of the path behind it.
%

\tikzset{
  /tikz/double copy shadow/.style={
    general shadow={%
      /utils/exec={\let\tikz@lib@shadow@fill=\tikz@fillcolor\let\tikz@lib@shadow@draw=\tikz@strokecolor},
      shadow scale=1,
      shadow xshift=.5ex,
      shadow yshift=.5ex,
      fill=\tikz@lib@shadow@fill,
      draw=\tikz@lib@shadow@draw,
      #1,
      shadow xshift/.expanded=2*\pgfkeysvalueof{/tikz/shadow xshift},
      shadow yshift/.expanded=2*\pgfkeysvalueof{/tikz/shadow yshift},
    },
    general shadow={%
      /utils/exec={\let\tikz@lib@shadow@fill=\tikz@fillcolor\let\tikz@lib@shadow@draw=\tikz@strokecolor},
      shadow scale=1,
      shadow xshift=.5ex,
      shadow yshift=.5ex,
      fill=\tikz@lib@shadow@fill,
      draw=\tikz@lib@shadow@draw,
      #1,
    },
  }
}


tikzlibraryshapes.arrows.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/tikzlibraryshapes.arrows.code.tex,v 1.1 2008/01/09 17:57:16 tantau Exp $

\usepgflibrary{shapes.arrows}

\pgfkeys{/tikz/arrow box arrows/.code={\pgf@lib@arrowbox@parsearrows{#1}}}

\endinput

tikzlibraryshapes.callouts.code.tex
% Copyright 2006 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.

\usepgflibrary{shapes.callouts}

\pgfkeys{/tikz/callout absolute pointer/.code={%
	\tikz@scan@one@point\tikz@lib@callout@checkforplus#1\relax%
	}%
}

\def\tikz@lib@callout@checkforplus#1{%
	\pgfutil@ifnextchar+{\def\tikz@lib@callout@originalpoint{#1}\tikz@lib@callout@scan@relative}%
		{\pgf@lib@callout@makeabsolutepointer{#1}}}%

\def\tikz@lib@callout@scan@relative+{%
	\pgfutil@ifnextchar+{\tikz@lib@callout@scan@plusplus}{\tikz@lib@callout@scan@plus}}
\def\tikz@lib@callout@scan@plusplus+{\tikz@scan@one@point\tikz@lib@callout@add}
\def\tikz@lib@callout@scan@plus{\tikz@scan@one@point\tikz@lib@callout@add}
\def\tikz@lib@callout@add#1{%
	\expandafter\pgf@lib@callout@makeabsolutepointer\expandafter{%
		\expandafter\pgfpointadd\expandafter{\tikz@lib@callout@originalpoint}{#1}}%
}%

\pgfkeys{/tikz/callout relative pointer/.code={%
		\tikz@scan@one@point\pgf@lib@callout@makerelativepointer#1\relax%
	}%
}

\endinput
tikzlibraryshapes.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/tikzlibraryshapes.code.tex,v 1.1 2008/01/09 17:57:16 tantau Exp $

\usetikzlibrary{shapes.geometric}
\usetikzlibrary{shapes.misc}
\usetikzlibrary{shapes.symbols}
\usetikzlibrary{shapes.arrows}
\usetikzlibrary{shapes.callouts}
\usetikzlibrary{shapes.multipart}

\endinput

tikzlibraryshapes.gates.logic.IEC.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.

\ProvidesFileRCS[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/frontendlayer/tikz/libraries/tikzlibraryshapes.gates.logic.IEC.code.tex,v 1.3 2008/01/27 11:39:49 vibrovski Exp $

\usepgflibrary{shapes.gates.logic.IEC}

\tikzset{%
  use IEC style logic gates/.code={%
  	\tikzset{%
			and gate/.style={shape=and gate IEC},
			nand gate/.style={shape=nand gate IEC},
			or gate/.style={shape=or gate IEC},
			nor gate/.style={shape=nor gate IEC},
			xor gate/.style={shape=xor gate IEC},
			xnor gate/.style={shape=xnor gate IEC},
			not gate/.style={shape=not gate IEC},
			buffer gate/.style={shape=buffer gate IEC},
			and gate symbol/.style={and gate IEC symbol={##1}},
			nand gate symbol/.style={nand gate IEC symbol={##1}},
			or gate symbol/.style={or gate IEC symbol={##1}},
			nor gate symbol/.style={nor gate IEC symbol={##1}},
			xor gate symbol/.style={xor gate IEC symbol={##1}},
			xnor gate symbol/.style={xnor gate IEC symbol={##1}},
			not gate symbol/.style={not gate IEC symbol={##1}},
			buffer gate symbol/.style={buffer gate IEC symbol={##1}},
			logic gate symbol align/.style={/pgf/logic gate IEC symbol align={##1}},
			logic gate symbol color/.style={/pgf/logic gate IEC symbol color={##1}}
		}%
	}%
}
\endinput



tikzlibraryshapes.gates.logic.US.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.

\ProvidesFileRCS[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/frontendlayer/tikz/libraries/tikzlibraryshapes.gates.logic.US.code.tex,v 1.1 2008/01/25 08:26:00 vibrovski Exp $

\usepgflibrary{shapes.gates.logic.US}

\tikzset{%
   use US style logic gates/.code={%
  	\tikzset{%
			and gate/.style={shape=and gate US},
			nand gate/.style={shape=nand gate US},
			or gate/.style={shape=or gate US},
			nor gate/.style={shape=nor gate US},
			xor gate/.style={shape=xor gate US},
			xnor gate/.style={shape=xnor gate US},
			not gate/.style={shape=not gate US},
			buffer gate/.style={shape=buffer gate US}
		}%
	},
	use CDH style logic gates/.code={%
  	\tikzset{%
			and gate/.style={shape=and gate CDH},
			nand gate/.style={shape=nand gate CDH},
			or gate/.style={shape=or gate US},
			nor gate/.style={shape=nor gate US},
			xor gate/.style={shape=xor gate US},
			xnor gate/.style={shape=xnor gate US},
			not gate/.style={shape=not gate US},
			buffer gate/.style={shape=buffer gate US}
		}
	}
}
\endinput

tikzlibraryshapes.geometric.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/tikzlibraryshapes.geometric.code.tex,v 1.1 2008/01/09 17:57:16 tantau Exp $

\usepgflibrary{shapes.geometric}

\endinput

tikzlibraryshapes.misc.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/tikzlibraryshapes.misc.code.tex,v 1.1 2008/01/09 17:57:16 tantau Exp $

\usepgflibrary{shapes.misc}

\endinput

tikzlibraryshapes.multipart.code.tex
% Copyright 2007 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.

\ProvidesFileRCS[v\pgfversion] $Header: /cvsroot/pgf/pgf/generic/pgf/frontendlayer/tikz/libraries/tikzlibraryshapes.multipart.code.tex,v 1.1 2008/01/09 17:57:16 tantau Exp $

\usepgflibrary{shapes.multipart}

\pgfkeys{/tikz/rectangle split/parts/.code={%
	\pgfkeys{/pgf/rectangle split parts=#1}%
	}%
}

\pgfkeys{/tikz/rectangle split use custom fill/.code={%
	\pgfkeys{/pgf/rectangle split use custom fill=#1}%
	\pgfkeys{/tikz/fill=none}}%
}

\pgfkeys{/tikz/rectangle split draw splits/.is if=pgfrectanglesplitdrawsplits}

\pgfkeys{/tikz/rectangle split part align/.code={%
		\pgfkeys{/pgf/rectangle split part align={#1}}%
	}%
}%

\pgfkeys{/tikz/rectangle split part fill/.code={%
		\pgfkeys{/pgf/rectangle split part fill={#1}}%
	}%
}%

\endinput

tikzlibraryshapes.symbols.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/tikzlibraryshapes.symbols.code.tex,v 1.1 2008/01/09 17:57:16 tantau Exp $

\pgfkeysifdefined{/tikz/shape border uses incircle}{}{%
	\pgfkeys{/tikz/shape border uses incircle/.is if=pgfshapeborderusesincircle}}
	
\usepgflibrary{shapes.symbols}

\endinput

tikzlibrarysnakes.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/tikzlibrarysnakes.code.tex,v 1.7 2013/07/15 12:05:31 tantau Exp $

\pgfwarning{Snakes have been superseded by
decorations. Please use the decoration libraries instead of the snakes
library}

\usetikzlibrary{decorations.pathmorphing,decorations.pathreplacing,decorations.shapes}


% Old snakes stuff:

\tikzoption{snake}[]{%
  \def\tikz@@snake{#1}%
  \ifx\tikz@@snake\pgfutil@empty%
    \tikz@snakedtrue%
  \else%
    \ifx\tikz@@snake\tikz@nonetext%
      \tikz@snakedfalse%
    \else%
      \tikz@snakedtrue%
      \let\tikz@snake=\tikz@@snake%
    \fi%
  \fi}

\tikzoption{raise snake}{\def\pgf@snake@raise{\pgftransformyshift{#1}}}
\tikzoption{mirror snake}[true]{%
  \csname if#1\endcsname
    \def\pgf@snake@mirror{\pgftransformyscale{-1}}%
  \else%
    \let\pgf@snake@mirror=\pgfutil@empty%
  \fi
}

\tikzoption{gap before snake}{\def\tikz@presnake{{moveto}{#1}{\noexpand\tikz@snake@install@trans}{}}}
\tikzoption{line before snake}{\def\tikz@presnake{{lineto}{#1}{\noexpand\tikz@snake@install@trans}{}}}

\tikzoption{gap after snake}{\def\tikz@postsnake{{moveto}{#1}{\noexpand\tikz@snake@install@trans}{}}\def\tikz@mainsnakelength{\pgfsnakeremainingdistance-#1}}
\tikzoption{line after snake}{\def\tikz@postsnake{{lineto}{#1}{\noexpand\tikz@snake@install@trans}{}}\def\tikz@mainsnakelength{\pgfsnakeremainingdistance-#1}}

\tikzoption{gap around snake}{%
  \def\tikz@presnake{{moveto}{#1}{\noexpand\tikz@snake@install@trans}{}}%
  \def\tikz@postsnake{{moveto}{#1}{\noexpand\tikz@snake@install@trans}{}}%
  \def\tikz@mainsnakelength{\pgfsnakeremainingdistance-#1}%
}
\tikzoption{line around snake}{%
  \def\tikz@presnake{{lineto}{#1}{\noexpand\tikz@snake@install@trans}{}}%
  \def\tikz@postsnake{{lineto}{#1}{\noexpand\tikz@snake@install@trans}{}}%
  \def\tikz@mainsnakelength{\pgfsnakeremainingdistance-#1}%
}
\let\pgf@snake@mirror=\pgfutil@empty
\let\pgf@snake@raise=\pgfutil@empty

\def\tikz@snake@install@trans{\pgfsetsnakesegmenttransformation{\pgf@snake@mirror\pgf@snake@raise}}

\def\tikz@snake{zigzag}

\let\tikz@presnake=\pgfutil@empty
\let\tikz@postsnake=\pgfutil@empty
\def\tikz@mainsnakelength{\pgfsnakeremainingdistance}


\tikzstyle{snake triangles 45}=      [snake=triangles,segment object length=2.41421356\pgfsnakesegmentamplitude]
\tikzstyle{snake triangles 60}=      [snake=triangles,segment object length=1.73205081\pgfsnakesegmentamplitude]
\tikzstyle{snake triangles 90}=      [snake=triangles,segment object length=\pgfsnakesegmentamplitude]



\endinput

tikzlibraryspy.code.tex
% Copyright 2008 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/tikzlibraryspy.code.tex,v 1.4 2011/05/19 08:56:54 tantau Exp $



% Spy styles

\tikzset{
  spy using outlines/.style={
    spy scope={
      every spy on node/.style={very thin,draw},
      every spy in node/.style={thick,draw},
      #1
    }
  },
  spy using overlays/.style={
    spy scope={
      every spy on node/.style={fill,fill opacity=0.2,text opacity=1},
      every spy in node/.style={fill,fill opacity=0.2,text opacity=1},
      #1
    }
  },
  connect spies/.style={
    spy connection path={\draw[thin] (tikzspyonnode) -- (tikzspyinnode);}
  }
}

\newbox\tikz@lib@spybox

\let\tikz@lib@spy@collection=\pgfutil@empty%

\tikzset{spy scope/.style={
    size/.style={minimum size=##1},
    height/.style={minimum height=##1},
    width/.style={minimum width=##1},
    execute at begin scope={%
      \let\tikz@lib@spy@save=\tikz@lib@spy@collection%
      \setbox\tikz@lib@spybox=\hbox\bgroup\bgroup%
      \let\spy=\tikz@lib@spy@parse},
    execute at end scope={%
      \egroup\egroup%
      {%
        \copy\tikz@lib@spybox%
        \tikz@lib@spy@collection%
      }%
      \global\let\tikz@lib@spy@collection=\tikz@lib@spy@save%
    },%
    tikz@lib@spy@style/.style={#1},
    tikz@lib@reset@gs
  },
  lens/.store in=\tikz@lib@spy@lens,
  lens=,
  magnification/.style={lens={scale=#1}},
  spy connection path/.store in=\tikz@lib@spy@path,
  spy connection path=
}

\tikzset{
  tikz@lib@reset@gs/.style={black,thin,solid,opaque,line cap=butt,line join=miter}
}

\def\tikz@lib@spy@parse{%
  \pgfutil@ifnextchar[{\tikz@lib@spy@parse@opt}{\tikz@lib@spy@parse@opt[]}%]
}
\def\tikz@lib@spy@parse@opt[#1]{
  \pgfutil@ifnextchar x{\tikz@lib@spy@parse@opta[#1]}{\tikz@lib@spy@parse@opta[#1]}%]
}
\def\tikz@lib@spy@parse@opta[#1]on#2in node#3;{%
  \pgfutil@g@addto@macro\tikz@lib@spy@collection{\tikz@lib@spy@do{#1}{#2}{#3}}%
}

\def\tikz@lib@spy@do#1#2#3{%
  \scope[tikz@lib@spy@style,#1]
    \node [alias=tikzspyonnode,inner sep=0pt,outer sep=0pt,every spy on node/.try,
    /utils/exec={
      {%
        \let\tikz@transform=\relax
        \pgftransformreset%
        \expandafter\tikzset\expandafter{\tikz@lib@spy@lens}
        \pgftransforminvert%
        \pgfgettransformentries\a\b\c\d\e\f%
        \global\let\pgf@lib@svg@a=\a%
        \global\let\pgf@lib@svg@b=\b%
        \global\let\pgf@lib@svg@c=\c%
        \global\let\pgf@lib@svg@d=\d%
      }%
      \tikz@addtransform{%
        \tikz@scan@one@point\pgftransformshift#2%
        \pgftransformcm{\pgf@lib@svg@a}{\pgf@lib@svg@b}{\pgf@lib@svg@c}{\pgf@lib@svg@d}{\pgfpointorigin}%
      }
    }]{};
    \node [alias=tikzspyinnode,inner sep=0pt,outer sep=0pt,at={#2},every spy in node/.try,
    path picture={\node[anchor=center,tikz@lib@reset@gs]{\nullfont%
        \pgfpicture\relax\pgfsetbaseline{default}\pgfsettrimleft{default}\pgfsettrimright{default}%
        \pgftransformreset%
        \let\tikz@transform=\relax%
        \expandafter\tikzset\expandafter{\tikz@lib@spy@lens}%
        \pgflowlevelsynccm%
        \tikz@scan@one@point\tikz@lib@spy@shift#2%
        \pgflowlevelsynccm%
        \copy\tikz@lib@spybox%
        \endpgfpicture};}]#3{};
    \tikz@lib@spy@path
  \endscope
}

\def\tikz@lib@spy@shift#1{%
  \pgf@process{#1}%
  \pgf@x=-\pgf@x%
  \pgf@y=-\pgf@y%
  \pgftransformshift{}%
}



\endinput

tikzlibrarysvg.path.code.tex
% Copyright 2009 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/tikzlibrarysvg.path.code.tex,v 1.2 2013/09/23 18:04:35 tantau Exp $

\usepgflibrary{svg.path}

\def\tikz@svg@path vg{\pgfutil@ifnextchar[\tikz@svg@@path{\tikz@svg@@path[]}}%}

\def\tikz@svg@@path[#1]{\pgfutil@ifnextchar"{\tikz@svg@@path@old{#1}}{\tikz@svg@@path@new{#1}}}
\def\tikz@svg@@path@new#1#2{\tikz@svg@@path@old{#1}"#2"}
\def\tikz@svg@@path@old#1"#2"{
  {%
    \tikzset{#1}%
    \pgfpathsvg{#2}%
  }%
  {
    \pgftransforminvert
    \pgf@process{\pgfpointtransformed{\pgfqpoint{\pgf@path@lastx}{\pgf@path@lasty}}}
  }
  \tikz@lastx=\pgf@x%
  \tikz@lasty=\pgf@y%
  \tikz@lastxsaved=\tikz@lastx%
  \tikz@lastysaved=\tikz@lasty%
  \tikz@updatecurrenttrue%
  \tikz@scan@next@command
}
tikzlibrarythrough.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/tikzlibrarythrough.code.tex,v 1.1 2008/02/03 19:37:27 tantau Exp $



\tikzset{circle through/.code={%
    \pgfkeysalso{shape=circle,inner sep=0pt,outer sep=0pt}%
    % Save transformations (correct?)
    \pgfgettransform{\tikz@lib@saved@transform}%
    \tikz@scan@one@point\tikz@lib@circle@through#1%
  }}

\def\tikz@lib@circle@through#1{%
  \tikz@addoption{%
    {%
      \pgfsettransform{\tikz@lib@saved@transform}%
      \pgf@process{\pgfpointtransformed{#1}}%
      \pgf@xa=\pgf@x%
      \pgf@ya=\pgf@y%
      \pgf@process{\pgfpointtransformed{\tikz@node@at}}%
      \advance\pgf@xa by-\pgf@x%
      \advance\pgf@ya by-\pgf@y%
      \pgfmathparse{2*veclen(\the\pgf@xa,\the\pgf@ya)}%
      \global\let\tikz@lib@circle@size=\pgfmathresult%
    }%
    \pgfset{/pgf/minimum size/.expanded=\tikz@lib@circle@size}%
  }%
}
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

tikzlibrarytrees.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/tikzlibrarytrees.code.tex,v 1.2 2008/02/24 10:00:52 tantau Exp $



%
% Three point growth
%

\tikzoption{grow via three points}{\let\tikz@grow=\tikz@grow@three\tikz@parse@three#1}

\def\tikz@parse@three one child at#1(#2)#3and two children at#4(#5)#6and#7(#8){%
  \def\tikz@tree@one@child{\tikz@scan@one@point\pgf@process(#2)}
  \def\tikz@tree@left@child{\tikz@scan@one@point\pgf@process(#5)}
  \def\tikz@tree@right@child{\tikz@scan@one@point\pgf@process(#8)}
}

\def\tikz@grow@three{%
  \pgf@process{\tikz@tree@one@child}%
  \pgf@xa=\pgf@x%
  \pgf@ya=\pgf@y%
  \pgf@process{\tikz@tree@left@child}%
  \pgf@xb=\pgf@x%
  \pgf@yb=\pgf@y%
  \advance\pgf@xb by-\pgf@xa%
  \advance\pgf@yb by-\pgf@ya%
  \pgf@process{\tikz@tree@right@child}%
  \pgf@xc=\pgf@x%
  \pgf@yc=\pgf@y%
  \advance\pgf@xc by-\pgf@xa%
  \advance\pgf@yc by-\pgf@ya%
  \advance\pgf@xc by-\pgf@xb%
  \advance\pgf@yc by-\pgf@yb%
  \advance\tikznumberofchildren by-1\relax%
  \pgf@xb=\tikznumberofchildren\pgf@xb\relax%
  \pgf@yb=\tikznumberofchildren\pgf@yb\relax%
  \advance\tikznumberofcurrentchild by-1\relax%
  \pgf@xc=\tikznumberofcurrentchild\pgf@xc\relax%
  \pgf@yc=\tikznumberofcurrentchild\pgf@yc\relax%
  \advance\pgf@xa by\pgf@xb%
  \advance\pgf@xa by\pgf@xc%
  \advance\pgf@ya by\pgf@yb%
  \advance\pgf@ya by\pgf@yc%
  \edef\pgf@temp{\noexpand\pgftransformshift{\noexpand\pgfqpoint{\the\pgf@xa}{\the\pgf@ya}}}%
  \pgf@temp%
}



%
% Circle grow
%

\tikzstyle{grow cyclic}=[growth function=\tikz@grow@circle]

\tikzset{sibling angle/.initial=20}

\def\tikz@grow@circle{%
  \pgftransformrotate{%
    (\pgfkeysvalueof{/tikz/sibling angle})*(-.5-.5*\tikznumberofchildren+\tikznumberofcurrentchild)}%
  \pgftransformxshift{\the\tikzleveldistance}%
}

\tikzoption{counterclockwise from}{\let\tikz@grow=\tikz@grow@circle@from\def\tikz@grow@circle@from@start{#1}}

\def\tikz@grow@circle@from{%
  \pgftransformshift{\pgfpointpolar{\tikz@grow@circle@from@start+(\pgfkeysvalueof{/tikz/sibling angle})*(\tikznumberofcurrentchild-1)}{\the\tikzleveldistance}}%
}

\tikzoption{clockwise from}{\let\tikz@grow=\tikz@grow@circle@from@\def\tikz@grow@circle@from@start{#1}}

\def\tikz@grow@circle@from@{%
  \pgftransformshift{\pgfpointpolar{\tikz@grow@circle@from@start-(\pgfkeysvalueof{/tikz/sibling angle})*(\tikznumberofcurrentchild-1)}{\the\tikzleveldistance}}%
}







%
% Connections
%

\tikzstyle{edge from parent fork down}=
  [edge from parent path={(\tikzparentnode\tikzparentanchor) -- +(0pt,-.5\tikzleveldistance)  -| (\tikzchildnode\tikzchildanchor)}]

\tikzstyle{edge from parent fork up}=
  [edge from parent path={(\tikzparentnode\tikzparentanchor) -- +(0pt,.5\tikzleveldistance)  -| (\tikzchildnode\tikzchildanchor)}]

\tikzstyle{edge from parent fork left}=
  [edge from parent path={(\tikzparentnode\tikzparentanchor) -- +(-.5\tikzleveldistance,0pt) |- (\tikzchildnode\tikzchildanchor)}]

\tikzstyle{edge from parent fork right}=
  [edge from parent path={(\tikzparentnode\tikzparentanchor) -- +(.5\tikzleveldistance,0pt) |- (\tikzchildnode\tikzchildanchor)}]


                                    
\endinput

tikzlibraryturtle.code.tex
% Copyright 2008 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/tikzlibraryturtle.code.tex,v 1.3 2008/06/18 23:34:49 tantau Exp $


\tikzset{turtle/.style={/tikz/turtle/.cd,#1}}

% The current angle is stored in this key.
\tikzset{turtle/direction/.code=\gdef\tikz@lib@turtle@dir{#1},turtle/direction=90}

% The current angle is stored in this key.
\tikzset{turtle/distance/.initial=1cm}

% The to path options that are used to move the turtle
\tikzset{turtle/how/.style=}

% Let the turtle jump home
\tikzset{turtle/home/.style={/tikz/insert path={(0,0) [turtle/direction=90]}}}

% Moves the turtle forward by the given distance or, if no distance is
% given, by turtle distance
\tikzset{
  turtle/forward/.default=\pgfkeysvalueof{/tikz/turtle/distance},
  turtle/forward/.style={/tikz/insert path={to[/tikz/turtle/how]++(\tikz@lib@turtle@dir:#1)}}
}



% Moves the turtle backward by the given distance or, if no distance is
% given, by turtle distance
\tikzset{
  turtle/back/.default=\pgfkeysvalueof{/tikz/turtle/distance},
  turtle/back/.style={turtle forward=-#1}
}



% Turns the turle left by the given number of degrees
\tikzset{
  turtle/left/.default=90,
  turtle/left/.code={%
    \pgfmathparse{#1+\tikz@lib@turtle@dir}%
    \ifdim\pgfmathresult pt>360pt\relax%
      \pgfmathparse{\pgfmathresult-360}%
    \fi%
    \global\let\tikz@lib@turtle@dir\pgfmathresult  
  }
}


% Turns the turle left by the given number of degrees
\tikzset{
  turtle/right/.default=90,
  turtle/right/.code={%
    \pgfmathparse{#1}
    \pgfmathparse{\tikz@lib@turtle@dir-\pgfmathresult}%
    \ifdim\pgfmathresult pt<0pt\relax%
      \pgfmathparse{\pgfmathresult+360}%
    \fi%
    \global\let\tikz@lib@turtle@dir\pgfmathresult  
  }
}


% Shortcuts:
\tikzset{turtle/.cd,
  fd/.style={forward=#1},
  fd/.default=\pgfkeysvalueof{/tikz/turtle/distance},
  bk/.style={back=#1},
  bk/.default=\pgfkeysvalueof{/tikz/turtle/distance},
  lt/.style={left=#1},
  lt/.default=90,
  rt/.style={right=#1},
  rt/.default=90}


\endinput

1604.02419.extracted_bib
{ACZ{T. Ahsendorf, C. Cheng, and Th. Zink, $\mathcal O$-displays and $\pi$-divisible formal $\mathcal O$-modules, J. Algebra 457 (2016), 129--193.
1604.02419.extracted_bib
{ARGOS{ARGOS seminar on intersections of modular correspondences, Ast\'erisque 312 (2007).
1604.02419.extracted_bib
{A{K. Arzdorf, On local models with special parahoric level structure, Michigan Math. J. 58 (2009), no. 3, 683--710.
1604.02419.extracted_bib
{D{V. G. Drinfeld, Coverings of $p$-adic symmetric domains, Funkcional. Anal. i Prilo\v zen. 10 (1976), no. 2, 29--40 (Russian).
1604.02419.extracted_bib
{F{L. Fargues, Cohomologie des espaces de modules de groupes $p$-divisibles et correspondances de Langlands locales, Ast\'erisque 291 (2004), 1--199.
1604.02419.extracted_bib
{Goertz{U. G\"ortz, On the flatness of models of certain Shimura varieties of PEL-type, Math. Ann. 321 (2001), no. 3, 689--727.
1604.02419.extracted_bib
{Goertz-He{U. G\"ortz and X. He, Basic loci in Shimura varieties of Coxeter type, Camb. J. Math. 3 (2015), no. 3, 323--353.
1604.02419.extracted_bib
{Go{J. Gordon, Transfer to characteristic zero, appendix to \cite{Y.
1604.02419.extracted_bib
{G{B. Gross, On canonical and quasicanonical liftings, Invent. Math. 84 (1986), no. 2, 321--326.
1604.02419.extracted_bib
{JR{H. Jacquet and S. Rallis, On the Gross-Prasad conjecture for unitary groups. In On certain $L$-functions, Clay Math. Proc., 13, Amer. Math. Soc., Providence, RI, 2011, pp. 205--264.
1604.02419.extracted_bib
{KR-U1{S. Kudla and M. Rapoport, Special cycles on unitary Shimura varieties I. Unramified local theory, Invent. Math. 184 (2011), no. 3, 629--682.
1604.02419.extracted_bib
{KR-alt{\bysame, An alternative description of the Drinfeld $p$-adic half-plane, Ann. Inst. Fourier (Grenoble) 64 (2014), no. 3, 1203--1228.
1604.02419.extracted_bib
{KRbarc{\bysame, Special cycles on the $\Gamma_0(p^n)$-moduli curve, unpublished.
1604.02419.extracted_bib
{Lau{E. Lau, Smoothness of the truncated display functor, J. Amer. Math. Soc. 26 (2013), no.~1, 129--165.
1604.02419.extracted_bib
{M-ATC{A. Mihatsch, An arithmetic transfer identity, Manuscripta Math. 150 (2016), no.~1, 1--19.
1604.02419.extracted_bib
{M-AFL{\bysame, On the arithmetic fundamental lemma conjecture through Lie algebras, to appear in Math. Z.
1604.02419.extracted_bib
{M-Th{\bysame, Relative unitary RZ-spaces and the Arithmetic Fundamental Lemma, preprint, 2016, \href{https://arxiv.org/abs/1611.06520{arXiv:1611.06520 [math.AG].
1604.02419.extracted_bib
{P{G. Pappas, On the arithmetic moduli schemes of PEL Shimura varieties, J. Algebraic Geom. 9 (2000), no. 3, 577--605.
1604.02419.extracted_bib
{PR-TLG{G. Pappas and M. Rapoport, Twisted loop groups and their affine flag varieties, Adv. Math. 219 (2008), no. 1, 118--198.
1604.02419.extracted_bib
{PR{\bysame, Local models in the ramified case. III. Unitary groups, J. Inst. Math. Jussieu 8 (2009), no. 3, 507--564.
1604.02419.extracted_bib
{PRS{G. Pappas, M. Rapoport, and B. Smithling, Local models of Shimura varieties, I. Geometry and combinatorics. In Handbook of Moduli. Vol. III, Adv. Lect. Math. (ALM), vol. 26, Int. Press, Somerville, MA, 2013, pp. 135--217.
1604.02419.extracted_bib
{PZ{G. Pappas and X. Zhu, Local models of Shimura varieties and a conjecture of Kottwitz, Invent. Math. 194 (2013), no. 1, 147--254.
1604.02419.extracted_bib
{RS{S. Rallis and G. Schiffmann, Multiplicity one conjectures, preprint, 2007, \href{http://arxiv.org/abs/0705.2168{arXiv:0705.2168 [math.NT].
1604.02419.extracted_bib
{RSZ{M. Rapoport, B. Smithling, and W. Zhang, On the arithmetic transfer conjecture for exotic smooth formal moduli spaces, to appear in Duke Math. J.
1604.02419.extracted_bib
{RSZglob{\bysame, Arithmetic diagonal cycles on unitary Shimura varieties, in preparation.
1604.02419.extracted_bib
{RTW{M. Rapoport, U. Terstiege, and S. Wilson, The supersingular locus of the Shimura variety for ${\rm GU(1, n - 1)$ over a ramified prime, Math. Z. 276 (2014), no. 3--4, 1165--1188.
1604.02419.extracted_bib
{RTZ{M. Rapoport, U. Terstiege, and W. Zhang, On the arithmetic fundamental lemma in the minuscule case, Compos. Math. 149 (2013), no. 10, 1631--1666.
1604.02419.extracted_bib
{RZ{M. Rapoport and Th. Zink, Period spaces for $p$-divisible groups, Annals of Mathematics Studies, vol. 141, Princeton University Press, Princeton, NJ, 1996.
1604.02419.extracted_bib
{Roy{A. Roy, Cancellation of quadratic forms over commutative rings, J. Algebra 10 (1968), 286--298.
1604.02419.extracted_bib
{San{S. Sankaran, Unitary cycles on Shimura curves and the Shimura lift I, Documenta Math. 18 (2013), 1403--1464.
1604.02419.extracted_bib
{San-mail{\bysame, e-mail to Rapoport, 11 April 2015.
1604.02419.extracted_bib
{S{B. Smithling, On the moduli description of local models for ramified unitary groups, Int. Math. Res. Not. 2015 (2015), no. 24, 13493--13532.
1604.02419.extracted_bib
{V1{I. Vollaard, Endomorphisms of quasi-canonical lifts, in \cite{ARGOS, pp. 105--112.
1604.02419.extracted_bib
{V2{\bysame, The supersingular locus of the Shimura variety for $GU(1,s)$, Can. J. Math. 62 (2010), 668--720.
1604.02419.extracted_bib
{VW{I. Vollaard and T. Wedhorn, The supersingular locus of the Shimura variety for $\mathrm{GU(1,n- 1)$ II, Invent. Math. 184 (2011), no. 3, 591--627.
1604.02419.extracted_bib
{Wewers{S. Wewers, Canonical and quasi-canonical liftings, in \cite{ARGOS, pp. 67--86.
1604.02419.extracted_bib
{Wu{H. Wu, The supersingular locus of unitary Shimura varieties with exotic good reduction, preprint, 2016, \href{https://arxiv.org/abs/1609.08775{arXiv:1609.08775 [math.AG].
1604.02419.extracted_bib
{Yu{S. Yu, in preparation.
1604.02419.extracted_bib
{Y{Z. Yun, The fundamental lemma of Jacquet--Rallis in positive characteristics, Duke Math. J. 156 (2011), no. 2, 167--228.
1604.02419.extracted_bib
{Y12{\bysame, An arithmetic fundamental lemma for function fields, in preparation.
1604.02419.extracted_bib
{Z12{W. Zhang, On arithmetic fundamental lemmas, Invent. Math. 188 (2012), no. 1, 197--252.
1604.02419.extracted_bib
{Z12b{\bysame, On the smooth transfer conjecture of Jacquet--Rallis for $n=3$, Ramanujan J. 29 (2012), no. 1--3, 225--256.
1604.02419.extracted_bib
{Z14{\bysame, Fourier transform and the global Gan--Gross--Prasad conjecture for unitary groups, Ann. of Math. (2) 180 (2014), no. 3, 971--1049.