%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% This file is a copy of some part of PGF/Tikz.
%%% It has been copied here to provide :
%%%  - compatibility with older PGF versions
%%%  - availability of PGF contributions by Christian Feuersaenger
%%%    which are necessary or helpful for pgfplots.
%%%
%%% For reasons of simplicity, I have copied the whole file, including own contributions AND
%%% PGF parts. The copyrights are as they appear in PGF.
%%%
%%% Note that pgfplots has compatible licenses.
%%%
%%% This copy has been modified in the following ways:
%%%  - nested \input commands have been updated
%%%
%
% Support for the contents of this file will NOT be done by the PGF/TikZ team.
% Please contact the author and/or maintainer of pgfplots (Christian Feuersaenger) if you need assistance in conjunction
% with the deployment of this patch or partial content of PGF. Note that the author and/or maintainer of pgfplots has no obligation to fix anything:
% This file comes without any warranty as the rest of pgfplots; there is no obligation for help.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Date of this copy: Mon Mar 22 16:42:03 CET 2010 %%%



% 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.14 2010/03/19 09:50:32 ludewich 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%
    \PackageWarning{pgf}%
    {File "#3" not found when defining image "#2".\MessageBreak
      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%
}

\newif\ifpgfexternal@allow@aux

\pgfkeys{
	/pgf/images/include external/.code={\pgfimage{#1}},
	/pgf/images/aux in dpth/.is if=pgfexternal@allow@aux,
	/pgf/images/aux in dpth/.default=true,
	/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}
\pgfkeys{/pgf/images/mask/.code=%
  {%
    \edef\pgf@imagemask{#1}%
    \ifx\pgf@imagemask\pgfutil@empty%
    \else%
      \pgfutil@ifundefined{pgf@mask@#1}%
      {\PackageError{pgf}{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%
    \PackageWarning{pgf}{Missing width for image "#1" ("#2") in draft mode.\MessageBreak  Using 1cm instead}%
    \edef\pgf@imagewidth{1cm}%
  \fi%
  \ifx\pgf@imageheight\pgfutil@empty%
    \PackageWarning{pgf}{Missing height for image "#1" ("#2") in draft mode.\MessageBreak 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\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%
    \PackageWarning{pgf}%
    {File "#3" not found when defining mask "#2".\MessageBreak
      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}%
  {\PackageError{pgf}{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}}








% 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
	\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@allow@aux
		\csname newwrite\endcsname\w@pgfexternal@auxout
	\fi
  \fi%
  \gdef\pgfrealjobname##1{}% avoid multiple calls.
}

\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

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


% "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
	\setbox1=\hbox{\pgfkeysvalueof{/pgf/images/include external/.@cmd}{#1}\pgfeov}%
	%
	\let\pgfincludeexternalgraphics@dp=\pgfutil@empty
	\endlinechar=-1 % suppress white space at end
	\catcode`\@=11
	\openin\r@pgf@reada=#1.dpth
	\pgfincludeexternalgraphics@read@dpth
	\ifx\pgfincludeexternalgraphics@dp\pgfutil@empty
		\box1
	\else
		\dimen0=\pgfincludeexternalgraphics@dp\relax
		\hbox{\lower\dimen0 \box1 }%
	\fi
	\endgroup
}
%
% 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
}%
\long\def\pgfincludeexternalgraphics@read@dpth@line#1#2\pgfincludeexternalgraphics@read@dpth@line@EOI{%
	\ifcat\noexpand#1\relax
		% Ah -- the first token is a control sequence. It belongs to
		% the .aux file.
		%
		% #1#2\relax% do NOT set the information! 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#2}%
				% 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
		}%
	\else
		\def\pgfincludeexternalgraphics@dp{#1#2}%
	\fi
}%



% 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@allow@aux
  	\begingroup
	\pgf@external@init@aux@in@dpth
  \fi
  \setbox\pgfpic=\hbox\bgroup\bgroup%
    \let\endpgfgraphicnamed=\pgf@externalend%
}

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

% REMARK:
%   this method is also invoked from within the tikz external library.
\def\pgf@externalend{%
  \unskip\egroup\egroup%
  {%
    \parindent0pt % leave the space
%    \leftmargin0pt%
%    \rightmargin0pt%
    \dimen0\ht\pgfpic%
    \advance\dimen0\dp\pgfpic%
	\ifdim\dp\pgfpic=0pt\relax
	\else% store the picture's depth. Otherwise, it would be lost.
		\ifpgfexternal@allow@aux
			\immediate\write\@auxout{\the\dp\pgfpic}%
			\immediate\closeout\@auxout
		\else
			\immediate\openout\pgf@plotwrite=\pgf@filename.dpth
			\immediate\write\pgf@plotwrite{\the\dp\pgfpic}%
			\immediate\closeout\pgf@plotwrite
		\fi
	\fi
    \pgfsys@papersize{\the\wd\pgfpic}{\the\dimen0}%
    \setbox0=\vbox{%
      \kern -1truein %
      \hbox{%
        \kern -1truein %
        \hbox to0pt{%
          \wd\pgfexternal@startupbox=0pt %
          \ht\pgfexternal@startupbox=0pt %
          \dp\pgfexternal@startupbox=0pt %
          \box\pgfexternal@startupbox%
          \pgfsys@atbegindocument\hss}%
        \box\pgfpic%
        \kern 1truein }%
      \kern1truein }%
    \pgfexternal@originalshipout\box0 %
  }%
  \ifpgfexternal@allow@aux
  	\endgroup
  \fi
}


\endinput
