\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{cachepic}[2009/05/31]

\RequirePackage{graphicx,verbatim}

\gdef\cachepic@picext{.eps}
\global\let\cachepic@multipicfile=\@undefined
\global\let\cachepic@includepic=\relax%

\ifx\pdfoutput\@undefined \else
  \ifx\pdfoutput\relax \else
    \ifnum\pdfoutput>\z@
      \gdef\cachepic@picext{.pdf}
      \IfFileExists{\jobname-cachepic.pdf}{\gdef\cachepic@multipicfile{\jobname-cachepic.pdf}}{}
    \fi
  \fi
\fi

\providecommand\CachePicDefMacro[4]{%
% #1 macro name (must be a valid file path without extension)
% #2 cached pic page No.
% #3 include graphics optional arguments
% #4 raisebox argument (negative depth)
\expandafter\def\csname cachepic@name@#1\endcsname{
  \ifx\cachepic@includepic\@undefined% #1 does not exist, check for \cachepic@multipicfile
    \ifx\cachepic@multipicfile\@undefined\else% \cachepic@multipicfile exists
      \def\cachepic@includepic{\raisebox{#4}{\includegraphics[page=#2,#3]{\cachepic@multipicfile}}}
    \fi
  \else% #1 exists (preffered)
    \def\cachepic@includepic{\raisebox{#4}{\includegraphics[#3]{#1}}}
  \fi
}}

\providecommand\cachepic@tryincludepic[2]{%
% #1 picture name to include
% #2 code to execute if picture file does not exist
\xdef\cachepic@name{#1}%
\let\cachepic@includepic=\@undefined%
\IfFileExists{\cachepic@name\cachepic@picext}{%
\def\cachepic@includepic{\includegraphics{\cachepic@name}}% default include
}{}%
\csname cachepic@name@#1\endcsname% define advanced include if available
\ifx\cachepic@includepic\@undefined#2\else\cachepic@includepic\fi%
}

\newcommand\cachepic[2]{\cachepic@tryincludepic{#1}{#2}}

\newcommand\cacheinput[1]{\cachepic{#1}{\input{#1}}}

\newenvironment{cachepicture}[1]{%
\cachepic@tryincludepic{#1}{%
\let\comment=\relax%
\let\endcomment=\relax%
}%
\comment%
}{%
\endcomment%
}

\AtBeginDocument{\InputIfFileExists{\jobname.cachepic}{}{}}

\endinput
